uxtheme/tests: Remove some trace messages.
[wine.git] / dlls / winhttp / net.c
blobd0d02d535eab3c163da04504bfea370363472728
1 /*
2 * Copyright 2008 Hans Leidekker for CodeWeavers
3 * Copyright 2013 Jacek Caban for CodeWeavers
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.
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.
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
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
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
42 #define NONAMELESSUNION
44 #include "wine/debug.h"
45 #include "wine/library.h"
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winhttp.h"
50 #include "wincrypt.h"
51 #include "schannel.h"
53 #include "winhttp_private.h"
55 /* to avoid conflicts with the Unix socket headers */
56 #define USE_WS_PREFIX
57 #include "winsock2.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
61 #ifndef HAVE_GETADDRINFO
63 /* critical section to protect non-reentrant gethostbyname() */
64 static CRITICAL_SECTION cs_gethostbyname;
65 static CRITICAL_SECTION_DEBUG critsect_debug =
67 0, 0, &cs_gethostbyname,
68 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
69 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
71 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
73 #endif
75 /* translate a unix error code into a winsock error code */
76 static int sock_get_error( int err )
78 #if !defined(__MINGW32__) && !defined (_MSC_VER)
79 switch (err)
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;
138 #endif
139 return err;
142 static int sock_send(int fd, const void *msg, size_t len, int flags)
144 int ret;
147 if ((ret = send(fd, msg, len, flags)) == -1) WARN("send error %s\n", strerror(errno));
149 while(ret == -1 && errno == EINTR);
150 return ret;
153 static int sock_recv(int fd, void *msg, size_t len, int flags)
155 int ret;
158 if ((ret = recv(fd, msg, len, flags)) == -1) WARN("recv error %s\n", strerror(errno));
160 while(ret == -1 && errno == EINTR);
161 return ret;
164 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, WCHAR *server, DWORD security_flags )
166 HCERTSTORE store = cert->hCertStore;
167 BOOL ret;
168 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
169 PCCERT_CHAIN_CONTEXT chain;
170 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
171 char *server_auth[] = { oid_server_auth };
172 DWORD err = ERROR_SUCCESS;
174 TRACE("verifying %s\n", debugstr_w( server ));
175 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
176 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
177 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara,
178 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT,
179 NULL, &chain )))
181 if (chain->TrustStatus.dwErrorStatus)
183 static const DWORD supportedErrors =
184 CERT_TRUST_IS_NOT_TIME_VALID |
185 CERT_TRUST_IS_UNTRUSTED_ROOT |
186 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
188 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
190 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
191 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
193 else if (chain->TrustStatus.dwErrorStatus &
194 CERT_TRUST_IS_UNTRUSTED_ROOT)
196 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
197 err = ERROR_WINHTTP_SECURE_INVALID_CA;
199 else if ((chain->TrustStatus.dwErrorStatus &
200 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
201 (chain->TrustStatus.dwErrorStatus &
202 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
203 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
204 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
205 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
206 else if (chain->TrustStatus.dwErrorStatus &
207 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
209 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
210 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
212 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
213 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
215 if (!err)
217 CERT_CHAIN_POLICY_PARA policyPara;
218 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
219 CERT_CHAIN_POLICY_STATUS policyStatus;
220 CERT_CHAIN_CONTEXT chainCopy;
222 /* Clear chain->TrustStatus.dwErrorStatus so
223 * CertVerifyCertificateChainPolicy will verify additional checks
224 * rather than stopping with an existing, ignored error.
226 memcpy(&chainCopy, chain, sizeof(chainCopy));
227 chainCopy.TrustStatus.dwErrorStatus = 0;
228 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
229 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
230 sslExtraPolicyPara.pwszServerName = server;
231 sslExtraPolicyPara.fdwChecks = security_flags;
232 policyPara.cbSize = sizeof(policyPara);
233 policyPara.dwFlags = 0;
234 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
235 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
236 &chainCopy, &policyPara,
237 &policyStatus );
238 /* Any error in the policy status indicates that the
239 * policy couldn't be verified.
241 if (ret && policyStatus.dwError)
243 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
244 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
245 else
246 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
249 CertFreeCertificateChain( chain );
251 else
252 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
253 TRACE("returning %08x\n", err);
254 return err;
257 void netconn_unload( void )
259 #ifndef HAVE_GETADDRINFO
260 DeleteCriticalSection(&cs_gethostbyname);
261 #endif
264 netconn_t *netconn_create( hostdata_t *host, const struct sockaddr_storage *sockaddr, int timeout )
266 netconn_t *conn;
267 unsigned int addr_len;
268 BOOL ret = FALSE;
269 int res;
270 ULONG state;
272 conn = heap_alloc_zero(sizeof(*conn));
273 if (!conn) return NULL;
274 conn->host = host;
275 conn->sockaddr = *sockaddr;
276 if ((conn->socket = socket( sockaddr->ss_family, SOCK_STREAM, 0 )) == -1)
278 WARN("unable to create socket (%s)\n", strerror(errno));
279 set_last_error( sock_get_error( errno ) );
280 heap_free(conn);
281 return NULL;
284 switch (conn->sockaddr.ss_family)
286 case AF_INET:
287 addr_len = sizeof(struct sockaddr_in);
288 break;
289 case AF_INET6:
290 addr_len = sizeof(struct sockaddr_in6);
291 break;
292 default:
293 assert(0);
296 if (timeout > 0)
298 state = 1;
299 ioctlsocket( conn->socket, FIONBIO, &state );
302 for (;;)
304 res = 0;
305 if (connect( conn->socket, (const struct sockaddr *)&conn->sockaddr, addr_len ) < 0)
307 res = sock_get_error( errno );
308 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
310 struct pollfd pfd;
312 pfd.fd = conn->socket;
313 pfd.events = POLLOUT;
314 for (;;)
316 res = 0;
317 if (poll( &pfd, 1, timeout ) > 0)
319 ret = TRUE;
320 break;
322 else
324 res = sock_get_error( errno );
325 if (res != WSAEINTR) break;
329 if (res != WSAEINTR) break;
331 else
333 ret = TRUE;
334 break;
337 if (timeout > 0)
339 state = 0;
340 ioctlsocket( conn->socket, FIONBIO, &state );
342 if (!ret)
344 WARN("unable to connect to host (%d)\n", res);
345 set_last_error( res );
346 netconn_close( conn );
347 return NULL;
349 return conn;
352 BOOL netconn_close( netconn_t *conn )
354 int res;
356 if (conn->secure)
358 heap_free( conn->peek_msg_mem );
359 heap_free(conn->ssl_buf);
360 heap_free(conn->extra_buf);
361 DeleteSecurityContext(&conn->ssl_ctx);
363 res = closesocket( conn->socket );
364 release_host( conn->host );
365 heap_free(conn);
366 if (res == -1)
368 set_last_error( sock_get_error( errno ) );
369 return FALSE;
371 return TRUE;
374 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname, DWORD security_flags, CredHandle *cred_handle )
376 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
377 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
378 BYTE *read_buf;
379 SIZE_T read_buf_size = 2048;
380 ULONG attrs = 0;
381 CtxtHandle ctx;
382 SSIZE_T size;
383 const CERT_CONTEXT *cert;
384 SECURITY_STATUS status;
385 DWORD res = ERROR_SUCCESS;
387 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
388 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
390 read_buf = heap_alloc(read_buf_size);
391 if(!read_buf)
392 return FALSE;
394 status = InitializeSecurityContextW(cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
395 &ctx, &out_desc, &attrs, NULL);
397 assert(status != SEC_E_OK);
399 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
400 if(out_buf.cbBuffer) {
401 assert(status == SEC_I_CONTINUE_NEEDED);
403 TRACE("sending %u bytes\n", out_buf.cbBuffer);
405 size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
406 if(size != out_buf.cbBuffer) {
407 ERR("send failed\n");
408 res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
409 break;
412 FreeContextBuffer(out_buf.pvBuffer);
413 out_buf.pvBuffer = NULL;
414 out_buf.cbBuffer = 0;
417 if(status == SEC_I_CONTINUE_NEEDED) {
418 assert(in_bufs[1].cbBuffer < read_buf_size);
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;
423 in_bufs[1].BufferType = SECBUFFER_EMPTY;
424 in_bufs[1].cbBuffer = 0;
425 in_bufs[1].pvBuffer = NULL;
428 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
429 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
431 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
432 BYTE *new_read_buf;
434 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
435 if(!new_read_buf) {
436 status = E_OUTOFMEMORY;
437 break;
440 in_bufs[0].pvBuffer = read_buf = new_read_buf;
441 read_buf_size += 1024;
444 size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
445 if(size < 1) {
446 status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
447 break;
450 TRACE("recv %lu bytes\n", size);
452 in_bufs[0].cbBuffer += size;
453 in_bufs[0].pvBuffer = read_buf;
454 status = InitializeSecurityContextW(cred_handle, &ctx, hostname, isc_req_flags, 0, 0, &in_desc,
455 0, NULL, &out_desc, &attrs, NULL);
456 TRACE("InitializeSecurityContext ret %08x\n", status);
458 if(status == SEC_E_OK) {
459 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
460 FIXME("SECBUFFER_EXTRA not supported\n");
462 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
463 if(status != SEC_E_OK) {
464 WARN("Could not get sizes\n");
465 break;
468 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
469 if(status == SEC_E_OK) {
470 res = netconn_verify_cert(cert, hostname, security_flags);
471 CertFreeCertificateContext(cert);
472 if(res != ERROR_SUCCESS) {
473 WARN("cert verify failed: %u\n", res);
474 break;
476 }else {
477 WARN("Could not get cert\n");
478 break;
481 conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
482 if(!conn->ssl_buf) {
483 res = GetLastError();
484 break;
489 heap_free(read_buf);
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;
501 TRACE("established SSL connection\n");
502 conn->secure = TRUE;
503 conn->ssl_ctx = ctx;
504 return TRUE;
507 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
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}
515 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
516 SECURITY_STATUS res;
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;
525 if(sock_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;
530 return TRUE;
533 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int *sent )
535 if (conn->secure)
537 const BYTE *ptr = msg;
538 size_t chunk_size;
540 *sent = 0;
542 while(len) {
543 chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
544 if(!send_ssl_chunk(conn, ptr, chunk_size))
545 return FALSE;
547 *sent += chunk_size;
548 ptr += chunk_size;
549 len -= chunk_size;
552 return TRUE;
554 if ((*sent = sock_send( conn->socket, msg, len, 0 )) == -1)
556 set_last_error( sock_get_error( errno ) );
557 return FALSE;
559 return TRUE;
562 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
564 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
565 SecBuffer bufs[4];
566 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
567 SSIZE_T size, buf_len;
568 unsigned int i;
569 SECURITY_STATUS res;
571 assert(conn->extra_len < ssl_buf_size);
573 if(conn->extra_len) {
574 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
575 buf_len = conn->extra_len;
576 conn->extra_len = 0;
577 heap_free(conn->extra_buf);
578 conn->extra_buf = NULL;
579 }else {
580 buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
581 if(buf_len < 0)
582 return FALSE;
584 if(!buf_len) {
585 *eof = TRUE;
586 return TRUE;
590 *ret_size = 0;
591 *eof = FALSE;
593 do {
594 memset(bufs, 0, sizeof(bufs));
595 bufs[0].BufferType = SECBUFFER_DATA;
596 bufs[0].cbBuffer = buf_len;
597 bufs[0].pvBuffer = conn->ssl_buf;
599 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
600 switch(res) {
601 case SEC_E_OK:
602 break;
603 case SEC_I_CONTEXT_EXPIRED:
604 TRACE("context expired\n");
605 *eof = TRUE;
606 return TRUE;
607 case SEC_E_INCOMPLETE_MESSAGE:
608 assert(buf_len < ssl_buf_size);
610 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
611 if(size < 1)
612 return FALSE;
614 buf_len += size;
615 continue;
616 default:
617 WARN("failed: %08x\n", res);
618 return FALSE;
620 } while(res != SEC_E_OK);
622 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
623 if(bufs[i].BufferType == SECBUFFER_DATA) {
624 size = min(buf_size, bufs[i].cbBuffer);
625 memcpy(buf, bufs[i].pvBuffer, size);
626 if(size < bufs[i].cbBuffer) {
627 assert(!conn->peek_len);
628 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
629 if(!conn->peek_msg)
630 return FALSE;
631 conn->peek_len = bufs[i].cbBuffer-size;
632 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
635 *ret_size = size;
639 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
640 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
641 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
642 if(!conn->extra_buf)
643 return FALSE;
645 conn->extra_len = bufs[i].cbBuffer;
646 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
650 return TRUE;
653 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
655 *recvd = 0;
656 if (!len) return TRUE;
658 if (conn->secure)
660 SIZE_T size, cread;
661 BOOL res, eof;
663 if (conn->peek_msg)
665 *recvd = min( len, conn->peek_len );
666 memcpy( buf, conn->peek_msg, *recvd );
667 conn->peek_len -= *recvd;
668 conn->peek_msg += *recvd;
670 if (conn->peek_len == 0)
672 heap_free( conn->peek_msg_mem );
673 conn->peek_msg_mem = NULL;
674 conn->peek_msg = NULL;
676 /* check if we have enough data from the peek buffer */
677 if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
679 size = *recvd;
681 do {
682 res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
683 if(!res) {
684 WARN("read_ssl_chunk failed\n");
685 if(!size)
686 return FALSE;
687 break;
690 if(eof) {
691 TRACE("EOF\n");
692 break;
695 size += cread;
696 }while(!size || ((flags & MSG_WAITALL) && size < len));
698 TRACE("received %ld bytes\n", size);
699 *recvd = size;
700 return TRUE;
702 if ((*recvd = sock_recv( conn->socket, buf, len, flags )) == -1)
704 set_last_error( sock_get_error( errno ) );
705 return FALSE;
707 return TRUE;
710 ULONG netconn_query_data_available( netconn_t *conn )
712 return conn->secure ? conn->peek_len : 0;
715 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
717 struct timeval tv;
719 /* value is in milliseconds, convert to struct timeval */
720 tv.tv_sec = value / 1000;
721 tv.tv_usec = (value % 1000) * 1000;
723 if (setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1)
725 WARN("setsockopt failed (%s)\n", strerror( errno ));
726 return sock_get_error( errno );
728 return ERROR_SUCCESS;
731 BOOL netconn_is_alive( netconn_t *netconn )
733 #ifdef MSG_DONTWAIT
734 ssize_t len;
735 BYTE b;
737 len = recv( netconn->socket, &b, 1, MSG_PEEK | MSG_DONTWAIT );
738 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
739 #elif defined(__MINGW32__) || defined(_MSC_VER)
740 ULONG mode;
741 int len;
742 char b;
744 mode = 1;
745 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
746 return FALSE;
748 len = recv(netconn->socket, &b, 1, MSG_PEEK);
750 mode = 0;
751 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
752 return FALSE;
754 return len == 1 || (len == -1 && WSAGetLastError() == WSAEWOULDBLOCK);
755 #else
756 FIXME("not supported on this platform\n");
757 return TRUE;
758 #endif
761 static DWORD resolve_hostname( const WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr_storage *sa )
763 char *hostname;
764 #ifdef HAVE_GETADDRINFO
765 struct addrinfo *res, hints;
766 int ret;
767 #else
768 struct hostent *he;
769 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
770 #endif
772 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
774 #ifdef HAVE_GETADDRINFO
775 memset( &hints, 0, sizeof(struct addrinfo) );
776 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
777 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
779 hints.ai_family = AF_INET;
781 ret = getaddrinfo( hostname, NULL, &hints, &res );
782 if (ret != 0)
784 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
785 hints.ai_family = AF_INET6;
786 ret = getaddrinfo( hostname, NULL, &hints, &res );
787 if (ret != 0)
789 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
790 heap_free( hostname );
791 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
794 heap_free( hostname );
795 memcpy( sa, res->ai_addr, res->ai_addrlen );
796 /* Copy port */
797 switch (res->ai_family)
799 case AF_INET:
800 ((struct sockaddr_in *)sa)->sin_port = htons( port );
801 break;
802 case AF_INET6:
803 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
804 break;
807 freeaddrinfo( res );
808 return ERROR_SUCCESS;
809 #else
810 EnterCriticalSection( &cs_gethostbyname );
812 he = gethostbyname( hostname );
813 heap_free( hostname );
814 if (!he)
816 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
817 LeaveCriticalSection( &cs_gethostbyname );
818 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
820 memset( sa, 0, sizeof(struct sockaddr_in) );
821 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
822 sin->sin_family = he->h_addrtype;
823 sin->sin_port = htons( port );
825 LeaveCriticalSection( &cs_gethostbyname );
826 return ERROR_SUCCESS;
827 #endif
830 struct resolve_args
832 const WCHAR *hostname;
833 INTERNET_PORT port;
834 struct sockaddr_storage *sa;
837 static DWORD CALLBACK resolve_proc( LPVOID arg )
839 struct resolve_args *ra = arg;
840 return resolve_hostname( ra->hostname, ra->port, ra->sa );
843 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr_storage *sa, int timeout )
845 DWORD ret;
847 if (timeout)
849 DWORD status;
850 HANDLE thread;
851 struct resolve_args ra;
853 ra.hostname = hostname;
854 ra.port = port;
855 ra.sa = sa;
857 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
858 if (!thread) return FALSE;
860 status = WaitForSingleObject( thread, timeout );
861 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
862 else ret = ERROR_WINHTTP_TIMEOUT;
863 CloseHandle( thread );
865 else ret = resolve_hostname( hostname, port, sa );
867 if (ret)
869 set_last_error( ret );
870 return FALSE;
872 return TRUE;
875 const void *netconn_get_certificate( netconn_t *conn )
877 const CERT_CONTEXT *ret;
878 SECURITY_STATUS res;
880 if (!conn->secure) return NULL;
881 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
882 return res == SEC_E_OK ? ret : NULL;
885 int netconn_get_cipher_strength( netconn_t *conn )
887 SecPkgContext_ConnectionInfo conn_info;
888 SECURITY_STATUS res;
890 if (!conn->secure) return 0;
891 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
892 if(res != SEC_E_OK)
893 WARN("QueryContextAttributesW failed: %08x\n", res);
894 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;