winhttp: Return error directly from netconn_verify_cert.
[wine/wine-gecko.git] / dlls / winhttp / net.c
blob588b11bfe8659899c20207a693f26ab87e350472
1 /*
2 * Copyright 2008 Hans Leidekker for CodeWeavers
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.
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.
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
19 #include "config.h"
20 #include "wine/port.h"
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
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 #undef FAR
42 #undef DSA
43 #endif
45 #define NONAMELESSUNION
47 #include "wine/debug.h"
48 #include "wine/library.h"
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winhttp.h"
53 #include "wincrypt.h"
55 #include "winhttp_private.h"
57 /* to avoid conflicts with the Unix socket headers */
58 #define USE_WS_PREFIX
59 #include "winsock2.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
63 #ifndef HAVE_GETADDRINFO
65 /* critical section to protect non-reentrant gethostbyname() */
66 static CRITICAL_SECTION cs_gethostbyname;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
69 0, 0, &cs_gethostbyname,
70 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
73 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
75 #endif
77 #ifdef SONAME_LIBSSL
79 #include <openssl/err.h>
81 static CRITICAL_SECTION init_ssl_cs;
82 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
84 0, 0, &init_ssl_cs,
85 { &init_ssl_cs_debug.ProcessLocksList,
86 &init_ssl_cs_debug.ProcessLocksList },
87 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
89 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
91 static void *libssl_handle;
92 static void *libcrypto_handle;
94 static SSL_METHOD *method;
95 static SSL_CTX *ctx;
96 static int hostname_idx;
98 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
100 MAKE_FUNCPTR( SSL_library_init );
101 MAKE_FUNCPTR( SSL_load_error_strings );
102 MAKE_FUNCPTR( SSLv23_method );
103 MAKE_FUNCPTR( SSL_CTX_free );
104 MAKE_FUNCPTR( SSL_CTX_new );
105 MAKE_FUNCPTR( SSL_new );
106 MAKE_FUNCPTR( SSL_free );
107 MAKE_FUNCPTR( SSL_set_fd );
108 MAKE_FUNCPTR( SSL_connect );
109 MAKE_FUNCPTR( SSL_shutdown );
110 MAKE_FUNCPTR( SSL_write );
111 MAKE_FUNCPTR( SSL_read );
112 MAKE_FUNCPTR( SSL_get_ex_new_index );
113 MAKE_FUNCPTR( SSL_get_ex_data );
114 MAKE_FUNCPTR( SSL_set_ex_data );
115 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
116 MAKE_FUNCPTR( SSL_get_verify_result );
117 MAKE_FUNCPTR( SSL_get_peer_certificate );
118 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
119 MAKE_FUNCPTR( SSL_CTX_set_verify );
121 MAKE_FUNCPTR( CRYPTO_num_locks );
122 MAKE_FUNCPTR( CRYPTO_set_id_callback );
123 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
124 MAKE_FUNCPTR( ERR_free_strings );
125 MAKE_FUNCPTR( ERR_get_error );
126 MAKE_FUNCPTR( ERR_error_string );
127 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
128 MAKE_FUNCPTR( i2d_X509 );
129 MAKE_FUNCPTR( sk_value );
130 MAKE_FUNCPTR( sk_num );
131 #undef MAKE_FUNCPTR
133 static CRITICAL_SECTION *ssl_locks;
134 static unsigned int num_ssl_locks;
136 static unsigned long ssl_thread_id(void)
138 return GetCurrentThreadId();
141 static void ssl_lock_callback(int mode, int type, const char *file, int line)
143 if (mode & CRYPTO_LOCK)
144 EnterCriticalSection( &ssl_locks[type] );
145 else
146 LeaveCriticalSection( &ssl_locks[type] );
149 #endif
151 /* translate a unix error code into a winsock error code */
152 static int sock_get_error( int err )
154 #if !defined(__MINGW32__) && !defined (_MSC_VER)
155 switch (err)
157 case EINTR: return WSAEINTR;
158 case EBADF: return WSAEBADF;
159 case EPERM:
160 case EACCES: return WSAEACCES;
161 case EFAULT: return WSAEFAULT;
162 case EINVAL: return WSAEINVAL;
163 case EMFILE: return WSAEMFILE;
164 case EWOULDBLOCK: return WSAEWOULDBLOCK;
165 case EINPROGRESS: return WSAEINPROGRESS;
166 case EALREADY: return WSAEALREADY;
167 case ENOTSOCK: return WSAENOTSOCK;
168 case EDESTADDRREQ: return WSAEDESTADDRREQ;
169 case EMSGSIZE: return WSAEMSGSIZE;
170 case EPROTOTYPE: return WSAEPROTOTYPE;
171 case ENOPROTOOPT: return WSAENOPROTOOPT;
172 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
173 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
174 case EOPNOTSUPP: return WSAEOPNOTSUPP;
175 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
176 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
177 case EADDRINUSE: return WSAEADDRINUSE;
178 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
179 case ENETDOWN: return WSAENETDOWN;
180 case ENETUNREACH: return WSAENETUNREACH;
181 case ENETRESET: return WSAENETRESET;
182 case ECONNABORTED: return WSAECONNABORTED;
183 case EPIPE:
184 case ECONNRESET: return WSAECONNRESET;
185 case ENOBUFS: return WSAENOBUFS;
186 case EISCONN: return WSAEISCONN;
187 case ENOTCONN: return WSAENOTCONN;
188 case ESHUTDOWN: return WSAESHUTDOWN;
189 case ETOOMANYREFS: return WSAETOOMANYREFS;
190 case ETIMEDOUT: return WSAETIMEDOUT;
191 case ECONNREFUSED: return WSAECONNREFUSED;
192 case ELOOP: return WSAELOOP;
193 case ENAMETOOLONG: return WSAENAMETOOLONG;
194 case EHOSTDOWN: return WSAEHOSTDOWN;
195 case EHOSTUNREACH: return WSAEHOSTUNREACH;
196 case ENOTEMPTY: return WSAENOTEMPTY;
197 #ifdef EPROCLIM
198 case EPROCLIM: return WSAEPROCLIM;
199 #endif
200 #ifdef EUSERS
201 case EUSERS: return WSAEUSERS;
202 #endif
203 #ifdef EDQUOT
204 case EDQUOT: return WSAEDQUOT;
205 #endif
206 #ifdef ESTALE
207 case ESTALE: return WSAESTALE;
208 #endif
209 #ifdef EREMOTE
210 case EREMOTE: return WSAEREMOTE;
211 #endif
212 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
214 #endif
215 return err;
218 #ifdef SONAME_LIBSSL
219 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
221 unsigned char *buffer, *p;
222 int len;
223 BOOL malloc = FALSE;
224 PCCERT_CONTEXT ret;
226 p = NULL;
227 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
229 * SSL 0.9.7 and above malloc the buffer if it is null.
230 * however earlier version do not and so we would need to alloc the buffer.
232 * see the i2d_X509 man page for more details.
234 if (!p)
236 if (!(buffer = heap_alloc( len ))) return NULL;
237 p = buffer;
238 len = pi2d_X509( cert, &p );
240 else
242 buffer = p;
243 malloc = TRUE;
246 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
248 if (malloc) free( buffer );
249 else heap_free( buffer );
251 return ret;
254 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
255 WCHAR *server )
257 BOOL ret;
258 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
259 PCCERT_CHAIN_CONTEXT chain;
260 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
261 char *server_auth[] = { oid_server_auth };
262 DWORD err = ERROR_SUCCESS;
264 TRACE("verifying %s\n", debugstr_w( server ));
265 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
266 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
267 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
268 NULL, &chain )))
270 if (chain->TrustStatus.dwErrorStatus)
272 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
273 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
274 else if (chain->TrustStatus.dwErrorStatus &
275 CERT_TRUST_IS_UNTRUSTED_ROOT)
276 err = ERROR_WINHTTP_SECURE_INVALID_CA;
277 else if ((chain->TrustStatus.dwErrorStatus &
278 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
279 (chain->TrustStatus.dwErrorStatus &
280 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
281 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
282 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
283 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
284 else if (chain->TrustStatus.dwErrorStatus &
285 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
286 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
287 else
288 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
290 else
292 CERT_CHAIN_POLICY_PARA policyPara;
293 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
294 CERT_CHAIN_POLICY_STATUS policyStatus;
296 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
297 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
298 sslExtraPolicyPara.pwszServerName = server;
299 policyPara.cbSize = sizeof(policyPara);
300 policyPara.dwFlags = 0;
301 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
302 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
303 chain, &policyPara,
304 &policyStatus );
305 /* Any error in the policy status indicates that the
306 * policy couldn't be verified.
308 if (ret && policyStatus.dwError)
310 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
311 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
312 else
313 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
316 CertFreeCertificateChain( chain );
318 else
319 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
320 TRACE("returning %08x\n", err);
321 return err;
324 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
326 SSL *ssl;
327 WCHAR *server;
328 BOOL ret = FALSE;
330 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
331 server = pSSL_get_ex_data( ssl, hostname_idx );
332 if (preverify_ok)
334 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
335 CERT_STORE_CREATE_NEW_FLAG, NULL );
337 if (store)
339 X509 *cert;
340 int i;
341 PCCERT_CONTEXT endCert = NULL;
343 ret = TRUE;
344 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
346 PCCERT_CONTEXT context;
348 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
349 if ((context = X509_to_cert_context( cert )))
351 if (i == 0)
352 ret = CertAddCertificateContextToStore( store, context,
353 CERT_STORE_ADD_ALWAYS, &endCert );
354 else
355 ret = CertAddCertificateContextToStore( store, context,
356 CERT_STORE_ADD_ALWAYS, NULL );
357 CertFreeCertificateContext( context );
360 if (!endCert) ret = FALSE;
361 if (ret)
363 DWORD err = netconn_verify_cert( endCert, store, server );
365 if (err)
367 set_last_error( err );
368 ret = FALSE;
371 CertFreeCertificateContext( endCert );
372 CertCloseStore( store, 0 );
375 return ret;
377 #endif
379 BOOL netconn_init( netconn_t *conn, BOOL secure )
381 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
382 int i;
383 #endif
385 conn->socket = -1;
386 if (!secure) return TRUE;
388 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
389 EnterCriticalSection( &init_ssl_cs );
390 if (libssl_handle)
392 LeaveCriticalSection( &init_ssl_cs );
393 return TRUE;
395 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
397 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
398 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
399 LeaveCriticalSection( &init_ssl_cs );
400 return FALSE;
402 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
404 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
405 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
406 LeaveCriticalSection( &init_ssl_cs );
407 return FALSE;
409 #define LOAD_FUNCPTR(x) \
410 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
412 ERR("Failed to load symbol %s\n", #x); \
413 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
414 LeaveCriticalSection( &init_ssl_cs ); \
415 return FALSE; \
417 LOAD_FUNCPTR( SSL_library_init );
418 LOAD_FUNCPTR( SSL_load_error_strings );
419 LOAD_FUNCPTR( SSLv23_method );
420 LOAD_FUNCPTR( SSL_CTX_free );
421 LOAD_FUNCPTR( SSL_CTX_new );
422 LOAD_FUNCPTR( SSL_new );
423 LOAD_FUNCPTR( SSL_free );
424 LOAD_FUNCPTR( SSL_set_fd );
425 LOAD_FUNCPTR( SSL_connect );
426 LOAD_FUNCPTR( SSL_shutdown );
427 LOAD_FUNCPTR( SSL_write );
428 LOAD_FUNCPTR( SSL_read );
429 LOAD_FUNCPTR( SSL_get_ex_new_index );
430 LOAD_FUNCPTR( SSL_get_ex_data );
431 LOAD_FUNCPTR( SSL_set_ex_data );
432 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
433 LOAD_FUNCPTR( SSL_get_verify_result );
434 LOAD_FUNCPTR( SSL_get_peer_certificate );
435 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
436 LOAD_FUNCPTR( SSL_CTX_set_verify );
437 #undef LOAD_FUNCPTR
439 #define LOAD_FUNCPTR(x) \
440 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
442 ERR("Failed to load symbol %s\n", #x); \
443 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
444 LeaveCriticalSection( &init_ssl_cs ); \
445 return FALSE; \
447 LOAD_FUNCPTR( CRYPTO_num_locks );
448 LOAD_FUNCPTR( CRYPTO_set_id_callback );
449 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
450 LOAD_FUNCPTR( ERR_free_strings );
451 LOAD_FUNCPTR( ERR_get_error );
452 LOAD_FUNCPTR( ERR_error_string );
453 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
454 LOAD_FUNCPTR( i2d_X509 );
455 LOAD_FUNCPTR( sk_value );
456 LOAD_FUNCPTR( sk_num );
457 #undef LOAD_FUNCPTR
459 pSSL_library_init();
460 pSSL_load_error_strings();
462 method = pSSLv23_method();
463 ctx = pSSL_CTX_new( method );
464 if (!pSSL_CTX_set_default_verify_paths( ctx ))
466 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
467 set_last_error( ERROR_OUTOFMEMORY );
468 LeaveCriticalSection( &init_ssl_cs );
469 return FALSE;
471 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
472 if (hostname_idx == -1)
474 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
475 set_last_error( ERROR_OUTOFMEMORY );
476 LeaveCriticalSection( &init_ssl_cs );
477 return FALSE;
479 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
481 pCRYPTO_set_id_callback(ssl_thread_id);
482 num_ssl_locks = pCRYPTO_num_locks();
483 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
484 if (!ssl_locks)
486 set_last_error( ERROR_OUTOFMEMORY );
487 LeaveCriticalSection( &init_ssl_cs );
488 return FALSE;
490 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
491 pCRYPTO_set_locking_callback(ssl_lock_callback);
493 LeaveCriticalSection( &init_ssl_cs );
494 #else
495 WARN("SSL support not compiled in.\n");
496 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
497 return FALSE;
498 #endif
499 return TRUE;
502 void netconn_unload( void )
504 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
505 if (libcrypto_handle)
507 pERR_free_strings();
508 wine_dlclose( libcrypto_handle, NULL, 0 );
510 if (libssl_handle)
512 if (ctx)
513 pSSL_CTX_free( ctx );
514 wine_dlclose( libssl_handle, NULL, 0 );
516 if (ssl_locks)
518 int i;
519 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
520 HeapFree( GetProcessHeap(), 0, ssl_locks );
522 #endif
525 BOOL netconn_connected( netconn_t *conn )
527 return (conn->socket != -1);
530 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
532 if ((conn->socket = socket( domain, type, protocol )) == -1)
534 WARN("unable to create socket (%s)\n", strerror(errno));
535 set_last_error( sock_get_error( errno ) );
536 return FALSE;
538 return TRUE;
541 BOOL netconn_close( netconn_t *conn )
543 int res;
545 #ifdef SONAME_LIBSSL
546 if (conn->secure)
548 heap_free( conn->peek_msg_mem );
549 conn->peek_msg_mem = NULL;
550 conn->peek_msg = NULL;
551 conn->peek_len = 0;
553 pSSL_shutdown( conn->ssl_conn );
554 pSSL_free( conn->ssl_conn );
556 conn->ssl_conn = NULL;
557 conn->secure = FALSE;
559 #endif
560 res = closesocket( conn->socket );
561 conn->socket = -1;
562 if (res == -1)
564 set_last_error( sock_get_error( errno ) );
565 return FALSE;
567 return TRUE;
570 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
572 BOOL ret = FALSE;
573 int res = 0, state;
575 if (timeout > 0)
577 state = 1;
578 ioctlsocket( conn->socket, FIONBIO, &state );
580 if (connect( conn->socket, sockaddr, addr_len ) < 0)
582 res = sock_get_error( errno );
583 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
585 struct pollfd pfd;
587 pfd.fd = conn->socket;
588 pfd.events = POLLOUT;
589 if (poll( &pfd, 1, timeout ) > 0)
590 ret = TRUE;
591 else
592 res = sock_get_error( errno );
595 else
596 ret = TRUE;
597 if (timeout > 0)
599 state = 0;
600 ioctlsocket( conn->socket, FIONBIO, &state );
602 if (!ret)
604 WARN("unable to connect to host (%d)\n", res);
605 set_last_error( res );
607 return ret;
610 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
612 #ifdef SONAME_LIBSSL
613 long res;
615 if (!(conn->ssl_conn = pSSL_new( ctx )))
617 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
618 set_last_error( ERROR_OUTOFMEMORY );
619 goto fail;
621 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
623 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
624 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
625 goto fail;
627 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
629 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
630 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
631 goto fail;
633 if (pSSL_connect( conn->ssl_conn ) <= 0)
635 ERR("SSL_connect failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
636 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
637 goto fail;
639 if ((res = pSSL_get_verify_result( conn->ssl_conn )) != X509_V_OK)
641 /* FIXME: we should set an error and return, but we only print an error at the moment */
642 ERR("couldn't verify server certificate (%ld)\n", res);
644 TRACE("established SSL connection\n");
645 conn->secure = TRUE;
646 return TRUE;
648 fail:
649 if (conn->ssl_conn)
651 pSSL_shutdown( conn->ssl_conn );
652 pSSL_free( conn->ssl_conn );
653 conn->ssl_conn = NULL;
655 #endif
656 return FALSE;
659 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
661 if (!netconn_connected( conn )) return FALSE;
662 if (conn->secure)
664 #ifdef SONAME_LIBSSL
665 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
666 *sent = pSSL_write( conn->ssl_conn, msg, len );
667 if (*sent < 1 && len) return FALSE;
668 return TRUE;
669 #else
670 return FALSE;
671 #endif
673 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
675 set_last_error( sock_get_error( errno ) );
676 return FALSE;
678 return TRUE;
681 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
683 *recvd = 0;
684 if (!netconn_connected( conn )) return FALSE;
685 if (!len) return TRUE;
687 if (conn->secure)
689 #ifdef SONAME_LIBSSL
690 if (flags & ~(MSG_PEEK | MSG_WAITALL))
691 FIXME("SSL_read does not support the following flags: %08x\n", flags);
693 /* this ugly hack is all for MSG_PEEK */
694 if (flags & MSG_PEEK && !conn->peek_msg)
696 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
698 else if (flags & MSG_PEEK && conn->peek_msg)
700 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
701 *recvd = min( len, conn->peek_len );
702 memcpy( buf, conn->peek_msg, *recvd );
703 return TRUE;
705 else if (conn->peek_msg)
707 *recvd = min( len, conn->peek_len );
708 memcpy( buf, conn->peek_msg, *recvd );
709 conn->peek_len -= *recvd;
710 conn->peek_msg += *recvd;
712 if (conn->peek_len == 0)
714 heap_free( conn->peek_msg_mem );
715 conn->peek_msg_mem = NULL;
716 conn->peek_msg = NULL;
718 /* check if we have enough data from the peek buffer */
719 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
721 *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
722 if (flags & MSG_PEEK) /* must copy into buffer */
724 conn->peek_len = *recvd;
725 if (!*recvd)
727 heap_free( conn->peek_msg_mem );
728 conn->peek_msg_mem = NULL;
729 conn->peek_msg = NULL;
731 else memcpy( conn->peek_msg, buf, *recvd );
733 if (*recvd < 1 && len) return FALSE;
734 return TRUE;
735 #else
736 return FALSE;
737 #endif
739 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
741 set_last_error( sock_get_error( errno ) );
742 return FALSE;
744 return TRUE;
747 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
749 #ifdef FIONREAD
750 int ret, unread;
751 #endif
752 *available = 0;
753 if (!netconn_connected( conn )) return FALSE;
755 if (conn->secure)
757 #ifdef SONAME_LIBSSL
758 if (conn->peek_msg) *available = conn->peek_len;
759 #endif
760 return TRUE;
762 #ifdef FIONREAD
763 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
764 #endif
765 return TRUE;
768 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
770 struct pollfd pfd;
771 BOOL ret = FALSE;
772 DWORD recvd = 0;
774 if (!netconn_connected( conn )) return FALSE;
776 if (conn->secure)
778 #ifdef SONAME_LIBSSL
779 while (recvd < *buflen)
781 int dummy;
782 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
784 set_last_error( ERROR_CONNECTION_ABORTED );
785 break;
787 if (buffer[recvd] == '\n')
789 ret = TRUE;
790 break;
792 if (buffer[recvd] != '\r') recvd++;
794 if (ret)
796 buffer[recvd++] = 0;
797 *buflen = recvd;
798 TRACE("received line %s\n", debugstr_a(buffer));
800 return ret;
801 #else
802 return FALSE;
803 #endif
806 pfd.fd = conn->socket;
807 pfd.events = POLLIN;
808 while (recvd < *buflen)
810 int timeout, res;
811 struct timeval tv;
812 socklen_t len = sizeof(tv);
814 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
815 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
816 else
817 timeout = -1;
818 if (poll( &pfd, 1, timeout ) > 0)
820 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
822 if (res == -1) set_last_error( sock_get_error( errno ) );
823 break;
825 if (buffer[recvd] == '\n')
827 ret = TRUE;
828 break;
830 if (buffer[recvd] != '\r') recvd++;
832 else
834 set_last_error( ERROR_WINHTTP_TIMEOUT );
835 break;
838 if (ret)
840 buffer[recvd++] = 0;
841 *buflen = recvd;
842 TRACE("received line %s\n", debugstr_a(buffer));
844 return ret;
847 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
849 int res;
850 struct timeval tv;
852 /* value is in milliseconds, convert to struct timeval */
853 tv.tv_sec = value / 1000;
854 tv.tv_usec = (value % 1000) * 1000;
856 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
858 WARN("setsockopt failed (%s)\n", strerror( errno ));
859 return sock_get_error( errno );
861 return ERROR_SUCCESS;
864 BOOL netconn_resolve( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
866 char *hostname;
867 #ifdef HAVE_GETADDRINFO
868 struct addrinfo *res, hints;
869 int ret;
870 #else
871 struct hostent *he;
872 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
873 #endif
875 if (!(hostname = strdupWA( hostnameW ))) return FALSE;
877 #ifdef HAVE_GETADDRINFO
878 memset( &hints, 0, sizeof(struct addrinfo) );
879 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
880 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
882 hints.ai_family = AF_INET;
884 ret = getaddrinfo( hostname, NULL, &hints, &res );
885 if (ret != 0)
887 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
888 hints.ai_family = AF_INET6;
889 ret = getaddrinfo( hostname, NULL, &hints, &res );
890 if (ret != 0)
892 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
893 heap_free( hostname );
894 return FALSE;
897 heap_free( hostname );
898 if (*sa_len < res->ai_addrlen)
900 WARN("address too small\n");
901 freeaddrinfo( res );
902 return FALSE;
904 *sa_len = res->ai_addrlen;
905 memcpy( sa, res->ai_addr, res->ai_addrlen );
906 /* Copy port */
907 switch (res->ai_family)
909 case AF_INET:
910 ((struct sockaddr_in *)sa)->sin_port = htons( port );
911 break;
912 case AF_INET6:
913 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
914 break;
917 freeaddrinfo( res );
918 return TRUE;
919 #else
920 EnterCriticalSection( &cs_gethostbyname );
922 he = gethostbyname( hostname );
923 heap_free( hostname );
924 if (!he)
926 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
927 LeaveCriticalSection( &cs_gethostbyname );
928 return FALSE;
930 if (*sa_len < sizeof(struct sockaddr_in))
932 WARN("address too small\n");
933 LeaveCriticalSection( &cs_gethostbyname );
934 return FALSE;
936 *sa_len = sizeof(struct sockaddr_in);
937 memset( sa, 0, sizeof(struct sockaddr_in) );
938 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
939 sin->sin_family = he->h_addrtype;
940 sin->sin_port = htons( port );
942 LeaveCriticalSection( &cs_gethostbyname );
943 return TRUE;
944 #endif
947 const void *netconn_get_certificate( netconn_t *conn )
949 #ifdef SONAME_LIBSSL
950 X509 *cert;
951 const CERT_CONTEXT *ret;
953 if (!conn->secure) return NULL;
955 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
956 ret = X509_to_cert_context( cert );
957 return ret;
958 #else
959 return NULL;
960 #endif