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