1 /* This example code is placed in the public domain. */
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <arpa/inet.h>
14 #include <gnutls/gnutls.h>
15 #include <gnutls/dtls.h>
17 /* A very basic Datagram TLS client, over UDP with X.509 authentication.
21 #define CAFILE "/etc/ssl/certs/ca-certificates.crt"
22 #define MSG "GET / HTTP/1.0\r\n\r\n"
24 extern int udp_connect (void);
25 extern void udp_close (int sd
);
26 extern int verify_certificate_callback (gnutls_session_t session
);
32 gnutls_session_t session
;
33 char buffer
[MAX_BUF
+ 1];
35 gnutls_certificate_credentials_t xcred
;
37 gnutls_global_init ();
40 gnutls_certificate_allocate_credentials (&xcred
);
42 /* sets the trusted cas file */
43 gnutls_certificate_set_x509_trust_file (xcred
, CAFILE
, GNUTLS_X509_FMT_PEM
);
44 gnutls_certificate_set_verify_function (xcred
, verify_certificate_callback
);
46 /* Initialize TLS session */
47 gnutls_init (&session
, GNUTLS_CLIENT
| GNUTLS_DATAGRAM
);
49 /* Use default priorities */
50 ret
= gnutls_priority_set_direct (session
, "NORMAL", &err
);
53 if (ret
== GNUTLS_E_INVALID_REQUEST
)
55 fprintf (stderr
, "Syntax error at: %s\n", err
);
60 /* put the x509 credentials to the current session */
61 gnutls_credentials_set (session
, GNUTLS_CRD_CERTIFICATE
, xcred
);
62 gnutls_server_name_set (session
, GNUTLS_NAME_DNS
, "my_host_name",
63 strlen("my_host_name"));
65 /* connect to the peer */
68 gnutls_transport_set_ptr (session
, (gnutls_transport_ptr_t
) sd
);
70 /* set the connection MTU */
71 gnutls_dtls_set_mtu (session
, 1000);
72 gnutls_handshake_set_timeout (session
, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT
);
74 /* Perform the TLS handshake */
77 ret
= gnutls_handshake (session
);
79 while (ret
< 0 && gnutls_error_is_fatal (ret
) == 0);
83 fprintf (stderr
, "*** Handshake failed\n");
89 printf ("- Handshake was completed\n");
92 gnutls_record_send (session
, MSG
, strlen (MSG
));
94 ret
= gnutls_record_recv (session
, buffer
, MAX_BUF
);
97 printf ("- Peer has closed the TLS connection\n");
102 fprintf (stderr
, "*** Error: %s\n", gnutls_strerror (ret
));
106 printf ("- Received %d bytes: ", ret
);
107 for (ii
= 0; ii
< ret
; ii
++)
109 fputc (buffer
[ii
], stdout
);
111 fputs ("\n", stdout
);
113 /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
114 * connections because the peer's closure message might
116 gnutls_bye (session
, GNUTLS_SHUT_WR
);
122 gnutls_deinit (session
);
124 gnutls_certificate_free_credentials (xcred
);
126 gnutls_global_deinit ();