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