widl: Don't force removal of progids since "CLSID" is also a progid.
[wine.git] / dlls / wininet / netconnection.c
blob6a06b9a1415bdcbe02790caec7ff5661c0a63435
1 /*
2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
4 * Copyright 2002 TransGaming Technologies Inc.
6 * David Hammerton
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #define NONAMELESSUNION
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 #include <ws2tcpip.h>
30 #endif
32 #include <sys/types.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
47 #endif
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
54 #include <time.h>
55 #ifdef HAVE_NETDB_H
56 # include <netdb.h>
57 #endif
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #ifdef HAVE_OPENSSL_SSL_H
62 # include <openssl/ssl.h>
63 # include <openssl/opensslv.h>
64 #undef FAR
65 #undef DSA
66 #endif
68 #include <stdarg.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <stdio.h>
72 #include <errno.h>
74 #include "wine/library.h"
75 #include "windef.h"
76 #include "winbase.h"
77 #include "wininet.h"
78 #include "winerror.h"
79 #include "wincrypt.h"
81 #include "wine/debug.h"
82 #include "internet.h"
84 /* To avoid conflicts with the Unix socket headers. we only need it for
85 * the error codes anyway. */
86 #define USE_WS_PREFIX
87 #include "winsock2.h"
89 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
92 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
94 /* FIXME!!!!!!
95 * This should use winsock - To use winsock the functions will have to change a bit
96 * as they are designed for unix sockets.
97 * SSL stuff should use crypt32.dll
100 #ifdef SONAME_LIBSSL
102 #include <openssl/err.h>
104 static CRITICAL_SECTION init_ssl_cs;
105 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
107 0, 0, &init_ssl_cs,
108 { &init_ssl_cs_debug.ProcessLocksList,
109 &init_ssl_cs_debug.ProcessLocksList },
110 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
112 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
114 static void *OpenSSL_ssl_handle;
115 static void *OpenSSL_crypto_handle;
117 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
118 static const SSL_METHOD *meth;
119 #else
120 static SSL_METHOD *meth;
121 #endif
122 static SSL_CTX *ctx;
123 static int hostname_idx;
124 static int error_idx;
125 static int conn_idx;
127 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
129 /* OpenSSL functions that we use */
130 MAKE_FUNCPTR(SSL_library_init);
131 MAKE_FUNCPTR(SSL_load_error_strings);
132 MAKE_FUNCPTR(SSLv23_method);
133 MAKE_FUNCPTR(SSL_CTX_free);
134 MAKE_FUNCPTR(SSL_CTX_new);
135 MAKE_FUNCPTR(SSL_new);
136 MAKE_FUNCPTR(SSL_free);
137 MAKE_FUNCPTR(SSL_set_fd);
138 MAKE_FUNCPTR(SSL_connect);
139 MAKE_FUNCPTR(SSL_shutdown);
140 MAKE_FUNCPTR(SSL_write);
141 MAKE_FUNCPTR(SSL_read);
142 MAKE_FUNCPTR(SSL_pending);
143 MAKE_FUNCPTR(SSL_get_error);
144 MAKE_FUNCPTR(SSL_get_ex_new_index);
145 MAKE_FUNCPTR(SSL_get_ex_data);
146 MAKE_FUNCPTR(SSL_set_ex_data);
147 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
148 MAKE_FUNCPTR(SSL_get_peer_certificate);
149 MAKE_FUNCPTR(SSL_CTX_get_timeout);
150 MAKE_FUNCPTR(SSL_CTX_set_timeout);
151 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
152 MAKE_FUNCPTR(SSL_CTX_set_verify);
153 MAKE_FUNCPTR(SSL_get_current_cipher);
154 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
156 /* OpenSSL's libcrypto functions that we use */
157 MAKE_FUNCPTR(BIO_new_fp);
158 MAKE_FUNCPTR(CRYPTO_num_locks);
159 MAKE_FUNCPTR(CRYPTO_set_id_callback);
160 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
161 MAKE_FUNCPTR(ERR_free_strings);
162 MAKE_FUNCPTR(ERR_get_error);
163 MAKE_FUNCPTR(ERR_error_string);
164 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
165 MAKE_FUNCPTR(i2d_X509);
166 MAKE_FUNCPTR(sk_num);
167 MAKE_FUNCPTR(sk_value);
168 #undef MAKE_FUNCPTR
170 static CRITICAL_SECTION *ssl_locks;
171 static unsigned int num_ssl_locks;
173 static unsigned long ssl_thread_id(void)
175 return GetCurrentThreadId();
178 static void ssl_lock_callback(int mode, int type, const char *file, int line)
180 if (mode & CRYPTO_LOCK)
181 EnterCriticalSection(&ssl_locks[type]);
182 else
183 LeaveCriticalSection(&ssl_locks[type]);
186 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
188 unsigned char* buffer,*p;
189 INT len;
190 BOOL malloced = FALSE;
191 PCCERT_CONTEXT ret;
193 p = NULL;
194 len = pi2d_X509(cert,&p);
196 * SSL 0.9.7 and above malloc the buffer if it is null.
197 * however earlier version do not and so we would need to alloc the buffer.
199 * see the i2d_X509 man page for more details.
201 if (!p)
203 buffer = HeapAlloc(GetProcessHeap(),0,len);
204 p = buffer;
205 len = pi2d_X509(cert,&p);
207 else
209 buffer = p;
210 malloced = TRUE;
213 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
215 if (malloced)
216 free(buffer);
217 else
218 HeapFree(GetProcessHeap(),0,buffer);
220 return ret;
223 static DWORD netconn_verify_cert(PCCERT_CONTEXT cert, HCERTSTORE store,
224 WCHAR *server, DWORD security_flags)
226 BOOL ret;
227 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
228 PCCERT_CHAIN_CONTEXT chain;
229 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
230 char *server_auth[] = { oid_server_auth };
231 DWORD err = ERROR_SUCCESS, chainFlags = 0;
233 TRACE("verifying %s\n", debugstr_w(server));
234 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
235 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
236 if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
237 chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
238 if ((ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara,
239 chainFlags, NULL, &chain)))
241 if (chain->TrustStatus.dwErrorStatus)
243 static const DWORD supportedErrors =
244 CERT_TRUST_IS_NOT_TIME_VALID |
245 CERT_TRUST_IS_UNTRUSTED_ROOT |
246 CERT_TRUST_IS_OFFLINE_REVOCATION |
247 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
248 CERT_TRUST_IS_REVOKED |
249 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
251 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
252 err = ERROR_INTERNET_SEC_CERT_DATE_INVALID;
253 else if (chain->TrustStatus.dwErrorStatus &
254 CERT_TRUST_IS_UNTRUSTED_ROOT &&
255 !(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
256 err = ERROR_INTERNET_INVALID_CA;
257 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
258 ((chain->TrustStatus.dwErrorStatus &
259 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
260 (chain->TrustStatus.dwErrorStatus &
261 CERT_TRUST_REVOCATION_STATUS_UNKNOWN)))
262 err = ERROR_INTERNET_SEC_CERT_NO_REV;
263 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
264 (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED))
265 err = ERROR_INTERNET_SEC_CERT_REVOKED;
266 else if (!(security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE) &&
267 (chain->TrustStatus.dwErrorStatus &
268 CERT_TRUST_IS_NOT_VALID_FOR_USAGE))
269 err = ERROR_INTERNET_SEC_INVALID_CERT;
270 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
271 err = ERROR_INTERNET_SEC_INVALID_CERT;
273 if (!err)
275 CERT_CHAIN_POLICY_PARA policyPara;
276 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
277 CERT_CHAIN_POLICY_STATUS policyStatus;
278 CERT_CHAIN_CONTEXT chainCopy;
280 /* Clear chain->TrustStatus.dwErrorStatus so
281 * CertVerifyCertificateChainPolicy will verify additional checks
282 * rather than stopping with an existing, ignored error.
284 memcpy(&chainCopy, chain, sizeof(chainCopy));
285 chainCopy.TrustStatus.dwErrorStatus = 0;
286 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
287 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
288 sslExtraPolicyPara.pwszServerName = server;
289 sslExtraPolicyPara.fdwChecks = security_flags;
290 policyPara.cbSize = sizeof(policyPara);
291 policyPara.dwFlags = 0;
292 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
293 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
294 &chainCopy, &policyPara, &policyStatus);
295 /* Any error in the policy status indicates that the
296 * policy couldn't be verified.
298 if (ret && policyStatus.dwError)
300 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
301 err = ERROR_INTERNET_SEC_CERT_CN_INVALID;
302 else
303 err = ERROR_INTERNET_SEC_INVALID_CERT;
306 CertFreeCertificateChain(chain);
308 TRACE("returning %08x\n", err);
309 return err;
312 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
314 SSL *ssl;
315 WCHAR *server;
316 BOOL ret = FALSE;
317 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
318 CERT_STORE_CREATE_NEW_FLAG, NULL);
319 WININET_NETCONNECTION *conn;
321 ssl = pX509_STORE_CTX_get_ex_data(ctx,
322 pSSL_get_ex_data_X509_STORE_CTX_idx());
323 server = pSSL_get_ex_data(ssl, hostname_idx);
324 conn = pSSL_get_ex_data(ssl, conn_idx);
325 if (store)
327 X509 *cert;
328 int i;
329 PCCERT_CONTEXT endCert = NULL;
331 ret = TRUE;
332 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
334 PCCERT_CONTEXT context;
336 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
337 if ((context = X509_to_cert_context(cert)))
339 if (i == 0)
340 ret = CertAddCertificateContextToStore(store, context,
341 CERT_STORE_ADD_ALWAYS, &endCert);
342 else
343 ret = CertAddCertificateContextToStore(store, context,
344 CERT_STORE_ADD_ALWAYS, NULL);
345 CertFreeCertificateContext(context);
348 if (!endCert) ret = FALSE;
349 if (ret)
351 DWORD_PTR err = netconn_verify_cert(endCert, store, server,
352 conn->security_flags);
354 if (err)
356 pSSL_set_ex_data(ssl, error_idx, (void *)err);
357 ret = FALSE;
360 CertFreeCertificateContext(endCert);
361 CertCloseStore(store, 0);
363 return ret;
366 #endif
368 DWORD NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
370 connection->useSSL = FALSE;
371 connection->socketFD = -1;
372 if (useSSL)
374 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
375 int i;
377 TRACE("using SSL connection\n");
378 EnterCriticalSection(&init_ssl_cs);
379 if (OpenSSL_ssl_handle) /* already initialized everything */
381 LeaveCriticalSection(&init_ssl_cs);
382 return ERROR_SUCCESS;
384 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
385 if (!OpenSSL_ssl_handle)
387 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
388 SONAME_LIBSSL);
389 LeaveCriticalSection(&init_ssl_cs);
390 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
392 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
393 if (!OpenSSL_crypto_handle)
395 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
396 SONAME_LIBCRYPTO);
397 LeaveCriticalSection(&init_ssl_cs);
398 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
401 /* mmm nice ugly macroness */
402 #define DYNSSL(x) \
403 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
404 if (!p##x) \
406 ERR("failed to load symbol %s\n", #x); \
407 LeaveCriticalSection(&init_ssl_cs); \
408 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
411 DYNSSL(SSL_library_init);
412 DYNSSL(SSL_load_error_strings);
413 DYNSSL(SSLv23_method);
414 DYNSSL(SSL_CTX_free);
415 DYNSSL(SSL_CTX_new);
416 DYNSSL(SSL_new);
417 DYNSSL(SSL_free);
418 DYNSSL(SSL_set_fd);
419 DYNSSL(SSL_connect);
420 DYNSSL(SSL_shutdown);
421 DYNSSL(SSL_write);
422 DYNSSL(SSL_read);
423 DYNSSL(SSL_pending);
424 DYNSSL(SSL_get_error);
425 DYNSSL(SSL_get_ex_new_index);
426 DYNSSL(SSL_get_ex_data);
427 DYNSSL(SSL_set_ex_data);
428 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
429 DYNSSL(SSL_get_peer_certificate);
430 DYNSSL(SSL_CTX_get_timeout);
431 DYNSSL(SSL_CTX_set_timeout);
432 DYNSSL(SSL_CTX_set_default_verify_paths);
433 DYNSSL(SSL_CTX_set_verify);
434 DYNSSL(SSL_get_current_cipher);
435 DYNSSL(SSL_CIPHER_get_bits);
436 #undef DYNSSL
438 #define DYNCRYPTO(x) \
439 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
440 if (!p##x) \
442 ERR("failed to load symbol %s\n", #x); \
443 LeaveCriticalSection(&init_ssl_cs); \
444 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
446 DYNCRYPTO(BIO_new_fp);
447 DYNCRYPTO(CRYPTO_num_locks);
448 DYNCRYPTO(CRYPTO_set_id_callback);
449 DYNCRYPTO(CRYPTO_set_locking_callback);
450 DYNCRYPTO(ERR_free_strings);
451 DYNCRYPTO(ERR_get_error);
452 DYNCRYPTO(ERR_error_string);
453 DYNCRYPTO(X509_STORE_CTX_get_ex_data);
454 DYNCRYPTO(i2d_X509);
455 DYNCRYPTO(sk_num);
456 DYNCRYPTO(sk_value);
457 #undef DYNCRYPTO
459 pSSL_library_init();
460 pSSL_load_error_strings();
461 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
463 meth = pSSLv23_method();
464 ctx = pSSL_CTX_new(meth);
465 if (!pSSL_CTX_set_default_verify_paths(ctx))
467 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
468 pERR_error_string(pERR_get_error(), 0));
469 LeaveCriticalSection(&init_ssl_cs);
470 return ERROR_OUTOFMEMORY;
472 hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index",
473 NULL, NULL, NULL);
474 if (hostname_idx == -1)
476 ERR("SSL_get_ex_new_index failed; %s\n",
477 pERR_error_string(pERR_get_error(), 0));
478 LeaveCriticalSection(&init_ssl_cs);
479 return ERROR_OUTOFMEMORY;
481 error_idx = pSSL_get_ex_new_index(0, (void *)"error index",
482 NULL, NULL, NULL);
483 if (error_idx == -1)
485 ERR("SSL_get_ex_new_index failed; %s\n",
486 pERR_error_string(pERR_get_error(), 0));
487 LeaveCriticalSection(&init_ssl_cs);
488 return ERROR_OUTOFMEMORY;
490 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index",
491 NULL, NULL, NULL);
492 if (conn_idx == -1)
494 ERR("SSL_get_ex_new_index failed; %s\n",
495 pERR_error_string(pERR_get_error(), 0));
496 LeaveCriticalSection(&init_ssl_cs);
497 return ERROR_OUTOFMEMORY;
499 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
501 pCRYPTO_set_id_callback(ssl_thread_id);
502 num_ssl_locks = pCRYPTO_num_locks();
503 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
504 if (!ssl_locks)
506 LeaveCriticalSection(&init_ssl_cs);
507 return ERROR_OUTOFMEMORY;
509 for (i = 0; i < num_ssl_locks; i++)
510 InitializeCriticalSection(&ssl_locks[i]);
511 pCRYPTO_set_locking_callback(ssl_lock_callback);
512 LeaveCriticalSection(&init_ssl_cs);
513 #else
514 FIXME("can't use SSL, not compiled in.\n");
515 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
516 #endif
518 return ERROR_SUCCESS;
521 void NETCON_unload(void)
523 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
524 if (OpenSSL_crypto_handle)
526 pERR_free_strings();
527 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
529 if (OpenSSL_ssl_handle)
531 if (ctx)
532 pSSL_CTX_free(ctx);
533 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
535 if (ssl_locks)
537 int i;
538 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
539 HeapFree(GetProcessHeap(), 0, ssl_locks);
541 #endif
544 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
546 if (connection->socketFD == -1)
547 return FALSE;
548 else
549 return TRUE;
552 /* translate a unix error code into a winsock one */
553 int sock_get_error( int err )
555 #if !defined(__MINGW32__) && !defined (_MSC_VER)
556 switch (err)
558 case EINTR: return WSAEINTR;
559 case EBADF: return WSAEBADF;
560 case EPERM:
561 case EACCES: return WSAEACCES;
562 case EFAULT: return WSAEFAULT;
563 case EINVAL: return WSAEINVAL;
564 case EMFILE: return WSAEMFILE;
565 case EWOULDBLOCK: return WSAEWOULDBLOCK;
566 case EINPROGRESS: return WSAEINPROGRESS;
567 case EALREADY: return WSAEALREADY;
568 case ENOTSOCK: return WSAENOTSOCK;
569 case EDESTADDRREQ: return WSAEDESTADDRREQ;
570 case EMSGSIZE: return WSAEMSGSIZE;
571 case EPROTOTYPE: return WSAEPROTOTYPE;
572 case ENOPROTOOPT: return WSAENOPROTOOPT;
573 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
574 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
575 case EOPNOTSUPP: return WSAEOPNOTSUPP;
576 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
577 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
578 case EADDRINUSE: return WSAEADDRINUSE;
579 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
580 case ENETDOWN: return WSAENETDOWN;
581 case ENETUNREACH: return WSAENETUNREACH;
582 case ENETRESET: return WSAENETRESET;
583 case ECONNABORTED: return WSAECONNABORTED;
584 case EPIPE:
585 case ECONNRESET: return WSAECONNRESET;
586 case ENOBUFS: return WSAENOBUFS;
587 case EISCONN: return WSAEISCONN;
588 case ENOTCONN: return WSAENOTCONN;
589 case ESHUTDOWN: return WSAESHUTDOWN;
590 case ETOOMANYREFS: return WSAETOOMANYREFS;
591 case ETIMEDOUT: return WSAETIMEDOUT;
592 case ECONNREFUSED: return WSAECONNREFUSED;
593 case ELOOP: return WSAELOOP;
594 case ENAMETOOLONG: return WSAENAMETOOLONG;
595 case EHOSTDOWN: return WSAEHOSTDOWN;
596 case EHOSTUNREACH: return WSAEHOSTUNREACH;
597 case ENOTEMPTY: return WSAENOTEMPTY;
598 #ifdef EPROCLIM
599 case EPROCLIM: return WSAEPROCLIM;
600 #endif
601 #ifdef EUSERS
602 case EUSERS: return WSAEUSERS;
603 #endif
604 #ifdef EDQUOT
605 case EDQUOT: return WSAEDQUOT;
606 #endif
607 #ifdef ESTALE
608 case ESTALE: return WSAESTALE;
609 #endif
610 #ifdef EREMOTE
611 case EREMOTE: return WSAEREMOTE;
612 #endif
613 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
615 #endif
616 return err;
619 /******************************************************************************
620 * NETCON_create
621 * Basically calls 'socket()'
623 DWORD NETCON_create(WININET_NETCONNECTION *connection, int domain,
624 int type, int protocol)
626 #ifdef SONAME_LIBSSL
627 if (connection->useSSL)
628 return ERROR_NOT_SUPPORTED;
629 #endif
631 connection->socketFD = socket(domain, type, protocol);
632 if (connection->socketFD == -1)
633 return sock_get_error(errno);
635 return ERROR_SUCCESS;
638 /******************************************************************************
639 * NETCON_close
640 * Basically calls 'close()' unless we should use SSL
642 DWORD NETCON_close(WININET_NETCONNECTION *connection)
644 int result;
646 if (!NETCON_connected(connection)) return ERROR_SUCCESS;
648 #ifdef SONAME_LIBSSL
649 if (connection->useSSL)
651 pSSL_shutdown(connection->ssl_s);
652 pSSL_free(connection->ssl_s);
653 connection->ssl_s = NULL;
655 connection->useSSL = FALSE;
657 #endif
659 result = closesocket(connection->socketFD);
660 connection->socketFD = -1;
662 if (result == -1)
663 return sock_get_error(errno);
664 return ERROR_SUCCESS;
667 /******************************************************************************
668 * NETCON_secure_connect
669 * Initiates a secure connection over an existing plaintext connection.
671 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPWSTR hostname)
673 DWORD res = ERROR_NOT_SUPPORTED;
675 #ifdef SONAME_LIBSSL
676 /* can't connect if we are already connected */
677 if (connection->useSSL)
679 ERR("already connected\n");
680 return ERROR_INTERNET_CANNOT_CONNECT;
683 connection->ssl_s = pSSL_new(ctx);
684 if (!connection->ssl_s)
686 ERR("SSL_new failed: %s\n",
687 pERR_error_string(pERR_get_error(), 0));
688 res = ERROR_OUTOFMEMORY;
689 goto fail;
692 if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
694 ERR("SSL_set_fd failed: %s\n",
695 pERR_error_string(pERR_get_error(), 0));
696 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
697 goto fail;
700 if (!pSSL_set_ex_data(connection->ssl_s, hostname_idx, hostname))
702 ERR("SSL_set_ex_data failed: %s\n",
703 pERR_error_string(pERR_get_error(), 0));
704 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
705 goto fail;
707 if (!pSSL_set_ex_data(connection->ssl_s, conn_idx, connection))
709 ERR("SSL_set_ex_data failed: %s\n",
710 pERR_error_string(pERR_get_error(), 0));
711 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
712 goto fail;
714 if (pSSL_connect(connection->ssl_s) <= 0)
716 res = (DWORD_PTR)pSSL_get_ex_data(connection->ssl_s, error_idx);
717 if (!res)
718 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
719 ERR("SSL_connect failed: %d\n", res);
720 goto fail;
723 connection->useSSL = TRUE;
724 return ERROR_SUCCESS;
726 fail:
727 if (connection->ssl_s)
729 pSSL_shutdown(connection->ssl_s);
730 pSSL_free(connection->ssl_s);
731 connection->ssl_s = NULL;
733 #endif
734 return res;
737 /******************************************************************************
738 * NETCON_connect
739 * Connects to the specified address.
741 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
742 unsigned int addrlen)
744 int result;
746 result = connect(connection->socketFD, serv_addr, addrlen);
747 if (result == -1)
749 WARN("Unable to connect to host (%s)\n", strerror(errno));
751 closesocket(connection->socketFD);
752 connection->socketFD = -1;
753 return sock_get_error(errno);
756 return ERROR_SUCCESS;
759 /******************************************************************************
760 * NETCON_send
761 * Basically calls 'send()' unless we should use SSL
762 * number of chars send is put in *sent
764 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
765 int *sent /* out */)
767 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
768 if (!connection->useSSL)
770 *sent = send(connection->socketFD, msg, len, flags);
771 if (*sent == -1)
772 return sock_get_error(errno);
773 return ERROR_SUCCESS;
775 else
777 #ifdef SONAME_LIBSSL
778 if (flags)
779 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
780 *sent = pSSL_write(connection->ssl_s, msg, len);
781 if (*sent < 1 && len)
782 return ERROR_INTERNET_CONNECTION_ABORTED;
783 return ERROR_SUCCESS;
784 #else
785 return ERROR_NOT_SUPPORTED;
786 #endif
790 /******************************************************************************
791 * NETCON_recv
792 * Basically calls 'recv()' unless we should use SSL
793 * number of chars received is put in *recvd
795 DWORD NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
796 int *recvd /* out */)
798 *recvd = 0;
799 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
800 if (!len)
801 return ERROR_SUCCESS;
802 if (!connection->useSSL)
804 *recvd = recv(connection->socketFD, buf, len, flags);
805 if(!*recvd)
806 NETCON_close(connection);
807 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
809 else
811 #ifdef SONAME_LIBSSL
812 *recvd = pSSL_read(connection->ssl_s, buf, len);
814 /* Check if EOF was received */
815 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
816 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL)) {
817 NETCON_close(connection);
818 return ERROR_SUCCESS;
821 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
822 #else
823 return ERROR_NOT_SUPPORTED;
824 #endif
828 /******************************************************************************
829 * NETCON_query_data_available
830 * Returns the number of bytes of peeked data plus the number of bytes of
831 * queued, but unread data.
833 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
835 *available = 0;
836 if (!NETCON_connected(connection))
837 return FALSE;
839 if (!connection->useSSL)
841 #ifdef FIONREAD
842 int unread;
843 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
844 if (!retval)
846 TRACE("%d bytes of queued, but unread data\n", unread);
847 *available += unread;
849 #endif
851 else
853 #ifdef SONAME_LIBSSL
854 *available = pSSL_pending(connection->ssl_s);
855 #endif
857 return TRUE;
860 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
862 #ifdef SONAME_LIBSSL
863 X509* cert;
864 LPCVOID r = NULL;
866 if (!connection->useSSL)
867 return NULL;
869 cert = pSSL_get_peer_certificate(connection->ssl_s);
870 r = X509_to_cert_context(cert);
871 return r;
872 #else
873 return NULL;
874 #endif
877 int NETCON_GetCipherStrength(WININET_NETCONNECTION *connection)
879 #ifdef SONAME_LIBSSL
880 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
881 const SSL_CIPHER *cipher;
882 #else
883 SSL_CIPHER *cipher;
884 #endif
885 int bits = 0;
887 if (!connection->useSSL)
888 return 0;
889 cipher = pSSL_get_current_cipher(connection->ssl_s);
890 if (!cipher)
891 return 0;
892 pSSL_CIPHER_get_bits(cipher, &bits);
893 return bits;
894 #else
895 return 0;
896 #endif
899 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
901 int result;
902 struct timeval tv;
904 /* FIXME: we should probably store the timeout in the connection to set
905 * when we do connect */
906 if (!NETCON_connected(connection))
907 return ERROR_SUCCESS;
909 /* value is in milliseconds, convert to struct timeval */
910 tv.tv_sec = value / 1000;
911 tv.tv_usec = (value % 1000) * 1000;
913 result = setsockopt(connection->socketFD, SOL_SOCKET,
914 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
915 sizeof(tv));
917 if (result == -1)
919 WARN("setsockopt failed (%s)\n", strerror(errno));
920 return sock_get_error(errno);
923 return ERROR_SUCCESS;