Move the initiation of the SSL connection into a separate function.
[wine] / dlls / 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #ifdef HAVE_SYS_TIME_H
27 # include <sys/time.h>
28 #endif
29 #include <sys/types.h>
30 #ifdef HAVE_SYS_SOCKET_H
31 # include <sys/socket.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include "wine/library.h"
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wininet.h"
44 #include "winerror.h"
45
46 #include "wine/debug.h"
47 #include "internet.h"
48
49 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
50
51
52 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
53
54 /* FIXME!!!!!!
55  *    This should use winsock - To use winsock the functions will have to change a bit
56  *        as they are designed for unix sockets.
57  *    SSL stuff should use crypt32.dll
58  */
59
60 #ifdef HAVE_OPENSSL_SSL_H
61
62 #ifndef SONAME_LIBSSL
63 #define SONAME_LIBSSL "libssl.so"
64 #endif
65 #ifndef SONAME_LIBCRYPTO
66 #define SONAME_LIBCRYPTO "libcrypto.so"
67 #endif
68
69 static void *OpenSSL_ssl_handle;
70 static void *OpenSSL_crypto_handle;
71
72 static SSL_METHOD *meth;
73 static SSL_CTX *ctx;
74
75 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
76
77 /* OpenSSL functions that we use */
78 MAKE_FUNCPTR(SSL_library_init);
79 MAKE_FUNCPTR(SSL_load_error_strings);
80 MAKE_FUNCPTR(SSLv23_method);
81 MAKE_FUNCPTR(SSL_CTX_new);
82 MAKE_FUNCPTR(SSL_new);
83 MAKE_FUNCPTR(SSL_set_bio);
84 MAKE_FUNCPTR(SSL_connect);
85 MAKE_FUNCPTR(SSL_write);
86 MAKE_FUNCPTR(SSL_read);
87 MAKE_FUNCPTR(SSL_CTX_get_timeout);
88 MAKE_FUNCPTR(SSL_CTX_set_timeout);
89
90 /* OpenSSL's libcrypto functions that we use */
91 MAKE_FUNCPTR(BIO_new_socket);
92 MAKE_FUNCPTR(BIO_new_fp);
93 #undef MAKE_FUNCPTR
94
95 #endif
96
97 void NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
98 {
99     connection->useSSL = FALSE;
100     connection->socketFD = -1;
101     if (useSSL)
102     {
103 #ifdef HAVE_OPENSSL_SSL_H
104         TRACE("using SSL connection\n");
105         if (OpenSSL_ssl_handle) /* already initilzed everything */
106             return;
107         OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
108         if (!OpenSSL_ssl_handle)
109         {
110             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
111                 SONAME_LIBSSL);
112             connection->useSSL = FALSE;
113             return;
114         }
115         OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
116         if (!OpenSSL_crypto_handle)
117         {
118             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
119                 SONAME_LIBCRYPTO);
120             connection->useSSL = FALSE;
121             return;
122         }
123
124         /* mmm nice ugly macroness */
125 #define DYNSSL(x) \
126     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
127     if (!p##x) \
128     { \
129         ERR("failed to load symbol %s\n", #x); \
130         connection->useSSL = FALSE; \
131         return; \
132     }
133
134         DYNSSL(SSL_library_init);
135         DYNSSL(SSL_load_error_strings);
136         DYNSSL(SSLv23_method);
137         DYNSSL(SSL_CTX_new);
138         DYNSSL(SSL_new);
139         DYNSSL(SSL_set_bio);
140         DYNSSL(SSL_connect);
141         DYNSSL(SSL_write);
142         DYNSSL(SSL_read);
143         DYNSSL(SSL_CTX_get_timeout);
144         DYNSSL(SSL_CTX_set_timeout);
145 #undef DYNSSL
146
147 #define DYNCRYPTO(x) \
148     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
149     if (!p##x) \
150     { \
151         ERR("failed to load symbol %s\n", #x); \
152         connection->useSSL = FALSE; \
153         return; \
154     }
155         DYNCRYPTO(BIO_new_fp);
156         DYNCRYPTO(BIO_new_socket);
157 #undef DYNCRYPTO
158
159         pSSL_library_init();
160         pSSL_load_error_strings();
161         pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
162
163         meth = pSSLv23_method();
164         connection->peek_msg = NULL;
165         connection->peek_msg_mem = NULL;
166 #else
167         FIXME("can't use SSL, not compiled in.\n");
168         connection->useSSL = FALSE;
169 #endif
170     }
171 }
172
173 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
174 {
175     if (connection->socketFD == -1)
176         return FALSE;
177     else
178         return TRUE;
179 }
180
181 /******************************************************************************
182  * NETCON_create
183  * Basically calls 'socket()'
184  */
185 BOOL NETCON_create(WININET_NETCONNECTION *connection, int domain,
186               int type, int protocol)
187 {
188 #ifndef HAVE_OPENSSL_SSL_H
189     if (connection->useSSL)
190         return FALSE;
191 #endif
192
193     connection->socketFD = socket(domain, type, protocol);
194     if (connection->socketFD == -1)
195         return FALSE;
196     return TRUE;
197 }
198
199 /******************************************************************************
200  * NETCON_close
201  * Basically calls 'close()' unless we should use SSL
202  */
203 BOOL NETCON_close(WININET_NETCONNECTION *connection)
204 {
205     int result;
206
207     if (!NETCON_connected(connection)) return FALSE;
208
209     result = closesocket(connection->socketFD);
210     connection->socketFD = -1;
211
212 #ifdef HAVE_OPENSSL_SSL_H
213     if (connection->useSSL)
214     {
215         HeapFree(GetProcessHeap(),0,connection->peek_msg_mem);
216         connection->peek_msg = NULL;
217         connection->peek_msg_mem = NULL;
218         /* FIXME should we call SSL_shutdown here?? Probably on whatever is the
219          * opposite of NETCON_secure_connect.... */
220         connection->useSSL = FALSE;
221     }
222 #endif
223
224     if (result == -1)
225         return FALSE;
226     return TRUE;
227 }
228
229 /******************************************************************************
230  * NETCON_secure_connect
231  * Initiates a secure connection over an existing plaintext connection.
232  */
233 BOOL NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
234 {
235 #ifdef HAVE_OPENSSL_SSL_H
236     BIO *sbio;
237
238     /* nothing to do if we are already connected */
239     if (connection->useSSL)
240         return FALSE;
241
242     ctx = pSSL_CTX_new(meth);
243     connection->ssl_s = pSSL_new(ctx);
244
245     sbio = pBIO_new_socket(connection->socketFD, BIO_NOCLOSE);
246     pSSL_set_bio(connection->ssl_s, sbio, sbio);
247     if (pSSL_connect(connection->ssl_s) <= 0)
248     {
249         ERR("ssl couldn't connect\n");
250         return FALSE;
251     }
252     /* FIXME: verify the security of the connection and that the
253      * hostname of the certificate matches */
254     connection->useSSL = TRUE;
255     return TRUE;
256 #else
257     return FALSE;
258 #endif
259 }
260
261 /******************************************************************************
262  * NETCON_connect
263  * Connects to the specified address.
264  */
265 BOOL NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
266                     unsigned int addrlen)
267 {
268     int result;
269
270     if (!NETCON_connected(connection)) return FALSE;
271
272     result = connect(connection->socketFD, serv_addr, addrlen);
273     if (result == -1)
274     {
275         closesocket(connection->socketFD);
276         connection->socketFD = -1;
277         return FALSE;
278     }
279
280     return TRUE;
281 }
282
283 /******************************************************************************
284  * NETCON_send
285  * Basically calls 'send()' unless we should use SSL
286  * number of chars send is put in *sent
287  */
288 BOOL NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
289                 int *sent /* out */)
290 {
291     if (!NETCON_connected(connection)) return FALSE;
292     if (!connection->useSSL)
293     {
294         *sent = send(connection->socketFD, msg, len, flags);
295         if (*sent == -1)
296             return FALSE;
297         return TRUE;
298     }
299     else
300     {
301 #ifdef HAVE_OPENSSL_SSL_H
302         if (flags)
303             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
304         *sent = pSSL_write(connection->ssl_s, msg, len);
305         if (*sent < 1 && len)
306             return FALSE;
307         return TRUE;
308 #else
309         return FALSE;
310 #endif
311     }
312 }
313
314 /******************************************************************************
315  * NETCON_recv
316  * Basically calls 'recv()' unless we should use SSL
317  * number of chars received is put in *recvd
318  */
319 BOOL NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
320                 int *recvd /* out */)
321 {
322     if (!NETCON_connected(connection)) return FALSE;
323     if (!connection->useSSL)
324     {
325         *recvd = recv(connection->socketFD, buf, len, flags);
326         if (*recvd == -1)
327             return FALSE;
328         return TRUE;
329     }
330     else
331     {
332 #ifdef HAVE_OPENSSL_SSL_H
333         if (flags & (~MSG_PEEK))
334             FIXME("SSL_read does not support the following flag: %08x\n", flags);
335
336         /* this ugly hack is all for MSG_PEEK. eww gross */
337         if (flags & MSG_PEEK && !connection->peek_msg)
338         {
339             connection->peek_msg = connection->peek_msg_mem = HeapAlloc(GetProcessHeap(), 0, (sizeof(char) * len) + 1);
340         }
341         else if (flags & MSG_PEEK && connection->peek_msg)
342         {
343             size_t peek_msg_len = strlen(connection->peek_msg);
344             if (len < peek_msg_len)
345                 FIXME("buffer isn't big enough. Do the expect us to wrap?\n");
346             memcpy(buf, connection->peek_msg, min(len,peek_msg_len+1));
347             *recvd = min(len, peek_msg_len);
348             return TRUE;
349         }
350         else if (connection->peek_msg)
351         {
352             size_t peek_msg_len = strlen(connection->peek_msg);
353             memcpy(buf, connection->peek_msg, min(len,peek_msg_len+1));
354             connection->peek_msg += *recvd = min(len, peek_msg_len);
355             if (*connection->peek_msg == '\0' || *(connection->peek_msg - 1) == '\0')
356             {
357                 HeapFree(GetProcessHeap(), 0, connection->peek_msg_mem);
358                 connection->peek_msg_mem = NULL;
359                 connection->peek_msg = NULL;
360             }
361             return TRUE;
362         }
363         *recvd = pSSL_read(connection->ssl_s, buf, len);
364         if (flags & MSG_PEEK) /* must copy stuff into buffer */
365         {
366             if (!*recvd)
367             {
368                 HeapFree(GetProcessHeap(), 0, connection->peek_msg_mem);
369                 connection->peek_msg_mem = NULL;
370                 connection->peek_msg = NULL;
371             }
372             else
373             {
374                 memcpy(connection->peek_msg, buf, *recvd);
375                 connection->peek_msg[*recvd] = '\0';
376             }
377         }
378         if (*recvd < 1 && len)
379             return FALSE;
380         return TRUE;
381 #else
382         return FALSE;
383 #endif
384     }
385 }
386
387 /******************************************************************************
388  * NETCON_getNextLine
389  */
390 BOOL NETCON_getNextLine(WININET_NETCONNECTION *connection, LPSTR lpszBuffer, LPDWORD dwBuffer)
391 {
392
393     TRACE("\n");
394
395     if (!NETCON_connected(connection)) return FALSE;
396
397     if (!connection->useSSL)
398     {
399         struct timeval tv;
400         fd_set infd;
401         BOOL bSuccess = FALSE;
402         DWORD nRecv = 0;
403
404         FD_ZERO(&infd);
405         FD_SET(connection->socketFD, &infd);
406         tv.tv_sec=RESPONSE_TIMEOUT;
407         tv.tv_usec=0;
408
409         while (nRecv < *dwBuffer)
410         {
411             if (select(connection->socketFD+1,&infd,NULL,NULL,&tv) > 0)
412             {
413                 if (recv(connection->socketFD, &lpszBuffer[nRecv], 1, 0) <= 0)
414                 {
415                     INTERNET_SetLastError(ERROR_CONNECTION_ABORTED); /* fixme: right error? */
416                     goto lend;
417                 }
418
419                 if (lpszBuffer[nRecv] == '\n')
420                 {
421                     bSuccess = TRUE;
422                     break;
423                 }
424                 if (lpszBuffer[nRecv] != '\r')
425                     nRecv++;
426             }
427             else
428             {
429                 INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
430                 goto lend;
431             }
432         }
433
434     lend:             /* FIXME: don't use labels */
435         if (bSuccess)
436         {
437             lpszBuffer[nRecv++] = '\0';
438             *dwBuffer = nRecv;
439             TRACE(":%lu %s\n", nRecv, lpszBuffer);
440             return TRUE;
441         }
442         else
443         {
444             return FALSE;
445         }
446     }
447     else
448     {
449 #ifdef HAVE_OPENSSL_SSL_H
450         long prev_timeout;
451         DWORD nRecv = 0;
452         BOOL success = TRUE;
453
454         prev_timeout = pSSL_CTX_get_timeout(ctx);
455         pSSL_CTX_set_timeout(ctx, RESPONSE_TIMEOUT);
456
457         while (nRecv < *dwBuffer)
458         {
459             int recv = 1;
460             if (!NETCON_recv(connection, &lpszBuffer[nRecv], 1, 0, &recv))
461             {
462                 INTERNET_SetLastError(ERROR_CONNECTION_ABORTED);
463                 success = FALSE;
464             }
465
466             if (lpszBuffer[nRecv] == '\n')
467             {
468                 success = TRUE;
469                 break;
470             }
471             if (lpszBuffer[nRecv] != '\r')
472                 nRecv++;
473         }
474
475         pSSL_CTX_set_timeout(ctx, prev_timeout);
476         if (success)
477         {
478             lpszBuffer[nRecv++] = '\0';
479             *dwBuffer = nRecv;
480             TRACE("_SSL:%lu %s\n", nRecv, lpszBuffer);
481             return TRUE;
482         }
483         return FALSE;
484 #else
485         return FALSE;
486 #endif
487     }
488 }