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