Sync with trunk head (r49139)
[reactos.git] / dll / win32 / wininet / netconnection.c
1 /*
2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
3 *
4 * Copyright 2002 TransGaming Technologies Inc.
5 *
6 * David Hammerton
7 *
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.
12 *
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.
17 *
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
21 */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #define NONAMELESSUNION
27
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 #include <ws2tcpip.h>
30 #endif
31
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
67
68 #include <stdarg.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <stdio.h>
72 #include <errno.h>
73
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"
80
81 #include "wine/debug.h"
82 #include "internet.h"
83
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"
88
89 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
90
91
92 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
93
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
98 */
99
100 #ifdef SONAME_LIBSSL
101
102 #include <openssl/err.h>
103
104 static CRITICAL_SECTION init_ssl_cs;
105 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
106 {
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") }
111 };
112 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
113
114 static void *OpenSSL_ssl_handle;
115 static void *OpenSSL_crypto_handle;
116
117 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER> 0x1000000)
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;
126
127 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
128
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);
155 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
156
157 /* OpenSSL's libcrypto functions that we use */
158 MAKE_FUNCPTR(BIO_new_fp);
159 MAKE_FUNCPTR(CRYPTO_num_locks);
160 MAKE_FUNCPTR(CRYPTO_set_id_callback);
161 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
162 MAKE_FUNCPTR(ERR_free_strings);
163 MAKE_FUNCPTR(ERR_get_error);
164 MAKE_FUNCPTR(ERR_error_string);
165 MAKE_FUNCPTR(i2d_X509);
166 MAKE_FUNCPTR(sk_num);
167 MAKE_FUNCPTR(sk_value);
168 #undef MAKE_FUNCPTR
169
170 static CRITICAL_SECTION *ssl_locks;
171 static unsigned int num_ssl_locks;
172
173 static unsigned long ssl_thread_id(void)
174 {
175 return GetCurrentThreadId();
176 }
177
178 static void ssl_lock_callback(int mode, int type, const char *file, int line)
179 {
180 if (mode & CRYPTO_LOCK)
181 EnterCriticalSection(&ssl_locks[type]);
182 else
183 LeaveCriticalSection(&ssl_locks[type]);
184 }
185
186 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
187 {
188 unsigned char* buffer,*p;
189 INT len;
190 BOOL malloced = FALSE;
191 PCCERT_CONTEXT ret;
192
193 p = NULL;
194 len = pi2d_X509(cert,&p);
195 /*
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.
198 *
199 * see the i2d_X509 man page for more details.
200 */
201 if (!p)
202 {
203 buffer = HeapAlloc(GetProcessHeap(),0,len);
204 p = buffer;
205 len = pi2d_X509(cert,&p);
206 }
207 else
208 {
209 buffer = p;
210 malloced = TRUE;
211 }
212
213 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
214
215 if (malloced)
216 free(buffer);
217 else
218 HeapFree(GetProcessHeap(),0,buffer);
219
220 return ret;
221 }
222
223 static DWORD netconn_verify_cert(PCCERT_CONTEXT cert, HCERTSTORE store,
224 WCHAR *server, DWORD security_flags)
225 {
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;
232
233 TRACE("verifying %s\n", debugstr_w(server));
234 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
235 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
236 if ((ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0,
237 NULL, &chain)))
238 {
239 if (chain->TrustStatus.dwErrorStatus)
240 {
241 static const DWORD supportedErrors =
242 CERT_TRUST_IS_NOT_TIME_VALID |
243 CERT_TRUST_IS_UNTRUSTED_ROOT |
244 CERT_TRUST_IS_OFFLINE_REVOCATION |
245 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
246 CERT_TRUST_IS_REVOKED |
247 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
248
249 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
250 err = ERROR_INTERNET_SEC_CERT_DATE_INVALID;
251 else if (chain->TrustStatus.dwErrorStatus &
252 CERT_TRUST_IS_UNTRUSTED_ROOT &&
253 !(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
254 err = ERROR_INTERNET_INVALID_CA;
255 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
256 ((chain->TrustStatus.dwErrorStatus &
257 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
258 (chain->TrustStatus.dwErrorStatus &
259 CERT_TRUST_REVOCATION_STATUS_UNKNOWN)))
260 err = ERROR_INTERNET_SEC_CERT_NO_REV;
261 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
262 (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED))
263 err = ERROR_INTERNET_SEC_CERT_REVOKED;
264 else if (!(security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE) &&
265 (chain->TrustStatus.dwErrorStatus &
266 CERT_TRUST_IS_NOT_VALID_FOR_USAGE))
267 err = ERROR_INTERNET_SEC_INVALID_CERT;
268 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
269 err = ERROR_INTERNET_SEC_INVALID_CERT;
270 }
271 if (!err)
272 {
273 CERT_CHAIN_POLICY_PARA policyPara;
274 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
275 CERT_CHAIN_POLICY_STATUS policyStatus;
276 CERT_CHAIN_CONTEXT chainCopy;
277
278 /* Clear chain->TrustStatus.dwErrorStatus so
279 * CertVerifyCertificateChainPolicy will verify additional checks
280 * rather than stopping with an existing, ignored error.
281 */
282 memcpy(&chainCopy, chain, sizeof(chainCopy));
283 chainCopy.TrustStatus.dwErrorStatus = 0;
284 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
285 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
286 sslExtraPolicyPara.pwszServerName = server;
287 sslExtraPolicyPara.fdwChecks = security_flags;
288 policyPara.cbSize = sizeof(policyPara);
289 policyPara.dwFlags = 0;
290 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
291 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
292 &chainCopy, &policyPara, &policyStatus);
293 /* Any error in the policy status indicates that the
294 * policy couldn't be verified.
295 */
296 if (ret && policyStatus.dwError)
297 {
298 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
299 err = ERROR_INTERNET_SEC_CERT_CN_INVALID;
300 else
301 err = ERROR_INTERNET_SEC_INVALID_CERT;
302 }
303 }
304 CertFreeCertificateChain(chain);
305 }
306 TRACE("returning %08x\n", err);
307 return err;
308 }
309
310 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
311 {
312 SSL *ssl;
313 WCHAR *server;
314 BOOL ret = FALSE;
315 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
316 CERT_STORE_CREATE_NEW_FLAG, NULL);
317 WININET_NETCONNECTION *conn;
318
319 ssl = pX509_STORE_CTX_get_ex_data(ctx,
320 pSSL_get_ex_data_X509_STORE_CTX_idx());
321 server = pSSL_get_ex_data(ssl, hostname_idx);
322 conn = pSSL_get_ex_data(ssl, conn_idx);
323 if (store)
324 {
325 X509 *cert;
326 int i;
327 PCCERT_CONTEXT endCert = NULL;
328
329 ret = TRUE;
330 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
331 {
332 PCCERT_CONTEXT context;
333
334 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
335 if ((context = X509_to_cert_context(cert)))
336 {
337 if (i == 0)
338 ret = CertAddCertificateContextToStore(store, context,
339 CERT_STORE_ADD_ALWAYS, &endCert);
340 else
341 ret = CertAddCertificateContextToStore(store, context,
342 CERT_STORE_ADD_ALWAYS, NULL);
343 CertFreeCertificateContext(context);
344 }
345 }
346 if (!endCert) ret = FALSE;
347 if (ret)
348 {
349 DWORD_PTR err = netconn_verify_cert(endCert, store, server,
350 conn->security_flags);
351
352 if (err)
353 {
354 pSSL_set_ex_data(ssl, error_idx, (void *)err);
355 ret = FALSE;
356 }
357 }
358 CertFreeCertificateContext(endCert);
359 CertCloseStore(store, 0);
360 }
361 return ret;
362 }
363
364 #endif
365
366 DWORD NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
367 {
368 connection->useSSL = FALSE;
369 connection->socketFD = -1;
370 if (useSSL)
371 {
372 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
373 int i;
374
375 TRACE("using SSL connection\n");
376 EnterCriticalSection(&init_ssl_cs);
377 if (OpenSSL_ssl_handle) /* already initialized everything */
378 {
379 LeaveCriticalSection(&init_ssl_cs);
380 return ERROR_SUCCESS;
381 }
382 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
383 if (!OpenSSL_ssl_handle)
384 {
385 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
386 SONAME_LIBSSL);
387 LeaveCriticalSection(&init_ssl_cs);
388 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
389 }
390 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
391 if (!OpenSSL_crypto_handle)
392 {
393 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
394 SONAME_LIBCRYPTO);
395 LeaveCriticalSection(&init_ssl_cs);
396 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
397 }
398
399 /* mmm nice ugly macroness */
400 #define DYNSSL(x) \
401 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
402 if (!p##x) \
403 { \
404 ERR("failed to load symbol %s\n", #x); \
405 LeaveCriticalSection(&init_ssl_cs); \
406 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
407 }
408
409 DYNSSL(SSL_library_init);
410 DYNSSL(SSL_load_error_strings);
411 DYNSSL(SSLv23_method);
412 DYNSSL(SSL_CTX_free);
413 DYNSSL(SSL_CTX_new);
414 DYNSSL(SSL_new);
415 DYNSSL(SSL_free);
416 DYNSSL(SSL_set_fd);
417 DYNSSL(SSL_connect);
418 DYNSSL(SSL_shutdown);
419 DYNSSL(SSL_write);
420 DYNSSL(SSL_read);
421 DYNSSL(SSL_pending);
422 DYNSSL(SSL_get_error);
423 DYNSSL(SSL_get_ex_new_index);
424 DYNSSL(SSL_get_ex_data);
425 DYNSSL(SSL_set_ex_data);
426 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
427 DYNSSL(SSL_get_peer_certificate);
428 DYNSSL(SSL_CTX_get_timeout);
429 DYNSSL(SSL_CTX_set_timeout);
430 DYNSSL(SSL_CTX_set_default_verify_paths);
431 DYNSSL(SSL_CTX_set_verify);
432 DYNSSL(SSL_get_current_cipher);
433 DYNSSL(SSL_CIPHER_get_bits);
434 DYNSSL(X509_STORE_CTX_get_ex_data);
435 #undef DYNSSL
436
437 #define DYNCRYPTO(x) \
438 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
439 if (!p##x) \
440 { \
441 ERR("failed to load symbol %s\n", #x); \
442 LeaveCriticalSection(&init_ssl_cs); \
443 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
444 }
445 DYNCRYPTO(BIO_new_fp);
446 DYNCRYPTO(CRYPTO_num_locks);
447 DYNCRYPTO(CRYPTO_set_id_callback);
448 DYNCRYPTO(CRYPTO_set_locking_callback);
449 DYNCRYPTO(ERR_free_strings);
450 DYNCRYPTO(ERR_get_error);
451 DYNCRYPTO(ERR_error_string);
452 DYNCRYPTO(i2d_X509);
453 DYNCRYPTO(sk_num);
454 DYNCRYPTO(sk_value);
455 #undef DYNCRYPTO
456
457 pSSL_library_init();
458 pSSL_load_error_strings();
459 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
460
461 meth = pSSLv23_method();
462 ctx = pSSL_CTX_new(meth);
463 if (!pSSL_CTX_set_default_verify_paths(ctx))
464 {
465 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
466 pERR_error_string(pERR_get_error(), 0));
467 LeaveCriticalSection(&init_ssl_cs);
468 return ERROR_OUTOFMEMORY;
469 }
470 hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index",
471 NULL, NULL, NULL);
472 if (hostname_idx == -1)
473 {
474 ERR("SSL_get_ex_new_index failed; %s\n",
475 pERR_error_string(pERR_get_error(), 0));
476 LeaveCriticalSection(&init_ssl_cs);
477 return ERROR_OUTOFMEMORY;
478 }
479 error_idx = pSSL_get_ex_new_index(0, (void *)"error index",
480 NULL, NULL, NULL);
481 if (error_idx == -1)
482 {
483 ERR("SSL_get_ex_new_index failed; %s\n",
484 pERR_error_string(pERR_get_error(), 0));
485 LeaveCriticalSection(&init_ssl_cs);
486 return ERROR_OUTOFMEMORY;
487 }
488 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index",
489 NULL, NULL, NULL);
490 if (conn_idx == -1)
491 {
492 ERR("SSL_get_ex_new_index failed; %s\n",
493 pERR_error_string(pERR_get_error(), 0));
494 LeaveCriticalSection(&init_ssl_cs);
495 return ERROR_OUTOFMEMORY;
496 }
497 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
498
499 pCRYPTO_set_id_callback(ssl_thread_id);
500 num_ssl_locks = pCRYPTO_num_locks();
501 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
502 if (!ssl_locks)
503 {
504 LeaveCriticalSection(&init_ssl_cs);
505 return ERROR_OUTOFMEMORY;
506 }
507 for (i = 0; i < num_ssl_locks; i++)
508 InitializeCriticalSection(&ssl_locks[i]);
509 pCRYPTO_set_locking_callback(ssl_lock_callback);
510 LeaveCriticalSection(&init_ssl_cs);
511 #else
512 FIXME("can't use SSL, not compiled in.\n");
513 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
514 #endif
515 }
516 return ERROR_SUCCESS;
517 }
518
519 void NETCON_unload(void)
520 {
521 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
522 if (OpenSSL_crypto_handle)
523 {
524 pERR_free_strings();
525 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
526 }
527 if (OpenSSL_ssl_handle)
528 {
529 if (ctx)
530 pSSL_CTX_free(ctx);
531 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
532 }
533 if (ssl_locks)
534 {
535 int i;
536 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
537 HeapFree(GetProcessHeap(), 0, ssl_locks);
538 }
539 #endif
540 }
541
542 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
543 {
544 if (connection->socketFD == -1)
545 return FALSE;
546 else
547 return TRUE;
548 }
549
550 #if 0
551 /* translate a unix error code into a winsock one */
552 int sock_get_error( int err )
553 {
554 #if !defined(__MINGW32__) && !defined (_MSC_VER)
555 switch (err)
556 {
557 case EINTR: return WSAEINTR;
558 case EBADF: return WSAEBADF;
559 case EPERM:
560 case EACCES: return WSAEACCES;
561 case EFAULT: return WSAEFAULT;
562 case EINVAL: return WSAEINVAL;
563 case EMFILE: return WSAEMFILE;
564 case EWOULDBLOCK: return WSAEWOULDBLOCK;
565 case EINPROGRESS: return WSAEINPROGRESS;
566 case EALREADY: return WSAEALREADY;
567 case ENOTSOCK: return WSAENOTSOCK;
568 case EDESTADDRREQ: return WSAEDESTADDRREQ;
569 case EMSGSIZE: return WSAEMSGSIZE;
570 case EPROTOTYPE: return WSAEPROTOTYPE;
571 case ENOPROTOOPT: return WSAENOPROTOOPT;
572 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
573 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
574 case EOPNOTSUPP: return WSAEOPNOTSUPP;
575 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
576 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
577 case EADDRINUSE: return WSAEADDRINUSE;
578 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
579 case ENETDOWN: return WSAENETDOWN;
580 case ENETUNREACH: return WSAENETUNREACH;
581 case ENETRESET: return WSAENETRESET;
582 case ECONNABORTED: return WSAECONNABORTED;
583 case EPIPE:
584 case ECONNRESET: return WSAECONNRESET;
585 case ENOBUFS: return WSAENOBUFS;
586 case EISCONN: return WSAEISCONN;
587 case ENOTCONN: return WSAENOTCONN;
588 case ESHUTDOWN: return WSAESHUTDOWN;
589 case ETOOMANYREFS: return WSAETOOMANYREFS;
590 case ETIMEDOUT: return WSAETIMEDOUT;
591 case ECONNREFUSED: return WSAECONNREFUSED;
592 case ELOOP: return WSAELOOP;
593 case ENAMETOOLONG: return WSAENAMETOOLONG;
594 case EHOSTDOWN: return WSAEHOSTDOWN;
595 case EHOSTUNREACH: return WSAEHOSTUNREACH;
596 case ENOTEMPTY: return WSAENOTEMPTY;
597 #ifdef EPROCLIM
598 case EPROCLIM: return WSAEPROCLIM;
599 #endif
600 #ifdef EUSERS
601 case EUSERS: return WSAEUSERS;
602 #endif
603 #ifdef EDQUOT
604 case EDQUOT: return WSAEDQUOT;
605 #endif
606 #ifdef ESTALE
607 case ESTALE: return WSAESTALE;
608 #endif
609 #ifdef EREMOTE
610 case EREMOTE: return WSAEREMOTE;
611 #endif
612 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
613 }
614 #endif
615 return err;
616 }
617 #endif
618
619 /******************************************************************************
620 * NETCON_create
621 * Basically calls 'socket()'
622 */
623 DWORD NETCON_create(WININET_NETCONNECTION *connection, int domain,
624 int type, int protocol)
625 {
626 #ifdef SONAME_LIBSSL
627 if (connection->useSSL)
628 return ERROR_NOT_SUPPORTED;
629 #endif
630
631 connection->socketFD = socket(domain, type, protocol);
632 if (connection->socketFD == -1)
633 return sock_get_error(errno);
634
635 return ERROR_SUCCESS;
636 }
637
638 /******************************************************************************
639 * NETCON_close
640 * Basically calls 'close()' unless we should use SSL
641 */
642 DWORD NETCON_close(WININET_NETCONNECTION *connection)
643 {
644 int result;
645
646 if (!NETCON_connected(connection)) return ERROR_SUCCESS;
647
648 #ifdef SONAME_LIBSSL
649 if (connection->useSSL)
650 {
651 pSSL_shutdown(connection->ssl_s);
652 pSSL_free(connection->ssl_s);
653 connection->ssl_s = NULL;
654
655 connection->useSSL = FALSE;
656 }
657 #endif
658
659 result = closesocket(connection->socketFD);
660 connection->socketFD = -1;
661
662 if (result == -1)
663 return sock_get_error(errno);
664 return ERROR_SUCCESS;
665 }
666
667 /******************************************************************************
668 * NETCON_secure_connect
669 * Initiates a secure connection over an existing plaintext connection.
670 */
671 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPWSTR hostname)
672 {
673 DWORD res = ERROR_NOT_SUPPORTED;
674
675 #ifdef SONAME_LIBSSL
676 /* can't connect if we are already connected */
677 if (connection->useSSL)
678 {
679 ERR("already connected\n");
680 return ERROR_INTERNET_CANNOT_CONNECT;
681 }
682
683 connection->ssl_s = pSSL_new(ctx);
684 if (!connection->ssl_s)
685 {
686 ERR("SSL_new failed: %s\n",
687 pERR_error_string(pERR_get_error(), 0));
688 res = ERROR_OUTOFMEMORY;
689 goto fail;
690 }
691
692 if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
693 {
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;
698 }
699
700 if (!pSSL_set_ex_data(connection->ssl_s, hostname_idx, hostname))
701 {
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;
706 }
707 if (!pSSL_set_ex_data(connection->ssl_s, conn_idx, connection))
708 {
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;
713 }
714 if (pSSL_connect(connection->ssl_s) <= 0)
715 {
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;
721 }
722
723 connection->useSSL = TRUE;
724 return ERROR_SUCCESS;
725
726 fail:
727 if (connection->ssl_s)
728 {
729 pSSL_shutdown(connection->ssl_s);
730 pSSL_free(connection->ssl_s);
731 connection->ssl_s = NULL;
732 }
733 #endif
734 return res;
735 }
736
737 /******************************************************************************
738 * NETCON_connect
739 * Connects to the specified address.
740 */
741 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
742 unsigned int addrlen)
743 {
744 int result;
745
746 result = connect(connection->socketFD, serv_addr, addrlen);
747 if (result == -1)
748 {
749 WARN("Unable to connect to host (%s)\n", strerror(errno));
750
751 closesocket(connection->socketFD);
752 connection->socketFD = -1;
753 return sock_get_error(errno);
754 }
755
756 return ERROR_SUCCESS;
757 }
758
759 /******************************************************************************
760 * NETCON_send
761 * Basically calls 'send()' unless we should use SSL
762 * number of chars send is put in *sent
763 */
764 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
765 int *sent /* out */)
766 {
767 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
768 if (!connection->useSSL)
769 {
770 *sent = send(connection->socketFD, msg, len, flags);
771 if (*sent == -1)
772 return sock_get_error(errno);
773 return ERROR_SUCCESS;
774 }
775 else
776 {
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
787 }
788 }
789
790 /******************************************************************************
791 * NETCON_recv
792 * Basically calls 'recv()' unless we should use SSL
793 * number of chars received is put in *recvd
794 */
795 DWORD NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
796 int *recvd /* out */)
797 {
798 *recvd = 0;
799 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
800 if (!len)
801 return ERROR_SUCCESS;
802 if (!connection->useSSL)
803 {
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;
808 }
809 else
810 {
811 #ifdef SONAME_LIBSSL
812 *recvd = pSSL_read(connection->ssl_s, buf, len);
813
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;
819 }
820
821 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
822 #else
823 return ERROR_NOT_SUPPORTED;
824 #endif
825 }
826 }
827
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.
832 */
833 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
834 {
835 *available = 0;
836 if (!NETCON_connected(connection))
837 return FALSE;
838
839 if (!connection->useSSL)
840 {
841 #ifdef FIONREAD
842 int unread;
843 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
844 if (!retval)
845 {
846 TRACE("%d bytes of queued, but unread data\n", unread);
847 *available += unread;
848 }
849 #endif
850 }
851 else
852 {
853 #ifdef SONAME_LIBSSL
854 *available = pSSL_pending(connection->ssl_s);
855 #endif
856 }
857 return TRUE;
858 }
859
860 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
861 {
862 #ifdef SONAME_LIBSSL
863 X509* cert;
864 LPCVOID r = NULL;
865
866 if (!connection->useSSL)
867 return NULL;
868
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
875 }
876
877 int NETCON_GetCipherStrength(WININET_NETCONNECTION *connection)
878 {
879 #ifdef SONAME_LIBSSL
880 SSL_CIPHER *cipher;
881 int bits = 0;
882
883 if (!connection->useSSL)
884 return 0;
885 cipher = pSSL_get_current_cipher(connection->ssl_s);
886 if (!cipher)
887 return 0;
888 pSSL_CIPHER_get_bits(cipher, &bits);
889 return bits;
890 #else
891 return 0;
892 #endif
893 }
894
895 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
896 {
897 int result;
898 struct timeval tv;
899
900 /* FIXME: we should probably store the timeout in the connection to set
901 * when we do connect */
902 if (!NETCON_connected(connection))
903 return ERROR_SUCCESS;
904
905 /* value is in milliseconds, convert to struct timeval */
906 tv.tv_sec = value / 1000;
907 tv.tv_usec = (value % 1000) * 1000;
908
909 result = setsockopt(connection->socketFD, SOL_SOCKET,
910 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
911 sizeof(tv));
912
913 if (result == -1)
914 {
915 WARN("setsockopt failed (%s)\n", strerror(errno));
916 return sock_get_error(errno);
917 }
918
919 return ERROR_SUCCESS;
920 }