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