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