2 * Copyright (C) 2011 Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <gnutls/gnutls.h>
29 static void * get_creds(char *certfile)
31 static gnutls_certificate_credentials_t cred;
32 gnutls_certificate_allocate_credentials(&cred);
33 gnutls_certificate_set_x509_trust_file(cred, certfile,
38 static void session_new(gnutls_session_t *session)
41 cred = get_creds("cert.pem");
42 gnutls_init(session, GNUTLS_CLIENT);
43 gnutls_set_default_priority(*session);
44 gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE, cred);
47 static int deflateRecord(char *buffer, size_t len, char **out, size_t *olen)
51 zstrm.zalloc = Z_NULL;
53 zstrm.opaque = Z_NULL;
54 if ((r = deflateInit(&zstrm, Z_DEFAULT_COMPRESSION)) != Z_OK)
56 *out = malloc(len * 2 + 36);
61 zstrm.next_in = buffer;
63 zstrm.next_out = *out + 6;
64 zstrm.avail_out = len * 2 + 30;
65 while ((r = deflate(&zstrm, Z_FINISH)) != Z_STREAM_END &&
67 if ((r = deflate(&zstrm, Z_FINISH)) != Z_STREAM_END) {
72 *olen = zstrm.avail_out + 6;
74 (*out)[1] = (zstrm.avail_out >> 8);
75 (*out)[2] = (zstrm.avail_out & 0xff);
76 (*out)[3] = (len >> 8);
77 (*out)[4] = (len & 0xff);
83 int main(int argc, char **argv)
85 struct sockaddr_in saddr;
91 gnutls_session_t session;
93 session_new(&session);
94 c = socket(PF_INET, SOCK_STREAM, 0);
95 saddr.sin_family = AF_INET;
96 saddr.sin_port = htons(3456);
97 saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
98 connect(c, (struct sockaddr *) &saddr, sizeof(saddr));
99 gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) c);
102 write(c, "00000000000000", 14);
103 r = read(c, buffer, 1);
104 if (r != 1 && buffer[0] != 'E')
106 r = read(c, buffer, 14);
109 if ((r = gnutls_handshake(session)) < 0)
110 fprintf(stderr, "error in handshake: %s\n",
113 fprintf(stderr, "handshake ok\n");
115 deflateRecord(buffer, 1, &out, &olen);
116 gnutls_record_send(session, out, olen);
118 while ((r = gnutls_record_recv(session, buffer, sizeof(buffer))) > 0)
121 gnutls_global_deinit();