Sync with trunk r58033.
[reactos.git] / dll / win32 / winhttp / net.c
1 /*
2 * Copyright 2008 Hans Leidekker for CodeWeavers
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17 */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
25
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
32 #endif
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 # include <poll.h>
38 #endif
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
41 # include <openssl/opensslv.h>
42 #undef FAR
43 #undef DSA
44 #endif
45
46 #define NONAMELESSUNION
47
48 #include "wine/debug.h"
49 #include "wine/library.h"
50
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winhttp.h"
54 #include "wincrypt.h"
55
56 #include "winhttp_private.h"
57
58 /* to avoid conflicts with the Unix socket headers */
59 #define USE_WS_PREFIX
60 #include "winsock2.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
63
64 #ifndef HAVE_GETADDRINFO
65
66 /* critical section to protect non-reentrant gethostbyname() */
67 static CRITICAL_SECTION cs_gethostbyname;
68 static CRITICAL_SECTION_DEBUG critsect_debug =
69 {
70 0, 0, &cs_gethostbyname,
71 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
73 };
74 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
75
76 #endif
77
78 #ifdef SONAME_LIBSSL
79
80 #include <openssl/err.h>
81
82 static CRITICAL_SECTION init_ssl_cs;
83 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
84 {
85 0, 0, &init_ssl_cs,
86 { &init_ssl_cs_debug.ProcessLocksList,
87 &init_ssl_cs_debug.ProcessLocksList },
88 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
89 };
90 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
91
92 static void *libssl_handle;
93 static void *libcrypto_handle;
94
95 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
96 static const SSL_METHOD *method;
97 #else
98 static SSL_METHOD *method;
99 #endif
100 static SSL_CTX *ctx;
101 static int hostname_idx;
102 static int error_idx;
103 static int conn_idx;
104
105 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
106
107 MAKE_FUNCPTR( SSL_library_init );
108 MAKE_FUNCPTR( SSL_load_error_strings );
109 MAKE_FUNCPTR( SSLv23_method );
110 MAKE_FUNCPTR( SSL_CTX_free );
111 MAKE_FUNCPTR( SSL_CTX_new );
112 MAKE_FUNCPTR( SSL_new );
113 MAKE_FUNCPTR( SSL_free );
114 MAKE_FUNCPTR( SSL_set_fd );
115 MAKE_FUNCPTR( SSL_connect );
116 MAKE_FUNCPTR( SSL_shutdown );
117 MAKE_FUNCPTR( SSL_write );
118 MAKE_FUNCPTR( SSL_read );
119 MAKE_FUNCPTR( SSL_pending );
120 MAKE_FUNCPTR( SSL_get_error );
121 MAKE_FUNCPTR( SSL_get_ex_new_index );
122 MAKE_FUNCPTR( SSL_get_ex_data );
123 MAKE_FUNCPTR( SSL_set_ex_data );
124 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
125 MAKE_FUNCPTR( SSL_get_peer_certificate );
126 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
127 MAKE_FUNCPTR( SSL_CTX_set_verify );
128 MAKE_FUNCPTR( SSL_get_current_cipher );
129 MAKE_FUNCPTR( SSL_CIPHER_get_bits );
130
131 MAKE_FUNCPTR( CRYPTO_num_locks );
132 MAKE_FUNCPTR( CRYPTO_set_id_callback );
133 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
134 MAKE_FUNCPTR( ERR_free_strings );
135 MAKE_FUNCPTR( ERR_get_error );
136 MAKE_FUNCPTR( ERR_error_string );
137 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
138 MAKE_FUNCPTR( X509_STORE_CTX_get_chain );
139 MAKE_FUNCPTR( i2d_X509 );
140 MAKE_FUNCPTR( sk_value );
141 MAKE_FUNCPTR( sk_num );
142 #undef MAKE_FUNCPTR
143
144 static CRITICAL_SECTION *ssl_locks;
145 static unsigned int num_ssl_locks;
146
147 static unsigned long ssl_thread_id(void)
148 {
149 return GetCurrentThreadId();
150 }
151
152 static void ssl_lock_callback(int mode, int type, const char *file, int line)
153 {
154 if (mode & CRYPTO_LOCK)
155 EnterCriticalSection( &ssl_locks[type] );
156 else
157 LeaveCriticalSection( &ssl_locks[type] );
158 }
159
160 #endif
161
162 /* translate a unix error code into a winsock error code */
163 #ifndef __REACTOS__
164 static int sock_get_error( int err )
165 {
166 #if !defined(__MINGW32__) && !defined (_MSC_VER)
167 switch (err)
168 {
169 case EINTR: return WSAEINTR;
170 case EBADF: return WSAEBADF;
171 case EPERM:
172 case EACCES: return WSAEACCES;
173 case EFAULT: return WSAEFAULT;
174 case EINVAL: return WSAEINVAL;
175 case EMFILE: return WSAEMFILE;
176 case EWOULDBLOCK: return WSAEWOULDBLOCK;
177 case EINPROGRESS: return WSAEINPROGRESS;
178 case EALREADY: return WSAEALREADY;
179 case ENOTSOCK: return WSAENOTSOCK;
180 case EDESTADDRREQ: return WSAEDESTADDRREQ;
181 case EMSGSIZE: return WSAEMSGSIZE;
182 case EPROTOTYPE: return WSAEPROTOTYPE;
183 case ENOPROTOOPT: return WSAENOPROTOOPT;
184 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
185 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
186 case EOPNOTSUPP: return WSAEOPNOTSUPP;
187 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
188 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
189 case EADDRINUSE: return WSAEADDRINUSE;
190 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
191 case ENETDOWN: return WSAENETDOWN;
192 case ENETUNREACH: return WSAENETUNREACH;
193 case ENETRESET: return WSAENETRESET;
194 case ECONNABORTED: return WSAECONNABORTED;
195 case EPIPE:
196 case ECONNRESET: return WSAECONNRESET;
197 case ENOBUFS: return WSAENOBUFS;
198 case EISCONN: return WSAEISCONN;
199 case ENOTCONN: return WSAENOTCONN;
200 case ESHUTDOWN: return WSAESHUTDOWN;
201 case ETOOMANYREFS: return WSAETOOMANYREFS;
202 case ETIMEDOUT: return WSAETIMEDOUT;
203 case ECONNREFUSED: return WSAECONNREFUSED;
204 case ELOOP: return WSAELOOP;
205 case ENAMETOOLONG: return WSAENAMETOOLONG;
206 case EHOSTDOWN: return WSAEHOSTDOWN;
207 case EHOSTUNREACH: return WSAEHOSTUNREACH;
208 case ENOTEMPTY: return WSAENOTEMPTY;
209 #ifdef EPROCLIM
210 case EPROCLIM: return WSAEPROCLIM;
211 #endif
212 #ifdef EUSERS
213 case EUSERS: return WSAEUSERS;
214 #endif
215 #ifdef EDQUOT
216 case EDQUOT: return WSAEDQUOT;
217 #endif
218 #ifdef ESTALE
219 case ESTALE: return WSAESTALE;
220 #endif
221 #ifdef EREMOTE
222 case EREMOTE: return WSAEREMOTE;
223 #endif
224 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
225 }
226 #endif
227 return err;
228 }
229 #else
230 #define sock_get_error(x) WSAGetLastError()
231
232 static inline int unix_ioctl(int filedes, long request, void *arg)
233 {
234 return ioctlsocket(filedes, request, arg);
235 }
236 #define ioctlsocket unix_ioctl
237 #endif
238
239 #ifdef SONAME_LIBSSL
240 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
241 {
242 unsigned char *buffer, *p;
243 int len;
244 BOOL malloc = FALSE;
245 PCCERT_CONTEXT ret;
246
247 p = NULL;
248 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
249 /*
250 * SSL 0.9.7 and above malloc the buffer if it is null.
251 * however earlier version do not and so we would need to alloc the buffer.
252 *
253 * see the i2d_X509 man page for more details.
254 */
255 if (!p)
256 {
257 if (!(buffer = heap_alloc( len ))) return NULL;
258 p = buffer;
259 len = pi2d_X509( cert, &p );
260 }
261 else
262 {
263 buffer = p;
264 malloc = TRUE;
265 }
266
267 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
268
269 if (malloc) free( buffer );
270 else heap_free( buffer );
271
272 return ret;
273 }
274
275 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
276 WCHAR *server, DWORD security_flags )
277 {
278 BOOL ret;
279 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
280 PCCERT_CHAIN_CONTEXT chain;
281 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
282 char *server_auth[] = { oid_server_auth };
283 DWORD err = ERROR_SUCCESS;
284
285 TRACE("verifying %s\n", debugstr_w( server ));
286 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
287 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
288 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara,
289 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT,
290 NULL, &chain )))
291 {
292 if (chain->TrustStatus.dwErrorStatus)
293 {
294 static const DWORD supportedErrors =
295 CERT_TRUST_IS_NOT_TIME_VALID |
296 CERT_TRUST_IS_UNTRUSTED_ROOT |
297 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
298
299 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
300 {
301 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
302 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
303 }
304 else if (chain->TrustStatus.dwErrorStatus &
305 CERT_TRUST_IS_UNTRUSTED_ROOT)
306 {
307 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
308 err = ERROR_WINHTTP_SECURE_INVALID_CA;
309 }
310 else if ((chain->TrustStatus.dwErrorStatus &
311 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
312 (chain->TrustStatus.dwErrorStatus &
313 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
314 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
315 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
316 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
317 else if (chain->TrustStatus.dwErrorStatus &
318 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
319 {
320 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
321 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
322 }
323 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
324 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
325 }
326 if (!err)
327 {
328 CERT_CHAIN_POLICY_PARA policyPara;
329 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
330 CERT_CHAIN_POLICY_STATUS policyStatus;
331 CERT_CHAIN_CONTEXT chainCopy;
332
333 /* Clear chain->TrustStatus.dwErrorStatus so
334 * CertVerifyCertificateChainPolicy will verify additional checks
335 * rather than stopping with an existing, ignored error.
336 */
337 memcpy(&chainCopy, chain, sizeof(chainCopy));
338 chainCopy.TrustStatus.dwErrorStatus = 0;
339 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
340 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
341 sslExtraPolicyPara.pwszServerName = server;
342 sslExtraPolicyPara.fdwChecks = security_flags;
343 policyPara.cbSize = sizeof(policyPara);
344 policyPara.dwFlags = 0;
345 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
346 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
347 &chainCopy, &policyPara,
348 &policyStatus );
349 /* Any error in the policy status indicates that the
350 * policy couldn't be verified.
351 */
352 if (ret && policyStatus.dwError)
353 {
354 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
355 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
356 else
357 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
358 }
359 }
360 CertFreeCertificateChain( chain );
361 }
362 else
363 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
364 TRACE("returning %08x\n", err);
365 return err;
366 }
367
368 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
369 {
370 SSL *ssl;
371 WCHAR *server;
372 BOOL ret = FALSE;
373 netconn_t *conn;
374 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
375 CERT_STORE_CREATE_NEW_FLAG, NULL );
376
377 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
378 server = pSSL_get_ex_data( ssl, hostname_idx );
379 conn = pSSL_get_ex_data( ssl, conn_idx );
380 if (store)
381 {
382 X509 *cert;
383 int i;
384 PCCERT_CONTEXT endCert = NULL;
385 struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
386
387 ret = TRUE;
388 for (i = 0; ret && i < psk_num(chain); i++)
389 {
390 PCCERT_CONTEXT context;
391
392 cert = (X509 *)psk_value(chain, i);
393 if ((context = X509_to_cert_context( cert )))
394 {
395 if (i == 0)
396 ret = CertAddCertificateContextToStore( store, context,
397 CERT_STORE_ADD_ALWAYS, &endCert );
398 else
399 ret = CertAddCertificateContextToStore( store, context,
400 CERT_STORE_ADD_ALWAYS, NULL );
401 CertFreeCertificateContext( context );
402 }
403 }
404 if (!endCert) ret = FALSE;
405 if (ret)
406 {
407 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
408 conn->security_flags );
409
410 if (err)
411 {
412 pSSL_set_ex_data( ssl, error_idx, (void *)err );
413 ret = FALSE;
414 }
415 }
416 CertFreeCertificateContext( endCert );
417 CertCloseStore( store, 0 );
418 }
419 return ret;
420 }
421 #endif
422
423 BOOL netconn_init( netconn_t *conn, BOOL secure )
424 {
425 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
426 int i;
427 #endif
428
429 conn->socket = -1;
430 if (!secure) return TRUE;
431
432 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
433 EnterCriticalSection( &init_ssl_cs );
434 if (libssl_handle)
435 {
436 LeaveCriticalSection( &init_ssl_cs );
437 return TRUE;
438 }
439 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
440 {
441 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
442 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
443 LeaveCriticalSection( &init_ssl_cs );
444 return FALSE;
445 }
446 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
447 {
448 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
449 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
450 LeaveCriticalSection( &init_ssl_cs );
451 return FALSE;
452 }
453 #define LOAD_FUNCPTR(x) \
454 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
455 { \
456 ERR("Failed to load symbol %s\n", #x); \
457 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
458 LeaveCriticalSection( &init_ssl_cs ); \
459 return FALSE; \
460 }
461 LOAD_FUNCPTR( SSL_library_init );
462 LOAD_FUNCPTR( SSL_load_error_strings );
463 LOAD_FUNCPTR( SSLv23_method );
464 LOAD_FUNCPTR( SSL_CTX_free );
465 LOAD_FUNCPTR( SSL_CTX_new );
466 LOAD_FUNCPTR( SSL_new );
467 LOAD_FUNCPTR( SSL_free );
468 LOAD_FUNCPTR( SSL_set_fd );
469 LOAD_FUNCPTR( SSL_connect );
470 LOAD_FUNCPTR( SSL_shutdown );
471 LOAD_FUNCPTR( SSL_write );
472 LOAD_FUNCPTR( SSL_read );
473 LOAD_FUNCPTR( SSL_pending );
474 LOAD_FUNCPTR( SSL_get_error );
475 LOAD_FUNCPTR( SSL_get_ex_new_index );
476 LOAD_FUNCPTR( SSL_get_ex_data );
477 LOAD_FUNCPTR( SSL_set_ex_data );
478 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
479 LOAD_FUNCPTR( SSL_get_peer_certificate );
480 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
481 LOAD_FUNCPTR( SSL_CTX_set_verify );
482 LOAD_FUNCPTR( SSL_get_current_cipher );
483 LOAD_FUNCPTR( SSL_CIPHER_get_bits );
484 #undef LOAD_FUNCPTR
485
486 #define LOAD_FUNCPTR(x) \
487 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
488 { \
489 ERR("Failed to load symbol %s\n", #x); \
490 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
491 LeaveCriticalSection( &init_ssl_cs ); \
492 return FALSE; \
493 }
494 LOAD_FUNCPTR( CRYPTO_num_locks );
495 LOAD_FUNCPTR( CRYPTO_set_id_callback );
496 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
497 LOAD_FUNCPTR( ERR_free_strings );
498 LOAD_FUNCPTR( ERR_get_error );
499 LOAD_FUNCPTR( ERR_error_string );
500 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
501 LOAD_FUNCPTR( X509_STORE_CTX_get_chain );
502 LOAD_FUNCPTR( i2d_X509 );
503 LOAD_FUNCPTR( sk_value );
504 LOAD_FUNCPTR( sk_num );
505 #undef LOAD_FUNCPTR
506
507 pSSL_library_init();
508 pSSL_load_error_strings();
509
510 method = pSSLv23_method();
511 ctx = pSSL_CTX_new( method );
512 if (!pSSL_CTX_set_default_verify_paths( ctx ))
513 {
514 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
515 set_last_error( ERROR_OUTOFMEMORY );
516 LeaveCriticalSection( &init_ssl_cs );
517 return FALSE;
518 }
519 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
520 if (hostname_idx == -1)
521 {
522 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
523 set_last_error( ERROR_OUTOFMEMORY );
524 LeaveCriticalSection( &init_ssl_cs );
525 return FALSE;
526 }
527 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
528 if (error_idx == -1)
529 {
530 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
531 set_last_error( ERROR_OUTOFMEMORY );
532 LeaveCriticalSection( &init_ssl_cs );
533 return FALSE;
534 }
535 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
536 if (conn_idx == -1)
537 {
538 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
539 set_last_error( ERROR_OUTOFMEMORY );
540 LeaveCriticalSection( &init_ssl_cs );
541 return FALSE;
542 }
543 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
544
545 pCRYPTO_set_id_callback(ssl_thread_id);
546 num_ssl_locks = pCRYPTO_num_locks();
547 ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
548 if (!ssl_locks)
549 {
550 set_last_error( ERROR_OUTOFMEMORY );
551 LeaveCriticalSection( &init_ssl_cs );
552 return FALSE;
553 }
554 for (i = 0; i < num_ssl_locks; i++)
555 {
556 InitializeCriticalSection( &ssl_locks[i] );
557 ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
558 }
559 pCRYPTO_set_locking_callback(ssl_lock_callback);
560
561 LeaveCriticalSection( &init_ssl_cs );
562 #else
563 WARN("SSL support not compiled in.\n");
564 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
565 return FALSE;
566 #endif
567 return TRUE;
568 }
569
570 void netconn_unload( void )
571 {
572 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
573 if (libcrypto_handle)
574 {
575 pERR_free_strings();
576 wine_dlclose( libcrypto_handle, NULL, 0 );
577 }
578 if (libssl_handle)
579 {
580 if (ctx)
581 pSSL_CTX_free( ctx );
582 wine_dlclose( libssl_handle, NULL, 0 );
583 }
584 if (ssl_locks)
585 {
586 int i;
587 for (i = 0; i < num_ssl_locks; i++)
588 {
589 ssl_locks[i].DebugInfo->Spare[0] = 0;
590 DeleteCriticalSection( &ssl_locks[i] );
591 }
592 heap_free( ssl_locks );
593 }
594 DeleteCriticalSection(&init_ssl_cs);
595 #endif
596 #ifndef HAVE_GETADDRINFO
597 DeleteCriticalSection(&cs_gethostbyname);
598 #endif
599 }
600
601 BOOL netconn_connected( netconn_t *conn )
602 {
603 return (conn->socket != -1);
604 }
605
606 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
607 {
608 if ((conn->socket = socket( domain, type, protocol )) == -1)
609 {
610 WARN("unable to create socket (%s)\n", strerror(errno));
611 set_last_error( sock_get_error( errno ) );
612 return FALSE;
613 }
614 return TRUE;
615 }
616
617 BOOL netconn_close( netconn_t *conn )
618 {
619 int res;
620
621 #ifdef SONAME_LIBSSL
622 if (conn->secure)
623 {
624 heap_free( conn->peek_msg_mem );
625 conn->peek_msg_mem = NULL;
626 conn->peek_msg = NULL;
627 conn->peek_len = 0;
628
629 pSSL_shutdown( conn->ssl_conn );
630 pSSL_free( conn->ssl_conn );
631
632 conn->ssl_conn = NULL;
633 conn->secure = FALSE;
634 }
635 #endif
636 res = closesocket( conn->socket );
637 conn->socket = -1;
638 if (res == -1)
639 {
640 set_last_error( sock_get_error( errno ) );
641 return FALSE;
642 }
643 return TRUE;
644 }
645
646 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
647 {
648 BOOL ret = FALSE;
649 int res = 0, state;
650
651 if (timeout > 0)
652 {
653 state = 1;
654 ioctlsocket( conn->socket, FIONBIO, &state );
655 }
656 if (connect( conn->socket, sockaddr, addr_len ) < 0)
657 {
658 res = sock_get_error( errno );
659 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
660 {
661 // ReactOS: use select instead of poll
662 fd_set outfd;
663 struct timeval tv;
664
665 FD_ZERO(&outfd);
666 FD_SET(conn->socket, &outfd);
667
668 tv.tv_sec = 0;
669 tv.tv_usec = timeout * 1000;
670
671 if (select( 0, NULL, &outfd, NULL, &tv ) > 0)
672 ret = TRUE;
673 else
674 res = sock_get_error( errno );
675 }
676 }
677 else
678 ret = TRUE;
679 if (timeout > 0)
680 {
681 state = 0;
682 ioctlsocket( conn->socket, FIONBIO, &state );
683 }
684 if (!ret)
685 {
686 WARN("unable to connect to host (%d)\n", res);
687 set_last_error( res );
688 }
689 return ret;
690 }
691
692 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
693 {
694 #ifdef SONAME_LIBSSL
695 if (!(conn->ssl_conn = pSSL_new( ctx )))
696 {
697 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
698 set_last_error( ERROR_OUTOFMEMORY );
699 goto fail;
700 }
701 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
702 {
703 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
704 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
705 goto fail;
706 }
707 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
708 {
709 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
710 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
711 return FALSE;
712 }
713 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
714 {
715 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
716 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
717 goto fail;
718 }
719 if (pSSL_connect( conn->ssl_conn ) <= 0)
720 {
721 DWORD err;
722
723 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
724 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
725 ERR("couldn't verify server certificate (%d)\n", err);
726 set_last_error( err );
727 goto fail;
728 }
729 TRACE("established SSL connection\n");
730 conn->secure = TRUE;
731 return TRUE;
732
733 fail:
734 if (conn->ssl_conn)
735 {
736 pSSL_shutdown( conn->ssl_conn );
737 pSSL_free( conn->ssl_conn );
738 conn->ssl_conn = NULL;
739 }
740 #endif
741 return FALSE;
742 }
743
744 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
745 {
746 if (!netconn_connected( conn )) return FALSE;
747 if (conn->secure)
748 {
749 #ifdef SONAME_LIBSSL
750 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
751 *sent = pSSL_write( conn->ssl_conn, msg, len );
752 if (*sent < 1 && len) return FALSE;
753 return TRUE;
754 #else
755 return FALSE;
756 #endif
757 }
758 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
759 {
760 set_last_error( sock_get_error( errno ) );
761 return FALSE;
762 }
763 return TRUE;
764 }
765
766 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
767 {
768 *recvd = 0;
769 if (!netconn_connected( conn )) return FALSE;
770 if (!len) return TRUE;
771
772 if (conn->secure)
773 {
774 #ifdef SONAME_LIBSSL
775 int ret;
776
777 if (flags & ~(MSG_PEEK | MSG_WAITALL))
778 FIXME("SSL_read does not support the following flags: %08x\n", flags);
779
780 /* this ugly hack is all for MSG_PEEK */
781 if (flags & MSG_PEEK && !conn->peek_msg)
782 {
783 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
784 }
785 else if (flags & MSG_PEEK && conn->peek_msg)
786 {
787 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
788 *recvd = min( len, conn->peek_len );
789 memcpy( buf, conn->peek_msg, *recvd );
790 return TRUE;
791 }
792 else if (conn->peek_msg)
793 {
794 *recvd = min( len, conn->peek_len );
795 memcpy( buf, conn->peek_msg, *recvd );
796 conn->peek_len -= *recvd;
797 conn->peek_msg += *recvd;
798
799 if (conn->peek_len == 0)
800 {
801 heap_free( conn->peek_msg_mem );
802 conn->peek_msg_mem = NULL;
803 conn->peek_msg = NULL;
804 }
805 /* check if we have enough data from the peek buffer */
806 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
807 }
808 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
809 if (ret < 0)
810 return FALSE;
811
812 /* check if EOF was received */
813 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
814 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
815 {
816 netconn_close( conn );
817 return TRUE;
818 }
819 if (flags & MSG_PEEK) /* must copy into buffer */
820 {
821 conn->peek_len = ret;
822 if (!ret)
823 {
824 heap_free( conn->peek_msg_mem );
825 conn->peek_msg_mem = NULL;
826 conn->peek_msg = NULL;
827 }
828 else memcpy( conn->peek_msg, buf, ret );
829 }
830 *recvd += ret;
831 return TRUE;
832 #else
833 return FALSE;
834 #endif
835 }
836 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
837 {
838 set_last_error( sock_get_error( errno ) );
839 return FALSE;
840 }
841 return TRUE;
842 }
843
844 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
845 {
846 #ifdef FIONREAD
847 int ret, unread;
848 #endif
849 *available = 0;
850 if (!netconn_connected( conn )) return FALSE;
851
852 if (conn->secure)
853 {
854 #ifdef SONAME_LIBSSL
855 *available = pSSL_pending( conn->ssl_conn ) + conn->peek_len;
856 #endif
857 return TRUE;
858 }
859 #ifdef FIONREAD
860 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
861 #endif
862 return TRUE;
863 }
864
865 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
866 {
867 // ReactOS: use select instead of poll
868 fd_set infd;
869 BOOL ret = FALSE;
870 DWORD recvd = 0;
871
872 if (!netconn_connected( conn )) return FALSE;
873
874 if (conn->secure)
875 {
876 #ifdef SONAME_LIBSSL
877 while (recvd < *buflen)
878 {
879 int dummy;
880 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
881 {
882 set_last_error( ERROR_CONNECTION_ABORTED );
883 break;
884 }
885 if (buffer[recvd] == '\n')
886 {
887 ret = TRUE;
888 break;
889 }
890 if (buffer[recvd] != '\r') recvd++;
891 }
892 if (ret)
893 {
894 buffer[recvd++] = 0;
895 *buflen = recvd;
896 TRACE("received line %s\n", debugstr_a(buffer));
897 }
898 return ret;
899 #else
900 return FALSE;
901 #endif
902 }
903
904 FD_ZERO(&infd);
905 FD_SET(conn->socket, &infd);
906
907 while (recvd < *buflen)
908 {
909 int res;
910 struct timeval tv, *ptv;
911 socklen_t len = sizeof(tv);
912
913 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
914 ptv = &tv;
915 else
916 ptv = NULL;
917
918 if (select( 0, &infd, NULL, NULL, ptv ) > 0)
919 {
920 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
921 {
922 if (res == -1) set_last_error( sock_get_error( errno ) );
923 break;
924 }
925 if (buffer[recvd] == '\n')
926 {
927 ret = TRUE;
928 break;
929 }
930 if (buffer[recvd] != '\r') recvd++;
931 }
932 else
933 {
934 set_last_error( ERROR_WINHTTP_TIMEOUT );
935 break;
936 }
937 }
938 if (ret)
939 {
940 buffer[recvd++] = 0;
941 *buflen = recvd;
942 TRACE("received line %s\n", debugstr_a(buffer));
943 }
944 return ret;
945 }
946
947 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
948 {
949 int res;
950 struct timeval tv;
951
952 /* value is in milliseconds, convert to struct timeval */
953 tv.tv_sec = value / 1000;
954 tv.tv_usec = (value % 1000) * 1000;
955
956 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
957 {
958 WARN("setsockopt failed (%s)\n", strerror( errno ));
959 return sock_get_error( errno );
960 }
961 return ERROR_SUCCESS;
962 }
963
964 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
965 {
966 char *hostname;
967 #ifdef HAVE_GETADDRINFO
968 struct addrinfo *res, hints;
969 int ret;
970 #else
971 struct hostent *he;
972 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
973 #endif
974
975 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
976
977 #ifdef HAVE_GETADDRINFO
978 memset( &hints, 0, sizeof(struct addrinfo) );
979 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
980 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
981 */
982 hints.ai_family = AF_INET;
983
984 ret = getaddrinfo( hostname, NULL, &hints, &res );
985 if (ret != 0)
986 {
987 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
988 hints.ai_family = AF_INET6;
989 ret = getaddrinfo( hostname, NULL, &hints, &res );
990 if (ret != 0)
991 {
992 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
993 heap_free( hostname );
994 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
995 }
996 }
997 heap_free( hostname );
998 if (*sa_len < res->ai_addrlen)
999 {
1000 WARN("address too small\n");
1001 freeaddrinfo( res );
1002 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
1003 }
1004 *sa_len = res->ai_addrlen;
1005 memcpy( sa, res->ai_addr, res->ai_addrlen );
1006 /* Copy port */
1007 switch (res->ai_family)
1008 {
1009 case AF_INET:
1010 ((struct sockaddr_in *)sa)->sin_port = htons( port );
1011 break;
1012 case AF_INET6:
1013 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
1014 break;
1015 }
1016
1017 freeaddrinfo( res );
1018 return ERROR_SUCCESS;
1019 #else
1020 EnterCriticalSection( &cs_gethostbyname );
1021
1022 he = gethostbyname( hostname );
1023 heap_free( hostname );
1024 if (!he)
1025 {
1026 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
1027 LeaveCriticalSection( &cs_gethostbyname );
1028 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
1029 }
1030 if (*sa_len < sizeof(struct sockaddr_in))
1031 {
1032 WARN("address too small\n");
1033 LeaveCriticalSection( &cs_gethostbyname );
1034 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
1035 }
1036 *sa_len = sizeof(struct sockaddr_in);
1037 memset( sa, 0, sizeof(struct sockaddr_in) );
1038 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
1039 sin->sin_family = he->h_addrtype;
1040 sin->sin_port = htons( port );
1041
1042 LeaveCriticalSection( &cs_gethostbyname );
1043 return ERROR_SUCCESS;
1044 #endif
1045 }
1046
1047 struct resolve_args
1048 {
1049 WCHAR *hostname;
1050 INTERNET_PORT port;
1051 struct sockaddr *sa;
1052 socklen_t *sa_len;
1053 };
1054
1055 static DWORD CALLBACK resolve_proc( LPVOID arg )
1056 {
1057 struct resolve_args *ra = arg;
1058 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1059 }
1060
1061 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1062 {
1063 DWORD ret;
1064
1065 if (timeout)
1066 {
1067 DWORD status;
1068 HANDLE thread;
1069 struct resolve_args ra;
1070
1071 ra.hostname = hostname;
1072 ra.port = port;
1073 ra.sa = sa;
1074 ra.sa_len = sa_len;
1075
1076 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1077 if (!thread) return FALSE;
1078
1079 status = WaitForSingleObject( thread, timeout );
1080 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1081 else ret = ERROR_WINHTTP_TIMEOUT;
1082 CloseHandle( thread );
1083 }
1084 else ret = resolve_hostname( hostname, port, sa, sa_len );
1085
1086 if (ret)
1087 {
1088 set_last_error( ret );
1089 return FALSE;
1090 }
1091 return TRUE;
1092 }
1093
1094 const void *netconn_get_certificate( netconn_t *conn )
1095 {
1096 #ifdef SONAME_LIBSSL
1097 X509 *cert;
1098 const CERT_CONTEXT *ret;
1099
1100 if (!conn->secure) return NULL;
1101
1102 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1103 ret = X509_to_cert_context( cert );
1104 return ret;
1105 #else
1106 return NULL;
1107 #endif
1108 }
1109
1110 int netconn_get_cipher_strength( netconn_t *conn )
1111 {
1112 #ifdef SONAME_LIBSSL
1113 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1114 const SSL_CIPHER *cipher;
1115 #else
1116 SSL_CIPHER *cipher;
1117 #endif
1118 int bits = 0;
1119
1120 if (!conn->secure) return 0;
1121 if (!(cipher = pSSL_get_current_cipher( conn->ssl_conn ))) return 0;
1122 pSSL_CIPHER_get_bits( cipher, &bits );
1123 return bits;
1124 #else
1125 return 0;
1126 #endif
1127 }