xref: /reactos/dll/win32/winhttp/net.c (revision 64daf542)
1 /*
2  * Copyright 2008 Hans Leidekker for CodeWeavers
3  * Copyright 2013 Jacek Caban for CodeWeavers
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19 
20 #include "winhttp_private.h"
21 
22 #include <assert.h>
23 #include <schannel.h>
24 
25 #ifdef HAVE_SYS_SOCKET_H
26 # include <sys/socket.h>
27 #endif
28 #ifdef HAVE_SYS_IOCTL_H
29 # include <sys/ioctl.h>
30 #endif
31 #ifdef HAVE_SYS_FILIO_H
32 # include <sys/filio.h>
33 #endif
34 #ifdef HAVE_POLL_H
35 # include <poll.h>
36 #endif
37 
38 #ifndef HAVE_GETADDRINFO
39 
40 /* critical section to protect non-reentrant gethostbyname() */
41 static CRITICAL_SECTION cs_gethostbyname;
42 static CRITICAL_SECTION_DEBUG critsect_debug =
43 {
44     0, 0, &cs_gethostbyname,
45     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
46       0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
47 };
48 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
49 
50 #endif
51 
52 /* translate a unix error code into a winsock error code */
53 #ifndef __REACTOS__
54 static int sock_get_error( int err )
55 {
56 #if !defined(__MINGW32__) && !defined (_MSC_VER)
57     switch (err)
58     {
59         case EINTR:             return WSAEINTR;
60         case EBADF:             return WSAEBADF;
61         case EPERM:
62         case EACCES:            return WSAEACCES;
63         case EFAULT:            return WSAEFAULT;
64         case EINVAL:            return WSAEINVAL;
65         case EMFILE:            return WSAEMFILE;
66         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
67         case EINPROGRESS:       return WSAEINPROGRESS;
68         case EALREADY:          return WSAEALREADY;
69         case ENOTSOCK:          return WSAENOTSOCK;
70         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
71         case EMSGSIZE:          return WSAEMSGSIZE;
72         case EPROTOTYPE:        return WSAEPROTOTYPE;
73         case ENOPROTOOPT:       return WSAENOPROTOOPT;
74         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
75         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
76         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
77         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
78         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
79         case EADDRINUSE:        return WSAEADDRINUSE;
80         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
81         case ENETDOWN:          return WSAENETDOWN;
82         case ENETUNREACH:       return WSAENETUNREACH;
83         case ENETRESET:         return WSAENETRESET;
84         case ECONNABORTED:      return WSAECONNABORTED;
85         case EPIPE:
86         case ECONNRESET:        return WSAECONNRESET;
87         case ENOBUFS:           return WSAENOBUFS;
88         case EISCONN:           return WSAEISCONN;
89         case ENOTCONN:          return WSAENOTCONN;
90         case ESHUTDOWN:         return WSAESHUTDOWN;
91         case ETOOMANYREFS:      return WSAETOOMANYREFS;
92         case ETIMEDOUT:         return WSAETIMEDOUT;
93         case ECONNREFUSED:      return WSAECONNREFUSED;
94         case ELOOP:             return WSAELOOP;
95         case ENAMETOOLONG:      return WSAENAMETOOLONG;
96         case EHOSTDOWN:         return WSAEHOSTDOWN;
97         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
98         case ENOTEMPTY:         return WSAENOTEMPTY;
99 #ifdef EPROCLIM
100         case EPROCLIM:          return WSAEPROCLIM;
101 #endif
102 #ifdef EUSERS
103         case EUSERS:            return WSAEUSERS;
104 #endif
105 #ifdef EDQUOT
106         case EDQUOT:            return WSAEDQUOT;
107 #endif
108 #ifdef ESTALE
109         case ESTALE:            return WSAESTALE;
110 #endif
111 #ifdef EREMOTE
112         case EREMOTE:           return WSAEREMOTE;
113 #endif
114     default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
115     }
116 #endif
117     return err;
118 }
119 #else
120 #define sock_get_error(x) WSAGetLastError()
121 
122 static inline int unix_ioctl(int filedes, long request, void *arg)
123 {
124     return ioctlsocket(filedes, request, arg);
125 }
126 #define ioctlsocket unix_ioctl
127 #endif
128 
129 static int sock_send(int fd, const void *msg, size_t len, int flags)
130 {
131     int ret;
132     do
133     {
134         if ((ret = send(fd, msg, len, flags)) == -1) WARN("send error %s\n", strerror(errno));
135     }
136     while(ret == -1 && errno == EINTR);
137     return ret;
138 }
139 
140 static int sock_recv(int fd, void *msg, size_t len, int flags)
141 {
142     int ret;
143     do
144     {
145         if ((ret = recv(fd, msg, len, flags)) == -1) WARN("recv error %s\n", strerror(errno));
146     }
147     while(ret == -1 && errno == EINTR);
148     return ret;
149 }
150 
151 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, WCHAR *server, DWORD security_flags )
152 {
153     HCERTSTORE store = cert->hCertStore;
154     BOOL ret;
155     CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
156     PCCERT_CHAIN_CONTEXT chain;
157     char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
158     char *server_auth[] = { oid_server_auth };
159     DWORD err = ERROR_SUCCESS;
160 
161     TRACE("verifying %s\n", debugstr_w( server ));
162     chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
163     chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
164     if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara,
165                                         CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT,
166                                         NULL, &chain )))
167     {
168         if (chain->TrustStatus.dwErrorStatus)
169         {
170             static const DWORD supportedErrors =
171                 CERT_TRUST_IS_NOT_TIME_VALID |
172                 CERT_TRUST_IS_UNTRUSTED_ROOT |
173                 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
174 
175             if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
176             {
177                 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
178                     err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
179             }
180             else if (chain->TrustStatus.dwErrorStatus &
181                      CERT_TRUST_IS_UNTRUSTED_ROOT)
182             {
183                 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
184                     err = ERROR_WINHTTP_SECURE_INVALID_CA;
185             }
186             else if ((chain->TrustStatus.dwErrorStatus &
187                       CERT_TRUST_IS_OFFLINE_REVOCATION) ||
188                      (chain->TrustStatus.dwErrorStatus &
189                       CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
190                 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
191             else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
192                 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
193             else if (chain->TrustStatus.dwErrorStatus &
194                 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
195             {
196                 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
197                     err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
198             }
199             else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
200                 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
201         }
202         if (!err)
203         {
204             CERT_CHAIN_POLICY_PARA policyPara;
205             SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
206             CERT_CHAIN_POLICY_STATUS policyStatus;
207             CERT_CHAIN_CONTEXT chainCopy;
208 
209             /* Clear chain->TrustStatus.dwErrorStatus so
210              * CertVerifyCertificateChainPolicy will verify additional checks
211              * rather than stopping with an existing, ignored error.
212              */
213             memcpy(&chainCopy, chain, sizeof(chainCopy));
214             chainCopy.TrustStatus.dwErrorStatus = 0;
215             sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
216             sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
217             sslExtraPolicyPara.pwszServerName = server;
218             sslExtraPolicyPara.fdwChecks = security_flags;
219             policyPara.cbSize = sizeof(policyPara);
220             policyPara.dwFlags = 0;
221             policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
222             ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
223                                                     &chainCopy, &policyPara,
224                                                     &policyStatus );
225             /* Any error in the policy status indicates that the
226              * policy couldn't be verified.
227              */
228             if (ret && policyStatus.dwError)
229             {
230                 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
231                     err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
232                 else
233                     err = ERROR_WINHTTP_SECURE_INVALID_CERT;
234             }
235         }
236         CertFreeCertificateChain( chain );
237     }
238     else
239         err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
240     TRACE("returning %08x\n", err);
241     return err;
242 }
243 
244 #ifdef __REACTOS__
245 static BOOL winsock_initialized = FALSE;
246 BOOL netconn_init_winsock()
247 {
248     WSADATA wsaData;
249     int error;
250     if (!winsock_initialized)
251     {
252         error = WSAStartup(MAKEWORD(1, 1), &wsaData);
253         if (error)
254         {
255             ERR("WSAStartup failed: %d\n", error);
256             return FALSE;
257         }
258         else
259             winsock_initialized = TRUE;
260     }
261     return winsock_initialized;
262 }
263 
264 #endif
265 
266 void netconn_unload( void )
267 {
268 #ifndef HAVE_GETADDRINFO
269     DeleteCriticalSection(&cs_gethostbyname);
270 #endif
271 #ifdef __REACTOS__
272     if(winsock_initialized)
273         WSACleanup();
274 #endif
275 }
276 
277 netconn_t *netconn_create( hostdata_t *host, const struct sockaddr_storage *sockaddr, int timeout )
278 {
279     netconn_t *conn;
280     unsigned int addr_len;
281     BOOL ret = FALSE;
282     int res;
283     ULONG state;
284 
285     conn = heap_alloc_zero(sizeof(*conn));
286     if (!conn) return NULL;
287     conn->host = host;
288     conn->sockaddr = *sockaddr;
289     if ((conn->socket = socket( sockaddr->ss_family, SOCK_STREAM, 0 )) == -1)
290     {
291         WARN("unable to create socket (%s)\n", strerror(errno));
292         set_last_error( sock_get_error( errno ) );
293         heap_free(conn);
294         return NULL;
295     }
296 
297     switch (conn->sockaddr.ss_family)
298     {
299     case AF_INET:
300         addr_len = sizeof(struct sockaddr_in);
301         break;
302     case AF_INET6:
303         addr_len = sizeof(struct sockaddr_in6);
304         break;
305     default:
306         assert(0);
307     }
308 
309     if (timeout > 0)
310     {
311         state = 1;
312         ioctlsocket( conn->socket, FIONBIO, &state );
313     }
314 
315     for (;;)
316     {
317         res = 0;
318         if (connect( conn->socket, (const struct sockaddr *)&conn->sockaddr, addr_len ) < 0)
319         {
320             res = sock_get_error( errno );
321             if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
322             {
323 #ifdef __REACTOS__
324                 /* ReactOS: use select instead of poll */
325                 fd_set outfd;
326                 struct timeval tv;
327 
328                 FD_ZERO(&outfd);
329                 FD_SET(conn->socket, &outfd);
330 
331                 tv.tv_sec = 0;
332                 tv.tv_usec = timeout * 1000;
333                 for (;;)
334                 {
335                     res = 0;
336 
337                     if (select( 0, NULL, &outfd, NULL, &tv ) > 0)
338 #else
339                 struct pollfd pfd;
340 
341                 pfd.fd = conn->socket;
342                 pfd.events = POLLOUT;
343                 for (;;)
344                 {
345                     res = 0;
346                     if (poll( &pfd, 1, timeout ) > 0)
347 #endif
348                     {
349                         ret = TRUE;
350                         break;
351                     }
352                     else
353                     {
354                         res = sock_get_error( errno );
355                         if (res != WSAEINTR) break;
356                     }
357                 }
358             }
359             if (res != WSAEINTR) break;
360         }
361         else
362         {
363             ret = TRUE;
364             break;
365         }
366     }
367     if (timeout > 0)
368     {
369         state = 0;
370         ioctlsocket( conn->socket, FIONBIO, &state );
371     }
372     if (!ret)
373     {
374         WARN("unable to connect to host (%d)\n", res);
375         set_last_error( res );
376         netconn_close( conn );
377         return NULL;
378     }
379     return conn;
380 }
381 
382 BOOL netconn_close( netconn_t *conn )
383 {
384     int res;
385 
386     if (conn->secure)
387     {
388         heap_free( conn->peek_msg_mem );
389         heap_free(conn->ssl_buf);
390         heap_free(conn->extra_buf);
391         DeleteSecurityContext(&conn->ssl_ctx);
392     }
393     res = closesocket( conn->socket );
394     release_host( conn->host );
395     heap_free(conn);
396     if (res == -1)
397     {
398         set_last_error( sock_get_error( errno ) );
399         return FALSE;
400     }
401     return TRUE;
402 }
403 
404 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname, DWORD security_flags, CredHandle *cred_handle )
405 {
406     SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
407     SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
408     BYTE *read_buf;
409     SIZE_T read_buf_size = 2048;
410     ULONG attrs = 0;
411     CtxtHandle ctx;
412     SSIZE_T size;
413     const CERT_CONTEXT *cert;
414     SECURITY_STATUS status;
415     DWORD res = ERROR_SUCCESS;
416 
417     const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
418         |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
419 
420     read_buf = heap_alloc(read_buf_size);
421     if(!read_buf)
422         return FALSE;
423 
424     status = InitializeSecurityContextW(cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
425             &ctx, &out_desc, &attrs, NULL);
426 
427     assert(status != SEC_E_OK);
428 
429     while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
430         if(out_buf.cbBuffer) {
431             assert(status == SEC_I_CONTINUE_NEEDED);
432 
433             TRACE("sending %u bytes\n", out_buf.cbBuffer);
434 
435             size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
436             if(size != out_buf.cbBuffer) {
437                 ERR("send failed\n");
438                 res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
439                 break;
440             }
441 
442             FreeContextBuffer(out_buf.pvBuffer);
443             out_buf.pvBuffer = NULL;
444             out_buf.cbBuffer = 0;
445         }
446 
447         if(status == SEC_I_CONTINUE_NEEDED) {
448             assert(in_bufs[1].cbBuffer < read_buf_size);
449 
450             memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
451             in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
452 
453             in_bufs[1].BufferType = SECBUFFER_EMPTY;
454             in_bufs[1].cbBuffer = 0;
455             in_bufs[1].pvBuffer = NULL;
456         }
457 
458         assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
459         assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
460 
461         if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
462             BYTE *new_read_buf;
463 
464             new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
465             if(!new_read_buf) {
466                 status = E_OUTOFMEMORY;
467                 break;
468             }
469 
470             in_bufs[0].pvBuffer = read_buf = new_read_buf;
471             read_buf_size += 1024;
472         }
473 
474         size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
475         if(size < 1) {
476             status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
477             break;
478         }
479 
480         TRACE("recv %lu bytes\n", size);
481 
482         in_bufs[0].cbBuffer += size;
483         in_bufs[0].pvBuffer = read_buf;
484         status = InitializeSecurityContextW(cred_handle, &ctx, hostname,  isc_req_flags, 0, 0, &in_desc,
485                 0, NULL, &out_desc, &attrs, NULL);
486         TRACE("InitializeSecurityContext ret %08x\n", status);
487 
488         if(status == SEC_E_OK) {
489             if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
490                 FIXME("SECBUFFER_EXTRA not supported\n");
491 
492             status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
493             if(status != SEC_E_OK) {
494                 WARN("Could not get sizes\n");
495                 break;
496             }
497 
498             status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
499             if(status == SEC_E_OK) {
500                 res = netconn_verify_cert(cert, hostname, security_flags);
501                 CertFreeCertificateContext(cert);
502                 if(res != ERROR_SUCCESS) {
503                     WARN("cert verify failed: %u\n", res);
504                     break;
505                 }
506             }else {
507                 WARN("Could not get cert\n");
508                 break;
509             }
510 
511             conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
512             if(!conn->ssl_buf) {
513                 res = GetLastError();
514                 break;
515             }
516         }
517     }
518 
519     heap_free(read_buf);
520 
521     if(status != SEC_E_OK || res != ERROR_SUCCESS) {
522         WARN("Failed to initialize security context failed: %08x\n", status);
523         heap_free(conn->ssl_buf);
524         conn->ssl_buf = NULL;
525         DeleteSecurityContext(&ctx);
526         set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR);
527         return FALSE;
528     }
529 
530 
531     TRACE("established SSL connection\n");
532     conn->secure = TRUE;
533     conn->ssl_ctx = ctx;
534     return TRUE;
535 }
536 
537 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
538 {
539     SecBuffer bufs[4] = {
540         {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
541         {size,  SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
542         {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
543         {0, SECBUFFER_EMPTY, NULL}
544     };
545     SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
546     SECURITY_STATUS res;
547 
548     memcpy(bufs[1].pvBuffer, msg, size);
549     res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
550     if(res != SEC_E_OK) {
551         WARN("EncryptMessage failed\n");
552         return FALSE;
553     }
554 
555     if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
556         WARN("send failed\n");
557         return FALSE;
558     }
559 
560     return TRUE;
561 }
562 
563 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int *sent )
564 {
565     if (conn->secure)
566     {
567         const BYTE *ptr = msg;
568         size_t chunk_size;
569 
570         *sent = 0;
571 
572         while(len) {
573             chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
574             if(!send_ssl_chunk(conn, ptr, chunk_size))
575                 return FALSE;
576 
577             *sent += chunk_size;
578             ptr += chunk_size;
579             len -= chunk_size;
580         }
581 
582         return TRUE;
583     }
584     if ((*sent = sock_send( conn->socket, msg, len, 0 )) == -1)
585     {
586         set_last_error( sock_get_error( errno ) );
587         return FALSE;
588     }
589     return TRUE;
590 }
591 
592 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
593 {
594     const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
595     SecBuffer bufs[4];
596     SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
597     SSIZE_T size, buf_len;
598     unsigned int i;
599     SECURITY_STATUS res;
600 
601     assert(conn->extra_len < ssl_buf_size);
602 
603     if(conn->extra_len) {
604         memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
605         buf_len = conn->extra_len;
606         conn->extra_len = 0;
607         heap_free(conn->extra_buf);
608         conn->extra_buf = NULL;
609     }else {
610         buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
611         if(buf_len < 0)
612             return FALSE;
613 
614         if(!buf_len) {
615             *eof = TRUE;
616             return TRUE;
617         }
618     }
619 
620     *ret_size = 0;
621     *eof = FALSE;
622 
623     do {
624         memset(bufs, 0, sizeof(bufs));
625         bufs[0].BufferType = SECBUFFER_DATA;
626         bufs[0].cbBuffer = buf_len;
627         bufs[0].pvBuffer = conn->ssl_buf;
628 
629         res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
630         switch(res) {
631         case SEC_E_OK:
632             break;
633         case SEC_I_CONTEXT_EXPIRED:
634             TRACE("context expired\n");
635             *eof = TRUE;
636             return TRUE;
637         case SEC_E_INCOMPLETE_MESSAGE:
638             assert(buf_len < ssl_buf_size);
639 
640             size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
641             if(size < 1)
642                 return FALSE;
643 
644             buf_len += size;
645             continue;
646         default:
647             WARN("failed: %08x\n", res);
648             return FALSE;
649         }
650     } while(res != SEC_E_OK);
651 
652     for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
653         if(bufs[i].BufferType == SECBUFFER_DATA) {
654             size = min(buf_size, bufs[i].cbBuffer);
655             memcpy(buf, bufs[i].pvBuffer, size);
656             if(size < bufs[i].cbBuffer) {
657                 assert(!conn->peek_len);
658                 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
659                 if(!conn->peek_msg)
660                     return FALSE;
661                 conn->peek_len = bufs[i].cbBuffer-size;
662                 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
663             }
664 
665             *ret_size = size;
666         }
667     }
668 
669     for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
670         if(bufs[i].BufferType == SECBUFFER_EXTRA) {
671             conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
672             if(!conn->extra_buf)
673                 return FALSE;
674 
675             conn->extra_len = bufs[i].cbBuffer;
676             memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
677         }
678     }
679 
680     return TRUE;
681 }
682 
683 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
684 {
685     *recvd = 0;
686     if (!len) return TRUE;
687 
688     if (conn->secure)
689     {
690         SIZE_T size, cread;
691         BOOL res, eof;
692 
693         if (conn->peek_msg)
694         {
695             *recvd = min( len, conn->peek_len );
696             memcpy( buf, conn->peek_msg, *recvd );
697             conn->peek_len -= *recvd;
698             conn->peek_msg += *recvd;
699 
700             if (conn->peek_len == 0)
701             {
702                 heap_free( conn->peek_msg_mem );
703                 conn->peek_msg_mem = NULL;
704                 conn->peek_msg = NULL;
705             }
706             /* check if we have enough data from the peek buffer */
707             if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
708         }
709         size = *recvd;
710 
711         do {
712             res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
713             if(!res) {
714                 WARN("read_ssl_chunk failed\n");
715                 if(!size)
716                     return FALSE;
717                 break;
718             }
719 
720             if(eof) {
721                 TRACE("EOF\n");
722                 break;
723             }
724 
725             size += cread;
726         }while(!size || ((flags & MSG_WAITALL) && size < len));
727 
728         TRACE("received %ld bytes\n", size);
729         *recvd = size;
730         return TRUE;
731     }
732     if ((*recvd = sock_recv( conn->socket, buf, len, flags )) == -1)
733     {
734         set_last_error( sock_get_error( errno ) );
735         return FALSE;
736     }
737     return TRUE;
738 }
739 
740 ULONG netconn_query_data_available( netconn_t *conn )
741 {
742     return conn->secure ? conn->peek_len : 0;
743 }
744 
745 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
746 {
747     struct timeval tv;
748 
749     /* value is in milliseconds, convert to struct timeval */
750     tv.tv_sec = value / 1000;
751     tv.tv_usec = (value % 1000) * 1000;
752 
753     if (setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1)
754     {
755         WARN("setsockopt failed (%s)\n", strerror( errno ));
756         return sock_get_error( errno );
757     }
758     return ERROR_SUCCESS;
759 }
760 
761 BOOL netconn_is_alive( netconn_t *netconn )
762 {
763 #ifdef MSG_DONTWAIT
764     ssize_t len;
765     BYTE b;
766 
767     len = recv( netconn->socket, &b, 1, MSG_PEEK | MSG_DONTWAIT );
768     return len == 1 || (len == -1 && errno == EWOULDBLOCK);
769 #elif defined(__MINGW32__) || defined(_MSC_VER)
770     ULONG mode;
771     int len;
772     char b;
773 
774     mode = 1;
775     if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
776         return FALSE;
777 
778     len = recv(netconn->socket, &b, 1, MSG_PEEK);
779 
780     mode = 0;
781     if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
782         return FALSE;
783 
784     return len == 1 || (len == -1 && WSAGetLastError() == WSAEWOULDBLOCK);
785 #else
786     FIXME("not supported on this platform\n");
787     return TRUE;
788 #endif
789 }
790 
791 static DWORD resolve_hostname( const WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr_storage *sa )
792 {
793     char *hostname;
794 #ifdef HAVE_GETADDRINFO
795     struct addrinfo *res, hints;
796     int ret;
797 #else
798     struct hostent *he;
799     struct sockaddr_in *sin = (struct sockaddr_in *)sa;
800 #endif
801 
802     if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
803 
804 #ifdef HAVE_GETADDRINFO
805     memset( &hints, 0, sizeof(struct addrinfo) );
806     /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
807      * their IPv6 addresses even though they have IPv6 addresses in the DNS.
808      */
809     hints.ai_family = AF_INET;
810 
811     ret = getaddrinfo( hostname, NULL, &hints, &res );
812     if (ret != 0)
813     {
814         TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
815         hints.ai_family = AF_INET6;
816         ret = getaddrinfo( hostname, NULL, &hints, &res );
817         if (ret != 0)
818         {
819             TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
820             heap_free( hostname );
821             return ERROR_WINHTTP_NAME_NOT_RESOLVED;
822         }
823     }
824     heap_free( hostname );
825     memcpy( sa, res->ai_addr, res->ai_addrlen );
826     /* Copy port */
827     switch (res->ai_family)
828     {
829     case AF_INET:
830         ((struct sockaddr_in *)sa)->sin_port = htons( port );
831         break;
832     case AF_INET6:
833         ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
834         break;
835     }
836 
837     freeaddrinfo( res );
838     return ERROR_SUCCESS;
839 #else
840     EnterCriticalSection( &cs_gethostbyname );
841 
842     he = gethostbyname( hostname );
843     heap_free( hostname );
844     if (!he)
845     {
846         TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
847         LeaveCriticalSection( &cs_gethostbyname );
848         return ERROR_WINHTTP_NAME_NOT_RESOLVED;
849     }
850     memset( sa, 0, sizeof(struct sockaddr_in) );
851     memcpy( &sin->sin_addr, he->h_addr, he->h_length );
852     sin->sin_family = he->h_addrtype;
853     sin->sin_port = htons( port );
854 
855     LeaveCriticalSection( &cs_gethostbyname );
856     return ERROR_SUCCESS;
857 #endif
858 }
859 
860 struct resolve_args
861 {
862     const WCHAR             *hostname;
863     INTERNET_PORT            port;
864     struct sockaddr_storage *sa;
865 };
866 
867 static DWORD CALLBACK resolve_proc( LPVOID arg )
868 {
869     struct resolve_args *ra = arg;
870     return resolve_hostname( ra->hostname, ra->port, ra->sa );
871 }
872 
873 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr_storage *sa, int timeout )
874 {
875     DWORD ret;
876 
877     if (timeout)
878     {
879         DWORD status;
880         HANDLE thread;
881         struct resolve_args ra;
882 
883         ra.hostname = hostname;
884         ra.port     = port;
885         ra.sa       = sa;
886 
887         thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
888         if (!thread) return FALSE;
889 
890         status = WaitForSingleObject( thread, timeout );
891         if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
892         else ret = ERROR_WINHTTP_TIMEOUT;
893         CloseHandle( thread );
894     }
895     else ret = resolve_hostname( hostname, port, sa );
896 
897     if (ret)
898     {
899         set_last_error( ret );
900         return FALSE;
901     }
902     return TRUE;
903 }
904 
905 const void *netconn_get_certificate( netconn_t *conn )
906 {
907     const CERT_CONTEXT *ret;
908     SECURITY_STATUS res;
909 
910     if (!conn->secure) return NULL;
911     res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
912     return res == SEC_E_OK ? ret : NULL;
913 }
914 
915 int netconn_get_cipher_strength( netconn_t *conn )
916 {
917     SecPkgContext_ConnectionInfo conn_info;
918     SECURITY_STATUS res;
919 
920     if (!conn->secure) return 0;
921     res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
922     if(res != SEC_E_OK)
923         WARN("QueryContextAttributesW failed: %08x\n", res);
924     return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
925 }
926