2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
4 * Copyright 2002 TransGaming Technologies Inc.
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
24 #include "wine/port.h"
26 #if defined(__MINGW32__) || defined (_MSC_VER)
30 #include <sys/types.h>
34 #ifdef HAVE_SYS_POLL_H
35 # include <sys/poll.h>
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
40 #ifdef HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
56 #ifdef HAVE_NETINET_IN_H
57 # include <netinet/in.h>
59 #ifdef HAVE_OPENSSL_SSL_H
60 # include <openssl/ssl.h>
71 #include "wine/library.h"
78 #include "wine/debug.h"
81 /* To avoid conflicts with the Unix socket headers. we only need it for
82 * the error codes anyway. */
86 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
89 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
92 * This should use winsock - To use winsock the functions will have to change a bit
93 * as they are designed for unix sockets.
94 * SSL stuff should use crypt32.dll
99 #include <openssl/err.h>
101 static CRITICAL_SECTION init_ssl_cs;
102 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
105 { &init_ssl_cs_debug.ProcessLocksList,
106 &init_ssl_cs_debug.ProcessLocksList },
107 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
109 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
111 static void *OpenSSL_ssl_handle;
112 static void *OpenSSL_crypto_handle;
114 static SSL_METHOD *meth;
117 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
119 /* OpenSSL functions that we use */
120 MAKE_FUNCPTR(SSL_library_init);
121 MAKE_FUNCPTR(SSL_load_error_strings);
122 MAKE_FUNCPTR(SSLv23_method);
123 MAKE_FUNCPTR(SSL_CTX_free);
124 MAKE_FUNCPTR(SSL_CTX_new);
125 MAKE_FUNCPTR(SSL_new);
126 MAKE_FUNCPTR(SSL_free);
127 MAKE_FUNCPTR(SSL_set_fd);
128 MAKE_FUNCPTR(SSL_connect);
129 MAKE_FUNCPTR(SSL_shutdown);
130 MAKE_FUNCPTR(SSL_write);
131 MAKE_FUNCPTR(SSL_read);
132 MAKE_FUNCPTR(SSL_pending);
133 MAKE_FUNCPTR(SSL_get_verify_result);
134 MAKE_FUNCPTR(SSL_get_peer_certificate);
135 MAKE_FUNCPTR(SSL_CTX_get_timeout);
136 MAKE_FUNCPTR(SSL_CTX_set_timeout);
137 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
139 /* OpenSSL's libcrypto functions that we use */
140 MAKE_FUNCPTR(BIO_new_fp);
141 MAKE_FUNCPTR(CRYPTO_num_locks);
142 MAKE_FUNCPTR(CRYPTO_set_id_callback);
143 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
144 MAKE_FUNCPTR(ERR_get_error);
145 MAKE_FUNCPTR(ERR_error_string);
146 MAKE_FUNCPTR(i2d_X509);
149 static CRITICAL_SECTION *ssl_locks;
151 static unsigned long ssl_thread_id(void)
153 return GetCurrentThreadId();
156 static void ssl_lock_callback(int mode, int type, const char *file, int line)
158 if (mode & CRYPTO_LOCK)
159 EnterCriticalSection(&ssl_locks[type]);
161 LeaveCriticalSection(&ssl_locks[type]);
166 BOOL NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
168 connection->useSSL = FALSE;
169 connection->socketFD = -1;
172 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
175 TRACE("using SSL connection\n");
176 EnterCriticalSection(&init_ssl_cs);
177 if (OpenSSL_ssl_handle) /* already initialized everything */
179 LeaveCriticalSection(&init_ssl_cs);
182 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
183 if (!OpenSSL_ssl_handle)
185 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
187 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
188 LeaveCriticalSection(&init_ssl_cs);
191 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
192 if (!OpenSSL_crypto_handle)
194 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
196 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
197 LeaveCriticalSection(&init_ssl_cs);
201 /* mmm nice ugly macroness */
203 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
206 ERR("failed to load symbol %s\n", #x); \
207 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
208 LeaveCriticalSection(&init_ssl_cs); \
212 DYNSSL(SSL_library_init);
213 DYNSSL(SSL_load_error_strings);
214 DYNSSL(SSLv23_method);
215 DYNSSL(SSL_CTX_free);
221 DYNSSL(SSL_shutdown);
225 DYNSSL(SSL_get_verify_result);
226 DYNSSL(SSL_get_peer_certificate);
227 DYNSSL(SSL_CTX_get_timeout);
228 DYNSSL(SSL_CTX_set_timeout);
229 DYNSSL(SSL_CTX_set_default_verify_paths);
232 #define DYNCRYPTO(x) \
233 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
236 ERR("failed to load symbol %s\n", #x); \
237 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
238 LeaveCriticalSection(&init_ssl_cs); \
241 DYNCRYPTO(BIO_new_fp);
242 DYNCRYPTO(CRYPTO_num_locks);
243 DYNCRYPTO(CRYPTO_set_id_callback);
244 DYNCRYPTO(CRYPTO_set_locking_callback);
245 DYNCRYPTO(ERR_get_error);
246 DYNCRYPTO(ERR_error_string);
251 pSSL_load_error_strings();
252 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
254 meth = pSSLv23_method();
255 ctx = pSSL_CTX_new(meth);
256 if (!pSSL_CTX_set_default_verify_paths(ctx))
258 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
259 pERR_error_string(pERR_get_error(), 0));
260 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
261 LeaveCriticalSection(&init_ssl_cs);
265 pCRYPTO_set_id_callback(ssl_thread_id);
266 ssl_locks = HeapAlloc(GetProcessHeap(), 0,
267 pCRYPTO_num_locks() * sizeof(CRITICAL_SECTION));
270 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
271 LeaveCriticalSection(&init_ssl_cs);
274 for (i = 0; i < pCRYPTO_num_locks(); i++)
275 InitializeCriticalSection(&ssl_locks[i]);
276 pCRYPTO_set_locking_callback(ssl_lock_callback);
277 LeaveCriticalSection(&init_ssl_cs);
279 FIXME("can't use SSL, not compiled in.\n");
280 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
287 void NETCON_unload(void)
289 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
290 if (OpenSSL_crypto_handle)
292 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
294 if (OpenSSL_ssl_handle)
298 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
303 for (i = 0; i < pCRYPTO_num_locks(); i++) DeleteCriticalSection(&ssl_locks[i]);
304 HeapFree(GetProcessHeap(), 0, ssl_locks);
309 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
311 if (connection->socketFD == -1)
317 /* translate a unix error code into a winsock one */
318 int sock_get_error( int err )
320 #if !defined(__MINGW32__) && !defined (_MSC_VER)
323 case EINTR: return WSAEINTR;
324 case EBADF: return WSAEBADF;
326 case EACCES: return WSAEACCES;
327 case EFAULT: return WSAEFAULT;
328 case EINVAL: return WSAEINVAL;
329 case EMFILE: return WSAEMFILE;
330 case EWOULDBLOCK: return WSAEWOULDBLOCK;
331 case EINPROGRESS: return WSAEINPROGRESS;
332 case EALREADY: return WSAEALREADY;
333 case ENOTSOCK: return WSAENOTSOCK;
334 case EDESTADDRREQ: return WSAEDESTADDRREQ;
335 case EMSGSIZE: return WSAEMSGSIZE;
336 case EPROTOTYPE: return WSAEPROTOTYPE;
337 case ENOPROTOOPT: return WSAENOPROTOOPT;
338 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
339 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
340 case EOPNOTSUPP: return WSAEOPNOTSUPP;
341 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
342 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
343 case EADDRINUSE: return WSAEADDRINUSE;
344 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
345 case ENETDOWN: return WSAENETDOWN;
346 case ENETUNREACH: return WSAENETUNREACH;
347 case ENETRESET: return WSAENETRESET;
348 case ECONNABORTED: return WSAECONNABORTED;
350 case ECONNRESET: return WSAECONNRESET;
351 case ENOBUFS: return WSAENOBUFS;
352 case EISCONN: return WSAEISCONN;
353 case ENOTCONN: return WSAENOTCONN;
354 case ESHUTDOWN: return WSAESHUTDOWN;
355 case ETOOMANYREFS: return WSAETOOMANYREFS;
356 case ETIMEDOUT: return WSAETIMEDOUT;
357 case ECONNREFUSED: return WSAECONNREFUSED;
358 case ELOOP: return WSAELOOP;
359 case ENAMETOOLONG: return WSAENAMETOOLONG;
360 case EHOSTDOWN: return WSAEHOSTDOWN;
361 case EHOSTUNREACH: return WSAEHOSTUNREACH;
362 case ENOTEMPTY: return WSAENOTEMPTY;
364 case EPROCLIM: return WSAEPROCLIM;
367 case EUSERS: return WSAEUSERS;
370 case EDQUOT: return WSAEDQUOT;
373 case ESTALE: return WSAESTALE;
376 case EREMOTE: return WSAEREMOTE;
378 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
384 /******************************************************************************
386 * Basically calls 'socket()'
388 DWORD NETCON_create(WININET_NETCONNECTION *connection, int domain,
389 int type, int protocol)
392 if (connection->useSSL)
393 return ERROR_NOT_SUPPORTED;
396 connection->socketFD = socket(domain, type, protocol);
397 if (connection->socketFD == -1)
398 return sock_get_error(errno);
400 return ERROR_SUCCESS;
403 /******************************************************************************
405 * Basically calls 'close()' unless we should use SSL
407 DWORD NETCON_close(WININET_NETCONNECTION *connection)
411 if (!NETCON_connected(connection)) return ERROR_SUCCESS;
414 if (connection->useSSL)
416 pSSL_shutdown(connection->ssl_s);
417 pSSL_free(connection->ssl_s);
418 connection->ssl_s = NULL;
420 connection->useSSL = FALSE;
424 result = closesocket(connection->socketFD);
425 connection->socketFD = -1;
428 return sock_get_error(errno);
429 return ERROR_SUCCESS;
432 static BOOL check_hostname(X509 *cert, char *hostname)
434 /* FIXME: implement */
438 /******************************************************************************
439 * NETCON_secure_connect
440 * Initiates a secure connection over an existing plaintext connection.
442 DWORD NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
444 DWORD res = ERROR_NOT_SUPPORTED;
451 /* can't connect if we are already connected */
452 if (connection->useSSL)
454 ERR("already connected\n");
455 return ERROR_INTERNET_CANNOT_CONNECT;
458 connection->ssl_s = pSSL_new(ctx);
459 if (!connection->ssl_s)
461 ERR("SSL_new failed: %s\n",
462 pERR_error_string(pERR_get_error(), 0));
463 res = ERROR_OUTOFMEMORY;
467 if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
469 ERR("SSL_set_fd failed: %s\n",
470 pERR_error_string(pERR_get_error(), 0));
471 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
475 if (pSSL_connect(connection->ssl_s) <= 0)
477 ERR("SSL_connect failed: %s\n",
478 pERR_error_string(pERR_get_error(), 0));
479 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
482 cert = pSSL_get_peer_certificate(connection->ssl_s);
485 ERR("no certificate for server %s\n", debugstr_w(hostname));
486 /* FIXME: is this the best error? */
487 res = ERROR_INTERNET_INVALID_CA;
490 verify_res = pSSL_get_verify_result(connection->ssl_s);
491 if (verify_res != X509_V_OK)
493 ERR("couldn't verify the security of the connection, %ld\n", verify_res);
494 /* FIXME: we should set an error and return, but we only warn at
498 len = WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, NULL, 0, NULL, NULL);
499 hostname_unix = HeapAlloc(GetProcessHeap(), 0, len);
502 res = ERROR_OUTOFMEMORY;
505 WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, hostname_unix, len, NULL, NULL);
507 if (!check_hostname(cert, hostname_unix))
509 HeapFree(GetProcessHeap(), 0, hostname_unix);
510 res = ERROR_INTERNET_SEC_CERT_CN_INVALID;
514 HeapFree(GetProcessHeap(), 0, hostname_unix);
515 connection->useSSL = TRUE;
516 return ERROR_SUCCESS;
519 if (connection->ssl_s)
521 pSSL_shutdown(connection->ssl_s);
522 pSSL_free(connection->ssl_s);
523 connection->ssl_s = NULL;
529 /******************************************************************************
531 * Connects to the specified address.
533 DWORD NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
534 unsigned int addrlen)
538 result = connect(connection->socketFD, serv_addr, addrlen);
541 WARN("Unable to connect to host (%s)\n", strerror(errno));
543 closesocket(connection->socketFD);
544 connection->socketFD = -1;
545 return sock_get_error(errno);
548 return ERROR_SUCCESS;
551 /******************************************************************************
553 * Basically calls 'send()' unless we should use SSL
554 * number of chars send is put in *sent
556 DWORD NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
559 if (!NETCON_connected(connection)) return ERROR_INTERNET_CONNECTION_ABORTED;
560 if (!connection->useSSL)
562 *sent = send(connection->socketFD, msg, len, flags);
564 return sock_get_error(errno);
565 return ERROR_SUCCESS;
571 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
572 *sent = pSSL_write(connection->ssl_s, msg, len);
573 if (*sent < 1 && len)
574 return ERROR_INTERNET_CONNECTION_ABORTED;
575 return ERROR_SUCCESS;
577 return ERROR_NOT_SUPPORTED;
582 /******************************************************************************
584 * Basically calls 'recv()' unless we should use SSL
585 * number of chars received is put in *recvd
587 BOOL NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
588 int *recvd /* out */)
591 if (!NETCON_connected(connection)) return FALSE;
594 if (!connection->useSSL)
596 *recvd = recv(connection->socketFD, buf, len, flags);
599 INTERNET_SetLastError(sock_get_error(errno));
607 *recvd = pSSL_read(connection->ssl_s, buf, len);
608 return *recvd > 0 || !len;
615 /******************************************************************************
616 * NETCON_query_data_available
617 * Returns the number of bytes of peeked data plus the number of bytes of
618 * queued, but unread data.
620 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
623 if (!NETCON_connected(connection))
626 if (!connection->useSSL)
630 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
633 TRACE("%d bytes of queued, but unread data\n", unread);
634 *available += unread;
641 *available = pSSL_pending(connection->ssl_s);
647 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
651 unsigned char* buffer,*p;
653 BOOL malloced = FALSE;
656 if (!connection->useSSL)
659 cert = pSSL_get_peer_certificate(connection->ssl_s);
661 len = pi2d_X509(cert,&p);
663 * SSL 0.9.7 and above malloc the buffer if it is null.
664 * however earlier version do not and so we would need to alloc the buffer.
666 * see the i2d_X509 man page for more details.
670 buffer = HeapAlloc(GetProcessHeap(),0,len);
672 len = pi2d_X509(cert,&p);
680 r = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
685 HeapFree(GetProcessHeap(),0,buffer);
693 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
698 /* FIXME: we should probably store the timeout in the connection to set
699 * when we do connect */
700 if (!NETCON_connected(connection))
701 return ERROR_SUCCESS;
703 /* value is in milliseconds, convert to struct timeval */
704 tv.tv_sec = value / 1000;
705 tv.tv_usec = (value % 1000) * 1000;
707 result = setsockopt(connection->socketFD, SOL_SOCKET,
708 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
713 WARN("setsockopt failed (%s)\n", strerror(errno));
714 return sock_get_error(errno);
717 return ERROR_SUCCESS;