msvcrt: Add small blocks heap tests.
[wine.git] / dlls / winhttp / net.c
blobb77c706d3304a37078e36c77b2e95015aba2f0cf
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 ret = send(fd, msg, len, flags);
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 ret = recv(fd, msg, len, flags);
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 static SecHandle cred_handle;
258 static BOOL cred_handle_initialized;
260 static CRITICAL_SECTION init_sechandle_cs;
261 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
262 0, 0, &init_sechandle_cs,
263 { &init_sechandle_cs_debug.ProcessLocksList,
264 &init_sechandle_cs_debug.ProcessLocksList },
265 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
267 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
269 static BOOL ensure_cred_handle(void)
271 BOOL ret = TRUE;
273 EnterCriticalSection(&init_sechandle_cs);
275 if(!cred_handle_initialized) {
276 SECURITY_STATUS res;
278 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, NULL,
279 NULL, NULL, &cred_handle, NULL);
280 if(res == SEC_E_OK) {
281 cred_handle_initialized = TRUE;
282 }else {
283 WARN("AcquireCredentialsHandleW failed: %u\n", res);
284 ret = FALSE;
288 LeaveCriticalSection(&init_sechandle_cs);
289 return ret;
292 BOOL netconn_init( netconn_t *conn )
294 memset(conn, 0, sizeof(*conn));
295 conn->socket = -1;
296 return TRUE;
299 void netconn_unload( void )
301 if(cred_handle_initialized)
302 FreeCredentialsHandle(&cred_handle);
303 DeleteCriticalSection(&init_sechandle_cs);
304 #ifndef HAVE_GETADDRINFO
305 DeleteCriticalSection(&cs_gethostbyname);
306 #endif
309 BOOL netconn_connected( netconn_t *conn )
311 return (conn->socket != -1);
314 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
316 if ((conn->socket = socket( domain, type, protocol )) == -1)
318 WARN("unable to create socket (%s)\n", strerror(errno));
319 set_last_error( sock_get_error( errno ) );
320 return FALSE;
322 return TRUE;
325 BOOL netconn_close( netconn_t *conn )
327 int res;
329 if (conn->secure)
331 heap_free( conn->peek_msg_mem );
332 conn->peek_msg_mem = NULL;
333 conn->peek_msg = NULL;
334 conn->peek_len = 0;
335 heap_free(conn->ssl_buf);
336 conn->ssl_buf = NULL;
337 heap_free(conn->extra_buf);
338 conn->extra_buf = NULL;
339 conn->extra_len = 0;
340 DeleteSecurityContext(&conn->ssl_ctx);
341 conn->secure = FALSE;
343 res = closesocket( conn->socket );
344 conn->socket = -1;
345 if (res == -1)
347 set_last_error( sock_get_error( errno ) );
348 return FALSE;
350 return TRUE;
353 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
355 BOOL ret = FALSE;
356 int res = 0;
357 ULONG state;
359 if (timeout > 0)
361 state = 1;
362 ioctlsocket( conn->socket, FIONBIO, &state );
364 if (connect( conn->socket, sockaddr, addr_len ) < 0)
366 res = sock_get_error( errno );
367 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
369 struct pollfd pfd;
371 pfd.fd = conn->socket;
372 pfd.events = POLLOUT;
373 if (poll( &pfd, 1, timeout ) > 0)
374 ret = TRUE;
375 else
376 res = sock_get_error( errno );
379 else
380 ret = TRUE;
381 if (timeout > 0)
383 state = 0;
384 ioctlsocket( conn->socket, FIONBIO, &state );
386 if (!ret)
388 WARN("unable to connect to host (%d)\n", res);
389 set_last_error( res );
391 return ret;
394 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
396 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
397 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
398 BYTE *read_buf;
399 SIZE_T read_buf_size = 2048;
400 ULONG attrs = 0;
401 CtxtHandle ctx;
402 SSIZE_T size;
403 const CERT_CONTEXT *cert;
404 SECURITY_STATUS status;
405 DWORD res = ERROR_SUCCESS;
407 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
408 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
410 if(!ensure_cred_handle())
411 return FALSE;
413 read_buf = heap_alloc(read_buf_size);
414 if(!read_buf)
415 return FALSE;
417 status = InitializeSecurityContextW(&cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
418 &ctx, &out_desc, &attrs, NULL);
420 assert(status != SEC_E_OK);
422 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
423 if(out_buf.cbBuffer) {
424 assert(status == SEC_I_CONTINUE_NEEDED);
426 TRACE("sending %u bytes\n", out_buf.cbBuffer);
428 size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
429 if(size != out_buf.cbBuffer) {
430 ERR("send failed\n");
431 res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
432 break;
435 FreeContextBuffer(out_buf.pvBuffer);
436 out_buf.pvBuffer = NULL;
437 out_buf.cbBuffer = 0;
440 if(status == SEC_I_CONTINUE_NEEDED) {
441 assert(in_bufs[1].cbBuffer < read_buf_size);
443 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
444 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
446 in_bufs[1].BufferType = SECBUFFER_EMPTY;
447 in_bufs[1].cbBuffer = 0;
448 in_bufs[1].pvBuffer = NULL;
451 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
452 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
454 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
455 BYTE *new_read_buf;
457 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
458 if(!new_read_buf) {
459 status = E_OUTOFMEMORY;
460 break;
463 in_bufs[0].pvBuffer = read_buf = new_read_buf;
464 read_buf_size += 1024;
467 size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
468 if(size < 1) {
469 WARN("recv error\n");
470 status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
471 break;
474 TRACE("recv %lu bytes\n", size);
476 in_bufs[0].cbBuffer += size;
477 in_bufs[0].pvBuffer = read_buf;
478 status = InitializeSecurityContextW(&cred_handle, &ctx, hostname, isc_req_flags, 0, 0, &in_desc,
479 0, NULL, &out_desc, &attrs, NULL);
480 TRACE("InitializeSecurityContext ret %08x\n", status);
482 if(status == SEC_E_OK) {
483 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
484 FIXME("SECBUFFER_EXTRA not supported\n");
486 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
487 if(status != SEC_E_OK) {
488 WARN("Could not get sizes\n");
489 break;
492 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
493 if(status == SEC_E_OK) {
494 res = netconn_verify_cert(cert, hostname, conn->security_flags);
495 CertFreeCertificateContext(cert);
496 if(res != ERROR_SUCCESS) {
497 WARN("cert verify failed: %u\n", res);
498 break;
500 }else {
501 WARN("Could not get cert\n");
502 break;
505 conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
506 if(!conn->ssl_buf) {
507 res = GetLastError();
508 break;
513 heap_free(read_buf);
515 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
516 WARN("Failed to initialize security context failed: %08x\n", status);
517 heap_free(conn->ssl_buf);
518 conn->ssl_buf = NULL;
519 DeleteSecurityContext(&ctx);
520 set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR);
521 return FALSE;
525 TRACE("established SSL connection\n");
526 conn->secure = TRUE;
527 conn->ssl_ctx = ctx;
528 return TRUE;
531 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
533 SecBuffer bufs[4] = {
534 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
535 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
536 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
537 {0, SECBUFFER_EMPTY, NULL}
539 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
540 SECURITY_STATUS res;
542 memcpy(bufs[1].pvBuffer, msg, size);
543 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
544 if(res != SEC_E_OK) {
545 WARN("EncryptMessage failed\n");
546 return FALSE;
549 if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
550 WARN("send failed\n");
551 return FALSE;
554 return TRUE;
557 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int *sent )
559 if (!netconn_connected( conn )) return FALSE;
560 if (conn->secure)
562 const BYTE *ptr = msg;
563 size_t chunk_size;
565 *sent = 0;
567 while(len) {
568 chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
569 if(!send_ssl_chunk(conn, ptr, chunk_size))
570 return FALSE;
572 *sent += chunk_size;
573 ptr += chunk_size;
574 len -= chunk_size;
577 return TRUE;
579 if ((*sent = sock_send( conn->socket, msg, len, 0 )) == -1)
581 set_last_error( sock_get_error( errno ) );
582 return FALSE;
584 return TRUE;
587 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
589 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
590 SecBuffer bufs[4];
591 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
592 SSIZE_T size, buf_len;
593 unsigned int i;
594 SECURITY_STATUS res;
596 assert(conn->extra_len < ssl_buf_size);
598 if(conn->extra_len) {
599 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
600 buf_len = conn->extra_len;
601 conn->extra_len = 0;
602 heap_free(conn->extra_buf);
603 conn->extra_buf = NULL;
604 }else {
605 buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
606 if(buf_len < 0) {
607 WARN("recv failed\n");
608 return FALSE;
611 if(!buf_len) {
612 *eof = TRUE;
613 return TRUE;
617 *ret_size = 0;
618 *eof = FALSE;
620 do {
621 memset(bufs, 0, sizeof(bufs));
622 bufs[0].BufferType = SECBUFFER_DATA;
623 bufs[0].cbBuffer = buf_len;
624 bufs[0].pvBuffer = conn->ssl_buf;
626 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
627 switch(res) {
628 case SEC_E_OK:
629 break;
630 case SEC_I_CONTEXT_EXPIRED:
631 TRACE("context expired\n");
632 *eof = TRUE;
633 return TRUE;
634 case SEC_E_INCOMPLETE_MESSAGE:
635 assert(buf_len < ssl_buf_size);
637 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
638 if(size < 1)
639 return FALSE;
641 buf_len += size;
642 continue;
643 default:
644 WARN("failed: %08x\n", res);
645 return FALSE;
647 } while(res != SEC_E_OK);
649 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
650 if(bufs[i].BufferType == SECBUFFER_DATA) {
651 size = min(buf_size, bufs[i].cbBuffer);
652 memcpy(buf, bufs[i].pvBuffer, size);
653 if(size < bufs[i].cbBuffer) {
654 assert(!conn->peek_len);
655 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
656 if(!conn->peek_msg)
657 return FALSE;
658 conn->peek_len = bufs[i].cbBuffer-size;
659 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
662 *ret_size = size;
666 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
667 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
668 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
669 if(!conn->extra_buf)
670 return FALSE;
672 conn->extra_len = bufs[i].cbBuffer;
673 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
677 return TRUE;
680 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
682 *recvd = 0;
683 if (!netconn_connected( conn )) return FALSE;
684 if (!len) return TRUE;
686 if (conn->secure)
688 SIZE_T size, cread;
689 BOOL res, eof;
691 if (conn->peek_msg)
693 *recvd = min( len, conn->peek_len );
694 memcpy( buf, conn->peek_msg, *recvd );
695 conn->peek_len -= *recvd;
696 conn->peek_msg += *recvd;
698 if (conn->peek_len == 0)
700 heap_free( conn->peek_msg_mem );
701 conn->peek_msg_mem = NULL;
702 conn->peek_msg = NULL;
704 /* check if we have enough data from the peek buffer */
705 if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
707 size = *recvd;
709 do {
710 res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
711 if(!res) {
712 WARN("read_ssl_chunk failed\n");
713 if(!size)
714 return FALSE;
715 break;
718 if(eof) {
719 TRACE("EOF\n");
720 break;
723 size += cread;
724 }while(!size || ((flags & MSG_WAITALL) && size < len));
726 TRACE("received %ld bytes\n", size);
727 *recvd = size;
728 return TRUE;
730 if ((*recvd = sock_recv( conn->socket, buf, len, flags )) == -1)
732 set_last_error( sock_get_error( errno ) );
733 return FALSE;
735 return TRUE;
738 ULONG netconn_query_data_available( netconn_t *conn )
740 if(!netconn_connected(conn))
741 return 0;
743 if(conn->secure) {
744 return conn->peek_len;
745 }else {
746 #ifdef FIONREAD
747 ULONG unread;
749 if(!ioctlsocket(conn->socket, FIONREAD, &unread))
750 return unread;
751 #endif
754 return 0;
757 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
759 struct timeval tv;
761 /* value is in milliseconds, convert to struct timeval */
762 tv.tv_sec = value / 1000;
763 tv.tv_usec = (value % 1000) * 1000;
765 if (setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1)
767 WARN("setsockopt failed (%s)\n", strerror( errno ));
768 return sock_get_error( errno );
770 return ERROR_SUCCESS;
773 static DWORD resolve_hostname( const WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
775 char *hostname;
776 #ifdef HAVE_GETADDRINFO
777 struct addrinfo *res, hints;
778 int ret;
779 #else
780 struct hostent *he;
781 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
782 #endif
784 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
786 #ifdef HAVE_GETADDRINFO
787 memset( &hints, 0, sizeof(struct addrinfo) );
788 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
789 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
791 hints.ai_family = AF_INET;
793 ret = getaddrinfo( hostname, NULL, &hints, &res );
794 if (ret != 0)
796 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
797 hints.ai_family = AF_INET6;
798 ret = getaddrinfo( hostname, NULL, &hints, &res );
799 if (ret != 0)
801 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
802 heap_free( hostname );
803 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
806 heap_free( hostname );
807 if (*sa_len < res->ai_addrlen)
809 WARN("address too small\n");
810 freeaddrinfo( res );
811 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
813 *sa_len = res->ai_addrlen;
814 memcpy( sa, res->ai_addr, res->ai_addrlen );
815 /* Copy port */
816 switch (res->ai_family)
818 case AF_INET:
819 ((struct sockaddr_in *)sa)->sin_port = htons( port );
820 break;
821 case AF_INET6:
822 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
823 break;
826 freeaddrinfo( res );
827 return ERROR_SUCCESS;
828 #else
829 EnterCriticalSection( &cs_gethostbyname );
831 he = gethostbyname( hostname );
832 heap_free( hostname );
833 if (!he)
835 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
836 LeaveCriticalSection( &cs_gethostbyname );
837 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
839 if (*sa_len < sizeof(struct sockaddr_in))
841 WARN("address too small\n");
842 LeaveCriticalSection( &cs_gethostbyname );
843 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
845 *sa_len = sizeof(struct sockaddr_in);
846 memset( sa, 0, sizeof(struct sockaddr_in) );
847 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
848 sin->sin_family = he->h_addrtype;
849 sin->sin_port = htons( port );
851 LeaveCriticalSection( &cs_gethostbyname );
852 return ERROR_SUCCESS;
853 #endif
856 struct resolve_args
858 const WCHAR *hostname;
859 INTERNET_PORT port;
860 struct sockaddr *sa;
861 socklen_t *sa_len;
864 static DWORD CALLBACK resolve_proc( LPVOID arg )
866 struct resolve_args *ra = arg;
867 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
870 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
872 DWORD ret;
874 if (timeout)
876 DWORD status;
877 HANDLE thread;
878 struct resolve_args ra;
880 ra.hostname = hostname;
881 ra.port = port;
882 ra.sa = sa;
883 ra.sa_len = sa_len;
885 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
886 if (!thread) return FALSE;
888 status = WaitForSingleObject( thread, timeout );
889 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
890 else ret = ERROR_WINHTTP_TIMEOUT;
891 CloseHandle( thread );
893 else ret = resolve_hostname( hostname, port, sa, sa_len );
895 if (ret)
897 set_last_error( ret );
898 return FALSE;
900 return TRUE;
903 const void *netconn_get_certificate( netconn_t *conn )
905 const CERT_CONTEXT *ret;
906 SECURITY_STATUS res;
908 if (!conn->secure) return NULL;
909 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
910 return res == SEC_E_OK ? ret : NULL;
913 int netconn_get_cipher_strength( netconn_t *conn )
915 SecPkgContext_ConnectionInfo conn_info;
916 SECURITY_STATUS res;
918 if (!conn->secure) return 0;
919 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
920 if(res != SEC_E_OK)
921 WARN("QueryContextAttributesW failed: %08x\n", res);
922 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;