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