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