winhttp: Remove support for MSG_PEEK.
[wine.git] / dlls / winhttp / net.c
blob631939ab938136264c6425d9e530f942791fd176
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 DWORD netconn_verify_cert( PCCERT_CONTEXT cert, WCHAR *server, DWORD security_flags )
144 HCERTSTORE store = cert->hCertStore;
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;
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 )))
159 if (chain->TrustStatus.dwErrorStatus)
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;
166 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
168 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
169 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
171 else if (chain->TrustStatus.dwErrorStatus &
172 CERT_TRUST_IS_UNTRUSTED_ROOT)
174 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
175 err = ERROR_WINHTTP_SECURE_INVALID_CA;
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)
187 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
188 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
190 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
191 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
193 if (!err)
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;
200 /* Clear chain->TrustStatus.dwErrorStatus so
201 * CertVerifyCertificateChainPolicy will verify additional checks
202 * rather than stopping with an existing, ignored error.
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.
219 if (ret && policyStatus.dwError)
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;
227 CertFreeCertificateChain( chain );
229 else
230 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
231 TRACE("returning %08x\n", err);
232 return err;
235 static SecHandle cred_handle;
236 static BOOL cred_handle_initialized;
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") }
245 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
247 static BOOL ensure_cred_handle(void)
249 BOOL ret = TRUE;
251 EnterCriticalSection(&init_sechandle_cs);
253 if(!cred_handle_initialized) {
254 SECURITY_STATUS res;
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;
266 LeaveCriticalSection(&init_sechandle_cs);
267 return ret;
270 BOOL netconn_init( netconn_t *conn )
272 memset(conn, 0, sizeof(*conn));
273 conn->socket = -1;
274 return TRUE;
277 void netconn_unload( void )
279 if(cred_handle_initialized)
280 FreeCredentialsHandle(&cred_handle);
281 DeleteCriticalSection(&init_sechandle_cs);
282 #ifndef HAVE_GETADDRINFO
283 DeleteCriticalSection(&cs_gethostbyname);
284 #endif
287 BOOL netconn_connected( netconn_t *conn )
289 return (conn->socket != -1);
292 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
294 if ((conn->socket = socket( domain, type, protocol )) == -1)
296 WARN("unable to create socket (%s)\n", strerror(errno));
297 set_last_error( sock_get_error( errno ) );
298 return FALSE;
300 return TRUE;
303 BOOL netconn_close( netconn_t *conn )
305 int res;
307 if (conn->secure)
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;
321 res = closesocket( conn->socket );
322 conn->socket = -1;
323 if (res == -1)
325 set_last_error( sock_get_error( errno ) );
326 return FALSE;
328 return TRUE;
331 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
333 BOOL ret = FALSE;
334 int res = 0;
335 ULONG state;
337 if (timeout > 0)
339 state = 1;
340 ioctlsocket( conn->socket, FIONBIO, &state );
342 if (connect( conn->socket, sockaddr, addr_len ) < 0)
344 res = sock_get_error( errno );
345 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
347 struct pollfd pfd;
349 pfd.fd = conn->socket;
350 pfd.events = POLLOUT;
351 if (poll( &pfd, 1, timeout ) > 0)
352 ret = TRUE;
353 else
354 res = sock_get_error( errno );
357 else
358 ret = TRUE;
359 if (timeout > 0)
361 state = 0;
362 ioctlsocket( conn->socket, FIONBIO, &state );
364 if (!ret)
366 WARN("unable to connect to host (%d)\n", res);
367 set_last_error( res );
369 return ret;
372 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
374 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
375 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
376 BYTE *read_buf;
377 SIZE_T read_buf_size = 2048;
378 ULONG attrs = 0;
379 CtxtHandle ctx;
380 SSIZE_T size;
381 const CERT_CONTEXT *cert;
382 SECURITY_STATUS status;
383 DWORD res = ERROR_SUCCESS;
385 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
386 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
388 if(!ensure_cred_handle())
389 return FALSE;
391 read_buf = heap_alloc(read_buf_size);
392 if(!read_buf)
393 return FALSE;
395 status = InitializeSecurityContextW(&cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
396 &ctx, &out_desc, &attrs, NULL);
398 assert(status != SEC_E_OK);
400 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
401 if(out_buf.cbBuffer) {
402 assert(status == SEC_I_CONTINUE_NEEDED);
404 TRACE("sending %u bytes\n", out_buf.cbBuffer);
406 size = send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
407 if(size != out_buf.cbBuffer) {
408 ERR("send failed\n");
409 status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
410 break;
413 FreeContextBuffer(out_buf.pvBuffer);
414 out_buf.pvBuffer = NULL;
415 out_buf.cbBuffer = 0;
418 if(status == SEC_I_CONTINUE_NEEDED) {
419 assert(in_bufs[1].cbBuffer < read_buf_size);
421 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
422 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
424 in_bufs[1].BufferType = SECBUFFER_EMPTY;
425 in_bufs[1].cbBuffer = 0;
426 in_bufs[1].pvBuffer = NULL;
429 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
430 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
432 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
433 BYTE *new_read_buf;
435 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
436 if(!new_read_buf) {
437 status = E_OUTOFMEMORY;
438 break;
441 in_bufs[0].pvBuffer = read_buf = new_read_buf;
442 read_buf_size += 1024;
445 size = recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
446 if(size < 1) {
447 WARN("recv error\n");
448 status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
449 break;
452 TRACE("recv %lu bytes\n", size);
454 in_bufs[0].cbBuffer += size;
455 in_bufs[0].pvBuffer = read_buf;
456 status = InitializeSecurityContextW(&cred_handle, &ctx, hostname, isc_req_flags, 0, 0, &in_desc,
457 0, NULL, &out_desc, &attrs, NULL);
458 TRACE("InitializeSecurityContext ret %08x\n", status);
460 if(status == SEC_E_OK) {
461 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
462 FIXME("SECBUFFER_EXTRA not supported\n");
464 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
465 if(status != SEC_E_OK) {
466 WARN("Could not get sizes\n");
467 break;
470 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
471 if(status == SEC_E_OK) {
472 res = netconn_verify_cert(cert, hostname, conn->security_flags);
473 CertFreeCertificateContext(cert);
474 if(res != ERROR_SUCCESS) {
475 WARN("cert verify failed: %u\n", res);
476 break;
478 }else {
479 WARN("Could not get cert\n");
480 break;
483 conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
484 if(!conn->ssl_buf) {
485 res = GetLastError();
486 break;
492 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
493 WARN("Failed to initialize security context failed: %08x\n", status);
494 heap_free(conn->ssl_buf);
495 conn->ssl_buf = NULL;
496 DeleteSecurityContext(&ctx);
497 set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR);
498 return FALSE;
502 TRACE("established SSL connection\n");
503 conn->secure = TRUE;
504 conn->ssl_ctx = ctx;
505 return TRUE;
508 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
510 SecBuffer bufs[4] = {
511 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
512 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
513 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
514 {0, SECBUFFER_EMPTY, NULL}
516 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
517 SECURITY_STATUS res;
519 memcpy(bufs[1].pvBuffer, msg, size);
520 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
521 if(res != SEC_E_OK) {
522 WARN("EncryptMessage failed\n");
523 return FALSE;
526 if(send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
527 WARN("send failed\n");
528 return FALSE;
531 return TRUE;
534 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
536 if (!netconn_connected( conn )) return FALSE;
537 if (conn->secure)
539 const BYTE *ptr = msg;
540 size_t chunk_size;
542 if (flags) FIXME("flags %08x not supported in SSL\n", flags);
544 *sent = 0;
546 while(len) {
547 chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
548 if(!send_ssl_chunk(conn, ptr, chunk_size))
549 return FALSE;
551 *sent += chunk_size;
552 ptr += chunk_size;
553 len -= chunk_size;
556 return TRUE;
558 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
560 set_last_error( sock_get_error( errno ) );
561 return FALSE;
563 return TRUE;
566 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
568 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
569 SecBuffer bufs[4];
570 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
571 SSIZE_T size, buf_len;
572 unsigned int i;
573 SECURITY_STATUS res;
575 assert(conn->extra_len < ssl_buf_size);
577 if(conn->extra_len) {
578 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
579 buf_len = conn->extra_len;
580 conn->extra_len = 0;
581 heap_free(conn->extra_buf);
582 conn->extra_buf = NULL;
583 }else {
584 buf_len = recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
585 if(buf_len < 0) {
586 WARN("recv failed\n");
587 return FALSE;
590 if(!buf_len) {
591 *eof = TRUE;
592 return TRUE;
596 *ret_size = 0;
597 *eof = FALSE;
599 do {
600 memset(bufs, 0, sizeof(bufs));
601 bufs[0].BufferType = SECBUFFER_DATA;
602 bufs[0].cbBuffer = buf_len;
603 bufs[0].pvBuffer = conn->ssl_buf;
605 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
606 switch(res) {
607 case SEC_E_OK:
608 break;
609 case SEC_I_CONTEXT_EXPIRED:
610 TRACE("context expired\n");
611 *eof = TRUE;
612 return TRUE;
613 case SEC_E_INCOMPLETE_MESSAGE:
614 assert(buf_len < ssl_buf_size);
616 size = recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
617 if(size < 1)
618 return FALSE;
620 buf_len += size;
621 continue;
622 default:
623 WARN("failed: %08x\n", res);
624 return FALSE;
626 } while(res != SEC_E_OK);
628 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
629 if(bufs[i].BufferType == SECBUFFER_DATA) {
630 size = min(buf_size, bufs[i].cbBuffer);
631 memcpy(buf, bufs[i].pvBuffer, size);
632 if(size < bufs[i].cbBuffer) {
633 assert(!conn->peek_len);
634 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
635 if(!conn->peek_msg)
636 return FALSE;
637 conn->peek_len = bufs[i].cbBuffer-size;
638 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
641 *ret_size = size;
645 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
646 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
647 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
648 if(!conn->extra_buf)
649 return FALSE;
651 conn->extra_len = bufs[i].cbBuffer;
652 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
656 return TRUE;
659 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
661 *recvd = 0;
662 if (!netconn_connected( conn )) return FALSE;
663 if (!len) return TRUE;
665 if (conn->secure)
667 SIZE_T size, cread;
668 BOOL res, eof;
670 if (conn->peek_msg)
672 *recvd = min( len, conn->peek_len );
673 memcpy( buf, conn->peek_msg, *recvd );
674 conn->peek_len -= *recvd;
675 conn->peek_msg += *recvd;
677 if (conn->peek_len == 0)
679 heap_free( conn->peek_msg_mem );
680 conn->peek_msg_mem = NULL;
681 conn->peek_msg = NULL;
683 /* check if we have enough data from the peek buffer */
684 if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
686 size = *recvd;
688 do {
689 res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
690 if(!res) {
691 WARN("read_ssl_chunk failed\n");
692 if(!size)
693 return FALSE;
694 break;
697 if(eof) {
698 TRACE("EOF\n");
699 break;
702 size += cread;
703 }while(!size || ((flags & MSG_WAITALL) && size < len));
705 TRACE("received %ld bytes\n", size);
706 *recvd = size;
707 return TRUE;
709 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
711 set_last_error( sock_get_error( errno ) );
712 return FALSE;
714 return TRUE;
717 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
719 #ifdef FIONREAD
720 int ret;
721 ULONG unread;
722 #endif
723 *available = 0;
724 if (!netconn_connected( conn )) return FALSE;
726 if (conn->secure)
728 *available = conn->peek_len;
729 return TRUE;
731 #ifdef FIONREAD
732 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
733 #endif
734 return TRUE;
737 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
739 struct pollfd pfd;
740 BOOL ret = FALSE;
741 DWORD recvd = 0;
743 if (!netconn_connected( conn )) return FALSE;
745 if (conn->secure)
747 while (recvd < *buflen)
749 int dummy;
750 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
752 set_last_error( ERROR_CONNECTION_ABORTED );
753 break;
755 if (buffer[recvd] == '\n')
757 ret = TRUE;
758 break;
760 if (buffer[recvd] != '\r') recvd++;
762 if (ret)
764 buffer[recvd++] = 0;
765 *buflen = recvd;
766 TRACE("received line %s\n", debugstr_a(buffer));
768 return ret;
771 pfd.fd = conn->socket;
772 pfd.events = POLLIN;
773 while (recvd < *buflen)
775 int timeout, res;
776 struct timeval tv;
777 socklen_t len = sizeof(tv);
779 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
780 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
781 else
782 timeout = -1;
783 if (poll( &pfd, 1, timeout ) > 0)
785 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
787 if (res == -1) set_last_error( sock_get_error( errno ) );
788 break;
790 if (buffer[recvd] == '\n')
792 ret = TRUE;
793 break;
795 if (buffer[recvd] != '\r') recvd++;
797 else
799 set_last_error( ERROR_WINHTTP_TIMEOUT );
800 break;
803 if (ret)
805 buffer[recvd++] = 0;
806 *buflen = recvd;
807 TRACE("received line %s\n", debugstr_a(buffer));
809 return ret;
812 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
814 struct timeval tv;
816 /* value is in milliseconds, convert to struct timeval */
817 tv.tv_sec = value / 1000;
818 tv.tv_usec = (value % 1000) * 1000;
820 if (setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1)
822 WARN("setsockopt failed (%s)\n", strerror( errno ));
823 return sock_get_error( errno );
825 return ERROR_SUCCESS;
828 static DWORD resolve_hostname( const WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
830 char *hostname;
831 #ifdef HAVE_GETADDRINFO
832 struct addrinfo *res, hints;
833 int ret;
834 #else
835 struct hostent *he;
836 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
837 #endif
839 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
841 #ifdef HAVE_GETADDRINFO
842 memset( &hints, 0, sizeof(struct addrinfo) );
843 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
844 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
846 hints.ai_family = AF_INET;
848 ret = getaddrinfo( hostname, NULL, &hints, &res );
849 if (ret != 0)
851 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
852 hints.ai_family = AF_INET6;
853 ret = getaddrinfo( hostname, NULL, &hints, &res );
854 if (ret != 0)
856 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
857 heap_free( hostname );
858 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
861 heap_free( hostname );
862 if (*sa_len < res->ai_addrlen)
864 WARN("address too small\n");
865 freeaddrinfo( res );
866 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
868 *sa_len = res->ai_addrlen;
869 memcpy( sa, res->ai_addr, res->ai_addrlen );
870 /* Copy port */
871 switch (res->ai_family)
873 case AF_INET:
874 ((struct sockaddr_in *)sa)->sin_port = htons( port );
875 break;
876 case AF_INET6:
877 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
878 break;
881 freeaddrinfo( res );
882 return ERROR_SUCCESS;
883 #else
884 EnterCriticalSection( &cs_gethostbyname );
886 he = gethostbyname( hostname );
887 heap_free( hostname );
888 if (!he)
890 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
891 LeaveCriticalSection( &cs_gethostbyname );
892 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
894 if (*sa_len < sizeof(struct sockaddr_in))
896 WARN("address too small\n");
897 LeaveCriticalSection( &cs_gethostbyname );
898 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
900 *sa_len = sizeof(struct sockaddr_in);
901 memset( sa, 0, sizeof(struct sockaddr_in) );
902 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
903 sin->sin_family = he->h_addrtype;
904 sin->sin_port = htons( port );
906 LeaveCriticalSection( &cs_gethostbyname );
907 return ERROR_SUCCESS;
908 #endif
911 struct resolve_args
913 const WCHAR *hostname;
914 INTERNET_PORT port;
915 struct sockaddr *sa;
916 socklen_t *sa_len;
919 static DWORD CALLBACK resolve_proc( LPVOID arg )
921 struct resolve_args *ra = arg;
922 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
925 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
927 DWORD ret;
929 if (timeout)
931 DWORD status;
932 HANDLE thread;
933 struct resolve_args ra;
935 ra.hostname = hostname;
936 ra.port = port;
937 ra.sa = sa;
938 ra.sa_len = sa_len;
940 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
941 if (!thread) return FALSE;
943 status = WaitForSingleObject( thread, timeout );
944 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
945 else ret = ERROR_WINHTTP_TIMEOUT;
946 CloseHandle( thread );
948 else ret = resolve_hostname( hostname, port, sa, sa_len );
950 if (ret)
952 set_last_error( ret );
953 return FALSE;
955 return TRUE;
958 const void *netconn_get_certificate( netconn_t *conn )
960 const CERT_CONTEXT *ret;
961 SECURITY_STATUS res;
963 if (!conn->secure) return NULL;
964 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
965 return res == SEC_E_OK ? ret : NULL;
968 int netconn_get_cipher_strength( netconn_t *conn )
970 SecPkgContext_ConnectionInfo conn_info;
971 SECURITY_STATUS res;
973 if (!conn->secure) return 0;
974 res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
975 if(res != SEC_E_OK)
976 WARN("QueryContextAttributesW failed: %08x\n", res);
977 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;