1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
25 * but sslgen.c should ever call or use these functions.
27 * Note: don't use the GnuTLS' *_t variable type names in this source code,
28 * since they were not present in 1.0.X.
33 #include <gnutls/gnutls.h>
34 #include <gnutls/x509.h>
40 #ifdef HAVE_SYS_SOCKET_H
41 #include <sys/socket.h>
46 #include "inet_pton.h"
49 #include "parsedate.h"
50 #include "connect.h" /* for the connect timeout */
54 #define _MPRINTF_REPLACE /* use our functions only */
55 #include <curl/mprintf.h>
56 #include "curl_memory.h"
57 /* The last #include file should be: */
61 Some hackish cast macros based on:
62 http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html
64 #ifndef GNUTLS_POINTER_TO_INT_CAST
65 #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
67 #ifndef GNUTLS_INT_TO_POINTER_CAST
68 #define GNUTLS_INT_TO_POINTER_CAST(i) ((void*) (long) (i))
71 /* Enable GnuTLS debugging by defining GTLSDEBUG */
72 /*#define GTLSDEBUG */
75 static void tls_log_func(int level, const char *str)
77 fprintf(stderr, "|<%d>| %s", level, str);
80 static bool gtls_inited = FALSE;
83 * Custom push and pull callback functions used by GNU TLS to read and write
84 * to the socket. These functions are simple wrappers to send() and recv()
85 * (although here using the sread/swrite macros as defined by setup_once.h).
86 * We use custom functions rather than the GNU TLS defaults because it allows
87 * us to get specific about the fourth "flags" argument, and to use arbitrary
88 * private data with gnutls_transport_set_ptr if we wish.
90 * When these custom push and pull callbacks fail, GNU TLS checks its own
91 * session-specific error variable, and when not set also its own global
92 * errno variable, in order to take appropriate action. GNU TLS does not
93 * require that the transport is actually a socket. This implies that for
94 * Windows builds these callbacks should ideally set the session-specific
95 * error variable using function gnutls_transport_set_errno or as a last
96 * resort global errno variable using gnutls_transport_set_global_errno,
97 * with a transport agnostic error value. This implies that some winsock
98 * error translation must take place in these callbacks.
102 # define gtls_EINTR 4
104 # define gtls_EAGAIN 11
105 static int gtls_mapped_sockerrno(void)
119 static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
121 ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
124 gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
129 static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
131 ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
134 gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
141 * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
142 * are not thread-safe and thus this function itself is not thread-safe and
143 * must only be called from within curl_global_init() to keep the thread
144 * situation under control!
146 int Curl_gtls_init(void)
150 ret = gnutls_global_init()?0:1;
152 gnutls_global_set_log_function(tls_log_func);
153 gnutls_global_set_log_level(2);
160 int Curl_gtls_cleanup(void)
163 gnutls_global_deinit();
169 static void showtime(struct SessionHandle *data,
176 tm = (struct tm *)gmtime_r(&stamp, &buffer);
180 snprintf(data->state.buffer,
182 "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
184 Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
186 Curl_month[tm->tm_mon],
191 infof(data, "%s", data->state.buffer);
194 static gnutls_datum load_file (const char *file)
197 gnutls_datum loaded_file = { NULL, 0 };
201 if (!(f = fopen(file, "r")))
203 if (fseek(f, 0, SEEK_END) != 0
204 || (filelen = ftell(f)) < 0
205 || fseek(f, 0, SEEK_SET) != 0
206 || !(ptr = malloc((size_t)filelen)))
208 if (fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
213 loaded_file.data = ptr;
214 loaded_file.size = (unsigned int)filelen;
220 static void unload_file(gnutls_datum data) {
225 /* this function does a SSL/TLS (re-)handshake */
226 static CURLcode handshake(struct connectdata *conn,
231 struct SessionHandle *data = conn->data;
232 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
233 gnutls_session session = conn->ssl[sockindex].session;
234 curl_socket_t sockfd = conn->sock[sockindex];
240 /* check allowed time left */
241 timeout_ms = Curl_timeleft(conn, NULL, duringconnect);
244 /* no need to continue if time already is up */
245 failf(data, "SSL connection timeout");
246 return CURLE_OPERATION_TIMEDOUT;
249 /* if ssl is expecting something, check if it's available. */
250 if(connssl->connecting_state == ssl_connect_2_reading
251 || connssl->connecting_state == ssl_connect_2_writing) {
253 curl_socket_t writefd = ssl_connect_2_writing==
254 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
255 curl_socket_t readfd = ssl_connect_2_reading==
256 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
258 what = Curl_socket_ready(readfd, writefd,
259 nonblocking?0:(int)timeout_ms?1000:timeout_ms);
262 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
263 return CURLE_SSL_CONNECT_ERROR;
268 else if(timeout_ms) {
270 failf(data, "SSL connection timeout at %ld", timeout_ms);
271 return CURLE_OPERATION_TIMEDOUT;
274 /* socket is readable or writable */
277 rc = gnutls_handshake(session);
279 if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
280 connssl->connecting_state =
281 gnutls_record_get_direction(session)?
282 ssl_connect_2_writing:ssl_connect_2_reading;
287 failf(data, "gnutls_handshake() failed: %s", gnutls_strerror(rc));
288 return CURLE_SSL_CONNECT_ERROR;
291 /* Reset our connect state machine */
292 connssl->connecting_state = ssl_connect_1;
298 static gnutls_x509_crt_fmt do_file_type(const char *type)
300 if(!type || !type[0])
301 return GNUTLS_X509_FMT_PEM;
302 if(Curl_raw_equal(type, "PEM"))
303 return GNUTLS_X509_FMT_PEM;
304 if(Curl_raw_equal(type, "DER"))
305 return GNUTLS_X509_FMT_DER;
310 gtls_connect_step1(struct connectdata *conn,
313 static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
314 struct SessionHandle *data = conn->data;
315 gnutls_session session;
319 bool sni = TRUE; /* default is SNI enabled */
321 struct in6_addr addr;
326 if(conn->ssl[sockindex].state == ssl_connection_complete)
327 /* to make us tolerant against being called more than once for the
334 /* GnuTLS only supports SSLv3 and TLSv1 */
335 if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
336 failf(data, "GnuTLS does not support SSLv2");
337 return CURLE_SSL_CONNECT_ERROR;
339 else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
340 sni = FALSE; /* SSLv3 has no SNI */
342 /* allocate a cred struct */
343 rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
344 if(rc != GNUTLS_E_SUCCESS) {
345 failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
346 return CURLE_SSL_CONNECT_ERROR;
349 if(data->set.ssl.CAfile) {
350 /* set the trusted CA cert bundle file */
351 gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
352 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
354 rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
355 data->set.ssl.CAfile,
356 GNUTLS_X509_FMT_PEM);
358 infof(data, "error reading ca cert file %s (%s)\n",
359 data->set.ssl.CAfile, gnutls_strerror(rc));
360 if(data->set.ssl.verifypeer)
361 return CURLE_SSL_CACERT_BADFILE;
364 infof(data, "found %d certificates in %s\n",
365 rc, data->set.ssl.CAfile);
368 if(data->set.ssl.CRLfile) {
369 /* set the CRL list file */
370 rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
371 data->set.ssl.CRLfile,
372 GNUTLS_X509_FMT_PEM);
374 failf(data, "error reading crl file %s (%s)\n",
375 data->set.ssl.CRLfile, gnutls_strerror(rc));
376 return CURLE_SSL_CRL_BADFILE;
379 infof(data, "found %d CRL in %s\n",
380 rc, data->set.ssl.CRLfile);
383 /* Initialize TLS session as a client */
384 rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
385 if(rc != GNUTLS_E_SUCCESS) {
386 failf(data, "gnutls_init() failed: %d", rc);
387 return CURLE_SSL_CONNECT_ERROR;
390 /* convenient assign */
391 session = conn->ssl[sockindex].session;
393 if ((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
395 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
398 (gnutls_server_name_set(session, GNUTLS_NAME_DNS, conn->host.name,
399 strlen(conn->host.name)) < 0))
400 infof(data, "WARNING: failed to configure server name indication (SNI) "
403 /* Use default priorities */
404 rc = gnutls_set_default_priority(session);
405 if(rc != GNUTLS_E_SUCCESS)
406 return CURLE_SSL_CONNECT_ERROR;
408 if(data->set.ssl.version == CURL_SSLVERSION_SSLv3) {
409 static const int protocol_priority[] = { GNUTLS_SSL3, 0 };
410 gnutls_protocol_set_priority(session, protocol_priority);
411 if(rc != GNUTLS_E_SUCCESS)
412 return CURLE_SSL_CONNECT_ERROR;
415 /* Sets the priority on the certificate types supported by gnutls. Priority
416 is higher for types specified before others. After specifying the types
417 you want, you must append a 0. */
418 rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
419 if(rc != GNUTLS_E_SUCCESS)
420 return CURLE_SSL_CONNECT_ERROR;
422 if(data->set.str[STRING_CERT]) {
423 if( gnutls_certificate_set_x509_key_file(
424 conn->ssl[sockindex].cred,
425 data->set.str[STRING_CERT],
426 data->set.str[STRING_KEY] ?
427 data->set.str[STRING_KEY] : data->set.str[STRING_CERT],
428 do_file_type(data->set.str[STRING_CERT_TYPE]) ) != GNUTLS_E_SUCCESS) {
429 failf(data, "error reading X.509 key or certificate file");
430 return CURLE_SSL_CONNECT_ERROR;
434 /* put the credentials to the current session */
435 rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
436 conn->ssl[sockindex].cred);
438 /* set the connection handle (file descriptor for the socket) */
439 gnutls_transport_set_ptr(session,
440 GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]));
442 /* register callback functions to send and receive data. */
443 gnutls_transport_set_push_function(session, Curl_gtls_push);
444 gnutls_transport_set_pull_function(session, Curl_gtls_pull);
446 /* lowat must be set to zero when using custom push and pull functions. */
447 gnutls_transport_set_lowat(session, 0);
449 /* This might be a reconnect, so we check for a session ID in the cache
450 to speed up things */
452 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
453 /* we got a session id, use it! */
454 gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
456 /* Informational message */
457 infof (data, "SSL re-using session ID\n");
463 static Curl_recv gtls_recv;
464 static Curl_send gtls_send;
467 gtls_connect_step3(struct connectdata *conn,
470 unsigned int cert_list_size;
471 const gnutls_datum *chainp;
472 unsigned int verify_status;
473 gnutls_x509_crt x509_cert,x509_issuer;
474 gnutls_datum issuerp;
475 char certbuf[256]; /* big enough? */
481 struct SessionHandle *data = conn->data;
482 gnutls_session session = conn->ssl[sockindex].session;
487 /* This function will return the peer's raw certificate (chain) as sent by
488 the peer. These certificates are in raw format (DER encoded for
489 X.509). In case of a X.509 then a certificate list may be present. The
490 first certificate in the list is the peer's certificate, following the
491 issuer's certificate, then the issuer's issuer etc. */
493 chainp = gnutls_certificate_get_peers(session, &cert_list_size);
495 if(data->set.ssl.verifypeer ||
496 data->set.ssl.verifyhost ||
497 data->set.ssl.issuercert) {
498 failf(data, "failed to get server cert");
499 return CURLE_PEER_FAILED_VERIFICATION;
501 infof(data, "\t common name: WARNING couldn't obtain\n");
504 if(data->set.ssl.verifypeer) {
505 /* This function will try to verify the peer's certificate and return its
506 status (trusted, invalid etc.). The value of status should be one or
507 more of the gnutls_certificate_status_t enumerated elements bitwise
508 or'd. To avoid denial of service attacks some default upper limits
509 regarding the certificate key size and chain size are set. To override
510 them use gnutls_certificate_set_verify_limits(). */
512 rc = gnutls_certificate_verify_peers2(session, &verify_status);
514 failf(data, "server cert verify failed: %d", rc);
515 return CURLE_SSL_CONNECT_ERROR;
518 /* verify_status is a bitmask of gnutls_certificate_status bits */
519 if(verify_status & GNUTLS_CERT_INVALID) {
520 if(data->set.ssl.verifypeer) {
521 failf(data, "server certificate verification failed. CAfile: %s "
522 "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
523 data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
524 return CURLE_SSL_CACERT;
527 infof(data, "\t server certificate verification FAILED\n");
530 infof(data, "\t server certificate verification OK\n");
533 infof(data, "\t server certificate verification SKIPPED\n");
535 /* initialize an X.509 certificate structure. */
536 gnutls_x509_crt_init(&x509_cert);
538 /* convert the given DER or PEM encoded Certificate to the native
539 gnutls_x509_crt_t format */
540 gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
542 if (data->set.ssl.issuercert) {
543 gnutls_x509_crt_init(&x509_issuer);
544 issuerp = load_file(data->set.ssl.issuercert);
545 gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
546 rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
547 unload_file(issuerp);
549 failf(data, "server certificate issuer check failed (IssuerCert: %s)",
550 data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
551 return CURLE_SSL_ISSUER_ERROR;
553 infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
554 data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
557 size=sizeof(certbuf);
558 rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
559 0, /* the first and only one */
564 infof(data, "error fetching CN from cert:%s\n",
565 gnutls_strerror(rc));
568 /* This function will check if the given certificate's subject matches the
569 given hostname. This is a basic implementation of the matching described
570 in RFC2818 (HTTPS), which takes into account wildcards, and the subject
571 alternative name PKIX extension. Returns non zero on success, and zero on
573 rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
576 if(data->set.ssl.verifyhost > 1) {
577 failf(data, "SSL: certificate subject name (%s) does not match "
578 "target host name '%s'", certbuf, conn->host.dispname);
579 gnutls_x509_crt_deinit(x509_cert);
580 return CURLE_PEER_FAILED_VERIFICATION;
583 infof(data, "\t common name: %s (does not match '%s')\n",
584 certbuf, conn->host.dispname);
587 infof(data, "\t common name: %s (matched)\n", certbuf);
589 /* Check for time-based validity */
590 certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
592 if(certclock == (time_t)-1) {
593 failf(data, "server cert expiration date verify failed");
594 return CURLE_SSL_CONNECT_ERROR;
597 if(certclock < time(NULL)) {
598 if(data->set.ssl.verifypeer) {
599 failf(data, "server certificate expiration date has passed.");
600 return CURLE_PEER_FAILED_VERIFICATION;
603 infof(data, "\t server certificate expiration date FAILED\n");
606 infof(data, "\t server certificate expiration date OK\n");
608 certclock = gnutls_x509_crt_get_activation_time(x509_cert);
610 if(certclock == (time_t)-1) {
611 failf(data, "server cert activation date verify failed");
612 return CURLE_SSL_CONNECT_ERROR;
615 if(certclock > time(NULL)) {
616 if(data->set.ssl.verifypeer) {
617 failf(data, "server certificate not activated yet.");
618 return CURLE_PEER_FAILED_VERIFICATION;
621 infof(data, "\t server certificate activation date FAILED\n");
624 infof(data, "\t server certificate activation date OK\n");
637 /* public key algorithm's parameters */
638 algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
639 infof(data, "\t certificate public key: %s\n",
640 gnutls_pk_algorithm_get_name(algo));
642 /* version of the X.509 certificate. */
643 infof(data, "\t certificate version: #%d\n",
644 gnutls_x509_crt_get_version(x509_cert));
647 size = sizeof(certbuf);
648 gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
649 infof(data, "\t subject: %s\n", certbuf);
651 certclock = gnutls_x509_crt_get_activation_time(x509_cert);
652 showtime(data, "start date", certclock);
654 certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
655 showtime(data, "expire date", certclock);
657 size = sizeof(certbuf);
658 gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
659 infof(data, "\t issuer: %s\n", certbuf);
661 gnutls_x509_crt_deinit(x509_cert);
663 /* compression algorithm (if any) */
664 ptr = gnutls_compression_get_name(gnutls_compression_get(session));
665 /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
666 infof(data, "\t compression: %s\n", ptr);
668 /* the name of the cipher used. ie 3DES. */
669 ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
670 infof(data, "\t cipher: %s\n", ptr);
672 /* the MAC algorithms name. ie SHA1 */
673 ptr = gnutls_mac_get_name(gnutls_mac_get(session));
674 infof(data, "\t MAC: %s\n", ptr);
676 conn->ssl[sockindex].state = ssl_connection_complete;
677 conn->recv[sockindex] = gtls_recv;
678 conn->send[sockindex] = gtls_send;
681 /* we always unconditionally get the session id here, as even if we
682 already got it from the cache and asked to use it in the connection, it
683 might've been rejected and then a new one is in use now and we need to
685 void *connect_sessionid;
686 size_t connect_idsize;
688 /* get the session ID data size */
689 gnutls_session_get_data(session, NULL, &connect_idsize);
690 connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
692 if(connect_sessionid) {
693 /* extract session ID to the allocated buffer */
694 gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
696 incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
698 /* there was one before in the cache, so instead of risking that the
699 previous one was rejected, we just kill that and store the new */
700 Curl_ssl_delsessionid(conn, ssl_sessionid);
703 /* store this session id */
704 return Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
713 * This function is called after the TCP connect has completed. Setup the TLS
714 * layer and do all necessary magic.
716 /* We use connssl->connecting_state to keep track of the connection status;
717 there are three states: 'ssl_connect_1' (not started yet or complete),
718 'ssl_connect_2_reading' (waiting for data from server), and
719 'ssl_connect_2_writing' (waiting to be able to write).
722 gtls_connect_common(struct connectdata *conn,
728 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
730 /* Initiate the connection, if not already done */
731 if(ssl_connect_1==connssl->connecting_state) {
732 rc = gtls_connect_step1 (conn, sockindex);
737 rc = handshake(conn, sockindex, TRUE, nonblocking);
739 /* handshake() sets its own error message with failf() */
742 /* Finish connecting once the handshake is done */
743 if(ssl_connect_1==connssl->connecting_state) {
744 rc = gtls_connect_step3(conn, sockindex);
749 *done = ssl_connect_1==connssl->connecting_state;
755 Curl_gtls_connect_nonblocking(struct connectdata *conn,
759 return gtls_connect_common(conn, sockindex, TRUE, done);
763 Curl_gtls_connect(struct connectdata *conn,
770 retcode = gtls_connect_common(conn, sockindex, FALSE, &done);
779 static ssize_t gtls_send(struct connectdata *conn,
785 ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
788 *curlcode = (rc == GNUTLS_E_AGAIN)
798 void Curl_gtls_close_all(struct SessionHandle *data)
800 /* FIX: make the OpenSSL code more generic and use parts of it here */
804 static void close_one(struct connectdata *conn,
807 if(conn->ssl[idx].session) {
808 gnutls_bye(conn->ssl[idx].session, GNUTLS_SHUT_RDWR);
809 gnutls_deinit(conn->ssl[idx].session);
810 conn->ssl[idx].session = NULL;
812 if(conn->ssl[idx].cred) {
813 gnutls_certificate_free_credentials(conn->ssl[idx].cred);
814 conn->ssl[idx].cred = NULL;
818 void Curl_gtls_close(struct connectdata *conn, int sockindex)
820 close_one(conn, sockindex);
824 * This function is called to shut down the SSL layer but keep the
825 * socket open (CCC - Clear Command Channel)
827 int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
831 struct SessionHandle *data = conn->data;
835 /* This has only been tested on the proftpd server, and the mod_tls code
836 sends a close notify alert without waiting for a close notify alert in
837 response. Thus we wait for a close notify alert from the server, but
838 we do not send one. Let's hope other servers do the same... */
840 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
841 gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
843 if(conn->ssl[sockindex].session) {
845 int what = Curl_socket_ready(conn->sock[sockindex],
846 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
848 /* Something to read, let's do it and hope that it is the close
849 notify alert from the server */
850 result = gnutls_record_recv(conn->ssl[sockindex].session,
854 /* This is the expected response. There was no data but only
855 the close notify alert */
859 case GNUTLS_E_INTERRUPTED:
860 infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
870 failf(data, "SSL shutdown timeout");
875 /* anything that gets here is fatally bad */
876 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
881 gnutls_deinit(conn->ssl[sockindex].session);
883 gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
885 conn->ssl[sockindex].cred = NULL;
886 conn->ssl[sockindex].session = NULL;
891 static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
892 int num, /* socketindex */
893 char *buf, /* store read data here */
894 size_t buffersize, /* max amount to read */
899 ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
900 if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
901 *curlcode = CURLE_AGAIN;
905 if(ret == GNUTLS_E_REHANDSHAKE) {
906 /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
907 proper way" takes a whole lot of work. */
908 CURLcode rc = handshake(conn, num, FALSE, FALSE);
910 /* handshake() writes error message on its own */
913 *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
918 failf(conn->data, "GnuTLS recv error (%d): %s",
919 (int)ret, gnutls_strerror((int)ret));
920 *curlcode = CURLE_RECV_ERROR;
927 void Curl_gtls_session_free(void *ptr)
932 size_t Curl_gtls_version(char *buffer, size_t size)
934 return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
937 int Curl_gtls_seed(struct SessionHandle *data)
939 /* we have the "SSL is seeded" boolean static to prevent multiple
940 time-consuming seedings in vain */
941 static bool ssl_seeded = FALSE;
943 /* Quickly add a bit of entropy */
944 gcry_fast_random_poll();
946 if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
947 data->set.str[STRING_SSL_EGDSOCKET]) {
949 /* TODO: to a good job seeding the RNG
950 This may involve the gcry_control function and these options:
951 GCRYCTL_SET_RANDOM_SEED_FILE
952 GCRYCTL_SET_RNDEGD_SOCKET
959 #endif /* USE_GNUTLS */