quartz/tests: Remove superfluous pointer casts.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #if defined(__MINGW32__) || defined (_MSC_VER)
27 #include <ws2tcpip.h>
28 #endif
29
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
64
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdio.h>
69 #include <errno.h>
70
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"
77
78 #include "wine/debug.h"
79 #include "internet.h"
80
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"
85
86 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
87
88
89 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
90
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
95  */
96
97 #ifdef SONAME_LIBSSL
98
99 #include <openssl/err.h>
100
101 static void *OpenSSL_ssl_handle;
102 static void *OpenSSL_crypto_handle;
103
104 static SSL_METHOD *meth;
105 static SSL_CTX *ctx;
106
107 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
108
109 /* OpenSSL functions that we use */
110 MAKE_FUNCPTR(SSL_library_init);
111 MAKE_FUNCPTR(SSL_load_error_strings);
112 MAKE_FUNCPTR(SSLv23_method);
113 MAKE_FUNCPTR(SSL_CTX_new);
114 MAKE_FUNCPTR(SSL_new);
115 MAKE_FUNCPTR(SSL_free);
116 MAKE_FUNCPTR(SSL_set_fd);
117 MAKE_FUNCPTR(SSL_connect);
118 MAKE_FUNCPTR(SSL_shutdown);
119 MAKE_FUNCPTR(SSL_write);
120 MAKE_FUNCPTR(SSL_read);
121 MAKE_FUNCPTR(SSL_pending);
122 MAKE_FUNCPTR(SSL_get_verify_result);
123 MAKE_FUNCPTR(SSL_get_peer_certificate);
124 MAKE_FUNCPTR(SSL_CTX_get_timeout);
125 MAKE_FUNCPTR(SSL_CTX_set_timeout);
126 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
127 MAKE_FUNCPTR(i2d_X509);
128
129 /* OpenSSL's libcrypto functions that we use */
130 MAKE_FUNCPTR(BIO_new_fp);
131 MAKE_FUNCPTR(ERR_get_error);
132 MAKE_FUNCPTR(ERR_error_string);
133 #undef MAKE_FUNCPTR
134
135 #endif
136
137 BOOL NETCON_init(WININET_NETCONNECTION *connection, BOOL useSSL)
138 {
139     connection->useSSL = FALSE;
140     connection->socketFD = -1;
141     if (useSSL)
142     {
143 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
144         TRACE("using SSL connection\n");
145         if (OpenSSL_ssl_handle) /* already initialized everything */
146             return TRUE;
147         OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
148         if (!OpenSSL_ssl_handle)
149         {
150             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
151                 SONAME_LIBSSL);
152             INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
153             return FALSE;
154         }
155         OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
156         if (!OpenSSL_crypto_handle)
157         {
158             ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n",
159                 SONAME_LIBCRYPTO);
160             INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
161             return FALSE;
162         }
163
164         /* mmm nice ugly macroness */
165 #define DYNSSL(x) \
166     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
167     if (!p##x) \
168     { \
169         ERR("failed to load symbol %s\n", #x); \
170         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
171         return FALSE; \
172     }
173
174         DYNSSL(SSL_library_init);
175         DYNSSL(SSL_load_error_strings);
176         DYNSSL(SSLv23_method);
177         DYNSSL(SSL_CTX_new);
178         DYNSSL(SSL_new);
179         DYNSSL(SSL_free);
180         DYNSSL(SSL_set_fd);
181         DYNSSL(SSL_connect);
182         DYNSSL(SSL_shutdown);
183         DYNSSL(SSL_write);
184         DYNSSL(SSL_read);
185         DYNSSL(SSL_pending);
186         DYNSSL(SSL_get_verify_result);
187         DYNSSL(SSL_get_peer_certificate);
188         DYNSSL(SSL_CTX_get_timeout);
189         DYNSSL(SSL_CTX_set_timeout);
190         DYNSSL(SSL_CTX_set_default_verify_paths);
191         DYNSSL(i2d_X509);
192 #undef DYNSSL
193
194 #define DYNCRYPTO(x) \
195     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
196     if (!p##x) \
197     { \
198         ERR("failed to load symbol %s\n", #x); \
199         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR); \
200         return FALSE; \
201     }
202         DYNCRYPTO(BIO_new_fp);
203         DYNCRYPTO(ERR_get_error);
204         DYNCRYPTO(ERR_error_string);
205 #undef DYNCRYPTO
206
207         pSSL_library_init();
208         pSSL_load_error_strings();
209         pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
210
211         meth = pSSLv23_method();
212         connection->peek_msg = NULL;
213         connection->peek_msg_mem = NULL;
214 #else
215         FIXME("can't use SSL, not compiled in.\n");
216         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
217         return FALSE;
218 #endif
219     }
220     return TRUE;
221 }
222
223 BOOL NETCON_connected(WININET_NETCONNECTION *connection)
224 {
225     if (connection->socketFD == -1)
226         return FALSE;
227     else
228         return TRUE;
229 }
230
231 /* translate a unix error code into a winsock one */
232 static int sock_get_error( int err )
233 {
234 #if !defined(__MINGW32__) && !defined (_MSC_VER)
235     switch (err)
236     {
237         case EINTR:             return WSAEINTR;
238         case EBADF:             return WSAEBADF;
239         case EPERM:
240         case EACCES:            return WSAEACCES;
241         case EFAULT:            return WSAEFAULT;
242         case EINVAL:            return WSAEINVAL;
243         case EMFILE:            return WSAEMFILE;
244         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
245         case EINPROGRESS:       return WSAEINPROGRESS;
246         case EALREADY:          return WSAEALREADY;
247         case ENOTSOCK:          return WSAENOTSOCK;
248         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
249         case EMSGSIZE:          return WSAEMSGSIZE;
250         case EPROTOTYPE:        return WSAEPROTOTYPE;
251         case ENOPROTOOPT:       return WSAENOPROTOOPT;
252         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
253         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
254         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
255         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
256         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
257         case EADDRINUSE:        return WSAEADDRINUSE;
258         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
259         case ENETDOWN:          return WSAENETDOWN;
260         case ENETUNREACH:       return WSAENETUNREACH;
261         case ENETRESET:         return WSAENETRESET;
262         case ECONNABORTED:      return WSAECONNABORTED;
263         case EPIPE:
264         case ECONNRESET:        return WSAECONNRESET;
265         case ENOBUFS:           return WSAENOBUFS;
266         case EISCONN:           return WSAEISCONN;
267         case ENOTCONN:          return WSAENOTCONN;
268         case ESHUTDOWN:         return WSAESHUTDOWN;
269         case ETOOMANYREFS:      return WSAETOOMANYREFS;
270         case ETIMEDOUT:         return WSAETIMEDOUT;
271         case ECONNREFUSED:      return WSAECONNREFUSED;
272         case ELOOP:             return WSAELOOP;
273         case ENAMETOOLONG:      return WSAENAMETOOLONG;
274         case EHOSTDOWN:         return WSAEHOSTDOWN;
275         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
276         case ENOTEMPTY:         return WSAENOTEMPTY;
277 #ifdef EPROCLIM
278         case EPROCLIM:          return WSAEPROCLIM;
279 #endif
280 #ifdef EUSERS
281         case EUSERS:            return WSAEUSERS;
282 #endif
283 #ifdef EDQUOT
284         case EDQUOT:            return WSAEDQUOT;
285 #endif
286 #ifdef ESTALE
287         case ESTALE:            return WSAESTALE;
288 #endif
289 #ifdef EREMOTE
290         case EREMOTE:           return WSAEREMOTE;
291 #endif
292     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
293     }
294 #endif
295     return err;
296 }
297
298 /******************************************************************************
299  * NETCON_create
300  * Basically calls 'socket()'
301  */
302 BOOL NETCON_create(WININET_NETCONNECTION *connection, int domain,
303               int type, int protocol)
304 {
305 #ifdef SONAME_LIBSSL
306     if (connection->useSSL)
307         return FALSE;
308 #endif
309
310     connection->socketFD = socket(domain, type, protocol);
311     if (connection->socketFD == -1)
312     {
313         INTERNET_SetLastError(sock_get_error(errno));
314         return FALSE;
315     }
316     return TRUE;
317 }
318
319 /******************************************************************************
320  * NETCON_close
321  * Basically calls 'close()' unless we should use SSL
322  */
323 BOOL NETCON_close(WININET_NETCONNECTION *connection)
324 {
325     int result;
326
327     if (!NETCON_connected(connection)) return FALSE;
328
329 #ifdef SONAME_LIBSSL
330     if (connection->useSSL)
331     {
332         HeapFree(GetProcessHeap(),0,connection->peek_msg_mem);
333         connection->peek_msg = NULL;
334         connection->peek_msg_mem = NULL;
335         connection->peek_len = 0;
336
337         pSSL_shutdown(connection->ssl_s);
338         pSSL_free(connection->ssl_s);
339         connection->ssl_s = NULL;
340
341         connection->useSSL = FALSE;
342     }
343 #endif
344
345     result = closesocket(connection->socketFD);
346     connection->socketFD = -1;
347
348     if (result == -1)
349     {
350         INTERNET_SetLastError(sock_get_error(errno));
351         return FALSE;
352     }
353     return TRUE;
354 }
355 #ifdef SONAME_LIBSSL
356 static BOOL check_hostname(X509 *cert, char *hostname)
357 {
358     /* FIXME: implement */
359     return TRUE;
360 }
361 #endif
362 /******************************************************************************
363  * NETCON_secure_connect
364  * Initiates a secure connection over an existing plaintext connection.
365  */
366 BOOL NETCON_secure_connect(WININET_NETCONNECTION *connection, LPCWSTR hostname)
367 {
368 #ifdef SONAME_LIBSSL
369     long verify_res;
370     X509 *cert;
371     int len;
372     char *hostname_unix;
373
374     /* can't connect if we are already connected */
375     if (connection->useSSL)
376     {
377         ERR("already connected\n");
378         return FALSE;
379     }
380
381     ctx = pSSL_CTX_new(meth);
382     if (!pSSL_CTX_set_default_verify_paths(ctx))
383     {
384         ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
385             pERR_error_string(pERR_get_error(), 0));
386         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
387         return FALSE;
388     }
389     connection->ssl_s = pSSL_new(ctx);
390     if (!connection->ssl_s)
391     {
392         ERR("SSL_new failed: %s\n",
393             pERR_error_string(pERR_get_error(), 0));
394         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
395         goto fail;
396     }
397
398     if (!pSSL_set_fd(connection->ssl_s, connection->socketFD))
399     {
400         ERR("SSL_set_fd failed: %s\n",
401             pERR_error_string(pERR_get_error(), 0));
402         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
403         goto fail;
404     }
405
406     if (pSSL_connect(connection->ssl_s) <= 0)
407     {
408         ERR("SSL_connect failed: %s\n",
409             pERR_error_string(pERR_get_error(), 0));
410         INTERNET_SetLastError(ERROR_INTERNET_SECURITY_CHANNEL_ERROR);
411         goto fail;
412     }
413     cert = pSSL_get_peer_certificate(connection->ssl_s);
414     if (!cert)
415     {
416         ERR("no certificate for server %s\n", debugstr_w(hostname));
417         /* FIXME: is this the best error? */
418         INTERNET_SetLastError(ERROR_INTERNET_INVALID_CA);
419         goto fail;
420     }
421     verify_res = pSSL_get_verify_result(connection->ssl_s);
422     if (verify_res != X509_V_OK)
423     {
424         ERR("couldn't verify the security of the connection, %ld\n", verify_res);
425         /* FIXME: we should set an error and return, but we only warn at
426          * the moment */
427     }
428
429     len = WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, NULL, 0, NULL, NULL);
430     hostname_unix = HeapAlloc(GetProcessHeap(), 0, len);
431     if (!hostname_unix)
432     {
433         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
434         goto fail;
435     }
436     WideCharToMultiByte(CP_UNIXCP, 0, hostname, -1, hostname_unix, len, NULL, NULL);
437
438     if (!check_hostname(cert, hostname_unix))
439     {
440         HeapFree(GetProcessHeap(), 0, hostname_unix);
441         INTERNET_SetLastError(ERROR_INTERNET_SEC_CERT_CN_INVALID);
442         goto fail;
443     }
444
445     HeapFree(GetProcessHeap(), 0, hostname_unix);
446     connection->useSSL = TRUE;
447     return TRUE;
448
449 fail:
450     if (connection->ssl_s)
451     {
452         pSSL_shutdown(connection->ssl_s);
453         pSSL_free(connection->ssl_s);
454         connection->ssl_s = NULL;
455     }
456 #endif
457     return FALSE;
458 }
459
460 /******************************************************************************
461  * NETCON_connect
462  * Connects to the specified address.
463  */
464 BOOL NETCON_connect(WININET_NETCONNECTION *connection, const struct sockaddr *serv_addr,
465                     unsigned int addrlen)
466 {
467     int result;
468
469     if (!NETCON_connected(connection)) return FALSE;
470
471     result = connect(connection->socketFD, serv_addr, addrlen);
472     if (result == -1)
473     {
474         WARN("Unable to connect to host (%s)\n", strerror(errno));
475         INTERNET_SetLastError(sock_get_error(errno));
476
477         closesocket(connection->socketFD);
478         connection->socketFD = -1;
479         return FALSE;
480     }
481
482     return TRUE;
483 }
484
485 /******************************************************************************
486  * NETCON_send
487  * Basically calls 'send()' unless we should use SSL
488  * number of chars send is put in *sent
489  */
490 BOOL NETCON_send(WININET_NETCONNECTION *connection, const void *msg, size_t len, int flags,
491                 int *sent /* out */)
492 {
493     if (!NETCON_connected(connection)) return FALSE;
494     if (!connection->useSSL)
495     {
496         *sent = send(connection->socketFD, msg, len, flags);
497         if (*sent == -1)
498         {
499             INTERNET_SetLastError(sock_get_error(errno));
500             return FALSE;
501         }
502         return TRUE;
503     }
504     else
505     {
506 #ifdef SONAME_LIBSSL
507         if (flags)
508             FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
509         *sent = pSSL_write(connection->ssl_s, msg, len);
510         if (*sent < 1 && len)
511             return FALSE;
512         return TRUE;
513 #else
514         return FALSE;
515 #endif
516     }
517 }
518
519 /******************************************************************************
520  * NETCON_recv
521  * Basically calls 'recv()' unless we should use SSL
522  * number of chars received is put in *recvd
523  */
524 BOOL NETCON_recv(WININET_NETCONNECTION *connection, void *buf, size_t len, int flags,
525                 int *recvd /* out */)
526 {
527     *recvd = 0;
528     if (!NETCON_connected(connection)) return FALSE;
529     if (!len)
530         return TRUE;
531     if (!connection->useSSL)
532     {
533         *recvd = recv(connection->socketFD, buf, len, flags);
534         if (*recvd == -1)
535         {
536             INTERNET_SetLastError(sock_get_error(errno));
537             return FALSE;
538         }
539         return TRUE;
540     }
541     else
542     {
543 #ifdef SONAME_LIBSSL
544         size_t peek_read = 0, read;
545
546         if (flags & ~(MSG_PEEK|MSG_WAITALL))
547             FIXME("SSL_read does not support the following flag: %08x\n", flags);
548
549         /* this ugly hack is all for MSG_PEEK. eww gross */
550         if(connection->peek_msg) {
551             if(connection->peek_len >= len) {
552                 memcpy(buf, connection->peek_msg, len);
553                 if(!(flags & MSG_PEEK)) {
554                     if(connection->peek_len == len) {
555                         HeapFree(GetProcessHeap(), 0, connection->peek_msg);
556                         connection->peek_msg = NULL;
557                         connection->peek_len = 0;
558                     }else {
559                         memmove(connection->peek_msg, connection->peek_msg+len, connection->peek_len-len);
560                         connection->peek_len -= len;
561                         connection->peek_msg = HeapReAlloc(GetProcessHeap(), 0, connection->peek_msg, connection->peek_len);
562                     }
563                 }
564
565                 *recvd = len;
566                 return TRUE;
567             }
568
569             memcpy(buf, connection->peek_msg, connection->peek_len);
570             peek_read = connection->peek_len;
571
572             if(!(flags & MSG_PEEK)) {
573                 HeapFree(GetProcessHeap(), 0, connection->peek_msg);
574                 connection->peek_msg = NULL;
575                 connection->peek_len = 0;
576             }
577         }
578
579         read = pSSL_read(connection->ssl_s, (BYTE*)buf+peek_read, len-peek_read);
580
581         if(flags & MSG_PEEK) {
582             if(connection->peek_msg)
583                 connection->peek_msg = HeapReAlloc(GetProcessHeap(), 0, connection->peek_msg,
584                                                    connection->peek_len+read);
585             else
586                 connection->peek_msg = HeapAlloc(GetProcessHeap(), 0, read);
587             memcpy(connection->peek_msg+connection->peek_len, (BYTE*)buf+peek_read, read);
588             connection->peek_len += read;
589         }
590
591         *recvd = read + peek_read;
592         return *recvd > 0 || !len;
593 #else
594         return FALSE;
595 #endif
596     }
597 }
598
599 /******************************************************************************
600  * NETCON_query_data_available
601  * Returns the number of bytes of peeked data plus the number of bytes of
602  * queued, but unread data.
603  */
604 BOOL NETCON_query_data_available(WININET_NETCONNECTION *connection, DWORD *available)
605 {
606     *available = 0;
607     if (!NETCON_connected(connection))
608         return FALSE;
609
610 #ifdef SONAME_LIBSSL
611     if (connection->peek_msg) *available = connection->peek_len + pSSL_pending(connection->ssl_s);
612 #endif
613
614 #ifdef FIONREAD
615     if (!connection->useSSL)
616     {
617         int unread;
618         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
619         if (!retval)
620         {
621             TRACE("%d bytes of queued, but unread data\n", unread);
622             *available += unread;
623         }
624     }
625 #endif
626     return TRUE;
627 }
628
629 /******************************************************************************
630  * NETCON_getNextLine
631  */
632 BOOL NETCON_getNextLine(WININET_NETCONNECTION *connection, LPSTR lpszBuffer, LPDWORD dwBuffer)
633 {
634
635     TRACE("\n");
636
637     if (!NETCON_connected(connection)) return FALSE;
638
639     if (!connection->useSSL)
640     {
641         struct pollfd pfd;
642         DWORD nRecv = 0;
643         int ret;
644
645         pfd.fd = connection->socketFD;
646         pfd.events = POLLIN;
647
648         while (nRecv < *dwBuffer)
649         {
650             if (poll(&pfd,1, RESPONSE_TIMEOUT * 1000) > 0)
651             {
652                 if ((ret = recv(connection->socketFD, &lpszBuffer[nRecv], 1, 0)) <= 0)
653                 {
654                     if (ret == -1) INTERNET_SetLastError(sock_get_error(errno));
655                     break;
656                 }
657
658                 if (lpszBuffer[nRecv] == '\n')
659                 {
660                     lpszBuffer[nRecv++] = '\0';
661                     *dwBuffer = nRecv;
662                     TRACE(":%u %s\n", nRecv, lpszBuffer);
663                     return TRUE;
664                 }
665                 if (lpszBuffer[nRecv] != '\r')
666                     nRecv++;
667             }
668             else
669             {
670                 INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
671                 break;
672             }
673         }
674     }
675     else
676     {
677 #ifdef SONAME_LIBSSL
678         long prev_timeout;
679         DWORD nRecv = 0;
680         BOOL success = TRUE;
681
682         prev_timeout = pSSL_CTX_get_timeout(ctx);
683         pSSL_CTX_set_timeout(ctx, RESPONSE_TIMEOUT);
684
685         while (nRecv < *dwBuffer)
686         {
687             int recv = 1;
688             if (!NETCON_recv(connection, &lpszBuffer[nRecv], 1, 0, &recv))
689             {
690                 INTERNET_SetLastError(ERROR_CONNECTION_ABORTED);
691                 success = FALSE;
692             }
693
694             if (lpszBuffer[nRecv] == '\n')
695             {
696                 success = TRUE;
697                 break;
698             }
699             if (lpszBuffer[nRecv] != '\r')
700                 nRecv++;
701         }
702
703         pSSL_CTX_set_timeout(ctx, prev_timeout);
704         if (success)
705         {
706             lpszBuffer[nRecv++] = '\0';
707             *dwBuffer = nRecv;
708             TRACE("_SSL:%u %s\n", nRecv, lpszBuffer);
709             return TRUE;
710         }
711 #endif
712     }
713     return FALSE;
714 }
715
716
717 LPCVOID NETCON_GetCert(WININET_NETCONNECTION *connection)
718 {
719 #ifdef SONAME_LIBSSL
720     X509* cert;
721     unsigned char* buffer,*p;
722     INT len;
723     BOOL malloced = FALSE;
724     LPCVOID r = NULL;
725
726     if (!connection->useSSL)
727         return NULL;
728
729     cert = pSSL_get_peer_certificate(connection->ssl_s);
730     p = NULL;
731     len = pi2d_X509(cert,&p);
732     /*
733      * SSL 0.9.7 and above malloc the buffer if it is null. 
734      * however earlier version do not and so we would need to alloc the buffer.
735      *
736      * see the i2d_X509 man page for more details.
737      */
738     if (!p)
739     {
740         buffer = HeapAlloc(GetProcessHeap(),0,len);
741         p = buffer;
742         len = pi2d_X509(cert,&p);
743     }
744     else
745     {
746         buffer = p;
747         malloced = TRUE;
748     }
749
750     r = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
751
752     if (malloced)
753         free(buffer);
754     else
755         HeapFree(GetProcessHeap(),0,buffer);
756
757     return r;
758 #else
759     return NULL;
760 #endif
761 }
762
763 DWORD NETCON_set_timeout(WININET_NETCONNECTION *connection, BOOL send, int value)
764 {
765     int result;
766     struct timeval tv;
767
768     /* FIXME: we should probably store the timeout in the connection to set
769      * when we do connect */
770     if (!NETCON_connected(connection))
771         return ERROR_SUCCESS;
772
773     /* value is in milliseconds, convert to struct timeval */
774     tv.tv_sec = value / 1000;
775     tv.tv_usec = (value % 1000) * 1000;
776
777     result = setsockopt(connection->socketFD, SOL_SOCKET,
778                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
779                         sizeof(tv));
780
781     if (result == -1)
782     {
783         WARN("setsockopt failed (%s)\n", strerror(errno));
784         return sock_get_error(errno);
785     }
786
787     return ERROR_SUCCESS;
788 }