wininet: Protect OpenSSL initialization with critical section.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blobd54e3ac97bd26d3ae0f0991171c1480028ca5b0e
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 #if defined(__MINGW32__) || defined (_MSC_VER)
27 #include <ws2tcpip.h>
28 #endif
30 #include <sys/types.h>
31 #ifdef HAVE_POLL_H
32 #include <poll.h>
33 #endif
34 #ifdef HAVE_SYS_POLL_H
35 # include <sys/poll.h>
36 #endif
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #ifdef HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
42 #endif
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
51 #endif
52 #include <time.h>
53 #ifdef HAVE_NETDB_H
54 # include <netdb.h>
55 #endif
56 #ifdef HAVE_NETINET_IN_H
57 # include <netinet/in.h>
58 #endif
59 #ifdef HAVE_OPENSSL_SSL_H
60 # include <openssl/ssl.h>
61 #undef FAR
62 #undef DSA
63 #endif
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdio.h>
69 #include <errno.h>
71 #include "wine/library.h"
72 #include "windef.h"
73 #include "winbase.h"
74 #include "wininet.h"
75 #include "winerror.h"
76 #include "wincrypt.h"
78 #include "wine/debug.h"
79 #include "internet.h"
81 /* To avoid conflicts with the Unix socket headers. we only need it for
82 * the error codes anyway. */
83 #define USE_WS_PREFIX
84 #include "winsock2.h"
86 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
89 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
91 /* FIXME!!!!!!
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
97 #ifdef SONAME_LIBSSL
99 #include <openssl/err.h>
101 static CRITICAL_SECTION init_ssl_cs;
102 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
104 0, 0, &init_ssl_cs,
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;
115 static SSL_CTX *ctx;
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_new);
124 MAKE_FUNCPTR(SSL_new);
125 MAKE_FUNCPTR(SSL_free);
126 MAKE_FUNCPTR(SSL_set_fd);
127 MAKE_FUNCPTR(SSL_connect);
128 MAKE_FUNCPTR(SSL_shutdown);
129 MAKE_FUNCPTR(SSL_write);
130 MAKE_FUNCPTR(SSL_read);
131 MAKE_FUNCPTR(SSL_pending);
132 MAKE_FUNCPTR(SSL_get_verify_result);
133 MAKE_FUNCPTR(SSL_get_peer_certificate);
134 MAKE_FUNCPTR(SSL_CTX_get_timeout);
135 MAKE_FUNCPTR(SSL_CTX_set_timeout);
136 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
138 /* OpenSSL's libcrypto functions that we use */
139 MAKE_FUNCPTR(BIO_new_fp);
140 MAKE_FUNCPTR(ERR_get_error);
141 MAKE_FUNCPTR(ERR_error_string);
142 MAKE_FUNCPTR(i2d_X509);
143 #undef MAKE_FUNCPTR
145 #endif
147 BOOL NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
149 connection->useSSL = FALSE;
150 connection->socketFD = -1;
151 if (useSSL)
153 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
154 TRACE("using SSL connection\n");
155 EnterCriticalSection(&init_ssl_cs);
156 if (OpenSSL_ssl_handle) /* already initialized everything */
158 LeaveCriticalSection(&init_ssl_cs);
159 return TRUE;
161 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
162 if (!OpenSSL_ssl_handle)
164 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
165 SONAME_LIBSSL);
166 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
167 LeaveCriticalSection(&init_ssl_cs);
168 return FALSE;
170 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
171 if (!OpenSSL_crypto_handle)
173 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
174 SONAME_LIBCRYPTO);
175 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
176 LeaveCriticalSection(&init_ssl_cs);
177 return FALSE;
180 /* mmm nice ugly macroness */
181 #define DYNSSL(x) \
182 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
183 if (!p##x) \
185 ERR("failed to load symbol %s\n", #x); \
186 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
187 LeaveCriticalSection(&init_ssl_cs); \
188 return FALSE; \
191 DYNSSL(SSL_library_init);
192 DYNSSL(SSL_load_error_strings);
193 DYNSSL(SSLv23_method);
194 DYNSSL(SSL_CTX_new);
195 DYNSSL(SSL_new);
196 DYNSSL(SSL_free);
197 DYNSSL(SSL_set_fd);
198 DYNSSL(SSL_connect);
199 DYNSSL(SSL_shutdown);
200 DYNSSL(SSL_write);
201 DYNSSL(SSL_read);
202 DYNSSL(SSL_pending);
203 DYNSSL(SSL_get_verify_result);
204 DYNSSL(SSL_get_peer_certificate);
205 DYNSSL(SSL_CTX_get_timeout);
206 DYNSSL(SSL_CTX_set_timeout);
207 DYNSSL(SSL_CTX_set_default_verify_paths);
208 #undef DYNSSL
210 #define DYNCRYPTO(x) \
211 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
212 if (!p##x) \
214 ERR("failed to load symbol %s\n", #x); \
215 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
216 LeaveCriticalSection(&init_ssl_cs); \
217 return FALSE; \
219 DYNCRYPTO(BIO_new_fp);
220 DYNCRYPTO(ERR_get_error);
221 DYNCRYPTO(ERR_error_string);
222 DYNCRYPTO(i2d_X509);
223 #undef DYNCRYPTO
225 pSSL_library_init();
226 pSSL_load_error_strings();
227 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
229 meth = pSSLv23_method();
230 ctx = pSSL_CTX_new(meth);
231 if (!pSSL_CTX_set_default_verify_paths(ctx))
233 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
234 pERR_error_string(pERR_get_error(), 0));
235 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
236 LeaveCriticalSection(&init_ssl_cs);
237 return FALSE;
239 LeaveCriticalSection(&init_ssl_cs);
240 #else
241 FIXME("can't use SSL, not compiled in.\n");
242 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
243 return FALSE;
244 #endif
246 return TRUE;
249 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
251 if (connection->socketFD == -1)
252 return FALSE;
253 else
254 return TRUE;
257 /* translate a unix error code into a winsock one */
258 static int sock_get_error( int err )
260 #if !defined(__MINGW32__) && !defined (_MSC_VER)
261 switch (err)
263 case EINTR: return WSAEINTR;
264 case EBADF: return WSAEBADF;
265 case EPERM:
266 case EACCES: return WSAEACCES;
267 case EFAULT: return WSAEFAULT;
268 case EINVAL: return WSAEINVAL;
269 case EMFILE: return WSAEMFILE;
270 case EWOULDBLOCK: return WSAEWOULDBLOCK;
271 case EINPROGRESS: return WSAEINPROGRESS;
272 case EALREADY: return WSAEALREADY;
273 case ENOTSOCK: return WSAENOTSOCK;
274 case EDESTADDRREQ: return WSAEDESTADDRREQ;
275 case EMSGSIZE: return WSAEMSGSIZE;
276 case EPROTOTYPE: return WSAEPROTOTYPE;
277 case ENOPROTOOPT: return WSAENOPROTOOPT;
278 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
279 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
280 case EOPNOTSUPP: return WSAEOPNOTSUPP;
281 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
282 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
283 case EADDRINUSE: return WSAEADDRINUSE;
284 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
285 case ENETDOWN: return WSAENETDOWN;
286 case ENETUNREACH: return WSAENETUNREACH;
287 case ENETRESET: return WSAENETRESET;
288 case ECONNABORTED: return WSAECONNABORTED;
289 case EPIPE:
290 case ECONNRESET: return WSAECONNRESET;
291 case ENOBUFS: return WSAENOBUFS;
292 case EISCONN: return WSAEISCONN;
293 case ENOTCONN: return WSAENOTCONN;
294 case ESHUTDOWN: return WSAESHUTDOWN;
295 case ETOOMANYREFS: return WSAETOOMANYREFS;
296 case ETIMEDOUT: return WSAETIMEDOUT;
297 case ECONNREFUSED: return WSAECONNREFUSED;
298 case ELOOP: return WSAELOOP;
299 case ENAMETOOLONG: return WSAENAMETOOLONG;
300 case EHOSTDOWN: return WSAEHOSTDOWN;
301 case EHOSTUNREACH: return WSAEHOSTUNREACH;
302 case ENOTEMPTY: return WSAENOTEMPTY;
303 #ifdef EPROCLIM
304 case EPROCLIM: return WSAEPROCLIM;
305 #endif
306 #ifdef EUSERS
307 case EUSERS: return WSAEUSERS;
308 #endif
309 #ifdef EDQUOT
310 case EDQUOT: return WSAEDQUOT;
311 #endif
312 #ifdef ESTALE
313 case ESTALE: return WSAESTALE;
314 #endif
315 #ifdef EREMOTE
316 case EREMOTE: return WSAEREMOTE;
317 #endif
318 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
320 #endif
321 return err;
324 /******************************************************************************
325 * NETCON_create
326 * Basically calls 'socket()'
328 BOOL NETCON_create(WININET_NETCONNECTION *connection, int domain,
329 int type, int protocol)
331 #ifdef SONAME_LIBSSL
332 if (connection->useSSL)
333 return FALSE;
334 #endif
336 connection->socketFD = socket(domain, type, protocol);
337 if (connection->socketFD == -1)
339 INTERNET_SetLastError(sock_get_error(errno));
340 return FALSE;
342 return TRUE;
345 /******************************************************************************
346 * NETCON_close
347 * Basically calls 'close()' unless we should use SSL
349 BOOL NETCON_close(WININET_NETCONNECTION *connection)
351 int result;
353 if (!NETCON_connected(connection)) return FALSE;
355 #ifdef SONAME_LIBSSL
356 if (connection->useSSL)
358 pSSL_shutdown(connection->ssl_s);
359 pSSL_free(connection->ssl_s);
360 connection->ssl_s = NULL;
362 connection->useSSL = FALSE;
364 #endif
366 result = closesocket(connection->socketFD);
367 connection->socketFD = -1;
369 if (result == -1)
371 INTERNET_SetLastError(sock_get_error(errno));
372 return FALSE;
374 return TRUE;
376 #ifdef SONAME_LIBSSL
377 static BOOL check_hostname(X509 *cert, char *hostname)
379 /* FIXME: implement */
380 return TRUE;
382 #endif
383 /******************************************************************************
384 * NETCON_secure_connect
385 * Initiates a secure connection over an existing plaintext connection.
387 BOOL NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
389 #ifdef SONAME_LIBSSL
390 long verify_res;
391 X509 *cert;
392 int len;
393 char *hostname_unix;
395 /* can't connect if we are already connected */
396 if (connection->useSSL)
398 ERR("already connected\n");
399 return FALSE;
402 connection->ssl_s = pSSL_new(ctx);
403 if (!connection->ssl_s)
405 ERR("SSL_new failed: %s\n",
406 pERR_error_string(pERR_get_error(), 0));
407 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
408 goto fail;
411 if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
413 ERR("SSL_set_fd failed: %s\n",
414 pERR_error_string(pERR_get_error(), 0));
415 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
416 goto fail;
419 if (pSSL_connect(connection->ssl_s) <= 0)
421 ERR("SSL_connect failed: %s\n",
422 pERR_error_string(pERR_get_error(), 0));
423 INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
424 goto fail;
426 cert = pSSL_get_peer_certificate(connection->ssl_s);
427 if (!cert)
429 ERR("no certificate for server %s\n", debugstr_w(hostname));
430 /* FIXME: is this the best error? */
431 INTERNET_SetLastError(ERROR_INTERNET_INVALID_CA);
432 goto fail;
434 verify_res = pSSL_get_verify_result(connection->ssl_s);
435 if (verify_res != X509_V_OK)
437 ERR("couldn't verify the security of the connection, %ld\n", verify_res);
438 /* FIXME: we should set an error and return, but we only warn at
439 * the moment */
442 len = WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, NULL, 0, NULL, NULL);
443 hostname_unix = HeapAlloc(GetProcessHeap(), 0, len);
444 if (!hostname_unix)
446 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
447 goto fail;
449 WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, hostname_unix, len, NULL, NULL);
451 if (!check_hostname(cert, hostname_unix))
453 HeapFree(GetProcessHeap(), 0, hostname_unix);
454 INTERNET_SetLastError(ERROR_INTERNET_SEC_CERT_CN_INVALID);
455 goto fail;
458 HeapFree(GetProcessHeap(), 0, hostname_unix);
459 connection->useSSL = TRUE;
460 return TRUE;
462 fail:
463 if (connection->ssl_s)
465 pSSL_shutdown(connection->ssl_s);
466 pSSL_free(connection->ssl_s);
467 connection->ssl_s = NULL;
469 #endif
470 return FALSE;
473 /******************************************************************************
474 * NETCON_connect
475 * Connects to the specified address.
477 BOOL NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
478 unsigned int addrlen)
480 int result;
482 if (!NETCON_connected(connection)) return FALSE;
484 result = connect(connection->socketFD, serv_addr, addrlen);
485 if (result == -1)
487 WARN("Unable to connect to host (%s)\n", strerror(errno));
488 INTERNET_SetLastError(sock_get_error(errno));
490 closesocket(connection->socketFD);
491 connection->socketFD = -1;
492 return FALSE;
495 return TRUE;
498 /******************************************************************************
499 * NETCON_send
500 * Basically calls 'send()' unless we should use SSL
501 * number of chars send is put in *sent
503 BOOL NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
504 int *sent /* out */)
506 if (!NETCON_connected(connection)) return FALSE;
507 if (!connection->useSSL)
509 *sent = send(connection->socketFD, msg, len, flags);
510 if (*sent == -1)
512 INTERNET_SetLastError(sock_get_error(errno));
513 return FALSE;
515 return TRUE;
517 else
519 #ifdef SONAME_LIBSSL
520 if (flags)
521 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
522 *sent = pSSL_write(connection->ssl_s, msg, len);
523 if (*sent < 1 && len)
524 return FALSE;
525 return TRUE;
526 #else
527 return FALSE;
528 #endif
532 /******************************************************************************
533 * NETCON_recv
534 * Basically calls 'recv()' unless we should use SSL
535 * number of chars received is put in *recvd
537 BOOL NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
538 int *recvd /* out */)
540 *recvd = 0;
541 if (!NETCON_connected(connection)) return FALSE;
542 if (!len)
543 return TRUE;
544 if (!connection->useSSL)
546 *recvd = recv(connection->socketFD, buf, len, flags);
547 if (*recvd == -1)
549 INTERNET_SetLastError(sock_get_error(errno));
550 return FALSE;
552 return TRUE;
554 else
556 #ifdef SONAME_LIBSSL
557 *recvd = pSSL_read(connection->ssl_s, buf, len);
558 return *recvd > 0 || !len;
559 #else
560 return FALSE;
561 #endif
565 /******************************************************************************
566 * NETCON_query_data_available
567 * Returns the number of bytes of peeked data plus the number of bytes of
568 * queued, but unread data.
570 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
572 *available = 0;
573 if (!NETCON_connected(connection))
574 return FALSE;
576 if (!connection->useSSL)
578 #ifdef FIONREAD
579 int unread;
580 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
581 if (!retval)
583 TRACE("%d bytes of queued, but unread data\n", unread);
584 *available += unread;
586 #endif
588 else
590 #ifdef SONAME_LIBSSL
591 *available = pSSL_pending(connection->ssl_s);
592 #endif
594 return TRUE;
597 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
599 #ifdef SONAME_LIBSSL
600 X509* cert;
601 unsigned char* buffer,*p;
602 INT len;
603 BOOL malloced = FALSE;
604 LPCVOID r = NULL;
606 if (!connection->useSSL)
607 return NULL;
609 cert = pSSL_get_peer_certificate(connection->ssl_s);
610 p = NULL;
611 len = pi2d_X509(cert,&p);
613 * SSL 0.9.7 and above malloc the buffer if it is null.
614 * however earlier version do not and so we would need to alloc the buffer.
616 * see the i2d_X509 man page for more details.
618 if (!p)
620 buffer = HeapAlloc(GetProcessHeap(),0,len);
621 p = buffer;
622 len = pi2d_X509(cert,&p);
624 else
626 buffer = p;
627 malloced = TRUE;
630 r = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
632 if (malloced)
633 free(buffer);
634 else
635 HeapFree(GetProcessHeap(),0,buffer);
637 return r;
638 #else
639 return NULL;
640 #endif
643 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
645 int result;
646 struct timeval tv;
648 /* FIXME: we should probably store the timeout in the connection to set
649 * when we do connect */
650 if (!NETCON_connected(connection))
651 return ERROR_SUCCESS;
653 /* value is in milliseconds, convert to struct timeval */
654 tv.tv_sec = value / 1000;
655 tv.tv_usec = (value % 1000) * 1000;
657 result = setsockopt(connection->socketFD, SOL_SOCKET,
658 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
659 sizeof(tv));
661 if (result == -1)
663 WARN("setsockopt failed (%s)\n", strerror(errno));
664 return sock_get_error(errno);
667 return ERROR_SUCCESS;