4 #include <gnutls/gnutls.h>
5 #include <gnutls/gnutlsxx.h>
6 #include <cstring> /* for strlen */
8 /* A very basic TLS client, with anonymous authentication.
9 * written by Eduardo Villanueva Che.
13 #define SA struct sockaddr
15 #define CAFILE "ca.pem"
16 #define MSG "GET / HTTP/1.0\r\n\r\n"
20 int tcp_connect(void);
21 void tcp_close(int sd
);
33 /* Allow connections to servers that have OpenPGP keys as well.
35 gnutls::client_session session
;
38 gnutls::certificate_credentials credentials
;
41 /* sets the trusted cas file
43 credentials
.set_x509_trust_file(CAFILE
, GNUTLS_X509_FMT_PEM
);
44 /* put the x509 credentials to the current session
46 session
.set_credentials(credentials
);
48 /* Use default priorities */
49 session
.set_priority ("NORMAL", NULL
);
51 /* connect to the peer
54 session
.set_transport_ptr((gnutls_transport_ptr_t
) sd
);
56 /* Perform the TLS handshake
58 int ret
= session
.handshake();
61 throw std::runtime_error("Handshake failed");
65 std::cout
<< "- Handshake was completed" << std::endl
;
68 session
.send(MSG
, strlen(MSG
));
69 char buffer
[MAX_BUF
+ 1];
70 ret
= session
.recv(buffer
, MAX_BUF
);
73 throw std::runtime_error("Peer has closed the TLS connection");
77 throw std::runtime_error(gnutls_strerror(ret
));
80 std::cout
<< "- Received " << ret
<< " bytes:" << std::endl
;
81 std::cout
.write(buffer
, ret
);
82 std::cout
<< std::endl
;
84 session
.bye(GNUTLS_SHUT_RDWR
);
86 catch (std::exception
&ex
)
88 std::cerr
<< "Exception caught: " << ex
.what() << std::endl
;
94 gnutls_global_deinit();