7 #include <gnutls/gnutls.h>
8 #include <gnutls/gnutlsxx.h>
10 #include <string.h> /* for strlen */
12 /* A very basic TLS client, with anonymous authentication.
13 * written by Eduardo Villanueva Che.
17 #define SA struct sockaddr
19 #define CAFILE "ca.pem"
20 #define MSG "GET / HTTP/1.0\r\n\r\n"
24 int tcp_connect(void);
25 void tcp_close(int sd
);
37 /* Allow connections to servers that have OpenPGP keys as well.
39 gnutls::client_session session
;
42 gnutls::certificate_credentials credentials
;
45 /* sets the trusted cas file
47 credentials
.set_x509_trust_file(CAFILE
, GNUTLS_X509_FMT_PEM
);
48 /* put the x509 credentials to the current session
50 session
.set_credentials(credentials
);
52 /* Use default priorities */
53 session
.set_priority ("NORMAL", NULL
);
55 /* connect to the peer
58 session
.set_transport_ptr((gnutls_transport_ptr_t
) sd
);
60 /* Perform the TLS handshake
62 int ret
= session
.handshake();
65 // gnutls_perror(ret);
66 throw std::runtime_error("Handshake failed");
70 std::cout
<< "- Handshake was completed" << std::endl
;
73 session
.send(MSG
, strlen(MSG
));
74 char buffer
[MAX_BUF
+ 1];
75 ret
= session
.recv(buffer
, MAX_BUF
);
78 throw std::runtime_error("Peer has closed the TLS connection");
82 throw std::runtime_error(gnutls_strerror(ret
));
85 std::cout
<< "- Received " << ret
<< " bytes:" << std::endl
;
86 std::cout
.write(buffer
, ret
);
87 std::cout
<< std::endl
;
89 session
.bye(GNUTLS_SHUT_RDWR
);
91 catch (std::exception
&ex
)
93 std::cerr
<< "Exception caught: " << ex
.what() << std::endl
;
99 gnutls_global_deinit();