Tizen 2.0 Release
[external/libgnutls26.git] / doc / examples / ex-client-psk.c
1 /* This example code is placed in the public domain. */
2
3 #ifdef HAVE_CONFIG_H
4 #include <config.h>
5 #endif
6
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>
15
16 /* A very basic TLS client, with PSK authentication.
17  */
18
19 #define MAX_BUF 1024
20 #define MSG "GET / HTTP/1.0\r\n\r\n"
21
22 extern int tcp_connect (void);
23 extern void tcp_close (int sd);
24
25 int
26 main (void)
27 {
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 = { (char *) "DEADBEEF", 8 };
34
35   gnutls_global_init ();
36
37   gnutls_psk_allocate_client_credentials (&pskcred);
38   gnutls_psk_set_client_credentials (pskcred, "test", &key,
39                                      GNUTLS_PSK_KEY_HEX);
40
41   /* Initialize TLS session
42    */
43   gnutls_init (&session, GNUTLS_CLIENT);
44
45   /* Use default priorities */
46   ret = gnutls_priority_set_direct (session, "PERFORMANCE", &err);
47   if (ret < 0)
48     {
49       if (ret == GNUTLS_E_INVALID_REQUEST)
50         {
51           fprintf (stderr, "Syntax error at: %s\n", err);
52         }
53       exit (1);
54     }
55
56   /* put the x509 credentials to the current session
57    */
58   gnutls_credentials_set (session, GNUTLS_CRD_PSK, pskcred);
59
60   /* connect to the peer
61    */
62   sd = tcp_connect ();
63
64   gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
65
66   /* Perform the TLS handshake
67    */
68   ret = gnutls_handshake (session);
69
70   if (ret < 0)
71     {
72       fprintf (stderr, "*** Handshake failed\n");
73       gnutls_perror (ret);
74       goto end;
75     }
76   else
77     {
78       printf ("- Handshake was completed\n");
79     }
80
81   gnutls_record_send (session, MSG, strlen (MSG));
82
83   ret = gnutls_record_recv (session, buffer, MAX_BUF);
84   if (ret == 0)
85     {
86       printf ("- Peer has closed the TLS connection\n");
87       goto end;
88     }
89   else if (ret < 0)
90     {
91       fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
92       goto end;
93     }
94
95   printf ("- Received %d bytes: ", ret);
96   for (ii = 0; ii < ret; ii++)
97     {
98       fputc (buffer[ii], stdout);
99     }
100   fputs ("\n", stdout);
101
102   gnutls_bye (session, GNUTLS_SHUT_RDWR);
103
104 end:
105
106   tcp_close (sd);
107
108   gnutls_deinit (session);
109
110   gnutls_psk_free_client_credentials (pskcred);
111
112   gnutls_global_deinit ();
113
114   return 0;
115 }