Added gnutls_x509_crl_reason_flags_t.
[gnutls.git] / doc / examples / ex-client-psk.c
bloba456f6cf4cb388e9c773c0dc65cda7db806532f6
1 /* This example code is placed in the public domain. */
3 #ifdef HAVE_CONFIG_H
4 #include <config.h>
5 #endif
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <arpa/inet.h>
13 #include <unistd.h>
14 #include <gnutls/gnutls.h>
16 /* A very basic TLS client, with PSK authentication.
19 #define MAX_BUF 1024
20 #define MSG "GET / HTTP/1.0\r\n\r\n"
22 extern int tcp_connect (void);
23 extern void tcp_close (int sd);
25 int
26 main (void)
28 int ret, sd, ii;
29 gnutls_session_t session;
30 char buffer[MAX_BUF + 1];
31 const char *err;
32 gnutls_psk_client_credentials_t pskcred;
33 const gnutls_datum_t key = { (void *) "DEADBEEF", 8 };
35 gnutls_global_init ();
37 gnutls_psk_allocate_client_credentials (&pskcred);
38 gnutls_psk_set_client_credentials (pskcred, "test", &key,
39 GNUTLS_PSK_KEY_HEX);
41 /* Initialize TLS session
43 gnutls_init (&session, GNUTLS_CLIENT);
45 /* Use default priorities */
46 ret = gnutls_priority_set_direct (session, "PERFORMANCE:+ECDHE-PSK:+DHE-PSK:+PSK", &err);
47 if (ret < 0)
49 if (ret == GNUTLS_E_INVALID_REQUEST)
51 fprintf (stderr, "Syntax error at: %s\n", err);
53 exit (1);
56 /* put the x509 credentials to the current session
58 gnutls_credentials_set (session, GNUTLS_CRD_PSK, pskcred);
60 /* connect to the peer
62 sd = tcp_connect ();
64 gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
65 gnutls_handshake_set_timeout (session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
67 /* Perform the TLS handshake
71 ret = gnutls_handshake (session);
73 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
75 if (ret < 0)
77 fprintf (stderr, "*** Handshake failed\n");
78 gnutls_perror (ret);
79 goto end;
81 else
83 printf ("- Handshake was completed\n");
86 gnutls_record_send (session, MSG, strlen (MSG));
88 ret = gnutls_record_recv (session, buffer, MAX_BUF);
89 if (ret == 0)
91 printf ("- Peer has closed the TLS connection\n");
92 goto end;
94 else if (ret < 0)
96 fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
97 goto end;
100 printf ("- Received %d bytes: ", ret);
101 for (ii = 0; ii < ret; ii++)
103 fputc (buffer[ii], stdout);
105 fputs ("\n", stdout);
107 gnutls_bye (session, GNUTLS_SHUT_RDWR);
109 end:
111 tcp_close (sd);
113 gnutls_deinit (session);
115 gnutls_psk_free_client_credentials (pskcred);
117 gnutls_global_deinit ();
119 return 0;