shlwapi: Beginning implementation of IUnknown_QueryServiceForWebBrowserApp.
[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
98 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
99
100 MAKE_FUNCPTR( SSL_library_init );
101 MAKE_FUNCPTR( SSL_load_error_strings );
102 MAKE_FUNCPTR( SSLv23_method );
103 MAKE_FUNCPTR( SSL_CTX_free );
104 MAKE_FUNCPTR( SSL_CTX_new );
105 MAKE_FUNCPTR( SSL_new );
106 MAKE_FUNCPTR( SSL_free );
107 MAKE_FUNCPTR( SSL_set_fd );
108 MAKE_FUNCPTR( SSL_connect );
109 MAKE_FUNCPTR( SSL_shutdown );
110 MAKE_FUNCPTR( SSL_write );
111 MAKE_FUNCPTR( SSL_read );
112 MAKE_FUNCPTR( SSL_get_ex_new_index );
113 MAKE_FUNCPTR( SSL_get_ex_data );
114 MAKE_FUNCPTR( SSL_set_ex_data );
115 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
116 MAKE_FUNCPTR( SSL_get_verify_result );
117 MAKE_FUNCPTR( SSL_get_peer_certificate );
118 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
119 MAKE_FUNCPTR( SSL_CTX_set_verify );
120
121 MAKE_FUNCPTR( BIO_new_fp );
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 BOOL 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;
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             set_last_error( err );
291             ret = FALSE;
292         }
293         else
294         {
295             CERT_CHAIN_POLICY_PARA policyPara;
296             SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
297             CERT_CHAIN_POLICY_STATUS policyStatus;
298
299             sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
300             sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
301             sslExtraPolicyPara.pwszServerName = server;
302             policyPara.cbSize = sizeof(policyPara);
303             policyPara.dwFlags = 0;
304             policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
305             ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
306                                                     chain, &policyPara,
307                                                     &policyStatus );
308             /* Any error in the policy status indicates that the
309              * policy couldn't be verified.
310              */
311             if (ret && policyStatus.dwError)
312             {
313                 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
314                     err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
315                 else
316                     err = ERROR_WINHTTP_SECURE_INVALID_CERT;
317                 set_last_error( err );
318                 ret = FALSE;
319             }
320         }
321         CertFreeCertificateChain( chain );
322     }
323     TRACE("returning %d\n", ret);
324     return ret;
325 }
326
327 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
328 {
329     SSL *ssl;
330     WCHAR *server;
331     BOOL ret = FALSE;
332
333     ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
334     server = pSSL_get_ex_data( ssl, hostname_idx );
335     if (preverify_ok)
336     {
337         HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
338          CERT_STORE_CREATE_NEW_FLAG, NULL );
339
340         if (store)
341         {
342             X509 *cert;
343             int i;
344             PCCERT_CONTEXT endCert = NULL;
345
346             ret = TRUE;
347             for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
348             {
349                 PCCERT_CONTEXT context;
350
351                 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
352                 if ((context = X509_to_cert_context( cert )))
353                 {
354                     if (i == 0)
355                         ret = CertAddCertificateContextToStore( store, context,
356                             CERT_STORE_ADD_ALWAYS, &endCert );
357                     else
358                         ret = CertAddCertificateContextToStore( store, context,
359                             CERT_STORE_ADD_ALWAYS, NULL );
360                     CertFreeCertificateContext( context );
361                 }
362             }
363             if (!endCert) ret = FALSE;
364             if (ret)
365                 ret = netconn_verify_cert( endCert, store, server );
366             CertFreeCertificateContext( endCert );
367             CertCloseStore( store, 0 );
368         }
369     }
370     return ret;
371 }
372 #endif
373
374 BOOL netconn_init( netconn_t *conn, BOOL secure )
375 {
376 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
377     int i;
378 #endif
379
380     conn->socket = -1;
381     if (!secure) return TRUE;
382
383 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
384     EnterCriticalSection( &init_ssl_cs );
385     if (libssl_handle)
386     {
387         LeaveCriticalSection( &init_ssl_cs );
388         return TRUE;
389     }
390     if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
391     {
392         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
393         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
394         LeaveCriticalSection( &init_ssl_cs );
395         return FALSE;
396     }
397     if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
398     {
399         ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
400         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
401         LeaveCriticalSection( &init_ssl_cs );
402         return FALSE;
403     }
404 #define LOAD_FUNCPTR(x) \
405     if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
406     { \
407         ERR("Failed to load symbol %s\n", #x); \
408         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
409         LeaveCriticalSection( &init_ssl_cs ); \
410         return FALSE; \
411     }
412     LOAD_FUNCPTR( SSL_library_init );
413     LOAD_FUNCPTR( SSL_load_error_strings );
414     LOAD_FUNCPTR( SSLv23_method );
415     LOAD_FUNCPTR( SSL_CTX_free );
416     LOAD_FUNCPTR( SSL_CTX_new );
417     LOAD_FUNCPTR( SSL_new );
418     LOAD_FUNCPTR( SSL_free );
419     LOAD_FUNCPTR( SSL_set_fd );
420     LOAD_FUNCPTR( SSL_connect );
421     LOAD_FUNCPTR( SSL_shutdown );
422     LOAD_FUNCPTR( SSL_write );
423     LOAD_FUNCPTR( SSL_read );
424     LOAD_FUNCPTR( SSL_get_ex_new_index );
425     LOAD_FUNCPTR( SSL_get_ex_data );
426     LOAD_FUNCPTR( SSL_set_ex_data );
427     LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
428     LOAD_FUNCPTR( SSL_get_verify_result );
429     LOAD_FUNCPTR( SSL_get_peer_certificate );
430     LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
431     LOAD_FUNCPTR( SSL_CTX_set_verify );
432 #undef LOAD_FUNCPTR
433
434 #define LOAD_FUNCPTR(x) \
435     if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
436     { \
437         ERR("Failed to load symbol %s\n", #x); \
438         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
439         LeaveCriticalSection( &init_ssl_cs ); \
440         return FALSE; \
441     }
442     LOAD_FUNCPTR( BIO_new_fp );
443     LOAD_FUNCPTR( CRYPTO_num_locks );
444     LOAD_FUNCPTR( CRYPTO_set_id_callback );
445     LOAD_FUNCPTR( CRYPTO_set_locking_callback );
446     LOAD_FUNCPTR( ERR_free_strings );
447     LOAD_FUNCPTR( ERR_get_error );
448     LOAD_FUNCPTR( ERR_error_string );
449     LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
450     LOAD_FUNCPTR( i2d_X509 );
451     LOAD_FUNCPTR( sk_value );
452     LOAD_FUNCPTR( sk_num );
453 #undef LOAD_FUNCPTR
454
455     pSSL_library_init();
456     pSSL_load_error_strings();
457     pBIO_new_fp( stderr, BIO_NOCLOSE );
458
459     method = pSSLv23_method();
460     ctx = pSSL_CTX_new( method );
461     if (!pSSL_CTX_set_default_verify_paths( ctx ))
462     {
463         ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
464         set_last_error( ERROR_OUTOFMEMORY );
465         LeaveCriticalSection( &init_ssl_cs );
466         return FALSE;
467     }
468     hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
469     if (hostname_idx == -1)
470     {
471         ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
472         set_last_error( ERROR_OUTOFMEMORY );
473         LeaveCriticalSection( &init_ssl_cs );
474         return FALSE;
475     }
476     pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
477
478     pCRYPTO_set_id_callback(ssl_thread_id);
479     num_ssl_locks = pCRYPTO_num_locks();
480     ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
481     if (!ssl_locks)
482     {
483         set_last_error( ERROR_OUTOFMEMORY );
484         LeaveCriticalSection( &init_ssl_cs );
485         return FALSE;
486     }
487     for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
488     pCRYPTO_set_locking_callback(ssl_lock_callback);
489
490     LeaveCriticalSection( &init_ssl_cs );
491 #else
492     WARN("SSL support not compiled in.\n");
493     set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
494     return FALSE;
495 #endif
496     return TRUE;
497 }
498
499 void netconn_unload( void )
500 {
501 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
502     if (libcrypto_handle)
503     {
504         pERR_free_strings();
505         wine_dlclose( libcrypto_handle, NULL, 0 );
506     }
507     if (libssl_handle)
508     {
509         if (ctx)
510             pSSL_CTX_free( ctx );
511         wine_dlclose( libssl_handle, NULL, 0 );
512     }
513     if (ssl_locks)
514     {
515         int i;
516         for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
517         HeapFree( GetProcessHeap(), 0, ssl_locks );
518     }
519 #endif
520 }
521
522 BOOL netconn_connected( netconn_t *conn )
523 {
524     return (conn->socket != -1);
525 }
526
527 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
528 {
529     if ((conn->socket = socket( domain, type, protocol )) == -1)
530     {
531         WARN("unable to create socket (%s)\n", strerror(errno));
532         set_last_error( sock_get_error( errno ) );
533         return FALSE;
534     }
535     return TRUE;
536 }
537
538 BOOL netconn_close( netconn_t *conn )
539 {
540     int res;
541
542 #ifdef SONAME_LIBSSL
543     if (conn->secure)
544     {
545         heap_free( conn->peek_msg_mem );
546         conn->peek_msg_mem = NULL;
547         conn->peek_msg = NULL;
548         conn->peek_len = 0;
549
550         pSSL_shutdown( conn->ssl_conn );
551         pSSL_free( conn->ssl_conn );
552
553         conn->ssl_conn = NULL;
554         conn->secure = FALSE;
555     }
556 #endif
557     res = closesocket( conn->socket );
558     conn->socket = -1;
559     if (res == -1)
560     {
561         set_last_error( sock_get_error( errno ) );
562         return FALSE;
563     }
564     return TRUE;
565 }
566
567 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
568 {
569     BOOL ret = FALSE;
570     int res = 0, state;
571
572     if (timeout > 0)
573     {
574         state = 1;
575         ioctlsocket( conn->socket, FIONBIO, &state );
576     }
577     if (connect( conn->socket, sockaddr, addr_len ) < 0)
578     {
579         res = sock_get_error( errno );
580         if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
581         {
582             struct pollfd pfd;
583
584             pfd.fd = conn->socket;
585             pfd.events = POLLOUT;
586             if (poll( &pfd, 1, timeout ) > 0)
587                 ret = TRUE;
588             else
589                 res = sock_get_error( errno );
590         }
591     }
592     else
593         ret = TRUE;
594     if (timeout > 0)
595     {
596         state = 0;
597         ioctlsocket( conn->socket, FIONBIO, &state );
598     }
599     if (!ret)
600     {
601         WARN("unable to connect to host (%d)\n", res);
602         set_last_error( res );
603     }
604     return ret;
605 }
606
607 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
608 {
609 #ifdef SONAME_LIBSSL
610     long res;
611
612     if (!(conn->ssl_conn = pSSL_new( ctx )))
613     {
614         ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
615         set_last_error( ERROR_OUTOFMEMORY );
616         goto fail;
617     }
618     if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
619     {
620         ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
621         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
622         goto fail;
623     }
624     if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
625     {
626         ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
627         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
628         goto fail;
629     }
630     if (pSSL_connect( conn->ssl_conn ) <= 0)
631     {
632         ERR("SSL_connect failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
633         set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
634         goto fail;
635     }
636     if ((res = pSSL_get_verify_result( conn->ssl_conn )) != X509_V_OK)
637     {
638         /* FIXME: we should set an error and return, but we only print an error at the moment */
639         ERR("couldn't verify server certificate (%ld)\n", res);
640     }
641     TRACE("established SSL connection\n");
642     conn->secure = TRUE;
643     return TRUE;
644
645 fail:
646     if (conn->ssl_conn)
647     {
648         pSSL_shutdown( conn->ssl_conn );
649         pSSL_free( conn->ssl_conn );
650         conn->ssl_conn = NULL;
651     }
652 #endif
653     return FALSE;
654 }
655
656 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
657 {
658     if (!netconn_connected( conn )) return FALSE;
659     if (conn->secure)
660     {
661 #ifdef SONAME_LIBSSL
662         if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
663         *sent = pSSL_write( conn->ssl_conn, msg, len );
664         if (*sent < 1 && len) return FALSE;
665         return TRUE;
666 #else
667         return FALSE;
668 #endif
669     }
670     if ((*sent = send( conn->socket, msg, len, flags )) == -1)
671     {
672         set_last_error( sock_get_error( errno ) );
673         return FALSE;
674     }
675     return TRUE;
676 }
677
678 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
679 {
680     *recvd = 0;
681     if (!netconn_connected( conn )) return FALSE;
682     if (!len) return TRUE;
683
684     if (conn->secure)
685     {
686 #ifdef SONAME_LIBSSL
687         if (flags & ~(MSG_PEEK | MSG_WAITALL))
688             FIXME("SSL_read does not support the following flags: %08x\n", flags);
689
690         /* this ugly hack is all for MSG_PEEK */
691         if (flags & MSG_PEEK && !conn->peek_msg)
692         {
693             if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
694         }
695         else if (flags & MSG_PEEK && conn->peek_msg)
696         {
697             if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
698             *recvd = min( len, conn->peek_len );
699             memcpy( buf, conn->peek_msg, *recvd );
700             return TRUE;
701         }
702         else if (conn->peek_msg)
703         {
704             *recvd = min( len, conn->peek_len );
705             memcpy( buf, conn->peek_msg, *recvd );
706             conn->peek_len -= *recvd;
707             conn->peek_msg += *recvd;
708
709             if (conn->peek_len == 0)
710             {
711                 heap_free( conn->peek_msg_mem );
712                 conn->peek_msg_mem = NULL;
713                 conn->peek_msg = NULL;
714             }
715             /* check if we have enough data from the peek buffer */
716             if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
717         }
718         *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
719         if (flags & MSG_PEEK) /* must copy into buffer */
720         {
721             conn->peek_len = *recvd;
722             if (!*recvd)
723             {
724                 heap_free( conn->peek_msg_mem );
725                 conn->peek_msg_mem = NULL;
726                 conn->peek_msg = NULL;
727             }
728             else memcpy( conn->peek_msg, buf, *recvd );
729         }
730         if (*recvd < 1 && len) return FALSE;
731         return TRUE;
732 #else
733         return FALSE;
734 #endif
735     }
736     if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
737     {
738         set_last_error( sock_get_error( errno ) );
739         return FALSE;
740     }
741     return TRUE;
742 }
743
744 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
745 {
746 #ifdef FIONREAD
747     int ret, unread;
748 #endif
749     *available = 0;
750     if (!netconn_connected( conn )) return FALSE;
751
752     if (conn->secure)
753     {
754 #ifdef SONAME_LIBSSL
755         if (conn->peek_msg) *available = conn->peek_len;
756 #endif
757         return TRUE;
758     }
759 #ifdef FIONREAD
760     if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
761 #endif
762     return TRUE;
763 }
764
765 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
766 {
767     struct pollfd pfd;
768     BOOL ret = FALSE;
769     DWORD recvd = 0;
770
771     if (!netconn_connected( conn )) return FALSE;
772
773     if (conn->secure)
774     {
775 #ifdef SONAME_LIBSSL
776         while (recvd < *buflen)
777         {
778             int dummy;
779             if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
780             {
781                 set_last_error( ERROR_CONNECTION_ABORTED );
782                 break;
783             }
784             if (buffer[recvd] == '\n')
785             {
786                 ret = TRUE;
787                 break;
788             }
789             if (buffer[recvd] != '\r') recvd++;
790         }
791         if (ret)
792         {
793             buffer[recvd++] = 0;
794             *buflen = recvd;
795             TRACE("received line %s\n", debugstr_a(buffer));
796         }
797         return ret;
798 #else
799         return FALSE;
800 #endif
801     }
802
803     pfd.fd = conn->socket;
804     pfd.events = POLLIN;
805     while (recvd < *buflen)
806     {
807         int timeout, res;
808         struct timeval tv;
809         socklen_t len = sizeof(tv);
810
811         if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
812             timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
813         else
814             timeout = -1;
815         if (poll( &pfd, 1, timeout ) > 0)
816         {
817             if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
818             {
819                 if (res == -1) set_last_error( sock_get_error( errno ) );
820                 break;
821             }
822             if (buffer[recvd] == '\n')
823             {
824                 ret = TRUE;
825                 break;
826             }
827             if (buffer[recvd] != '\r') recvd++;
828         }
829         else
830         {
831             set_last_error( ERROR_WINHTTP_TIMEOUT );
832             break;
833         }
834     }
835     if (ret)
836     {
837         buffer[recvd++] = 0;
838         *buflen = recvd;
839         TRACE("received line %s\n", debugstr_a(buffer));
840     }
841     return ret;
842 }
843
844 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
845 {
846     int res;
847     struct timeval tv;
848
849     /* value is in milliseconds, convert to struct timeval */
850     tv.tv_sec = value / 1000;
851     tv.tv_usec = (value % 1000) * 1000;
852
853     if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
854     {
855         WARN("setsockopt failed (%s)\n", strerror( errno ));
856         return sock_get_error( errno );
857     }
858     return ERROR_SUCCESS;
859 }
860
861 BOOL netconn_resolve( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
862 {
863     char *hostname;
864 #ifdef HAVE_GETADDRINFO
865     struct addrinfo *res, hints;
866     int ret;
867 #else
868     struct hostent *he;
869     struct sockaddr_in *sin = (struct sockaddr_in *)sa;
870 #endif
871
872     if (!(hostname = strdupWA( hostnameW ))) return FALSE;
873
874 #ifdef HAVE_GETADDRINFO
875     memset( &hints, 0, sizeof(struct addrinfo) );
876     /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
877      * their IPv6 addresses even though they have IPv6 addresses in the DNS.
878      */
879     hints.ai_family = AF_INET;
880
881     ret = getaddrinfo( hostname, NULL, &hints, &res );
882     if (ret != 0)
883     {
884         TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
885         hints.ai_family = AF_INET6;
886         ret = getaddrinfo( hostname, NULL, &hints, &res );
887         if (ret != 0)
888         {
889             TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
890             heap_free( hostname );
891             return FALSE;
892         }
893     }
894     heap_free( hostname );
895     if (*sa_len < res->ai_addrlen)
896     {
897         WARN("address too small\n");
898         freeaddrinfo( res );
899         return FALSE;
900     }
901     *sa_len = res->ai_addrlen;
902     memcpy( sa, res->ai_addr, res->ai_addrlen );
903     /* Copy port */
904     switch (res->ai_family)
905     {
906     case AF_INET:
907         ((struct sockaddr_in *)sa)->sin_port = htons( port );
908         break;
909     case AF_INET6:
910         ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
911         break;
912     }
913
914     freeaddrinfo( res );
915     return TRUE;
916 #else
917     EnterCriticalSection( &cs_gethostbyname );
918
919     he = gethostbyname( hostname );
920     heap_free( hostname );
921     if (!he)
922     {
923         TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
924         LeaveCriticalSection( &cs_gethostbyname );
925         return FALSE;
926     }
927     if (*sa_len < sizeof(struct sockaddr_in))
928     {
929         WARN("address too small\n");
930         LeaveCriticalSection( &cs_gethostbyname );
931         return FALSE;
932     }
933     *sa_len = sizeof(struct sockaddr_in);
934     memset( sa, 0, sizeof(struct sockaddr_in) );
935     memcpy( &sin->sin_addr, he->h_addr, he->h_length );
936     sin->sin_family = he->h_addrtype;
937     sin->sin_port = htons( port );
938
939     LeaveCriticalSection( &cs_gethostbyname );
940     return TRUE;
941 #endif
942 }
943
944 const void *netconn_get_certificate( netconn_t *conn )
945 {
946 #ifdef SONAME_LIBSSL
947     X509 *cert;
948     const CERT_CONTEXT *ret;
949
950     if (!conn->secure) return NULL;
951
952     if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
953     ret = X509_to_cert_context( cert );
954     return ret;
955 #else
956     return NULL;
957 #endif
958 }