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_ex_new_index );
115 MAKE_FUNCPTR( SSL_get_ex_data );
116 MAKE_FUNCPTR( SSL_set_ex_data );
117 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
118 MAKE_FUNCPTR( SSL_get_verify_result );
119 MAKE_FUNCPTR( SSL_get_peer_certificate );
120 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
121 MAKE_FUNCPTR( SSL_CTX_set_verify );
123 MAKE_FUNCPTR( CRYPTO_num_locks );
124 MAKE_FUNCPTR( CRYPTO_set_id_callback );
125 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
126 MAKE_FUNCPTR( ERR_free_strings );
127 MAKE_FUNCPTR( ERR_get_error );
128 MAKE_FUNCPTR( ERR_error_string );
129 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
130 MAKE_FUNCPTR( i2d_X509 );
131 MAKE_FUNCPTR( sk_value );
132 MAKE_FUNCPTR( sk_num );
135 static CRITICAL_SECTION *ssl_locks;
136 static unsigned int num_ssl_locks;
138 static unsigned long ssl_thread_id(void)
140 return GetCurrentThreadId();
143 static void ssl_lock_callback(int mode, int type, const char *file, int line)
145 if (mode & CRYPTO_LOCK)
146 EnterCriticalSection( &ssl_locks[type] );
148 LeaveCriticalSection( &ssl_locks[type] );
153 /* translate a unix error code into a winsock error code */
154 static int sock_get_error( int err )
156 #if !defined(__MINGW32__) && !defined (_MSC_VER)
159 case EINTR: return WSAEINTR;
160 case EBADF: return WSAEBADF;
162 case EACCES: return WSAEACCES;
163 case EFAULT: return WSAEFAULT;
164 case EINVAL: return WSAEINVAL;
165 case EMFILE: return WSAEMFILE;
166 case EWOULDBLOCK: return WSAEWOULDBLOCK;
167 case EINPROGRESS: return WSAEINPROGRESS;
168 case EALREADY: return WSAEALREADY;
169 case ENOTSOCK: return WSAENOTSOCK;
170 case EDESTADDRREQ: return WSAEDESTADDRREQ;
171 case EMSGSIZE: return WSAEMSGSIZE;
172 case EPROTOTYPE: return WSAEPROTOTYPE;
173 case ENOPROTOOPT: return WSAENOPROTOOPT;
174 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
175 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
176 case EOPNOTSUPP: return WSAEOPNOTSUPP;
177 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
178 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
179 case EADDRINUSE: return WSAEADDRINUSE;
180 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
181 case ENETDOWN: return WSAENETDOWN;
182 case ENETUNREACH: return WSAENETUNREACH;
183 case ENETRESET: return WSAENETRESET;
184 case ECONNABORTED: return WSAECONNABORTED;
186 case ECONNRESET: return WSAECONNRESET;
187 case ENOBUFS: return WSAENOBUFS;
188 case EISCONN: return WSAEISCONN;
189 case ENOTCONN: return WSAENOTCONN;
190 case ESHUTDOWN: return WSAESHUTDOWN;
191 case ETOOMANYREFS: return WSAETOOMANYREFS;
192 case ETIMEDOUT: return WSAETIMEDOUT;
193 case ECONNREFUSED: return WSAECONNREFUSED;
194 case ELOOP: return WSAELOOP;
195 case ENAMETOOLONG: return WSAENAMETOOLONG;
196 case EHOSTDOWN: return WSAEHOSTDOWN;
197 case EHOSTUNREACH: return WSAEHOSTUNREACH;
198 case ENOTEMPTY: return WSAENOTEMPTY;
200 case EPROCLIM: return WSAEPROCLIM;
203 case EUSERS: return WSAEUSERS;
206 case EDQUOT: return WSAEDQUOT;
209 case ESTALE: return WSAESTALE;
212 case EREMOTE: return WSAEREMOTE;
214 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
221 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
223 unsigned char *buffer, *p;
229 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
231 * SSL 0.9.7 and above malloc the buffer if it is null.
232 * however earlier version do not and so we would need to alloc the buffer.
234 * see the i2d_X509 man page for more details.
238 if (!(buffer = heap_alloc( len ))) return NULL;
240 len = pi2d_X509( cert, &p );
248 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
250 if (malloc) free( buffer );
251 else heap_free( buffer );
256 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
257 WCHAR *server, DWORD security_flags )
260 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
261 PCCERT_CHAIN_CONTEXT chain;
262 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
263 char *server_auth[] = { oid_server_auth };
264 DWORD err = ERROR_SUCCESS;
266 TRACE("verifying %s\n", debugstr_w( server ));
267 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
268 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
269 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
272 if (chain->TrustStatus.dwErrorStatus)
274 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
276 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
277 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
279 else if (chain->TrustStatus.dwErrorStatus &
280 CERT_TRUST_IS_UNTRUSTED_ROOT)
281 err = ERROR_WINHTTP_SECURE_INVALID_CA;
282 else if ((chain->TrustStatus.dwErrorStatus &
283 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
284 (chain->TrustStatus.dwErrorStatus &
285 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
286 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
287 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
288 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
289 else if (chain->TrustStatus.dwErrorStatus &
290 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
292 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
293 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
296 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
300 CERT_CHAIN_POLICY_PARA policyPara;
301 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
302 CERT_CHAIN_POLICY_STATUS policyStatus;
304 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
305 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
306 sslExtraPolicyPara.pwszServerName = server;
307 policyPara.cbSize = sizeof(policyPara);
308 policyPara.dwFlags = 0;
309 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
310 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
313 /* Any error in the policy status indicates that the
314 * policy couldn't be verified.
316 if (ret && policyStatus.dwError)
318 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
320 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
321 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
324 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
327 CertFreeCertificateChain( chain );
330 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
331 TRACE("returning %08x\n", err);
335 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
342 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
343 server = pSSL_get_ex_data( ssl, hostname_idx );
344 conn = pSSL_get_ex_data( ssl, conn_idx );
347 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
348 CERT_STORE_CREATE_NEW_FLAG, NULL );
354 PCCERT_CONTEXT endCert = NULL;
357 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
359 PCCERT_CONTEXT context;
361 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
362 if ((context = X509_to_cert_context( cert )))
365 ret = CertAddCertificateContextToStore( store, context,
366 CERT_STORE_ADD_ALWAYS, &endCert );
368 ret = CertAddCertificateContextToStore( store, context,
369 CERT_STORE_ADD_ALWAYS, NULL );
370 CertFreeCertificateContext( context );
373 if (!endCert) ret = FALSE;
376 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
377 conn->security_flags );
381 pSSL_set_ex_data( ssl, error_idx, (void *)err );
385 CertFreeCertificateContext( endCert );
386 CertCloseStore( store, 0 );
393 BOOL netconn_init( netconn_t *conn, BOOL secure )
395 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
400 if (!secure) return TRUE;
402 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
403 EnterCriticalSection( &init_ssl_cs );
406 LeaveCriticalSection( &init_ssl_cs );
409 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
411 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
412 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
413 LeaveCriticalSection( &init_ssl_cs );
416 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
418 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
419 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
420 LeaveCriticalSection( &init_ssl_cs );
423 #define LOAD_FUNCPTR(x) \
424 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
426 ERR("Failed to load symbol %s\n", #x); \
427 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
428 LeaveCriticalSection( &init_ssl_cs ); \
431 LOAD_FUNCPTR( SSL_library_init );
432 LOAD_FUNCPTR( SSL_load_error_strings );
433 LOAD_FUNCPTR( SSLv23_method );
434 LOAD_FUNCPTR( SSL_CTX_free );
435 LOAD_FUNCPTR( SSL_CTX_new );
436 LOAD_FUNCPTR( SSL_new );
437 LOAD_FUNCPTR( SSL_free );
438 LOAD_FUNCPTR( SSL_set_fd );
439 LOAD_FUNCPTR( SSL_connect );
440 LOAD_FUNCPTR( SSL_shutdown );
441 LOAD_FUNCPTR( SSL_write );
442 LOAD_FUNCPTR( SSL_read );
443 LOAD_FUNCPTR( SSL_get_ex_new_index );
444 LOAD_FUNCPTR( SSL_get_ex_data );
445 LOAD_FUNCPTR( SSL_set_ex_data );
446 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
447 LOAD_FUNCPTR( SSL_get_verify_result );
448 LOAD_FUNCPTR( SSL_get_peer_certificate );
449 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
450 LOAD_FUNCPTR( SSL_CTX_set_verify );
453 #define LOAD_FUNCPTR(x) \
454 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
456 ERR("Failed to load symbol %s\n", #x); \
457 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
458 LeaveCriticalSection( &init_ssl_cs ); \
461 LOAD_FUNCPTR( CRYPTO_num_locks );
462 LOAD_FUNCPTR( CRYPTO_set_id_callback );
463 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
464 LOAD_FUNCPTR( ERR_free_strings );
465 LOAD_FUNCPTR( ERR_get_error );
466 LOAD_FUNCPTR( ERR_error_string );
467 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
468 LOAD_FUNCPTR( i2d_X509 );
469 LOAD_FUNCPTR( sk_value );
470 LOAD_FUNCPTR( sk_num );
474 pSSL_load_error_strings();
476 method = pSSLv23_method();
477 ctx = pSSL_CTX_new( method );
478 if (!pSSL_CTX_set_default_verify_paths( ctx ))
480 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
481 set_last_error( ERROR_OUTOFMEMORY );
482 LeaveCriticalSection( &init_ssl_cs );
485 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
486 if (hostname_idx == -1)
488 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
489 set_last_error( ERROR_OUTOFMEMORY );
490 LeaveCriticalSection( &init_ssl_cs );
493 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
496 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
497 set_last_error( ERROR_OUTOFMEMORY );
498 LeaveCriticalSection( &init_ssl_cs );
501 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
504 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
505 set_last_error( ERROR_OUTOFMEMORY );
506 LeaveCriticalSection( &init_ssl_cs );
509 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
511 pCRYPTO_set_id_callback(ssl_thread_id);
512 num_ssl_locks = pCRYPTO_num_locks();
513 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
516 set_last_error( ERROR_OUTOFMEMORY );
517 LeaveCriticalSection( &init_ssl_cs );
520 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
521 pCRYPTO_set_locking_callback(ssl_lock_callback);
523 LeaveCriticalSection( &init_ssl_cs );
525 WARN("SSL support not compiled in.\n");
526 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
532 void netconn_unload( void )
534 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
535 if (libcrypto_handle)
538 wine_dlclose( libcrypto_handle, NULL, 0 );
543 pSSL_CTX_free( ctx );
544 wine_dlclose( libssl_handle, NULL, 0 );
549 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
550 HeapFree( GetProcessHeap(), 0, ssl_locks );
555 BOOL netconn_connected( netconn_t *conn )
557 return (conn->socket != -1);
560 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
562 if ((conn->socket = socket( domain, type, protocol )) == -1)
564 WARN("unable to create socket (%s)\n", strerror(errno));
565 set_last_error( sock_get_error( errno ) );
571 BOOL netconn_close( netconn_t *conn )
578 heap_free( conn->peek_msg_mem );
579 conn->peek_msg_mem = NULL;
580 conn->peek_msg = NULL;
583 pSSL_shutdown( conn->ssl_conn );
584 pSSL_free( conn->ssl_conn );
586 conn->ssl_conn = NULL;
587 conn->secure = FALSE;
590 res = closesocket( conn->socket );
594 set_last_error( sock_get_error( errno ) );
600 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
608 ioctlsocket( conn->socket, FIONBIO, &state );
610 if (connect( conn->socket, sockaddr, addr_len ) < 0)
612 res = sock_get_error( errno );
613 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
617 pfd.fd = conn->socket;
618 pfd.events = POLLOUT;
619 if (poll( &pfd, 1, timeout ) > 0)
622 res = sock_get_error( errno );
630 ioctlsocket( conn->socket, FIONBIO, &state );
634 WARN("unable to connect to host (%d)\n", res);
635 set_last_error( res );
640 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
643 if (!(conn->ssl_conn = pSSL_new( ctx )))
645 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
646 set_last_error( ERROR_OUTOFMEMORY );
649 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
651 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
652 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
655 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
657 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
658 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
661 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
663 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
664 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
667 if (pSSL_connect( conn->ssl_conn ) <= 0)
671 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
672 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
673 ERR("couldn't verify server certificate (%d)\n", err);
674 set_last_error( err );
677 TRACE("established SSL connection\n");
684 pSSL_shutdown( conn->ssl_conn );
685 pSSL_free( conn->ssl_conn );
686 conn->ssl_conn = NULL;
692 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
694 if (!netconn_connected( conn )) return FALSE;
698 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
699 *sent = pSSL_write( conn->ssl_conn, msg, len );
700 if (*sent < 1 && len) return FALSE;
706 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
708 set_last_error( sock_get_error( errno ) );
714 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
717 if (!netconn_connected( conn )) return FALSE;
718 if (!len) return TRUE;
723 if (flags & ~(MSG_PEEK | MSG_WAITALL))
724 FIXME("SSL_read does not support the following flags: %08x\n", flags);
726 /* this ugly hack is all for MSG_PEEK */
727 if (flags & MSG_PEEK && !conn->peek_msg)
729 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
731 else if (flags & MSG_PEEK && conn->peek_msg)
733 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
734 *recvd = min( len, conn->peek_len );
735 memcpy( buf, conn->peek_msg, *recvd );
738 else if (conn->peek_msg)
740 *recvd = min( len, conn->peek_len );
741 memcpy( buf, conn->peek_msg, *recvd );
742 conn->peek_len -= *recvd;
743 conn->peek_msg += *recvd;
745 if (conn->peek_len == 0)
747 heap_free( conn->peek_msg_mem );
748 conn->peek_msg_mem = NULL;
749 conn->peek_msg = NULL;
751 /* check if we have enough data from the peek buffer */
752 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
754 *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
755 if (flags & MSG_PEEK) /* must copy into buffer */
757 conn->peek_len = *recvd;
760 heap_free( conn->peek_msg_mem );
761 conn->peek_msg_mem = NULL;
762 conn->peek_msg = NULL;
764 else memcpy( conn->peek_msg, buf, *recvd );
766 if (*recvd < 1) return FALSE;
772 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
774 set_last_error( sock_get_error( errno ) );
780 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
786 if (!netconn_connected( conn )) return FALSE;
791 if (conn->peek_msg) *available = conn->peek_len;
796 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
801 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
807 if (!netconn_connected( conn )) return FALSE;
812 while (recvd < *buflen)
815 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
817 set_last_error( ERROR_CONNECTION_ABORTED );
820 if (buffer[recvd] == '\n')
825 if (buffer[recvd] != '\r') recvd++;
831 TRACE("received line %s\n", debugstr_a(buffer));
839 pfd.fd = conn->socket;
841 while (recvd < *buflen)
845 socklen_t len = sizeof(tv);
847 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
848 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
851 if (poll( &pfd, 1, timeout ) > 0)
853 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
855 if (res == -1) set_last_error( sock_get_error( errno ) );
858 if (buffer[recvd] == '\n')
863 if (buffer[recvd] != '\r') recvd++;
867 set_last_error( ERROR_WINHTTP_TIMEOUT );
875 TRACE("received line %s\n", debugstr_a(buffer));
880 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
885 /* value is in milliseconds, convert to struct timeval */
886 tv.tv_sec = value / 1000;
887 tv.tv_usec = (value % 1000) * 1000;
889 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
891 WARN("setsockopt failed (%s)\n", strerror( errno ));
892 return sock_get_error( errno );
894 return ERROR_SUCCESS;
897 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
900 #ifdef HAVE_GETADDRINFO
901 struct addrinfo *res, hints;
905 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
908 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
910 #ifdef HAVE_GETADDRINFO
911 memset( &hints, 0, sizeof(struct addrinfo) );
912 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
913 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
915 hints.ai_family = AF_INET;
917 ret = getaddrinfo( hostname, NULL, &hints, &res );
920 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
921 hints.ai_family = AF_INET6;
922 ret = getaddrinfo( hostname, NULL, &hints, &res );
925 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
926 heap_free( hostname );
927 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
930 heap_free( hostname );
931 if (*sa_len < res->ai_addrlen)
933 WARN("address too small\n");
935 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
937 *sa_len = res->ai_addrlen;
938 memcpy( sa, res->ai_addr, res->ai_addrlen );
940 switch (res->ai_family)
943 ((struct sockaddr_in *)sa)->sin_port = htons( port );
946 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
951 return ERROR_SUCCESS;
953 EnterCriticalSection( &cs_gethostbyname );
955 he = gethostbyname( hostname );
956 heap_free( hostname );
959 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
960 LeaveCriticalSection( &cs_gethostbyname );
961 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
963 if (*sa_len < sizeof(struct sockaddr_in))
965 WARN("address too small\n");
966 LeaveCriticalSection( &cs_gethostbyname );
967 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
969 *sa_len = sizeof(struct sockaddr_in);
970 memset( sa, 0, sizeof(struct sockaddr_in) );
971 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
972 sin->sin_family = he->h_addrtype;
973 sin->sin_port = htons( port );
975 LeaveCriticalSection( &cs_gethostbyname );
976 return ERROR_SUCCESS;
988 static DWORD CALLBACK resolve_proc( LPVOID arg )
990 struct resolve_args *ra = arg;
991 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
994 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1002 struct resolve_args ra;
1004 ra.hostname = hostname;
1009 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1010 if (!thread) return FALSE;
1012 status = WaitForSingleObject( thread, timeout );
1013 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1014 else ret = ERROR_WINHTTP_TIMEOUT;
1015 CloseHandle( thread );
1017 else ret = resolve_hostname( hostname, port, sa, sa_len );
1021 set_last_error( ret );
1027 const void *netconn_get_certificate( netconn_t *conn )
1029 #ifdef SONAME_LIBSSL
1031 const CERT_CONTEXT *ret;
1033 if (!conn->secure) return NULL;
1035 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1036 ret = X509_to_cert_context( cert );