blob: a03ea9080d9653798b923cee93c6c492e34a1f8d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
#include <config.h>
#include <iostream>
#include <stdexcept>
#include <gnutls/gnutls.h>
#include <gnutls/gnutlsxx.h>
#include <cstring> /* for strlen */
/* A very basic TLS client, with anonymous authentication.
* written by Eduardo Villanueva Che.
*/
#define MAX_BUF 1024
#define SA struct sockaddr
#define CAFILE "ca.pem"
#define MSG "GET / HTTP/1.0\r\n\r\n"
extern "C"
{
int tcp_connect(void);
void tcp_close(int sd);
}
int main(void)
{
int sd = -1;
gnutls_global_init();
try
{
/* Allow connections to servers that have OpenPGP keys as well.
*/
gnutls::client_session session;
/* X509 stuff */
gnutls::certificate_credentials credentials;
/* sets the trusted cas file
*/
credentials.set_x509_trust_file(CAFILE, GNUTLS_X509_FMT_PEM);
/* put the x509 credentials to the current session
*/
session.set_credentials(credentials);
/* Use default priorities */
session.set_priority ("NORMAL", NULL);
/* connect to the peer
*/
sd = tcp_connect();
session.set_transport_ptr((gnutls_transport_ptr_t) (ptrdiff_t)sd);
/* Perform the TLS handshake
*/
int ret = session.handshake();
if (ret < 0)
{
throw std::runtime_error("Handshake failed");
}
else
{
std::cout << "- Handshake was completed" << std::endl;
}
session.send(MSG, strlen(MSG));
char buffer[MAX_BUF + 1];
ret = session.recv(buffer, MAX_BUF);
if (ret == 0)
{
throw std::runtime_error("Peer has closed the TLS connection");
}
else if (ret < 0)
{
throw std::runtime_error(gnutls_strerror(ret));
}
std::cout << "- Received " << ret << " bytes:" << std::endl;
std::cout.write(buffer, ret);
std::cout << std::endl;
session.bye(GNUTLS_SHUT_RDWR);
}
catch (std::exception &ex)
{
std::cerr << "Exception caught: " << ex.what() << std::endl;
}
if (sd != -1)
tcp_close(sd);
gnutls_global_deinit();
return 0;
}
|