winhttp: Check the certificate in an https connection using the crypto api.
[wine] / dlls / winhttp / net.c
1 /*
2  * Copyright 2008 Hans Leidekker for CodeWeavers
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
25
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
44
45 #include "wine/debug.h"
46 #include "wine/library.h"
47
48 #include "windef.h"
49 #include "winbase.h"
50 #include "winhttp.h"
51 #include "wincrypt.h"
52
53 #include "winhttp_private.h"
54
55 /* to avoid conflicts with the Unix socket headers */
56 #define USE_WS_PREFIX
57 #include "winsock2.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
60
61 #ifndef HAVE_GETADDRINFO
62
63 /* critical section to protect non-reentrant gethostbyname() */
64 static CRITICAL_SECTION cs_gethostbyname;
65 static CRITICAL_SECTION_DEBUG critsect_debug =
66 {
67     0, 0, &cs_gethostbyname,
68     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
69       0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
70 };
71 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
72
73 #endif
74
75 #ifdef SONAME_LIBSSL
76
77 #include <openssl/err.h>
78
79 static CRITICAL_SECTION init_ssl_cs;
80 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
81 {
82     0, 0, &init_ssl_cs,
83     { &init_ssl_cs_debug.ProcessLocksList,
84       &init_ssl_cs_debug.ProcessLocksList },
85     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
86 };
87 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
88
89 static void *libssl_handle;
90 static void *libcrypto_handle;
91
92 static SSL_METHOD *method;
93 static SSL_CTX *ctx;
94 static int hostname_idx;
95
96 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
97
98 MAKE_FUNCPTR( SSL_library_init );
99 MAKE_FUNCPTR( SSL_load_error_strings );
100 MAKE_FUNCPTR( SSLv23_method );
101 MAKE_FUNCPTR( SSL_CTX_free );
102 MAKE_FUNCPTR( SSL_CTX_new );
103 MAKE_FUNCPTR( SSL_new );
104 MAKE_FUNCPTR( SSL_free );
105 MAKE_FUNCPTR( SSL_set_fd );
106 MAKE_FUNCPTR( SSL_connect );
107 MAKE_FUNCPTR( SSL_shutdown );
108 MAKE_FUNCPTR( SSL_write );
109 MAKE_FUNCPTR( SSL_read );
110 MAKE_FUNCPTR( SSL_get_ex_new_index );
111 MAKE_FUNCPTR( SSL_get_ex_data );
112 MAKE_FUNCPTR( SSL_set_ex_data );
113 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
114 MAKE_FUNCPTR( SSL_get_verify_result );
115 MAKE_FUNCPTR( SSL_get_peer_certificate );
116 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
117 MAKE_FUNCPTR( SSL_CTX_set_verify );
118 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
119
120 MAKE_FUNCPTR( BIO_new_fp );
121 MAKE_FUNCPTR( CRYPTO_num_locks );
122 MAKE_FUNCPTR( CRYPTO_set_id_callback );
123 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
124 MAKE_FUNCPTR( ERR_get_error );
125 MAKE_FUNCPTR( ERR_error_string );
126 MAKE_FUNCPTR( i2d_X509 );
127 #undef MAKE_FUNCPTR
128
129 static CRITICAL_SECTION *ssl_locks;
130 static unsigned int num_ssl_locks;
131
132 static unsigned long ssl_thread_id(void)
133 {
134     return GetCurrentThreadId();
135 }
136
137 static void ssl_lock_callback(int mode, int type, const char *file, int line)
138 {
139     if (mode & CRYPTO_LOCK)
140         EnterCriticalSection( &ssl_locks[type] );
141     else
142         LeaveCriticalSection( &ssl_locks[type] );
143 }
144
145 #endif
146
147 /* translate a unix error code into a winsock error code */
148 static int sock_get_error( int err )
149 {
150 #if !defined(__MINGW32__) && !defined (_MSC_VER)
151     switch (err)
152     {
153         case EINTR:             return WSAEINTR;
154         case EBADF:             return WSAEBADF;
155         case EPERM:
156         case EACCES:            return WSAEACCES;
157         case EFAULT:            return WSAEFAULT;
158         case EINVAL:            return WSAEINVAL;
159         case EMFILE:            return WSAEMFILE;
160         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
161         case EINPROGRESS:       return WSAEINPROGRESS;
162         case EALREADY:          return WSAEALREADY;
163         case ENOTSOCK:          return WSAENOTSOCK;
164         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
165         case EMSGSIZE:          return WSAEMSGSIZE;
166         case EPROTOTYPE:        return WSAEPROTOTYPE;
167         case ENOPROTOOPT:       return WSAENOPROTOOPT;
168         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
169         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
170         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
171         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
172         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
173         case EADDRINUSE:        return WSAEADDRINUSE;
174         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
175         case ENETDOWN:          return WSAENETDOWN;
176         case ENETUNREACH:       return WSAENETUNREACH;
177         case ENETRESET:         return WSAENETRESET;
178         case ECONNABORTED:      return WSAECONNABORTED;
179         case EPIPE:
180         case ECONNRESET:        return WSAECONNRESET;
181         case ENOBUFS:           return WSAENOBUFS;
182         case EISCONN:           return WSAEISCONN;
183         case ENOTCONN:          return WSAENOTCONN;
184         case ESHUTDOWN:         return WSAESHUTDOWN;
185         case ETOOMANYREFS:      return WSAETOOMANYREFS;
186         case ETIMEDOUT:         return WSAETIMEDOUT;
187         case ECONNREFUSED:      return WSAECONNREFUSED;
188         case ELOOP:             return WSAELOOP;
189         case ENAMETOOLONG:      return WSAENAMETOOLONG;
190         case EHOSTDOWN:         return WSAEHOSTDOWN;
191         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
192         case ENOTEMPTY:         return WSAENOTEMPTY;
193 #ifdef EPROCLIM
194         case EPROCLIM:          return WSAEPROCLIM;
195 #endif
196 #ifdef EUSERS
197         case EUSERS:            return WSAEUSERS;
198 #endif
199 #ifdef EDQUOT
200         case EDQUOT:            return WSAEDQUOT;
201 #endif
202 #ifdef ESTALE
203         case ESTALE:            return WSAESTALE;
204 #endif
205 #ifdef EREMOTE
206         case EREMOTE:           return WSAEREMOTE;
207 #endif
208     default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
209     }
210 #endif
211     return err;
212 }
213
214 #ifdef SONAME_LIBSSL
215 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
216 {
217     unsigned char *buffer, *p;
218     int len;
219     BOOL malloc = FALSE;
220     PCCERT_CONTEXT ret;
221
222     p = NULL;
223     if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
224     /*
225      * SSL 0.9.7 and above malloc the buffer if it is null.
226      * however earlier version do not and so we would need to alloc the buffer.
227      *
228      * see the i2d_X509 man page for more details.
229      */
230     if (!p)
231     {
232         if (!(buffer = heap_alloc( len ))) return NULL;
233         p = buffer;
234         len = pi2d_X509( cert, &p );
235     }
236     else
237     {
238         buffer = p;
239         malloc = TRUE;
240     }
241
242     ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
243
244     if (malloc) free( buffer );
245     else heap_free( buffer );
246
247     return ret;
248 }
249
250 static BOOL netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
251                                  WCHAR *server )
252 {
253     BOOL ret;
254     CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
255     PCCERT_CHAIN_CONTEXT chain;
256     char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
257     char *server_auth[] = { oid_server_auth };
258     DWORD err;
259
260     TRACE("verifying %s\n", debugstr_w( server ));
261     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
262     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
263     if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
264                                         NULL, &chain )))
265     {
266         if (chain->TrustStatus.dwErrorStatus)
267         {
268             if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
269                 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
270             else if (chain->TrustStatus.dwErrorStatus &
271                      CERT_TRUST_IS_UNTRUSTED_ROOT)
272                 err = ERROR_WINHTTP_SECURE_INVALID_CA;
273             else if ((chain->TrustStatus.dwErrorStatus &
274                       CERT_TRUST_IS_OFFLINE_REVOCATION) ||
275                      (chain->TrustStatus.dwErrorStatus &
276                       CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
277                 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
278             else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
279                 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
280             else if (chain->TrustStatus.dwErrorStatus &
281                 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
282                 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
283             else
284                 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
285             set_last_error( err );
286             ret = FALSE;
287         }
288         else
289         {
290             CERT_CHAIN_POLICY_PARA policyPara;
291             SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
292             CERT_CHAIN_POLICY_STATUS policyStatus;
293
294             sslExtraPolicyPara.cbSize = sizeof(sslExtraPolicyPara);
295             sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
296             sslExtraPolicyPara.pwszServerName = server;
297             policyPara.cbSize = sizeof(policyPara);
298             policyPara.dwFlags = 0;
299             policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
300             ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
301                                                     chain, &policyPara,
302                                                     &policyStatus );
303             /* Any error in the policy status indicates that the
304              * policy couldn't be verified.
305              */
306             if (ret && policyStatus.dwError)
307             {
308                 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
309                     err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
310                 else
311                     err = ERROR_WINHTTP_SECURE_INVALID_CERT;
312                 set_last_error( err );
313                 ret = FALSE;
314             }
315         }
316         CertFreeCertificateChain( chain );
317     }
318     TRACE("returning %d\n", ret);
319     return ret;
320 }
321
322 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
323 {
324     SSL *ssl;
325     WCHAR *server;
326     BOOL ret = FALSE;
327
328     ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
329     server = pSSL_get_ex_data( ssl, hostname_idx );
330     if (preverify_ok)
331     {
332         HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
333          CERT_STORE_CREATE_NEW_FLAG, NULL );
334
335         if (store)
336         {
337             X509 *cert;
338             int i;
339             PCCERT_CONTEXT endCert = NULL;
340
341             ret = TRUE;
342             for (i = 0; ret && i < ctx->chain->num; i++)
343             {
344                 PCCERT_CONTEXT context;
345
346                 cert = (X509 *)ctx->chain->data[i];
347                 if ((context = X509_to_cert_context( cert )))
348                 {
349                     if (i == 0)
350                         ret = CertAddCertificateContextToStore( store, context,
351                             CERT_STORE_ADD_ALWAYS, &endCert );
352                     else
353                         ret = CertAddCertificateContextToStore( store, context,
354                             CERT_STORE_ADD_ALWAYS, NULL );
355                     CertFreeCertificateContext( context );
356                 }
357             }
358             if (ret)
359                 ret = netconn_verify_cert( endCert, store, server );
360             CertFreeCertificateContext( endCert );
361             CertCloseStore( store, 0 );
362         }
363     }
364     return ret;
365 }
366 #endif
367
368 BOOL netconn_init( netconn_t *conn, BOOL secure )
369 {
370 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
371     int i;
372 #endif
373
374     conn->socket = -1;
375     if (!secure) return TRUE;
376
377 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
378     EnterCriticalSection( &init_ssl_cs );
379     if (libssl_handle)
380     {
381         LeaveCriticalSection( &init_ssl_cs );
382         return TRUE;
383     }
384     if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
385     {
386         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
387         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
388         LeaveCriticalSection( &init_ssl_cs );
389         return FALSE;
390     }
391     if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
392     {
393         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
394         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
395         LeaveCriticalSection( &init_ssl_cs );
396         return FALSE;
397     }
398 #define LOAD_FUNCPTR(x) \
399     if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
400     { \
401         ERR("Failed to load symbol %s\n", #x); \
402         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
403         LeaveCriticalSection( &init_ssl_cs ); \
404         return FALSE; \
405     }
406     LOAD_FUNCPTR( SSL_library_init );
407     LOAD_FUNCPTR( SSL_load_error_strings );
408     LOAD_FUNCPTR( SSLv23_method );
409     LOAD_FUNCPTR( SSL_CTX_free );
410     LOAD_FUNCPTR( SSL_CTX_new );
411     LOAD_FUNCPTR( SSL_new );
412     LOAD_FUNCPTR( SSL_free );
413     LOAD_FUNCPTR( SSL_set_fd );
414     LOAD_FUNCPTR( SSL_connect );
415     LOAD_FUNCPTR( SSL_shutdown );
416     LOAD_FUNCPTR( SSL_write );
417     LOAD_FUNCPTR( SSL_read );
418     LOAD_FUNCPTR( SSL_get_ex_new_index );
419     LOAD_FUNCPTR( SSL_get_ex_data );
420     LOAD_FUNCPTR( SSL_set_ex_data );
421     LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
422     LOAD_FUNCPTR( SSL_get_verify_result );
423     LOAD_FUNCPTR( SSL_get_peer_certificate );
424     LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
425     LOAD_FUNCPTR( SSL_CTX_set_verify );
426     LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
427 #undef LOAD_FUNCPTR
428
429 #define LOAD_FUNCPTR(x) \
430     if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
431     { \
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; \
436     }
437     LOAD_FUNCPTR( BIO_new_fp );
438     LOAD_FUNCPTR( CRYPTO_num_locks );
439     LOAD_FUNCPTR( CRYPTO_set_id_callback );
440     LOAD_FUNCPTR( CRYPTO_set_locking_callback );
441     LOAD_FUNCPTR( ERR_get_error );
442     LOAD_FUNCPTR( ERR_error_string );
443     LOAD_FUNCPTR( i2d_X509 );
444 #undef LOAD_FUNCPTR
445
446     pSSL_library_init();
447     pSSL_load_error_strings();
448     pBIO_new_fp( stderr, BIO_NOCLOSE );
449
450     method = pSSLv23_method();
451     ctx = pSSL_CTX_new( method );
452     if (!pSSL_CTX_set_default_verify_paths( ctx ))
453     {
454         ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
455         set_last_error( ERROR_OUTOFMEMORY );
456         LeaveCriticalSection( &init_ssl_cs );
457         return FALSE;
458     }
459     hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
460     if (hostname_idx == -1)
461     {
462         ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
463         set_last_error( ERROR_OUTOFMEMORY );
464         LeaveCriticalSection( &init_ssl_cs );
465         return FALSE;
466     }
467     pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
468
469     pCRYPTO_set_id_callback(ssl_thread_id);
470     num_ssl_locks = pCRYPTO_num_locks();
471     ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
472     if (!ssl_locks)
473     {
474         set_last_error( ERROR_OUTOFMEMORY );
475         LeaveCriticalSection( &init_ssl_cs );
476         return FALSE;
477     }
478     for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
479     pCRYPTO_set_locking_callback(ssl_lock_callback);
480
481     LeaveCriticalSection( &init_ssl_cs );
482 #else
483     WARN("SSL support not compiled in.\n");
484     set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
485     return FALSE;
486 #endif
487     return TRUE;
488 }
489
490 void netconn_unload( void )
491 {
492 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
493     if (libcrypto_handle)
494     {
495         wine_dlclose( libcrypto_handle, NULL, 0 );
496     }
497     if (libssl_handle)
498     {
499         if (ctx)
500             pSSL_CTX_free( ctx );
501         wine_dlclose( libssl_handle, NULL, 0 );
502     }
503     if (ssl_locks)
504     {
505         int i;
506         for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
507         HeapFree( GetProcessHeap(), 0, ssl_locks );
508     }
509 #endif
510 }
511
512 BOOL netconn_connected( netconn_t *conn )
513 {
514     return (conn->socket != -1);
515 }
516
517 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
518 {
519     if ((conn->socket = socket( domain, type, protocol )) == -1)
520     {
521         WARN("unable to create socket (%s)\n", strerror(errno));
522         set_last_error( sock_get_error( errno ) );
523         return FALSE;
524     }
525     return TRUE;
526 }
527
528 BOOL netconn_close( netconn_t *conn )
529 {
530     int res;
531
532 #ifdef SONAME_LIBSSL
533     if (conn->secure)
534     {
535         heap_free( conn->peek_msg_mem );
536         conn->peek_msg_mem = NULL;
537         conn->peek_msg = NULL;
538         conn->peek_len = 0;
539
540         pSSL_shutdown( conn->ssl_conn );
541         pSSL_free( conn->ssl_conn );
542
543         conn->ssl_conn = NULL;
544         conn->secure = FALSE;
545     }
546 #endif
547     res = closesocket( conn->socket );
548     conn->socket = -1;
549     if (res == -1)
550     {
551         set_last_error( sock_get_error( errno ) );
552         return FALSE;
553     }
554     return TRUE;
555 }
556
557 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
558 {
559     BOOL ret = FALSE;
560     int res = 0, state;
561
562     if (timeout > 0)
563     {
564         state = 1;
565         ioctlsocket( conn->socket, FIONBIO, &state );
566     }
567     if (connect( conn->socket, sockaddr, addr_len ) < 0)
568     {
569         res = sock_get_error( errno );
570         if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
571         {
572             struct pollfd pfd;
573
574             pfd.fd = conn->socket;
575             pfd.events = POLLOUT;
576             if (poll( &pfd, 1, timeout ) > 0)
577                 ret = TRUE;
578             else
579                 res = sock_get_error( errno );
580         }
581     }
582     else
583         ret = TRUE;
584     if (timeout > 0)
585     {
586         state = 0;
587         ioctlsocket( conn->socket, FIONBIO, &state );
588     }
589     if (!ret)
590     {
591         WARN("unable to connect to host (%d)\n", res);
592         set_last_error( res );
593     }
594     return ret;
595 }
596
597 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
598 {
599 #ifdef SONAME_LIBSSL
600     long res;
601
602     if (!(conn->ssl_conn = pSSL_new( ctx )))
603     {
604         ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
605         set_last_error( ERROR_OUTOFMEMORY );
606         goto fail;
607     }
608     if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
609     {
610         ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
611         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
612         goto fail;
613     }
614     if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
615     {
616         ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
617         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
618         goto fail;
619     }
620     if (pSSL_connect( conn->ssl_conn ) <= 0)
621     {
622         ERR("SSL_connect failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
623         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
624         goto fail;
625     }
626     if ((res = pSSL_get_verify_result( conn->ssl_conn )) != X509_V_OK)
627     {
628         /* FIXME: we should set an error and return, but we only print an error at the moment */
629         ERR("couldn't verify server certificate (%ld)\n", res);
630     }
631     TRACE("established SSL connection\n");
632     conn->secure = TRUE;
633     return TRUE;
634
635 fail:
636     if (conn->ssl_conn)
637     {
638         pSSL_shutdown( conn->ssl_conn );
639         pSSL_free( conn->ssl_conn );
640         conn->ssl_conn = NULL;
641     }
642 #endif
643     return FALSE;
644 }
645
646 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
647 {
648     if (!netconn_connected( conn )) return FALSE;
649     if (conn->secure)
650     {
651 #ifdef SONAME_LIBSSL
652         if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
653         *sent = pSSL_write( conn->ssl_conn, msg, len );
654         if (*sent < 1 && len) return FALSE;
655         return TRUE;
656 #else
657         return FALSE;
658 #endif
659     }
660     if ((*sent = send( conn->socket, msg, len, flags )) == -1)
661     {
662         set_last_error( sock_get_error( errno ) );
663         return FALSE;
664     }
665     return TRUE;
666 }
667
668 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
669 {
670     *recvd = 0;
671     if (!netconn_connected( conn )) return FALSE;
672     if (!len) return TRUE;
673
674     if (conn->secure)
675     {
676 #ifdef SONAME_LIBSSL
677         if (flags & ~(MSG_PEEK | MSG_WAITALL))
678             FIXME("SSL_read does not support the following flags: %08x\n", flags);
679
680         /* this ugly hack is all for MSG_PEEK */
681         if (flags & MSG_PEEK && !conn->peek_msg)
682         {
683             if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
684         }
685         else if (flags & MSG_PEEK && conn->peek_msg)
686         {
687             if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
688             *recvd = min( len, conn->peek_len );
689             memcpy( buf, conn->peek_msg, *recvd );
690             return TRUE;
691         }
692         else if (conn->peek_msg)
693         {
694             *recvd = min( len, conn->peek_len );
695             memcpy( buf, conn->peek_msg, *recvd );
696             conn->peek_len -= *recvd;
697             conn->peek_msg += *recvd;
698
699             if (conn->peek_len == 0)
700             {
701                 heap_free( conn->peek_msg_mem );
702                 conn->peek_msg_mem = NULL;
703                 conn->peek_msg = NULL;
704             }
705             /* check if we have enough data from the peek buffer */
706             if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
707         }
708         *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
709         if (flags & MSG_PEEK) /* must copy into buffer */
710         {
711             conn->peek_len = *recvd;
712             if (!*recvd)
713             {
714                 heap_free( conn->peek_msg_mem );
715                 conn->peek_msg_mem = NULL;
716                 conn->peek_msg = NULL;
717             }
718             else memcpy( conn->peek_msg, buf, *recvd );
719         }
720         if (*recvd < 1 && len) return FALSE;
721         return TRUE;
722 #else
723         return FALSE;
724 #endif
725     }
726     if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
727     {
728         set_last_error( sock_get_error( errno ) );
729         return FALSE;
730     }
731     return TRUE;
732 }
733
734 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
735 {
736 #ifdef FIONREAD
737     int ret, unread;
738 #endif
739     *available = 0;
740     if (!netconn_connected( conn )) return FALSE;
741
742     if (conn->secure)
743     {
744 #ifdef SONAME_LIBSSL
745         if (conn->peek_msg) *available = conn->peek_len;
746 #endif
747         return TRUE;
748     }
749 #ifdef FIONREAD
750     if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
751 #endif
752     return TRUE;
753 }
754
755 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
756 {
757     struct pollfd pfd;
758     BOOL ret = FALSE;
759     DWORD recvd = 0;
760
761     if (!netconn_connected( conn )) return FALSE;
762
763     if (conn->secure)
764     {
765 #ifdef SONAME_LIBSSL
766         while (recvd < *buflen)
767         {
768             int dummy;
769             if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
770             {
771                 set_last_error( ERROR_CONNECTION_ABORTED );
772                 break;
773             }
774             if (buffer[recvd] == '\n')
775             {
776                 ret = TRUE;
777                 break;
778             }
779             if (buffer[recvd] != '\r') recvd++;
780         }
781         if (ret)
782         {
783             buffer[recvd++] = 0;
784             *buflen = recvd;
785             TRACE("received line %s\n", debugstr_a(buffer));
786         }
787         return ret;
788 #else
789         return FALSE;
790 #endif
791     }
792
793     pfd.fd = conn->socket;
794     pfd.events = POLLIN;
795     while (recvd < *buflen)
796     {
797         int timeout, res;
798         struct timeval tv;
799         socklen_t len = sizeof(tv);
800
801         if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
802             timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
803         else
804             timeout = -1;
805         if (poll( &pfd, 1, timeout ) > 0)
806         {
807             if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
808             {
809                 if (res == -1) set_last_error( sock_get_error( errno ) );
810                 break;
811             }
812             if (buffer[recvd] == '\n')
813             {
814                 ret = TRUE;
815                 break;
816             }
817             if (buffer[recvd] != '\r') recvd++;
818         }
819         else
820         {
821             set_last_error( ERROR_WINHTTP_TIMEOUT );
822             break;
823         }
824     }
825     if (ret)
826     {
827         buffer[recvd++] = 0;
828         *buflen = recvd;
829         TRACE("received line %s\n", debugstr_a(buffer));
830     }
831     return ret;
832 }
833
834 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
835 {
836     int res;
837     struct timeval tv;
838
839     /* value is in milliseconds, convert to struct timeval */
840     tv.tv_sec = value / 1000;
841     tv.tv_usec = (value % 1000) * 1000;
842
843     if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
844     {
845         WARN("setsockopt failed (%s)\n", strerror( errno ));
846         return sock_get_error( errno );
847     }
848     return ERROR_SUCCESS;
849 }
850
851 BOOL netconn_resolve( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
852 {
853     char *hostname;
854 #ifdef HAVE_GETADDRINFO
855     struct addrinfo *res, hints;
856     int ret;
857 #else
858     struct hostent *he;
859     struct sockaddr_in *sin = (struct sockaddr_in *)sa;
860 #endif
861
862     if (!(hostname = strdupWA( hostnameW ))) return FALSE;
863
864 #ifdef HAVE_GETADDRINFO
865     memset( &hints, 0, sizeof(struct addrinfo) );
866     /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
867      * their IPv6 addresses even though they have IPv6 addresses in the DNS.
868      */
869     hints.ai_family = AF_INET;
870
871     ret = getaddrinfo( hostname, NULL, &hints, &res );
872     if (ret != 0)
873     {
874         TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
875         hints.ai_family = AF_INET6;
876         ret = getaddrinfo( hostname, NULL, &hints, &res );
877         if (ret != 0)
878         {
879             TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
880             heap_free( hostname );
881             return FALSE;
882         }
883     }
884     heap_free( hostname );
885     if (*sa_len < res->ai_addrlen)
886     {
887         WARN("address too small\n");
888         freeaddrinfo( res );
889         return FALSE;
890     }
891     *sa_len = res->ai_addrlen;
892     memcpy( sa, res->ai_addr, res->ai_addrlen );
893     /* Copy port */
894     switch (res->ai_family)
895     {
896     case AF_INET:
897         ((struct sockaddr_in *)sa)->sin_port = htons( port );
898         break;
899     case AF_INET6:
900         ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
901         break;
902     }
903
904     freeaddrinfo( res );
905     return TRUE;
906 #else
907     EnterCriticalSection( &cs_gethostbyname );
908
909     he = gethostbyname( hostname );
910     heap_free( hostname );
911     if (!he)
912     {
913         TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
914         LeaveCriticalSection( &cs_gethostbyname );
915         return FALSE;
916     }
917     if (*sa_len < sizeof(struct sockaddr_in))
918     {
919         WARN("address too small\n");
920         LeaveCriticalSection( &cs_gethostbyname );
921         return FALSE;
922     }
923     *sa_len = sizeof(struct sockaddr_in);
924     memset( sa, 0, sizeof(struct sockaddr_in) );
925     memcpy( &sin->sin_addr, he->h_addr, he->h_length );
926     sin->sin_family = he->h_addrtype;
927     sin->sin_port = htons( port );
928
929     LeaveCriticalSection( &cs_gethostbyname );
930     return TRUE;
931 #endif
932 }
933
934 const void *netconn_get_certificate( netconn_t *conn )
935 {
936 #ifdef SONAME_LIBSSL
937     X509 *cert;
938     const CERT_CONTEXT *ret;
939
940     if (!conn->secure) return NULL;
941
942     if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
943     ret = X509_to_cert_context( cert );
944     return ret;
945 #else
946     return NULL;
947 #endif
948 }