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