+/*
+ * Copyright (C) 2011 Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <gnutls/gnutls.h>
+
+#define DH_BITS 1024
+static void * get_creds(char *certfile, char *keyfile)
+{
+ static gnutls_certificate_credentials_t cred;
+ gnutls_dh_params_t dh_params;
+ gnutls_dh_params_init(&dh_params);
+ gnutls_dh_params_generate2(dh_params, DH_BITS);
+ gnutls_certificate_allocate_credentials(&cred);
+ gnutls_certificate_set_x509_key_file(cred, certfile, keyfile,
+ GNUTLS_X509_FMT_PEM);
+ gnutls_certificate_set_dh_params(cred, dh_params);
+ return cred;
+}
+
+static void session_new(gnutls_session_t *session)
+{
+ static void *cred;
+ cred = get_creds("cert.pem", "key.pem");
+ gnutls_init(session, GNUTLS_SERVER);
+ gnutls_set_default_priority(*session);
+ gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE, cred);
+ gnutls_dh_set_prime_bits(*session, DH_BITS);
+}
+#undef DH_BITS
+
+int main(int argc, char **argv)
+{
+ int s;
+ struct sockaddr_in saddr;
+ int c;
+ int r;
+ char buffer[256];
+ gnutls_session_t session;
+ gnutls_global_init();
+ session_new(&session);
+ s = socket(PF_INET, SOCK_STREAM, 0);
+ saddr.sin_family = AF_INET;
+ saddr.sin_port = htons(3456);
+ saddr.sin_addr.s_addr = htonl(INADDR_ANY);
+ bind(s, (struct sockaddr *) &saddr, sizeof(saddr));
+ listen(s, 5);
+ c = accept(s, NULL, NULL);
+ close(s);
+ gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) c);
+ r = read(c, buffer, 1);
+ if (r == 1 && buffer[0] == 1)
+ write(c, "E", 1);
+ r = read(c, buffer, 14);
+ if (r == 14 && !memcmp(buffer, "00000000000000", 14))
+ write(c, "14032011002200", 14);
+ if ((r = gnutls_handshake(session)) < 0)
+ fprintf(stderr, "error in handshake: %s\n",
+ gnutls_strerror(r));
+ else
+ fprintf(stderr, "handshake ok\n");
+ close(c);
+ gnutls_global_deinit();
+ return 0;
+}