d3dcompiler_37: Stub dll.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blob54ca51b74e532cda7d79fc614d9f00ea5e503830
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> 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;
126 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
128 /* OpenSSL functions that we use */
129 MAKE_FUNCPTR(SSL_library_init);
130 MAKE_FUNCPTR(SSL_load_error_strings);
131 MAKE_FUNCPTR(SSLv23_method);
132 MAKE_FUNCPTR(SSL_CTX_free);
133 MAKE_FUNCPTR(SSL_CTX_new);
134 MAKE_FUNCPTR(SSL_new);
135 MAKE_FUNCPTR(SSL_free);
136 MAKE_FUNCPTR(SSL_set_fd);
137 MAKE_FUNCPTR(SSL_connect);
138 MAKE_FUNCPTR(SSL_shutdown);
139 MAKE_FUNCPTR(SSL_write);
140 MAKE_FUNCPTR(SSL_read);
141 MAKE_FUNCPTR(SSL_pending);
142 MAKE_FUNCPTR(SSL_get_error);
143 MAKE_FUNCPTR(SSL_get_ex_new_index);
144 MAKE_FUNCPTR(SSL_get_ex_data);
145 MAKE_FUNCPTR(SSL_set_ex_data);
146 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
147 MAKE_FUNCPTR(SSL_get_verify_result);
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(X509_STORE_CTX_get_ex_data);
155 /* OpenSSL's libcrypto functions that we use */
156 MAKE_FUNCPTR(BIO_new_fp);
157 MAKE_FUNCPTR(CRYPTO_num_locks);
158 MAKE_FUNCPTR(CRYPTO_set_id_callback);
159 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
160 MAKE_FUNCPTR(ERR_free_strings);
161 MAKE_FUNCPTR(ERR_get_error);
162 MAKE_FUNCPTR(ERR_error_string);
163 MAKE_FUNCPTR(i2d_X509);
164 MAKE_FUNCPTR(sk_num);
165 MAKE_FUNCPTR(sk_value);
166 #undef MAKE_FUNCPTR
168 static CRITICAL_SECTION *ssl_locks;
169 static unsigned int num_ssl_locks;
171 static unsigned long ssl_thread_id(void)
173 return GetCurrentThreadId();
176 static void ssl_lock_callback(int mode, int type, const char *file, int line)
178 if (mode & CRYPTO_LOCK)
179 EnterCriticalSection(&ssl_locks[type]);
180 else
181 LeaveCriticalSection(&ssl_locks[type]);
184 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
186 unsigned char* buffer,*p;
187 INT len;
188 BOOL malloced = FALSE;
189 PCCERT_CONTEXT ret;
191 p = NULL;
192 len = pi2d_X509(cert,&p);
194 * SSL 0.9.7 and above malloc the buffer if it is null.
195 * however earlier version do not and so we would need to alloc the buffer.
197 * see the i2d_X509 man page for more details.
199 if (!p)
201 buffer = HeapAlloc(GetProcessHeap(),0,len);
202 p = buffer;
203 len = pi2d_X509(cert,&p);
205 else
207 buffer = p;
208 malloced = TRUE;
211 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
213 if (malloced)
214 free(buffer);
215 else
216 HeapFree(GetProcessHeap(),0,buffer);
218 return ret;
221 static DWORD netconn_verify_cert(PCCERT_CONTEXT cert, HCERTSTORE store,
222 WCHAR *server)
224 BOOL ret;
225 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
226 PCCERT_CHAIN_CONTEXT chain;
227 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
228 char *server_auth[] = { oid_server_auth };
229 DWORD err = ERROR_SUCCESS;
231 TRACE("verifying %s\n", debugstr_w(server));
232 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
233 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
234 if ((ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0,
235 NULL, &chain)))
237 if (chain->TrustStatus.dwErrorStatus)
239 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
240 err = ERROR_INTERNET_SEC_CERT_DATE_INVALID;
241 else if (chain->TrustStatus.dwErrorStatus &
242 CERT_TRUST_IS_UNTRUSTED_ROOT)
243 err = ERROR_INTERNET_INVALID_CA;
244 else if ((chain->TrustStatus.dwErrorStatus &
245 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
246 (chain->TrustStatus.dwErrorStatus &
247 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
248 err = ERROR_INTERNET_SEC_CERT_NO_REV;
249 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
250 err = ERROR_INTERNET_SEC_CERT_REVOKED;
251 else if (chain->TrustStatus.dwErrorStatus &
252 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
253 err = ERROR_INTERNET_SEC_INVALID_CERT;
254 else
255 err = ERROR_INTERNET_SEC_INVALID_CERT;
257 else
259 CERT_CHAIN_POLICY_PARA policyPara;
260 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
261 CERT_CHAIN_POLICY_STATUS policyStatus;
263 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
264 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
265 sslExtraPolicyPara.pwszServerName = server;
266 policyPara.cbSize = sizeof(policyPara);
267 policyPara.dwFlags = 0;
268 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
269 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
270 chain, &policyPara, &policyStatus);
271 /* Any error in the policy status indicates that the
272 * policy couldn't be verified.
274 if (ret && policyStatus.dwError)
276 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
277 err = ERROR_INTERNET_SEC_CERT_CN_INVALID;
278 else
279 err = ERROR_INTERNET_SEC_INVALID_CERT;
282 CertFreeCertificateChain(chain);
284 TRACE("returning %08x\n", err);
285 return err;
288 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
290 SSL *ssl;
291 WCHAR *server;
292 BOOL ret = FALSE;
294 ssl = pX509_STORE_CTX_get_ex_data(ctx,
295 pSSL_get_ex_data_X509_STORE_CTX_idx());
296 server = pSSL_get_ex_data(ssl, hostname_idx);
297 if (preverify_ok)
299 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
300 CERT_STORE_CREATE_NEW_FLAG, NULL);
302 if (store)
304 X509 *cert;
305 int i;
306 PCCERT_CONTEXT endCert = NULL;
308 ret = TRUE;
309 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
311 PCCERT_CONTEXT context;
313 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
314 if ((context = X509_to_cert_context(cert)))
316 if (i == 0)
317 ret = CertAddCertificateContextToStore(store, context,
318 CERT_STORE_ADD_ALWAYS, &endCert);
319 else
320 ret = CertAddCertificateContextToStore(store, context,
321 CERT_STORE_ADD_ALWAYS, NULL);
322 CertFreeCertificateContext(context);
325 if (!endCert) ret = FALSE;
326 if (ret)
328 DWORD_PTR err = netconn_verify_cert(endCert, store, server);
330 if (err)
332 pSSL_set_ex_data(ssl, error_idx, (void *)err);
333 ret = FALSE;
336 CertFreeCertificateContext(endCert);
337 CertCloseStore(store, 0);
339 } else
340 pSSL_set_ex_data(ssl, error_idx, (void *)ERROR_INTERNET_SEC_CERT_ERRORS);
342 return ret;
345 #endif
347 DWORD NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
349 connection->useSSL = FALSE;
350 connection->socketFD = -1;
351 if (useSSL)
353 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
354 int i;
356 TRACE("using SSL connection\n");
357 EnterCriticalSection(&init_ssl_cs);
358 if (OpenSSL_ssl_handle) /* already initialized everything */
360 LeaveCriticalSection(&init_ssl_cs);
361 return ERROR_SUCCESS;
363 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
364 if (!OpenSSL_ssl_handle)
366 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
367 SONAME_LIBSSL);
368 LeaveCriticalSection(&init_ssl_cs);
369 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
371 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
372 if (!OpenSSL_crypto_handle)
374 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
375 SONAME_LIBCRYPTO);
376 LeaveCriticalSection(&init_ssl_cs);
377 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
380 /* mmm nice ugly macroness */
381 #define DYNSSL(x) \
382 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
383 if (!p##x) \
385 ERR("failed to load symbol %s\n", #x); \
386 LeaveCriticalSection(&init_ssl_cs); \
387 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
390 DYNSSL(SSL_library_init);
391 DYNSSL(SSL_load_error_strings);
392 DYNSSL(SSLv23_method);
393 DYNSSL(SSL_CTX_free);
394 DYNSSL(SSL_CTX_new);
395 DYNSSL(SSL_new);
396 DYNSSL(SSL_free);
397 DYNSSL(SSL_set_fd);
398 DYNSSL(SSL_connect);
399 DYNSSL(SSL_shutdown);
400 DYNSSL(SSL_write);
401 DYNSSL(SSL_read);
402 DYNSSL(SSL_pending);
403 DYNSSL(SSL_get_error);
404 DYNSSL(SSL_get_ex_new_index);
405 DYNSSL(SSL_get_ex_data);
406 DYNSSL(SSL_set_ex_data);
407 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
408 DYNSSL(SSL_get_verify_result);
409 DYNSSL(SSL_get_peer_certificate);
410 DYNSSL(SSL_CTX_get_timeout);
411 DYNSSL(SSL_CTX_set_timeout);
412 DYNSSL(SSL_CTX_set_default_verify_paths);
413 DYNSSL(SSL_CTX_set_verify);
414 DYNSSL(X509_STORE_CTX_get_ex_data);
415 #undef DYNSSL
417 #define DYNCRYPTO(x) \
418 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
419 if (!p##x) \
421 ERR("failed to load symbol %s\n", #x); \
422 LeaveCriticalSection(&init_ssl_cs); \
423 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
425 DYNCRYPTO(BIO_new_fp);
426 DYNCRYPTO(CRYPTO_num_locks);
427 DYNCRYPTO(CRYPTO_set_id_callback);
428 DYNCRYPTO(CRYPTO_set_locking_callback);
429 DYNCRYPTO(ERR_free_strings);
430 DYNCRYPTO(ERR_get_error);
431 DYNCRYPTO(ERR_error_string);
432 DYNCRYPTO(i2d_X509);
433 DYNCRYPTO(sk_num);
434 DYNCRYPTO(sk_value);
435 #undef DYNCRYPTO
437 pSSL_library_init();
438 pSSL_load_error_strings();
439 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
441 meth = pSSLv23_method();
442 ctx = pSSL_CTX_new(meth);
443 if (!pSSL_CTX_set_default_verify_paths(ctx))
445 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
446 pERR_error_string(pERR_get_error(), 0));
447 LeaveCriticalSection(&init_ssl_cs);
448 return ERROR_OUTOFMEMORY;
450 hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index",
451 NULL, NULL, NULL);
452 if (hostname_idx == -1)
454 ERR("SSL_get_ex_new_index failed; %s\n",
455 pERR_error_string(pERR_get_error(), 0));
456 LeaveCriticalSection(&init_ssl_cs);
457 return ERROR_OUTOFMEMORY;
459 error_idx = pSSL_get_ex_new_index(0, (void *)"error index",
460 NULL, NULL, NULL);
461 if (error_idx == -1)
463 ERR("SSL_get_ex_new_index failed; %s\n",
464 pERR_error_string(pERR_get_error(), 0));
465 LeaveCriticalSection(&init_ssl_cs);
466 return ERROR_OUTOFMEMORY;
468 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
470 pCRYPTO_set_id_callback(ssl_thread_id);
471 num_ssl_locks = pCRYPTO_num_locks();
472 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
473 if (!ssl_locks)
475 LeaveCriticalSection(&init_ssl_cs);
476 return ERROR_OUTOFMEMORY;
478 for (i = 0; i < num_ssl_locks; i++)
479 InitializeCriticalSection(&ssl_locks[i]);
480 pCRYPTO_set_locking_callback(ssl_lock_callback);
481 LeaveCriticalSection(&init_ssl_cs);
482 #else
483 FIXME("can't use SSL, not compiled in.\n");
484 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
485 #endif
487 return ERROR_SUCCESS;
490 void NETCON_unload(void)
492 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
493 if (OpenSSL_crypto_handle)
495 pERR_free_strings();
496 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
498 if (OpenSSL_ssl_handle)
500 if (ctx)
501 pSSL_CTX_free(ctx);
502 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
504 if (ssl_locks)
506 int i;
507 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
508 HeapFree(GetProcessHeap(), 0, ssl_locks);
510 #endif
513 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
515 if (connection->socketFD == -1)
516 return FALSE;
517 else
518 return TRUE;
521 /* translate a unix error code into a winsock one */
522 int sock_get_error( int err )
524 #if !defined(__MINGW32__) && !defined (_MSC_VER)
525 switch (err)
527 case EINTR: return WSAEINTR;
528 case EBADF: return WSAEBADF;
529 case EPERM:
530 case EACCES: return WSAEACCES;
531 case EFAULT: return WSAEFAULT;
532 case EINVAL: return WSAEINVAL;
533 case EMFILE: return WSAEMFILE;
534 case EWOULDBLOCK: return WSAEWOULDBLOCK;
535 case EINPROGRESS: return WSAEINPROGRESS;
536 case EALREADY: return WSAEALREADY;
537 case ENOTSOCK: return WSAENOTSOCK;
538 case EDESTADDRREQ: return WSAEDESTADDRREQ;
539 case EMSGSIZE: return WSAEMSGSIZE;
540 case EPROTOTYPE: return WSAEPROTOTYPE;
541 case ENOPROTOOPT: return WSAENOPROTOOPT;
542 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
543 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
544 case EOPNOTSUPP: return WSAEOPNOTSUPP;
545 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
546 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
547 case EADDRINUSE: return WSAEADDRINUSE;
548 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
549 case ENETDOWN: return WSAENETDOWN;
550 case ENETUNREACH: return WSAENETUNREACH;
551 case ENETRESET: return WSAENETRESET;
552 case ECONNABORTED: return WSAECONNABORTED;
553 case EPIPE:
554 case ECONNRESET: return WSAECONNRESET;
555 case ENOBUFS: return WSAENOBUFS;
556 case EISCONN: return WSAEISCONN;
557 case ENOTCONN: return WSAENOTCONN;
558 case ESHUTDOWN: return WSAESHUTDOWN;
559 case ETOOMANYREFS: return WSAETOOMANYREFS;
560 case ETIMEDOUT: return WSAETIMEDOUT;
561 case ECONNREFUSED: return WSAECONNREFUSED;
562 case ELOOP: return WSAELOOP;
563 case ENAMETOOLONG: return WSAENAMETOOLONG;
564 case EHOSTDOWN: return WSAEHOSTDOWN;
565 case EHOSTUNREACH: return WSAEHOSTUNREACH;
566 case ENOTEMPTY: return WSAENOTEMPTY;
567 #ifdef EPROCLIM
568 case EPROCLIM: return WSAEPROCLIM;
569 #endif
570 #ifdef EUSERS
571 case EUSERS: return WSAEUSERS;
572 #endif
573 #ifdef EDQUOT
574 case EDQUOT: return WSAEDQUOT;
575 #endif
576 #ifdef ESTALE
577 case ESTALE: return WSAESTALE;
578 #endif
579 #ifdef EREMOTE
580 case EREMOTE: return WSAEREMOTE;
581 #endif
582 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
584 #endif
585 return err;
588 /******************************************************************************
589 * NETCON_create
590 * Basically calls 'socket()'
592 DWORD NETCON_create(WININET_NETCONNECTION *connection, int domain,
593 int type, int protocol)
595 #ifdef SONAME_LIBSSL
596 if (connection->useSSL)
597 return ERROR_NOT_SUPPORTED;
598 #endif
600 connection->socketFD = socket(domain, type, protocol);
601 if (connection->socketFD == -1)
602 return sock_get_error(errno);
604 return ERROR_SUCCESS;
607 /******************************************************************************
608 * NETCON_close
609 * Basically calls 'close()' unless we should use SSL
611 DWORD NETCON_close(WININET_NETCONNECTION *connection)
613 int result;
615 if (!NETCON_connected(connection)) return ERROR_SUCCESS;
617 #ifdef SONAME_LIBSSL
618 if (connection->useSSL)
620 pSSL_shutdown(connection->ssl_s);
621 pSSL_free(connection->ssl_s);
622 connection->ssl_s = NULL;
624 connection->useSSL = FALSE;
626 #endif
628 result = closesocket(connection->socketFD);
629 connection->socketFD = -1;
631 if (result == -1)
632 return sock_get_error(errno);
633 return ERROR_SUCCESS;
636 /******************************************************************************
637 * NETCON_secure_connect
638 * Initiates a secure connection over an existing plaintext connection.
640 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPWSTR hostname)
642 DWORD res = ERROR_NOT_SUPPORTED;
643 #ifdef SONAME_LIBSSL
644 long verify_res;
645 X509 *cert;
647 /* can't connect if we are already connected */
648 if (connection->useSSL)
650 ERR("already connected\n");
651 return ERROR_INTERNET_CANNOT_CONNECT;
654 connection->ssl_s = pSSL_new(ctx);
655 if (!connection->ssl_s)
657 ERR("SSL_new failed: %s\n",
658 pERR_error_string(pERR_get_error(), 0));
659 res = ERROR_OUTOFMEMORY;
660 goto fail;
663 if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
665 ERR("SSL_set_fd failed: %s\n",
666 pERR_error_string(pERR_get_error(), 0));
667 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
668 goto fail;
671 if (pSSL_connect(connection->ssl_s) <= 0)
673 res = (DWORD_PTR)pSSL_get_ex_data(connection->ssl_s, error_idx);
674 if (!res)
675 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
676 ERR("SSL_connect failed: %d\n", res);
677 goto fail;
679 pSSL_set_ex_data(connection->ssl_s, hostname_idx, hostname);
680 cert = pSSL_get_peer_certificate(connection->ssl_s);
681 if (!cert)
683 ERR("no certificate for server %s\n", debugstr_w(hostname));
684 /* FIXME: is this the best error? */
685 res = ERROR_INTERNET_INVALID_CA;
686 goto fail;
688 verify_res = pSSL_get_verify_result(connection->ssl_s);
689 if (verify_res != X509_V_OK)
691 ERR("couldn't verify the security of the connection, %ld\n", verify_res);
692 /* FIXME: we should set an error and return, but we only warn at
693 * the moment */
696 connection->useSSL = TRUE;
697 return ERROR_SUCCESS;
699 fail:
700 if (connection->ssl_s)
702 pSSL_shutdown(connection->ssl_s);
703 pSSL_free(connection->ssl_s);
704 connection->ssl_s = NULL;
706 #endif
707 return res;
710 /******************************************************************************
711 * NETCON_connect
712 * Connects to the specified address.
714 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
715 unsigned int addrlen)
717 int result;
719 result = connect(connection->socketFD, serv_addr, addrlen);
720 if (result == -1)
722 WARN("Unable to connect to host (%s)\n", strerror(errno));
724 closesocket(connection->socketFD);
725 connection->socketFD = -1;
726 return sock_get_error(errno);
729 return ERROR_SUCCESS;
732 /******************************************************************************
733 * NETCON_send
734 * Basically calls 'send()' unless we should use SSL
735 * number of chars send is put in *sent
737 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
738 int *sent /* out */)
740 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
741 if (!connection->useSSL)
743 *sent = send(connection->socketFD, msg, len, flags);
744 if (*sent == -1)
745 return sock_get_error(errno);
746 return ERROR_SUCCESS;
748 else
750 #ifdef SONAME_LIBSSL
751 if (flags)
752 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
753 *sent = pSSL_write(connection->ssl_s, msg, len);
754 if (*sent < 1 && len)
755 return ERROR_INTERNET_CONNECTION_ABORTED;
756 return ERROR_SUCCESS;
757 #else
758 return ERROR_NOT_SUPPORTED;
759 #endif
763 /******************************************************************************
764 * NETCON_recv
765 * Basically calls 'recv()' unless we should use SSL
766 * number of chars received is put in *recvd
768 DWORD NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
769 int *recvd /* out */)
771 *recvd = 0;
772 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
773 if (!len)
774 return ERROR_SUCCESS;
775 if (!connection->useSSL)
777 *recvd = recv(connection->socketFD, buf, len, flags);
778 if(!*recvd)
779 NETCON_close(connection);
780 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
782 else
784 #ifdef SONAME_LIBSSL
785 *recvd = pSSL_read(connection->ssl_s, buf, len);
787 /* Check if EOF was received */
788 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
789 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL)) {
790 NETCON_close(connection);
791 return ERROR_SUCCESS;
794 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
795 #else
796 return ERROR_NOT_SUPPORTED;
797 #endif
801 /******************************************************************************
802 * NETCON_query_data_available
803 * Returns the number of bytes of peeked data plus the number of bytes of
804 * queued, but unread data.
806 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
808 *available = 0;
809 if (!NETCON_connected(connection))
810 return FALSE;
812 if (!connection->useSSL)
814 #ifdef FIONREAD
815 int unread;
816 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
817 if (!retval)
819 TRACE("%d bytes of queued, but unread data\n", unread);
820 *available += unread;
822 #endif
824 else
826 #ifdef SONAME_LIBSSL
827 *available = pSSL_pending(connection->ssl_s);
828 #endif
830 return TRUE;
833 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
835 #ifdef SONAME_LIBSSL
836 X509* cert;
837 LPCVOID r = NULL;
839 if (!connection->useSSL)
840 return NULL;
842 cert = pSSL_get_peer_certificate(connection->ssl_s);
843 r = X509_to_cert_context(cert);
844 return r;
845 #else
846 return NULL;
847 #endif
850 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
852 int result;
853 struct timeval tv;
855 /* FIXME: we should probably store the timeout in the connection to set
856 * when we do connect */
857 if (!NETCON_connected(connection))
858 return ERROR_SUCCESS;
860 /* value is in milliseconds, convert to struct timeval */
861 tv.tv_sec = value / 1000;
862 tv.tv_usec = (value % 1000) * 1000;
864 result = setsockopt(connection->socketFD, SOL_SOCKET,
865 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
866 sizeof(tv));
868 if (result == -1)
870 WARN("setsockopt failed (%s)\n", strerror(errno));
871 return sock_get_error(errno);
874 return ERROR_SUCCESS;