[Pkg-privacy-commits] [libotr] 03/07: 0002-Test-Add-new-test-suite-in-tests.patch: cherry-pick new upstream test suite.

Intrigeri intrigeri at moszumanska.debian.org
Tue Jan 12 04:50:32 UTC 2016


This is an automated email from the git hooks/post-receive script.

intrigeri pushed a commit to branch master
in repository libotr.

commit c45f233f3b8c759d3e28e55309812dd528759959
Author: intrigeri <intrigeri at debian.org>
Date:   Tue Jan 12 03:19:16 2016 +0000

    0002-Test-Add-new-test-suite-in-tests.patch: cherry-pick new upstream test suite.
---
 .../0002-Test-Add-new-test-suite-in-tests.patch    | 5319 ++++++++++++++++++++
 debian/patches/series                              |    1 +
 2 files changed, 5320 insertions(+)

diff --git a/debian/patches/0002-Test-Add-new-test-suite-in-tests.patch b/debian/patches/0002-Test-Add-new-test-suite-in-tests.patch
new file mode 100644
index 0000000..3bd16f8
--- /dev/null
+++ b/debian/patches/0002-Test-Add-new-test-suite-in-tests.patch
@@ -0,0 +1,5319 @@
+From: David Goulet <dgoulet at ev0ke.net>
+Date: Wed, 23 Apr 2014 15:01:16 -0400
+Origin: https://bugs.otr.im/projects/libotr/repository/revisions/7b860e03c660abfa911e7a7e41f9e5e040de4d32
+Forwarded: not-needed
+Subject: Test: Add new test-suite in tests/
+
+This is a completely new test suite that adds unit and regression tests.
+Still not everything is covered but it's at 76.3% line coverage and
+87.5% function coverage. See the current status here.
+
+	https://coverage.otr.im/
+
+In order to run the tests, simply type "make check" from the top
+directory of the repository.
+
+The test suite uses libtap and adds both a shell and C library located
+in tests/utils/tap.
+
+Note that this test suite is not related at all to the tests located in
+the directory test_suite. Future work should be done to either merge
+them or remove the old one.
+
+Tested with libgcrypt 1.5.4 and 1.6.2.
+
+Signed-off-by: Julien Voisin <julien.voisin at dustri.org>
+Signed-off-by: David Goulet <dgoulet at ev0ke.net>
+Signed-off-by: Ian Goldberg <iang at cs.uwaterloo.ca>
+
+Fixes #8
+---
+ Makefile.am                                        |    2 +-
+ configure.ac                                       |   10 +-
+ tests/Makefile.am                                  |   11 +
+ tests/regression/Makefile.am                       |    5 +
+ tests/regression/client/Makefile.am                |   15 +
+ tests/regression/client/client.c                   | 1158 ++++++++++++++++++++
+ tests/regression/client/otr.key                    |   41 +
+ tests/regression/random-msg-auth.sh                |   14 +
+ tests/regression/random-msg-disconnect-auth.sh     |   14 +
+ .../regression/random-msg-disconnect-frag-auth.sh  |   14 +
+ tests/regression/random-msg-disconnect-frag.sh     |   14 +
+ tests/regression/random-msg-disconnect.sh          |   14 +
+ tests/regression/random-msg-fast.sh                |   14 +
+ tests/regression/random-msg-frag.sh                |   14 +
+ tests/regression/random-msg.sh                     |   14 +
+ tests/run.sh                                       |   26 +
+ tests/test_list                                    |   19 +
+ tests/unit/Makefile.am                             |   49 +
+ tests/unit/instag.txt                              |    4 +
+ tests/unit/test_auth.c                             |  181 +++
+ tests/unit/test_b64.c                              |  114 ++
+ tests/unit/test_context.c                          |  214 ++++
+ tests/unit/test_dh.c                               |  515 +++++++++
+ tests/unit/test_instag.c                           |  222 ++++
+ tests/unit/test_mem.c                              |   58 +
+ tests/unit/test_privkey.c                          |  264 +++++
+ tests/unit/test_proto.c                            |  371 +++++++
+ tests/unit/test_sm.c                               |  343 ++++++
+ tests/unit/test_tlv.c                              |  163 +++
+ tests/unit/test_userstate.c                        |   52 +
+ tests/utils/Makefile.am                            |    3 +
+ tests/utils/tap/Makefile.am                        |    7 +
+ tests/utils/tap/tap.c                              |  433 ++++++++
+ tests/utils/tap/tap.h                              |   89 ++
+ tests/utils/tap/tap.sh                             |  456 ++++++++
+ tests/utils/utils.c                                |   18 +
+ tests/utils/utils.h                                |   29 +
+ 37 files changed, 4978 insertions(+), 6 deletions(-)
+ create mode 100644 tests/Makefile.am
+ create mode 100644 tests/regression/Makefile.am
+ create mode 100644 tests/regression/client/Makefile.am
+ create mode 100644 tests/regression/client/client.c
+ create mode 100644 tests/regression/client/otr.key
+ create mode 100755 tests/regression/random-msg-auth.sh
+ create mode 100755 tests/regression/random-msg-disconnect-auth.sh
+ create mode 100755 tests/regression/random-msg-disconnect-frag-auth.sh
+ create mode 100755 tests/regression/random-msg-disconnect-frag.sh
+ create mode 100755 tests/regression/random-msg-disconnect.sh
+ create mode 100755 tests/regression/random-msg-fast.sh
+ create mode 100755 tests/regression/random-msg-frag.sh
+ create mode 100755 tests/regression/random-msg.sh
+ create mode 100755 tests/run.sh
+ create mode 100644 tests/test_list
+ create mode 100644 tests/unit/Makefile.am
+ create mode 100644 tests/unit/instag.txt
+ create mode 100644 tests/unit/test_auth.c
+ create mode 100644 tests/unit/test_b64.c
+ create mode 100644 tests/unit/test_context.c
+ create mode 100644 tests/unit/test_dh.c
+ create mode 100644 tests/unit/test_instag.c
+ create mode 100644 tests/unit/test_mem.c
+ create mode 100644 tests/unit/test_privkey.c
+ create mode 100644 tests/unit/test_proto.c
+ create mode 100644 tests/unit/test_sm.c
+ create mode 100644 tests/unit/test_tlv.c
+ create mode 100644 tests/unit/test_userstate.c
+ create mode 100644 tests/utils/Makefile.am
+ create mode 100644 tests/utils/tap/Makefile.am
+ create mode 100644 tests/utils/tap/tap.c
+ create mode 100644 tests/utils/tap/tap.h
+ create mode 100755 tests/utils/tap/tap.sh
+ create mode 100644 tests/utils/utils.c
+ create mode 100644 tests/utils/utils.h
+
+diff --git a/Makefile.am b/Makefile.am
+index 7e44beb..27a1395 100644
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -1,6 +1,6 @@
+ ACLOCAL_AMFLAGS = -I config
+ 
+-SUBDIRS = src toolkit
++SUBDIRS = src toolkit tests
+ 
+ EXTRA_DIST = Protocol-v3.html UPGRADING packaging libotr.m4 libotr.pc.in
+ 
+diff --git a/configure.ac b/configure.ac
+index 262f766..ab291d3 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -170,11 +170,11 @@ if test x$enable_linker_hardening != xno; then
+     OTR_CHECK_LDFLAGS(-z relro -z now, "$all_ldflags_for_check", "$all_libs_for_check")
+ fi
+ 
+-AC_CONFIG_FILES([
+-	Makefile
+-	src/Makefile
+-	toolkit/Makefile
+-	libotr.pc
++AC_OUTPUT([Makefile src/Makefile toolkit/Makefile tests/Makefile tests/utils/Makefile libotr.pc
++           tests/utils/tap/Makefile
++           tests/unit/Makefile
++           tests/regression/Makefile
++           tests/regression/client/Makefile
+ ])
+ 
+ AC_OUTPUT
+diff --git a/tests/Makefile.am b/tests/Makefile.am
+new file mode 100644
+index 0000000..b5949db
+--- /dev/null
++++ b/tests/Makefile.am
+@@ -0,0 +1,11 @@
++SUBDIRS = utils unit regression
++
++AM_CFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/src -I$(top_srcdir)/tests/utils/ -I$(srcdir)
++
++LIBTAP=$(top_builddir)/tests/utils/tap/libtap.la
++
++check-am:
++	./run.sh test_list
++
++dist_noinst_SCRIPTS = test_list run.sh
++EXTRA_DIST = run.sh test_list
+diff --git a/tests/regression/Makefile.am b/tests/regression/Makefile.am
+new file mode 100644
+index 0000000..c4d20f4
+--- /dev/null
++++ b/tests/regression/Makefile.am
+@@ -0,0 +1,5 @@
++SUBDIRS = client
++
++EXTRA_DIST = random-msg.sh random-msg-disconnect.sh random-msg-disconnect-auth.sh \
++             random-msg-disconnect-frag-auth.sh random-msg-fast.sh random-msg-auth.sh \
++             random-msg-disconnect-frag.sh random-msg-frag.sh
+diff --git a/tests/regression/client/Makefile.am b/tests/regression/client/Makefile.am
+new file mode 100644
+index 0000000..37447c1
+--- /dev/null
++++ b/tests/regression/client/Makefile.am
+@@ -0,0 +1,15 @@
++AM_CFLAGS = -I$(top_srcdir)/include \
++			-I$(top_srcdir)/src \
++			-I$(top_srcdir)/tests/utils/ \
++			-I$(srcdir)
++
++LIBTAP=$(top_builddir)/tests/utils/tap/libtap.la
++
++LIBOTR=$(top_builddir)/src/libotr.la
++
++noinst_PROGRAMS = client
++
++client_SOURCES = client.c
++client_LDADD = $(LIBTAP) $(LIBOTR) -lpthread @LIBGCRYPT_LIBS@
++
++EXTRA_DIST = otr.key
+diff --git a/tests/regression/client/client.c b/tests/regression/client/client.c
+new file mode 100644
+index 0000000..e72b661
+--- /dev/null
++++ b/tests/regression/client/client.c
+@@ -0,0 +1,1158 @@
++/*
++ * Copyright (C) 2014 - David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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.
++ */
++
++#define _GNU_SOURCE
++#include <assert.h>
++#include <ctype.h>
++#include <gcrypt.h>
++#include <getopt.h>
++#include <inttypes.h>
++#include <pthread.h>
++#include <signal.h>
++#include <stdlib.h>
++#include <syscall.h>
++#include <sys/epoll.h>
++#include <sys/types.h>
++#include <sys/un.h>
++#include <unistd.h>
++
++#include <context.h>
++#include <privkey.h>
++#include <proto.h>
++#include <message.h>
++
++#include <tap/tap.h>
++
++#define zmalloc(x) calloc(1, x)
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++/* Global OTR user state. */
++static OtrlUserState user_state;
++
++/* Getopt options. */
++static struct option long_opts[] = {
++	{ "load-instag", 1, NULL, 'i' },
++	{ "load-key",    1, NULL, 'k' },
++	{ "load-fp",     1, NULL, 'f' },
++	{ "timeout",     1, NULL, 't' },
++	{ "max-msg",     1, NULL, 'm' },
++	{ "disconnect",  0, NULL, 'd' },
++	{ "auth",        0, NULL, 'a' },
++	{ "fragment",    0, NULL, 'F' },
++
++	/* Closure. */
++	{ NULL, 0, NULL, 0 }
++};
++
++static char *opt_instag_path;
++static char *opt_key_path;
++static char *opt_key_fp_path;
++static unsigned int opt_max_num_msg;
++static int opt_disconnect;
++static int opt_auth;
++static int opt_fragment;
++
++/* Currently, the message size sent is between 1 and 600 len so 100 is a good
++ * middle ground. */
++static const int fragment_size = 100;
++/* By default, don't send frag. */
++static OtrlFragmentPolicy fragPolicy = OTRL_FRAGMENT_SEND_SKIP;
++
++static const char *protocol = "otr-test";
++static const char *alice_name = "alice";
++static const char *bob_name = "bob";
++
++static const char *unix_sock_bob_path = "/tmp/otr-test-bob.sock";
++static const char *unix_sock_alice_path = "/tmp/otr-test-alice.sock";
++
++static const char *auth_question = "What is NSA?";
++static const char *auth_secret = "No Sugar Added";
++
++/* Alice and Bob thread's socket. */
++static int alice_sock;
++static int bob_sock;
++/* Declare it global because we use it multiple times. */
++static struct sockaddr_un alice_sun;
++static struct sockaddr_un bob_sun;
++
++static int timeout_max = 1000;
++static unsigned int num_recv_msg;
++static unsigned int session_disconnected;
++
++static int quit_pipe[2] =  { -1, -1 };
++
++/*
++ * For now not really do much more but if we want to use the OK condition at
++ * some point to do something else, that will ease our life :).
++ */
++#define OK(cond, fmt, args...)				   \
++	do {										 \
++		ok(cond, fmt, ## args);				  \
++	} while (0)
++
++/*
++ * Used to pass OTR message between threads. This contains the cipher and
++ * plaintext so we are able to validate what's expected in both threads.
++ */
++struct otr_msg {
++	size_t plaintext_len;
++	size_t ciphertext_len;
++	char *plaintext;
++	char *ciphertext;
++};
++
++struct otr_info {
++	const char *user;
++	int sock;
++	unsigned int gone_secure;
++	unsigned int auth_done;
++};
++
++/* Stub */
++static int send_otr_msg(int sock, const char *to, const char *from,
++		struct otr_info *oinfo, const char *message);
++
++static OtrlPolicy ops_policy(void *opdata, ConnContext *context)
++{
++	return OTRL_POLICY_DEFAULT;
++}
++
++static void ops_inject_msg(void *opdata, const char *accountname,
++		const char *protocol, const char *recipient, const char *message)
++{
++	ssize_t ret;
++	struct otr_info *oinfo = opdata;
++	struct otr_msg *msg;
++
++	msg = zmalloc(sizeof(*msg));
++	if (!msg) {
++		perror("zmalloc inject");
++		return;
++	}
++
++	msg->ciphertext = strdup(message);
++	msg->ciphertext_len = strlen(message);
++
++	ret = send(oinfo->sock, &msg, sizeof(msg), 0);
++	if (ret < 0) {
++		perror("send msg");
++	}
++}
++
++static void ops_gone_secure(void *opdata, ConnContext *context)
++{
++	struct otr_info *oinfo = opdata;
++
++	session_disconnected = 0;
++	oinfo->gone_secure = 1;
++	/* XXX: gone_insecure is never called ref bug #40 so this will always be
++	 * true. */
++	OK(oinfo->gone_secure, "Gone secure for %s",
++			oinfo->user);
++}
++
++static void ops_gone_insecure(void *opdata, ConnContext *context)
++{
++	struct otr_info *oinfo = opdata;
++
++	OK(oinfo->gone_secure, "Gone insecure for %s",
++			oinfo->user);
++	oinfo->gone_secure = 0;
++}
++
++static int ops_max_message_size(void *opdata, ConnContext *context)
++{
++	if (opt_fragment) {
++		return fragment_size;
++	}
++	return 0;
++}
++
++static const char *ops_otr_error_message(void *opdata, ConnContext *context,
++		OtrlErrorCode code)
++{
++	char *msg = NULL;
++
++	switch (code) {
++	case OTRL_ERRCODE_NONE:
++		break;
++	case OTRL_ERRCODE_ENCRYPTION_ERROR:
++		msg = strdup("OTRL_ERRCODE_ENCRYPTION_ERROR");
++		break;
++	case OTRL_ERRCODE_MSG_NOT_IN_PRIVATE:
++		msg = strdup("OTRL_ERRCODE_MSG_NOT_IN_PRIVATE");
++		break;
++	case OTRL_ERRCODE_MSG_UNREADABLE:
++		msg = strdup("OTRL_ERRCODE_MSG_UNREADABLE");
++		break;
++	case OTRL_ERRCODE_MSG_MALFORMED:
++		msg = strdup("OTRL_ERRCODE_MSG_MALFORMED");
++		break;
++	}
++
++	return msg;
++}
++
++static void ops_otr_error_message_free(void *opdata, const char *err_msg)
++{
++	free((char *) err_msg);
++}
++
++static void ops_handle_msg_event(void *opdata, OtrlMessageEvent msg_event,
++		ConnContext *context, const char *message, gcry_error_t err)
++{
++	//char* msg = "";
++	struct otr_info *oinfo = opdata;
++
++	switch(msg_event) {
++	case OTRL_MSGEVENT_NONE:
++		//msg = "OTRL_MSGEVENT_NONE";
++		break;
++	case OTRL_MSGEVENT_ENCRYPTION_REQUIRED:
++		//msg = "OTRL_MSGEVENT_ENCRYPTION_REQUIRED";
++		break;
++	case OTRL_MSGEVENT_ENCRYPTION_ERROR:
++		//msg = "OTRL_MSGEVENT_ENCRYPTION_ERROR";
++		break;
++	case OTRL_MSGEVENT_CONNECTION_ENDED:
++		//msg = "OTRL_MSGEVENT_CONNECTION_ENDED";
++		oinfo->gone_secure = 0;
++		break;
++	case OTRL_MSGEVENT_SETUP_ERROR:
++		//msg = "OTRL_MSGEVENT_SETUP_ERROR";
++		break;
++	case OTRL_MSGEVENT_MSG_REFLECTED:
++		//msg = "OTRL_MSGEVENT_MSG_REFLECTED";
++		break;
++	case OTRL_MSGEVENT_MSG_RESENT:
++		//msg = "OTRL_MSGEVENT_MSG_RESENT";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_UNREADABLE:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_UNREADABLE";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_MALFORMED:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_MALFORMED";
++		break;
++	case OTRL_MSGEVENT_LOG_HEARTBEAT_RCVD:
++		//msg = "OTRL_MSGEVENT_LOG_HEARTBEAT_RCVD";
++		break;
++	case OTRL_MSGEVENT_LOG_HEARTBEAT_SENT:
++		//msg = "OTRL_MSGEVENT_LOG_HEARTBEAT_SENT";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED";
++		break;
++	case OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE:
++		//msg = "OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE";
++		break;
++	default:
++		//msg = "Unknown OTRL message event";
++		break;
++	}
++}
++
++static void ops_create_instag(void *opdata, const char *accountname,
++		const char *protocol)
++{
++	otrl_instag_generate(user_state, "/dev/null", accountname,
++			protocol);
++}
++
++static int ops_is_logged_in(void *opdata, const char *accountname,
++		const char *protocol, const char *recipient)
++{
++	/* Always logged in or else we don't receive a disconnected TLV. */
++	return 1;
++}
++
++static void ops_create_privkey(void *opdata, const char *accountname,
++		const char *protocol)
++{
++	/* XXX: We should gen. our own key each time at some point? */
++	return;
++}
++
++static void ops_update_context_list(void *opdata)
++{
++	return;
++}
++
++static void ops_new_fingerprint(void *opdata, OtrlUserState us,
++		const char *accountname, const char *protocol,
++		const char *username, unsigned char fingerprint[20])
++{
++	return;
++}
++
++static void ops_write_fingerprints(void *opdata)
++{
++	return;
++}
++
++static void ops_still_secure(void *opdata, ConnContext *context, int is_reply)
++{
++	struct otr_info *oinfo = opdata;
++
++	OK(oinfo->gone_secure, "OP still secure");
++}
++
++static void ops_received_symkey(void *opdata, ConnContext *context,
++		unsigned int use, const unsigned char *usedata,
++		size_t usedatalen, const unsigned char *symkey)
++{
++	return;
++}
++
++static const char *ops_resent_msg_prefix(void *opdata, ConnContext *context)
++{
++	/* Just so we can test resent_msg_prefix_free */
++	char *prefix = zmalloc(32);
++	strncpy(prefix, "[such resent]", 32);
++
++	return prefix;
++}
++
++static void ops_resent_msg_prefix_free(void *opdata, const char *prefix)
++{
++	free((char *) prefix);
++}
++
++static void ops_convert_msg(void *opdata, ConnContext *context,
++		OtrlConvertType convert_type, char ** dest, const char *src)
++{
++	switch (convert_type) {
++	case OTRL_CONVERT_SENDING:
++	case OTRL_CONVERT_RECEIVING:
++		break;
++	default:
++		OK(0, "OP convert_msg, got a unknown type %d", convert_type);
++		break;
++	}
++
++	*dest = NULL;
++}
++
++static void ops_convert_free(void *opdata, ConnContext *context, char *dest)
++{
++	return;
++}
++
++/* Stub */
++static void ops_handle_smp_event(void *opdata, OtrlSMPEvent smp_event,
++		ConnContext *context, unsigned short progress_percent, char *question);
++static void ops_timer_control(void *opdata, unsigned int interval);
++
++/* OTR message operations. */
++static OtrlMessageAppOps ops = {
++	ops_policy,
++	ops_create_privkey,
++	ops_is_logged_in,
++	ops_inject_msg,
++	ops_update_context_list,
++	ops_new_fingerprint,
++	ops_write_fingerprints,
++	ops_gone_secure,
++	ops_gone_insecure,
++	ops_still_secure,
++	ops_max_message_size,
++	NULL, /* account_name - NOT USED */
++	NULL, /* account_name_free - NOT USED */
++	ops_received_symkey,
++	ops_otr_error_message,
++	ops_otr_error_message_free,
++	ops_resent_msg_prefix,
++	ops_resent_msg_prefix_free,
++	ops_handle_smp_event,
++	ops_handle_msg_event,
++	ops_create_instag,
++	ops_convert_msg,
++	ops_convert_free,
++	ops_timer_control,
++};
++
++
++static void ops_timer_control(void *opdata, unsigned int interval)
++{
++	otrl_message_poll(user_state, &ops, NULL);
++}
++
++static void ops_handle_smp_event(void *opdata, OtrlSMPEvent smp_event,
++		ConnContext *context, unsigned short progress_percent, char *question)
++{
++	struct otr_info *oinfo = opdata;
++
++	switch (smp_event) {
++	case OTRL_SMPEVENT_ASK_FOR_SECRET:
++		OK(!oinfo->auth_done &&
++			!strncmp(oinfo->user, alice_name, strlen(alice_name)),
++			"SMP Event, %s asking for secret", alice_name);
++		break;
++	case OTRL_SMPEVENT_ASK_FOR_ANSWER:
++		OK(!oinfo->auth_done &&
++				!strncmp(oinfo->user, bob_name, strlen(bob_name)) &&
++				!strncmp(auth_question, question, strlen(auth_question)),
++				"SMP Event, %s asking for answer", bob_name);
++		/*
++		 * Directly respond to the SMP auth here. Much more easy instead of in
++		 * bob's thread.
++		 */
++		otrl_message_respond_smp(user_state, &ops, opdata, context,
++				(unsigned char *) auth_secret, strlen(auth_secret));
++		break;
++	case OTRL_SMPEVENT_IN_PROGRESS:
++		OK(!oinfo->auth_done &&
++				!strncmp(oinfo->user, alice_name, strlen(alice_name)),
++				"SMP Event, %s asking for secret", alice_name);
++		break;
++	case OTRL_SMPEVENT_SUCCESS:
++		oinfo->auth_done = 1;
++		OK(oinfo->auth_done, "SMP authentication success for %s", oinfo->user);
++		break;
++	case OTRL_SMPEVENT_ABORT:
++	case OTRL_SMPEVENT_FAILURE:
++	case OTRL_SMPEVENT_CHEATED:
++	case OTRL_SMPEVENT_ERROR:
++	default:
++		OK(0, "SMP auth failed with event %d", smp_event);
++		break;
++	}
++}
++
++static void cleanup(void)
++{
++	ssize_t ret;
++
++	/* Wake up threads. */
++	ret = write(quit_pipe[1], "42", 2);
++	if (ret < 0) {
++		perror("write quit pipe");
++	}
++
++	/* Cleanup residual Unix socket path. */
++	unlink(alice_sun.sun_path);
++	unlink(bob_sun.sun_path);
++}
++
++static void update_msg_counter(void)
++{
++	num_recv_msg++;
++	if (num_recv_msg == opt_max_num_msg) {
++		cleanup();
++	}
++}
++
++/*
++ * Generate random string and stores it in out of size len.
++ */
++static void gen_random_string(char *out, size_t len)
++{
++	size_t i;
++	static const char alphanum[] =
++		"0123456789"
++		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
++		"abcdefghijklmnopqrstuvwxyz";
++
++	for (i = 0; i < len; i++) {
++		out[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
++	}
++	out[len - 1] = '\0';
++}
++
++static int send_otr_msg(int sock, const char *to, const char *from,
++		struct otr_info *oinfo, const char *message)
++{
++	char *new_msg = NULL;
++	ssize_t ret;
++	gcry_error_t err;
++	struct otr_msg *omsg;
++
++	omsg = zmalloc(sizeof(*omsg));
++	if (!omsg) {
++		perror("zmalloc send otr msg");
++		goto error;
++	}
++
++	if (!message) {
++		size_t len = rand() % 600;
++		char *msg = zmalloc(len);
++		if (!msg) {
++			perror("random msg");
++			goto error;
++		}
++		gen_random_string(msg, len);
++		omsg->plaintext = msg;
++		omsg->plaintext_len = strlen(msg);
++	} else {
++		omsg->plaintext = strdup(message);
++		omsg->plaintext_len = strlen(message);
++	}
++
++	err = otrl_message_sending(user_state, &ops, oinfo, from, protocol, to,
++			OTRL_INSTAG_BEST, omsg->plaintext, NULL, &new_msg,
++			fragPolicy, NULL, NULL, NULL);
++	if (err) {
++		goto error;
++	}
++	if (new_msg) {
++		free(omsg->ciphertext);
++		omsg->ciphertext = strdup(new_msg);
++		omsg->ciphertext_len = strlen(omsg->ciphertext);
++		otrl_message_free(new_msg);
++	}
++
++	ret = send(sock, &omsg, sizeof(omsg), 0);
++	if (ret < 0) {
++		perror("send OTR msg");
++		goto error;
++	}
++
++	return 0;
++
++error:
++	if(omsg){
++		free(omsg->plaintext);
++		free(omsg->ciphertext);
++		free(omsg);
++	}
++	return -1;
++}
++
++static int recv_otr_msg(int sock, const char *to, const char *from,
++		struct otr_info *oinfo)
++{
++	int err;
++	ssize_t ret;
++	char *new_msg = NULL;
++	struct otr_msg *omsg;
++	OtrlTLV *tlvs = NULL;
++
++	ret = recv(sock, &omsg, sizeof(omsg), 0);
++	if (ret < 0) {
++		goto error;
++	}
++
++	err = otrl_message_receiving(user_state, &ops, oinfo, to, protocol, from,
++			omsg->ciphertext, &new_msg, &tlvs, NULL, NULL, NULL);
++	if (!err) {
++		if (new_msg) {
++			OK(strncmp(omsg->plaintext, new_msg, omsg->plaintext_len) == 0,
++					"Message exchanged is valid");
++			update_msg_counter();
++		}
++	} else {
++		OK(err == 1, "Internal OTR message valid");
++	}
++
++	free(omsg->plaintext);
++	free(omsg->ciphertext);
++	free(omsg);
++
++	OtrlTLV *tlv = otrl_tlv_find(tlvs, OTRL_TLV_DISCONNECTED);
++	/*
++	 * XXX: Somehow you can end up with a disconnected TLV in a gone secure
++	 * session (see #54). This is probably a bug but since the gone_insecure is
++	 * never called (see bug #48) we have no reliable way of knowing the state
++	 * of the session at this point.
++	 */
++	if (tlv && !oinfo->gone_secure) {
++		OK(session_disconnected, "Disconnected TLV confirmed");
++	}
++
++	otrl_tlv_free(tlvs);
++
++	return 0;
++
++error:
++	return -1;
++}
++
++static int add_sock_to_pollset(int epfd, int sock, uint32_t req_ev)
++{
++	int ret;
++	struct epoll_event ev;
++
++	memset(&ev, 0, sizeof(ev));
++	ev.events = req_ev;
++	ev.data.fd = sock;
++
++	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev);
++	if (ret < 0) {
++		perror("epoll_ctl add");
++	}
++	return ret;
++}
++
++static void *alice_thread(void *data)
++{
++	int sock_to_bob, sock_from_bob = 0, epfd, ret;
++	unsigned int auth_started = 0;
++	struct otr_info oinfo;
++
++	memset(&oinfo, 0, sizeof(oinfo));
++
++	/* Poll size is ignored since 2.6.8 */
++	epfd = epoll_create(42);
++	if (epfd < 0) {
++		perror("epoll_create Bob");
++		goto error;
++	}
++
++	sock_to_bob = socket(PF_UNIX, SOCK_STREAM, 0);
++	if (sock_to_bob < 0) {
++		perror("Bob socket to Alice");
++		goto sock_error;
++	}
++	oinfo.sock = sock_to_bob;
++	oinfo.user = alice_name;
++	if (!opt_auth) {
++		/* We are not going to SMP auth for this session so indicate it's
++		 * completed so we can go forward with random disconnect.
++		 */
++		oinfo.auth_done = 1;
++	}
++
++	ret = connect(sock_to_bob, (struct sockaddr *) &bob_sun,
++			sizeof(bob_sun));
++	if (ret < 0) {
++		perror("connect to Alice");
++		goto end;
++	}
++
++	/* Add quit pipe to pollset trigger by a cleanup. */
++	ret = add_sock_to_pollset(epfd, quit_pipe[0], EPOLLIN);
++	if (ret < 0) {
++		goto end;
++	}
++
++	/* Add our socket to epoll set. */
++	ret = add_sock_to_pollset(epfd, alice_sock,
++			EPOLLIN | EPOLLRDHUP);
++	if (ret < 0) {
++		goto end;
++	}
++
++	while (1) {
++		int i, nb_fd, timeout;
++		struct epoll_event ev[3];
++		memset(ev, 0, sizeof(ev));
++
++		/*
++		 * Set random timeout and when we do timeout, use that to send message
++		 * to Alice.
++		 */
++		timeout = (rand() % (timeout_max - 1));
++
++		ret = epoll_wait(epfd, ev, sizeof(ev), timeout);
++		if (ret < 0) {
++			perror("epoll_wait Alice");
++			goto end;
++		}
++		nb_fd = ret;
++
++		/* Each timeout to 10 finishes the OTR session. */
++		if (!(timeout % 3) && opt_disconnect && oinfo.auth_done) {
++			session_disconnected = 1;
++			oinfo.gone_secure = 0;
++			otrl_message_disconnect(user_state, &ops, &oinfo,
++					alice_name, protocol, bob_name, OTRL_INSTAG_BEST);
++			OK(!oinfo.gone_secure, "OTR message disconnect");
++		}
++
++		/* Start authentication with Bob. */
++		if (opt_auth && !auth_started && oinfo.gone_secure) {
++			ConnContext *ctx;
++
++			/* We have to find our context before auth. */
++			ctx = otrl_context_find(user_state, bob_name, alice_name,
++					protocol, OTRL_INSTAG_BEST, 0, NULL, NULL, &oinfo);
++			OK(ctx, "Alice context found for SMP auth");
++
++			otrl_message_initiate_smp_q(user_state, &ops, &oinfo, ctx,
++					auth_question, (unsigned char *) auth_secret,
++					strlen(auth_secret));
++			auth_started = 1;
++		}
++
++		/* No event thus timeout, send message to Alice. */
++		if (nb_fd == 0) {
++			(void) send_otr_msg(sock_to_bob, bob_name, alice_name, &oinfo,
++					NULL);
++			continue;
++		}
++
++		for (i = 0; i < nb_fd; i++) {
++			int fd;
++			uint32_t event;
++
++			fd = ev[i].data.fd;
++			event = ev[i].events;
++
++			if (fd == quit_pipe[0]) {
++				/* Time to leave. */
++				goto end;
++			} else if (fd == alice_sock) {
++				if (event & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
++					goto end;
++				} else if (event & EPOLLIN) {
++					socklen_t len;
++					struct sockaddr_un sun;
++
++					/* Connection from Bob, accept it so we can handle it. */
++					sock_from_bob = accept(fd, (struct sockaddr *) &sun,
++							&len);
++					ret = add_sock_to_pollset(epfd, sock_from_bob,
++							EPOLLIN | EPOLLERR | EPOLLHUP);
++					if (ret < 0) {
++						goto end;
++					}
++				}
++				continue;
++			} else if (fd == sock_from_bob) {
++				if (event & (EPOLLERR | EPOLLHUP)) {
++					/* Stop since Bob's thread just shut us down. */
++					goto end;
++				} else if (event & EPOLLIN) {
++					(void) recv_otr_msg(sock_from_bob, alice_name, bob_name,
++							&oinfo);
++				}
++				continue;
++			} else {
++				goto end;
++			}
++		}
++	}
++
++end:
++	if (sock_from_bob) {
++		(void) close(sock_from_bob);
++	}
++	(void) close(sock_to_bob);
++sock_error:
++	(void) close(epfd);
++error:
++	(void) close(alice_sock);
++
++	return NULL;
++}
++
++static void *bob_thread(void *data)
++{
++	int sock_to_alice, sock_from_alice = 0, epfd, ret;
++	struct otr_info oinfo;
++
++	memset(&oinfo, 0, sizeof(oinfo));
++
++	/* Poll size is ignored since 2.6.8 */
++	epfd = epoll_create(42);
++	if (epfd < 0) {
++		perror("epoll_create Bob");
++		goto error;
++	}
++
++	sock_to_alice = socket(PF_UNIX, SOCK_STREAM, 0);
++	if (sock_to_alice < 0) {
++		perror("Bob socket to Alice");
++		goto sock_error;
++	}
++	oinfo.sock = sock_to_alice;
++	oinfo.user = bob_name;
++
++	ret = connect(sock_to_alice, (struct sockaddr *) &alice_sun,
++			sizeof(alice_sun));
++	if (ret < 0) {
++		perror("connect to Alice");
++		goto end;
++	}
++
++	/* Add quit pipe to pollset trigger by a cleanup. */
++	ret = add_sock_to_pollset(epfd, quit_pipe[0], EPOLLIN);
++	if (ret < 0) {
++		goto end;
++	}
++
++	/* Add our socket to epoll set. */
++	ret = add_sock_to_pollset(epfd, bob_sock,
++			EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP);
++	if (ret < 0) {
++		goto end;
++	}
++
++	while (1) {
++		int i, timeout = 500, nb_fd;
++		struct epoll_event ev[3];
++		memset(ev, 0, sizeof(ev));
++
++		/*
++		 * Set random timeout and when we do timeout, use that to send message
++		 * to Alice.
++		 */
++		timeout = (rand() % (timeout_max - 1));
++
++		ret = epoll_wait(epfd, ev, sizeof(ev), timeout);
++		if (ret < 0) {
++			perror("epoll_wait Bob");
++			goto end;
++		}
++		nb_fd = ret;
++
++		/* No event thus timeout, send message to Alice. */
++		if (nb_fd == 0) {
++			(void) send_otr_msg(sock_to_alice, alice_name, bob_name, &oinfo,
++					NULL);
++			continue;
++		}
++
++		for (i = 0; i < nb_fd; i++) {
++			int fd;
++			uint32_t event;
++
++			fd = ev[i].data.fd;
++			event = ev[i].events;
++
++			if (fd == quit_pipe[0]) {
++				/* Time to leave. */
++				goto end;
++			} else if (fd == bob_sock) {
++				if (event & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
++					goto end;
++				} else if (event & (EPOLLIN | EPOLLHUP)) {
++					socklen_t len;
++					struct sockaddr_un sun;
++
++					/* Connection from Alice, accept it so we can handle it. */
++					sock_from_alice = accept(fd, (struct sockaddr *) &sun,
++							&len);
++					ret = add_sock_to_pollset(epfd, sock_from_alice,
++							EPOLLIN | EPOLLERR | EPOLLHUP);
++					if (ret < 0) {
++						goto end;
++					}
++				}
++				continue;
++			} else if (fd == sock_from_alice) {
++				if (event & (EPOLLERR | EPOLLHUP)) {
++					goto end;
++				} else if (event & EPOLLIN) {
++					(void) recv_otr_msg(sock_from_alice, bob_name,
++							alice_name, &oinfo);
++				}
++				continue;
++			} else {
++				goto end;
++			}
++		}
++	}
++
++end:
++	if (sock_from_alice) {
++		(void) close(sock_from_alice);
++	}
++	(void) close(sock_to_alice);
++sock_error:
++	(void) close(epfd);
++error:
++	(void) close(bob_sock);
++	return NULL;
++}
++
++static void run(void)
++{
++	int ret;
++	void *status;
++	pthread_t alice_th, bob_th;
++
++	/* Init quit pipe. */
++	ret = pipe(quit_pipe);
++	if (ret < 0) {
++		perror("pipe quit pipe");
++		goto end;
++	}
++
++	ret = pthread_create(&alice_th, NULL, alice_thread, NULL);
++	if (ret) {
++		fail("pthread_create sender thread failed (errno: %d)", errno);
++		goto end;
++	}
++
++	ret = pthread_create(&bob_th, NULL, bob_thread, NULL);
++	if (ret) {
++		fail("pthread_create receiver thread failed (errno: %d)", errno);
++		goto exit_receiver;
++	}
++
++	(void) pthread_join(bob_th, &status);
++
++exit_receiver:
++	(void) pthread_join(alice_th, &status);
++end:
++	/* Get rid of the quit pipe. */
++	close(quit_pipe[0]);
++	close(quit_pipe[1]);
++	return;
++}
++
++/*
++ * Load OTR instag using the given opt argument.
++ */
++static void load_instag(void)
++{
++	int ret;
++	gcry_error_t err;
++
++	ret = access(opt_instag_path, R_OK);
++	if (ret < 0) {
++		fail("Instag file %s is not readable", opt_instag_path);
++		return;
++	}
++
++	err = otrl_instag_read(user_state, opt_instag_path);
++	OK(err == GPG_ERR_NO_ERROR, "Loading instag from given file");
++}
++
++/*
++ * Load private key file using the given opt argument.
++ */
++static void load_key(void)
++{
++	int ret;
++	gcry_error_t err;
++
++	ret = access(opt_key_path, R_OK);
++	if (ret < 0) {
++		fail("Key file %s is not readable", opt_key_path);
++		return;
++	}
++
++	err = otrl_privkey_read(user_state, opt_key_path);
++	OK(err == GPG_ERR_NO_ERROR, "Loading key from given file");
++}
++
++/*
++ * Load private key fingerprint file using the given opt argument.
++ */
++static void load_key_fp(void)
++{
++	int ret;
++	gcry_error_t err;
++
++	ret = access(opt_key_fp_path, R_OK);
++	if (ret < 0) {
++		fail("Key fingerprints file %s is not readable", opt_key_fp_path);
++		return;
++	}
++
++	err = otrl_privkey_read_fingerprints(user_state, opt_key_fp_path, NULL,
++			NULL);
++	OK(err == GPG_ERR_NO_ERROR, "Loading key fingerprints from given file");
++}
++
++static int create_unix_socket(const char *pathname,
++		struct sockaddr_un *sun)
++{
++	int sock, ret;
++
++	/* Create both Unix socket. */
++	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
++		ret = -errno;
++		perror("Unix socket");
++		goto error;
++	}
++
++	memset(sun, 0, sizeof(struct sockaddr_un));
++	sun->sun_family = AF_UNIX;
++	strncpy(sun->sun_path, pathname, sizeof(sun->sun_path));
++	sun->sun_path[sizeof(sun->sun_path) - 1] = '\0';
++
++	ret = bind(sock, (struct sockaddr *) sun, sizeof(struct sockaddr_un));
++	if (ret < 0) {
++		perror("bind unix sock");
++		goto error;
++	}
++
++	ret = listen(sock, 10);
++	if (ret < 0) {
++		perror("listen unix sock");
++		goto error;
++	}
++
++	return sock;
++error:
++	return ret;
++}
++
++/*
++ * Bootstrap client by initializing the OTR library and creating an OTR user
++ * state.
++ *
++ * Return 0 on success else a negative value on error.
++ */
++static int init_client(void)
++{
++	int ret;
++
++	/* Init libgcrypt threading system. */
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++
++	/* Init OTR library. */
++	OTRL_INIT;
++	OK(1, "OTR library initialization done.");
++
++	user_state = otrl_userstate_create();
++	OK(user_state, "OTR userstate creation done.");
++	if (!user_state) {
++		fail("Out of memory on userstate create");
++		ret = -ENOMEM;
++		goto error;
++	}
++
++	/* Seed the prng. */
++	srand(time(NULL));
++
++	/* Cleanup Unix socket file before creating them. */
++	unlink(unix_sock_alice_path);
++	unlink(unix_sock_bob_path);
++
++	alice_sock = create_unix_socket(unix_sock_alice_path, &alice_sun);
++	bob_sock = create_unix_socket(unix_sock_bob_path, &bob_sun);
++	if (alice_sock < 0 || bob_sock < 0) {
++		ret = -EINVAL;
++		goto error;
++	}
++
++	if (opt_fragment) {
++		fragPolicy = OTRL_FRAGMENT_SEND_ALL;
++	}
++
++	return 0;
++
++error:
++	return ret;
++}
++
++static void sighandler(int sig)
++{
++	switch (sig) {
++	case SIGPIPE:
++	case SIGINT:
++	case SIGTERM:
++		cleanup();
++		break;
++	default:
++		break;
++	}
++}
++
++/*
++ * main entry point.
++ */
++int main(int argc, char **argv)
++{
++	int ret, opt;
++	struct sigaction sa;
++	sigset_t sigset;
++
++	plan_no_plan();
++
++	if ((ret = sigemptyset(&sigset)) < 0) {
++		perror("sigemptyset");
++		goto error;
++	}
++
++	sa.sa_handler = sighandler;
++	sa.sa_mask = sigset;
++	sa.sa_flags = 0;
++
++	if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
++		perror("sigaction");
++		goto error;
++	}
++	if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
++		perror("sigaction");
++		goto error;
++	}
++	if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
++		perror("sigaction");
++		goto error;
++	}
++
++	while ((opt = getopt_long(argc, argv, "+i:k:f:t:m:daF", long_opts, NULL)) != -1) {
++		switch (opt) {
++		case 'i':
++			opt_instag_path = strdup(optarg);
++			break;
++		case 'k':
++			opt_key_path = strdup(optarg);
++			break;
++		case 'f':
++			opt_key_fp_path = strdup(optarg);
++			break;
++		case 't':
++			timeout_max = atoi(optarg);
++			break;
++		case 'm':
++			opt_max_num_msg = atoi(optarg);
++			break;
++		case 'd':
++			opt_disconnect = 1;
++			break;
++		case 'a':
++			opt_auth = 1;
++			break;
++		case 'F':
++			opt_fragment = 1;
++			break;
++		default:
++			goto error;
++		}
++	}
++
++	if (!opt_key_path) {
++		fail("No key file, failing");
++		goto error;
++	}
++
++	/* Running OTR tests. */
++	ret = init_client();
++	if (ret < 0) {
++		goto error;
++	}
++
++	if (opt_instag_path) {
++		load_instag();
++	}
++	if (opt_key_fp_path) {
++		load_key_fp();
++	}
++	load_key();
++
++	run();
++
++	return exit_status();
++
++error:
++	return -1;
++}
+diff --git a/tests/regression/client/otr.key b/tests/regression/client/otr.key
+new file mode 100644
+index 0000000..ee8767d
+--- /dev/null
++++ b/tests/regression/client/otr.key
+@@ -0,0 +1,41 @@
++(privkeys
++ (account
++(name alice)
++(protocol otr-test)
++(private-key
++ (dsa
++  (p #00E4240AE9740D5FB1DF076A3270143BBD5B66DEB9BFD601CF3C3DC3E8D76BF1EA0D1A66E209516600E915B79552887EE9810D613C63EA6D2B6E69321C3C81F71F533F02430D20AF65C05C15BA46EF10C78EFF3BE687C33A4F6EA90877AB30E6423070AAFD3F22B5939D0DC8FBE5145A68F38EBA98ADCA7E06EFBC5E345E9AEDEF#)
++  (q "\x00�ջ�*��i#�b�U~�{U��q")
++  (g #00D3A15721AEF3A49DF26E875EC8C5FF4096B0B1717AF89485A015245176FD4AE3065D9F7B2D185B1E02CEAFB53E6984B1D341E62EBB4A5C189EB40959CFED0C48DAE73F3391C5E1482372E9DE539CD6911C54583DC0A3179547A38E19549F81A6DBFA8036C471C2A358D4B3AB86C7424556DFD61C35CC1EC08304B0102A0EEE08#)
++  (y #6E3996E07B6CB54DC443BD83033293956E5B7CCC511D19DCAC8735496B061D6EB6DF3D5540548D3C97201393E669EF9066BCA6A72E3AC68710188BEDF06FDF22548D8709BD4E9E1AD02DB0E193399BEB39DE5218D70C999D9856D3205DB79BA8DFC188726E646A1BE1722843F5E56A51C499C5BE5F63FACE7802ECD565E99F39#)
++  (x #2C5887BA7EC5F426B6BE4438E2FAE4589DBF2CB6#)
++  )
++ )
++ )
++ (account
++(name bob)
++(protocol otr-test)
++(private-key
++ (dsa
++  (p #00BD114F05B275A8A94954047983C5CD96ED95C782D2ED65A18E78C98E8EAFBAF58BBD046BE9895AD55FD0FF95907E7EBD6ACA2688D24779BDE9F0AAB13924CE65F597F9C9B9953DDBACF51DA7113FBAB9BE1DF6C6EA836DEB48983CCDCFC4125B5013D0CE52F890D0C391A035D30BCD5169A3451FD7023685274576DCB5F8FA47#)
++  (q #00D1DA3915346A704EB2D2F2A48CD48F3DCC4CF25D#)
++  (g #501BCFB989AD2C346BBD7782CA0230551F976B1A07EE3AEE27E4B63B7B00B1ACA712AD85784986411278163156D4DBA9DF75C8560F9C2E02C02AEC830EC403A56B6F64432869D6CA9314A648076511343507629BF4FC96F8FDBB9797258DDF11F437B1450BA23F1AA7E885EC6A33D37B7D7EC384A004420DB238E140B94AAAFE#)
++  (y #7C9CB7732164787DD1931BB58257665EB60D6AA72B8D64D634530A61BE93D5AF01427962646542F18401B73032B12B9CBCAE8E3CF080DAD55C6612A97D6D8776CF2CBDD3AAC75D302B60E6956E5B3C60B39E171A2D5F150A924C6E22981EFDF052D5C6507B2DEC15E96CB6CAF7B260D5386BBDD7D7F69B4BF14451D64D847AEB#)
++  (x #00AB1E941176D94505911118AC799A504ADCCE88F8#)
++  )
++ )
++ )
++ (account
++(name otrtest3)
++(protocol otr-test)
++(private-key
++ (dsa
++  (p #00BB4C57669E50E4C35F8E4CA84855CF2C83EE75C4F44B4BB4A7E88590D394D7A738E82EE97892E5051CE45E200741E18D423137AA8E6679B1CFAB4FF11D45D8C9CBDE388D30FC800B4879713E3C57BA48A92FE135BB9AF265F770B706FB9A04802244D12CBFFD97ACE5C73FCE88C2B716B4B22B994CD6429A7E16D9B6D1874137#)
++  (q #00C40DA63B679A80FC31BF49A68503BB39754D0A45#)
++  (g #6C0A48BEA859587D6677306D1777A2A0635470F149A86EB64EA62EAAA4C21ECE4375ACD016B776E3AD3411C18BB3FF37F963FCEBB8820FF8838AFA6FCD1B39558DAB78450AE2ED9457DEDBDCE13DF5A6B20A738D2973D375D360C044AF7F0204CCC372098F0B6460963274B1EA0B5FEC93571A15F5C03DCDF54EE83BB198F363#)
++  (y #00AB2C8A82F020DB99EF5B7A8330EC43E0D5EBD623FEB67D1B046D88FACA01D8E31E4D7865DC62D4DA58CF8BC7FF4B57C203A9F7F5C85DAB1B63D63299EF13AD89AAA7E6638C9DBC42D096408936C9F0382224CFB5C1528DCC8C7F2554CB4CA2FF3C3239BC921F1C690295DD9AE69C8EF5BBD8E58A8FAA8BB9D5F88463CAECEE7B#)
++  (x #7824B713A4E5FA6D6C69172196648CD4657A1ED1#)
++  )
++ )
++ )
++)
+diff --git a/tests/regression/random-msg-auth.sh b/tests/regression/random-msg-auth.sh
+new file mode 100755
+index 0000000..bb9938f
+--- /dev/null
++++ b/tests/regression/random-msg-auth.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=50
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL and authentication"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG --auth
+diff --git a/tests/regression/random-msg-disconnect-auth.sh b/tests/regression/random-msg-disconnect-auth.sh
+new file mode 100755
+index 0000000..875c49f
+--- /dev/null
++++ b/tests/regression/random-msg-disconnect-auth.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=50
++MAX_INTERVAL=100 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL with disconnect and authentication"
++$CLIENT --disconnect --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG --auth
+diff --git a/tests/regression/random-msg-disconnect-frag-auth.sh b/tests/regression/random-msg-disconnect-frag-auth.sh
+new file mode 100755
+index 0000000..f9c1b9b
+--- /dev/null
++++ b/tests/regression/random-msg-disconnect-frag-auth.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=20
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL with disconnect, framgents and authentication"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG --fragment --disconnect --auth
+diff --git a/tests/regression/random-msg-disconnect-frag.sh b/tests/regression/random-msg-disconnect-frag.sh
+new file mode 100755
+index 0000000..f58c315
+--- /dev/null
++++ b/tests/regression/random-msg-disconnect-frag.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=20
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL, disconnect and fragmentation"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG --fragment --disconnect
+diff --git a/tests/regression/random-msg-disconnect.sh b/tests/regression/random-msg-disconnect.sh
+new file mode 100755
+index 0000000..bae0703
+--- /dev/null
++++ b/tests/regression/random-msg-disconnect.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=50
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL with disconnect"
++$CLIENT --disconnect --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG
+diff --git a/tests/regression/random-msg-fast.sh b/tests/regression/random-msg-fast.sh
+new file mode 100755
+index 0000000..dc400fe
+--- /dev/null
++++ b/tests/regression/random-msg-fast.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=250
++MAX_INTERVAL=10 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL and number of message to $MAX_MSG"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG
+diff --git a/tests/regression/random-msg-frag.sh b/tests/regression/random-msg-frag.sh
+new file mode 100755
+index 0000000..0a4c6b0
+--- /dev/null
++++ b/tests/regression/random-msg-frag.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=20
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL and fragmentation"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG --fragment
+diff --git a/tests/regression/random-msg.sh b/tests/regression/random-msg.sh
+new file mode 100755
+index 0000000..d7679b2
+--- /dev/null
++++ b/tests/regression/random-msg.sh
+@@ -0,0 +1,14 @@
++#!/bin/bash
++
++CURDIR=$(dirname $0)/
++TESTDIR=$CURDIR/..
++CLIENT=$CURDIR/client/client
++KEYFILE=$CURDIR/client/otr.key
++
++MAX_MSG=50
++MAX_INTERVAL=500 # msec
++
++source $TESTDIR/utils/tap/tap.sh
++
++diag "Messaging with random interval of max $MAX_INTERVAL"
++$CLIENT --load-key $KEYFILE --timeout $MAX_INTERVAL --max-msg $MAX_MSG
+diff --git a/tests/run.sh b/tests/run.sh
+new file mode 100755
+index 0000000..33d850e
+--- /dev/null
++++ b/tests/run.sh
+@@ -0,0 +1,26 @@
++#!/bin/bash
++#
++# Copyright (C) 2013 - Christian Babeux <christian.babeux at efficios.com>
++#
++# Permission is hereby granted, free of charge, to any person obtaining a copy
++# of this software and associated documentation files (the "Software"), to deal
++# in the Software without restriction, including without limitation the rights
++# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++# copies of the Software, and to permit persons to whom the Software is
++# furnished to do so, subject to the following conditions:
++#
++# The above copyright notice and this permission notice shall be included in
++# all copies or substantial portions of the Software.
++#
++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++# SOFTWARE.
++#
++
++[ -z "$1" ] && echo "Error: No testlist. Please specify a testlist to run." && exit 1
++
++prove $2 --merge --exec '' - < $1
+diff --git a/tests/test_list b/tests/test_list
+new file mode 100644
+index 0000000..aab15e1
+--- /dev/null
++++ b/tests/test_list
+@@ -0,0 +1,19 @@
++unit/test_auth
++unit/test_proto
++unit/test_dh
++unit/test_b64
++unit/test_context
++unit/test_userstate
++unit/test_tlv
++unit/test_mem
++unit/test_sm
++unit/test_instag
++unit/test_privkey
++regression/random-msg.sh
++regression/random-msg-auth.sh
++regression/random-msg-fast.sh
++regression/random-msg-frag.sh
++regression/random-msg-disconnect.sh
++regression/random-msg-disconnect-frag.sh
++regression/random-msg-disconnect-auth.sh
++regression/random-msg-disconnect-frag-auth.sh
+diff --git a/tests/unit/Makefile.am b/tests/unit/Makefile.am
+new file mode 100644
+index 0000000..239859d
+--- /dev/null
++++ b/tests/unit/Makefile.am
+@@ -0,0 +1,49 @@
++AM_CFLAGS = -I$(top_srcdir)/include \
++			-I$(top_srcdir)/src \
++			-I$(top_srcdir)/tests/utils/ \
++			-I$(srcdir)
++
++LIBTAP=$(top_builddir)/tests/utils/tap/libtap.la
++
++LIBOTR=$(top_builddir)/src/libotr.la
++
++noinst_PROGRAMS = test_auth test_proto test_dh \
++				  test_b64 test_context \
++				  test_userstate test_tlv \
++				  test_mem test_sm test_instag \
++				  test_privkey
++
++test_auth_SOURCES = test_auth.c
++test_auth_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_proto_SOURCES = test_proto.c
++test_proto_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_dh_SOURCES = test_dh.c
++test_dh_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_b64_SOURCES = test_b64.c
++test_b64_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_context_SOURCES = test_context.c
++test_context_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_userstate_SOURCES = test_userstate.c
++test_userstate_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_tlv_SOURCES = test_tlv.c
++test_tlv_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_mem_SOURCES = test_mem.c
++test_mem_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_sm_SOURCES = test_sm.c
++test_sm_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_instag_SOURCES = test_instag.c
++test_instag_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++test_privkey_SOURCES = test_privkey.c
++test_privkey_LDADD = $(LIBTAP) $(LIBOTR) @LIBGCRYPT_LIBS@
++
++EXTRA_DIST = instag.txt
+diff --git a/tests/unit/instag.txt b/tests/unit/instag.txt
+new file mode 100644
+index 0000000..3cf4c31
+--- /dev/null
++++ b/tests/unit/instag.txt
+@@ -0,0 +1,4 @@
++alice_xmpp	XMPP	01234567
++alice_irc	IRC	9abcdef0
++alice_inv	IRC WRONG
++alice_icq	ICQ	98765432
+diff --git a/tests/unit/test_auth.c b/tests/unit/test_auth.c
+new file mode 100644
+index 0000000..06b5908
+--- /dev/null
++++ b/tests/unit/test_auth.c
+@@ -0,0 +1,181 @@
++/*
++ * Copyright (C) 2014 - David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <auth.h>
++#include <context.h>
++#include <gcrypt.h>
++#include <pthread.h>
++
++#include <tap/tap.h>
++#include <utils.h>
++#include <proto.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 5
++
++static void test_auth_new(void)
++{
++	struct context ctx;
++	OtrlAuthInfo *auth = &ctx.auth;
++
++	/* API call. */
++	otrl_auth_new(&ctx);
++
++	ok(auth->authstate == OTRL_AUTHSTATE_NONE &&
++		auth->our_keyid == 0 &&
++		auth->encgx == NULL &&
++		auth->encgx_len == 0 &&
++		utils_is_zeroed(auth->r, 16) &&
++		utils_is_zeroed(auth->hashgx, 32) &&
++		auth->their_pub == NULL &&
++		auth->their_keyid == 0 &&
++		auth->enc_c == NULL &&
++		auth->enc_cp == NULL &&
++		auth->mac_m1 == NULL &&
++		auth->mac_m1p == NULL &&
++		auth->mac_m2 == NULL &&
++		auth->mac_m2p == NULL &&
++		utils_is_zeroed(auth->their_fingerprint, 20) &&
++		auth->initiated == 0 &&
++		auth->protocol_version == 0 &&
++		utils_is_zeroed(auth->secure_session_id, 20) &&
++		auth->secure_session_id_len == 0 &&
++		auth->lastauthmsg == NULL &&
++		auth->commit_sent_time == 0 &&
++		auth->context == &ctx,
++		"OTR auth info init is valid");
++}
++
++static void test_auth_clear(void)
++{
++	struct context ctx;
++	OtrlAuthInfo *auth = &ctx.auth;
++
++	/* API call. */
++	otrl_auth_clear(auth);
++
++	ok(auth->authstate == OTRL_AUTHSTATE_NONE &&
++		auth->our_keyid == 0 &&
++		auth->encgx == NULL &&
++		auth->encgx_len == 0 &&
++		utils_is_zeroed(auth->r, 16) &&
++		utils_is_zeroed(auth->hashgx, 32) &&
++		auth->their_pub == NULL &&
++		auth->their_keyid == 0 &&
++		auth->enc_c == NULL &&
++		auth->enc_cp == NULL &&
++		auth->mac_m1 == NULL &&
++		auth->mac_m1p == NULL &&
++		auth->mac_m2 == NULL &&
++		auth->mac_m2p == NULL &&
++		utils_is_zeroed(auth->their_fingerprint, 20) &&
++		auth->initiated == 0 &&
++		auth->protocol_version == 0 &&
++		utils_is_zeroed(auth->secure_session_id, 20) &&
++		auth->secure_session_id_len == 0 &&
++		auth->lastauthmsg == NULL &&
++		auth->commit_sent_time == 0 &&
++		auth->context == &ctx,
++		"OTR auth info clear is valid");
++}
++
++static void test_auth_start_v23(void)
++{
++	unsigned int version = 3;
++	gcry_error_t err;
++	struct context ctx;
++	OtrlAuthInfo *auth = &ctx.auth;
++
++	/* API call. */
++	otrl_auth_new(&ctx);
++	err = otrl_auth_start_v23(auth, version);
++
++	ok(err == gcry_error(GPG_ERR_NO_ERROR) &&
++		auth->initiated == 1 &&
++		auth->protocol_version == version &&
++		auth->context->protocol_version == version &&
++		auth->our_keyid == 1 &&
++		!utils_is_zeroed(auth->r, sizeof(auth->r)) &&
++		auth->encgx != NULL &&
++		auth->encgx_len > 0 &&
++		!utils_is_zeroed(auth->hashgx, sizeof(auth->hashgx)) &&
++		auth->lastauthmsg != NULL &&
++		auth->authstate == OTRL_AUTHSTATE_AWAITING_DHKEY,
++		"OTR auth start v23 is valid");
++}
++
++static void test_otrl_auth_copy_on_key()
++{
++	struct context m_ctx, ctx;
++	OtrlAuthInfo *auth = &ctx.auth;
++	OtrlAuthInfo *m_auth = &m_ctx.auth;
++
++	otrl_auth_new(&ctx);
++	otrl_auth_new(&m_ctx);
++
++	otrl_auth_start_v23(auth, 3);
++	otrl_auth_start_v23(m_auth, 3);
++
++	m_auth->authstate = OTRL_AUTHSTATE_NONE;
++	auth->authstate = OTRL_AUTHSTATE_AWAITING_REVEALSIG,
++	otrl_auth_copy_on_key(m_auth, auth);
++
++	ok(gcry_mpi_cmp((m_auth->our_dh.priv), (auth->our_dh.priv)) != 0 &&
++		gcry_mpi_cmp((m_auth->our_dh.pub), (auth->our_dh.pub)) != 0 &&
++		m_auth->our_keyid == auth->our_keyid &&
++		memcmp(m_auth->r, auth->r, 16) != 0 &&
++		memcmp(m_auth->encgx, auth->encgx, 16) != 0 &&
++		memcmp(m_auth->hashgx, auth->hashgx, 16) != 0 &&
++		auth->authstate == OTRL_AUTHSTATE_AWAITING_REVEALSIG,
++		"Copy not done");
++
++	auth->authstate = OTRL_AUTHSTATE_AWAITING_DHKEY;
++	m_auth->authstate = OTRL_AUTHSTATE_AWAITING_DHKEY;
++	otrl_auth_copy_on_key(m_auth, auth);
++
++	ok(m_auth->initiated == auth->initiated &&
++		m_auth->our_keyid == auth->our_keyid &&
++		m_auth->our_dh.groupid == auth->our_dh.groupid &&
++		gcry_mpi_cmp((m_auth->our_dh.priv), (auth->our_dh.priv)) == 0 &&
++		gcry_mpi_cmp((m_auth->our_dh.pub), (auth->our_dh.pub)) == 0 &&
++		m_auth->our_keyid == auth->our_keyid &&
++		memcmp(m_auth->r, auth->r, 16) == 0 &&
++		memcmp(m_auth->encgx, auth->encgx, 16) == 0 &&
++		memcmp(m_auth->hashgx, auth->hashgx, 16) == 0 &&
++		auth->authstate == OTRL_AUTHSTATE_AWAITING_DHKEY,
++		"Copy OK");
++}
++
++int main(int argc, char **argv)
++{
++	/* Libtap call for the number of tests planned. */
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	/* Initialize libotr. */
++	otrl_dh_init();
++
++	test_auth_new();
++	test_auth_clear();
++	test_auth_start_v23();
++	test_otrl_auth_copy_on_key();
++
++	return 0;
++}
+diff --git a/tests/unit/test_b64.c b/tests/unit/test_b64.c
+new file mode 100644
+index 0000000..6d55992
+--- /dev/null
++++ b/tests/unit/test_b64.c
+@@ -0,0 +1,114 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *                      David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <stdlib.h>
++#include <string.h>
++#include <pthread.h>
++
++#include <b64.h>
++#include <tap/tap.h>
++#include <proto.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 10
++
++const char *alphanum_encoded =
++	"?OTR:" "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY3ODkwCg==" ".";
++const char *alphanum_decoded =
++	"abcdefghijklmnopqrstuvwxyz1234567890\n";
++
++static void test_otrl_base64_otr_decode(void)
++{
++	int ret;
++	unsigned char *bufp = NULL;
++	size_t len = 0;
++
++	/*
++	 * Invalid decoding.
++	 */
++
++	ok(otrl_base64_otr_decode("hello", NULL, NULL) == -2,
++			"Call with no prefix returned an error");
++	ok(otrl_base64_otr_decode("?OTR:" "MTIzNAo=", NULL, NULL) == -2,
++			"Call with no suffix returned an error");
++	/* Message of size 0. */
++	ret = otrl_base64_otr_decode("", &bufp, &len);
++	ok(ret == -2 && bufp == NULL && len == 0,
++			"Decode b64 with message of len 0");
++	/*
++	 * Valid decoding.
++	 */
++
++	/* Invalid chars are ignored */
++	ok(otrl_base64_otr_decode("?OTR:invalid_base64_thing.", &bufp, &len) == 0
++			&& len == 12, "Invalid b64 data");
++	free(bufp);
++	bufp = NULL;
++	len = 0;
++
++	ok(otrl_base64_otr_decode(alphanum_encoded, &bufp, &len) == 0,
++			"Call with valid data successfull");
++	ok(strcmp((const char*)bufp, alphanum_decoded) == 0
++			&& len == 37, "Decoded valid b64 test vector with success");
++	free(bufp);
++	bufp = NULL;
++	len = 0;
++
++	/* Invalid base64 char. */
++	ret = otrl_base64_otr_decode("?OTR:_*&?!!*\"().", &bufp, &len);
++	ok(ret == 0 && bufp != NULL && len == 0,
++			"Decode b64 with invalid b64 characters");
++	free(bufp);
++	bufp = NULL;
++	len = 0;
++
++}
++
++static void test_otrl_base64_otr_encode(void)
++{
++	unsigned char *bufp = NULL;
++	size_t len = 0;
++	char *encoded;
++
++	encoded = otrl_base64_otr_encode((const unsigned char *) alphanum_decoded,
++			strlen(alphanum_decoded));
++
++	ok(strcmp(encoded, alphanum_encoded) == 0,
++			"Encoded b64 test vector with success");
++	ok(otrl_base64_otr_decode(encoded, &bufp, &len) == 0,
++			"Decoded previously encoded test vector");
++	ok(memcmp(bufp, alphanum_decoded, len) == 0
++		&& len == strlen(alphanum_decoded),
++		"Decoded value is exact");
++	free(bufp);
++	free(encoded);
++}
++
++int main(int argc, char** argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	test_otrl_base64_otr_decode();
++	test_otrl_base64_otr_encode();
++
++	return 0;
++}
+diff --git a/tests/unit/test_context.c b/tests/unit/test_context.c
+new file mode 100644
+index 0000000..6e173cd
+--- /dev/null
++++ b/tests/unit/test_context.c
+@@ -0,0 +1,214 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <limits.h>
++#include <pthread.h>
++
++#include <context.h>
++
++#include <tap/tap.h>
++
++#define NUM_TESTS 22
++
++static void test_otrl_context_find_fingerprint(void)
++{
++	unsigned char fingerprint[20] = {0};
++	int add_if_missing = 0, addedp = 0;
++
++	ok(otrl_context_find_fingerprint(NULL, fingerprint,
++			add_if_missing, &addedp) == NULL, "NULL context detected");
++}
++
++static ConnContext *new_context(const char *user, const char *account,
++		const char *protocol)
++{
++	ConnContext *context;
++	context = calloc(1, sizeof(ConnContext));
++	context->username = strdup(user);
++	context->accountname = strdup(account);
++	context->protocol = strdup(protocol);
++	context->m_context = context;
++	context->active_fingerprint = calloc(1, sizeof(Fingerprint));
++	context->context_priv = calloc(1, sizeof(ConnContextPriv));
++
++	return context;
++}
++
++static void free_context(ConnContext *context)
++{
++	free(context->username);
++	free(context->accountname);
++	free(context->protocol);
++	free(context);
++}
++
++static void test_otrl_context_find_recent_instance()
++{
++	ConnContext *context = new_context("main", "main", "main");
++	ConnContext *context_child = new_context("child", "child", "child");
++	ConnContext *context_rcvd = new_context("rcvd", "rcvd", "rcvd");
++	ConnContext *context_sent = new_context("sent", "sent", "sent");
++	ConnContext *tmp;
++
++	context->recent_child = context_child;
++	context->recent_rcvd_child = context_rcvd;
++	context->recent_sent_child = context_sent;
++
++	ok(otrl_context_find_recent_instance(NULL, OTRL_INSTAG_RECENT) == NULL,
++			"NULL context detected");
++
++	tmp = otrl_context_find_recent_instance(context, OTRL_INSTAG_RECENT);
++	ok(strcmp(tmp->username, "child") == 0, "OTRL_INSTAG_RECENT ok");
++
++	tmp = otrl_context_find_recent_instance(context,
++			OTRL_INSTAG_RECENT_RECEIVED);
++	ok(strcmp(tmp->username, "rcvd") == 0, "OTRL_INSTAG_RECENT_RECEIVED ok");
++
++	tmp = otrl_context_find_recent_instance(context, OTRL_INSTAG_RECENT_SENT);
++	ok(strcmp(tmp->username, "sent") == 0, "OTRL_INSTAG_RECENT_SENT ok");
++
++	tmp = otrl_context_find_recent_instance(context, INT_MAX);
++	ok(!tmp, "Invalid instag detected");
++
++	free_context(context);
++	free_context(context_child);
++	free_context(context_rcvd);
++	free_context(context_sent);
++}
++
++static void test_otrl_context_find_recent_secure_instance(void)
++{
++	ConnContext *context1 = new_context("1", "1", "1");
++	ConnContext *context2 = new_context("2", "2", "2");
++	ConnContext *tmp;
++
++	ok(otrl_context_find_recent_secure_instance(NULL) == NULL,
++			"NULL detected");
++
++	context1->next = context2;
++	context2->next = NULL;
++	context2->m_context = context1;
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "Same msgstate");
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->msgstate = OTRL_MSGSTATE_FINISHED;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "plaintext then finished");
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->msgstate = OTRL_MSGSTATE_ENCRYPTED;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "Most secure context found");
++
++	context1->msgstate = OTRL_MSGSTATE_ENCRYPTED;
++	context2->msgstate = OTRL_MSGSTATE_ENCRYPTED;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "Most secure context found");
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->active_fingerprint->trust = strdup("hello");
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "Most secure context found");
++	free(context2->active_fingerprint);
++	context2->active_fingerprint = NULL;
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context2->context_priv->lastrecv = 1;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context2, "Most secure context found");
++
++	context1->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	context1->context_priv->lastrecv = 2;
++	context2->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	tmp = otrl_context_find_recent_secure_instance(context1);
++	ok(tmp == context1, "Most secure context found");
++
++	free_context(context1);
++	free_context(context2);
++}
++
++static void test_otrl_context_is_fingerprint_trusted()
++{
++	Fingerprint fprint;
++	fprint.trust = NULL;
++
++	ok(otrl_context_is_fingerprint_trusted(NULL) == 0,
++			"NULL fingerprint detected");
++	ok(otrl_context_is_fingerprint_trusted(&fprint) == 0,
++			"NULL trust detected");
++	fprint.trust = "1234";
++	ok(otrl_context_is_fingerprint_trusted(&fprint) != 0,
++			"Trusted fingerprint detected");
++}
++
++static void test_otrl_context_update_recent_child()
++{
++	ConnContext context1, context2;
++	context1.m_context = &context1;
++	context2.m_context = &context1;
++
++	otrl_context_update_recent_child(&context1, 0);
++	ok(context1.recent_rcvd_child == &context1 &&
++			context1.recent_child == &context1,
++			"Recent self rcvd set");
++
++	otrl_context_update_recent_child(&context1, 1);
++	ok(context1.recent_sent_child == &context1 &&
++			context1.recent_child == &context1,
++			"Recent self sent set");
++
++	otrl_context_update_recent_child(&context2, 0);
++	ok(context1.recent_rcvd_child == &context2 &&
++			context1.recent_child == &context2,
++			"Recent rcvd set");
++
++	otrl_context_update_recent_child(&context2, 1);
++	ok(context1.recent_sent_child == &context2 &&
++			context1.recent_child == &context2,
++			"Recent sent set");
++}
++
++static void test_otrl_context_set_trust(void)
++{
++	Fingerprint fprint;
++	const char *trust = "I don't trust anyone.";
++
++	fprint.trust = NULL;
++
++	otrl_context_set_trust(&fprint, trust);
++	ok(strcmp(fprint.trust, trust) == 0, "Fingerprint set with success");
++}
++
++int main(int argc, char **argv)
++{
++	plan_tests(NUM_TESTS);
++
++	test_otrl_context_set_trust();
++	test_otrl_context_find_recent_instance();
++	test_otrl_context_find_fingerprint();
++	test_otrl_context_find_recent_secure_instance();
++	test_otrl_context_is_fingerprint_trusted();
++	test_otrl_context_update_recent_child();
++
++	return 0;
++}
+diff --git a/tests/unit/test_dh.c b/tests/unit/test_dh.c
+new file mode 100644
+index 0000000..c27c09b
+--- /dev/null
++++ b/tests/unit/test_dh.c
+@@ -0,0 +1,515 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++
++#include <dh.h>
++#include <proto.h>
++
++#include <tap/tap.h>
++#include <utils.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 38
++
++/*
++ * The re-implementation/inclusion of crypto stuff is necessary because libotr
++ * doesn't expose them.
++ */
++
++static const char* DH1536_MODULUS_S = "0x"
++	"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
++	"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
++	"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
++	"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
++	"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
++	"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
++	"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
++	"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF";
++static const char *DH1536_GENERATOR_S = "0x02";
++static const int DH1536_MOD_LEN_BITS = 1536;
++
++static gcry_mpi_t DH1536_MODULUS = NULL;
++static gcry_mpi_t DH1536_MODULUS_MINUS_2 = NULL;
++static gcry_mpi_t DH1536_GENERATOR = NULL;
++
++static void test_otrl_dh_keypair_init(void)
++{
++	DH_keypair kp;
++
++	otrl_dh_keypair_init(&kp);
++
++	ok(kp.groupid == 0 &&
++			kp.priv == NULL &&
++			kp.pub == NULL,
++			"Keypair initialized");
++}
++
++static void test_otrl_dh_keypair_copy(void)
++{
++	DH_keypair k1, k2;
++	unsigned char *buf;
++
++	k1.groupid = rand();
++
++	buf = gcry_random_bytes(32, GCRY_WEAK_RANDOM);
++	gcry_mpi_scan(&(k1.priv), GCRYMPI_FMT_USG, buf, 32, NULL);
++	gcry_free(buf);
++
++	buf = gcry_random_bytes(32, GCRY_WEAK_RANDOM);
++	gcry_mpi_scan(&(k1.pub), GCRYMPI_FMT_USG, buf, 32, NULL);
++	gcry_free(buf);
++
++	otrl_dh_keypair_copy(&k2, &k1);
++
++	ok(k1.groupid == k2.groupid &&
++			gcry_mpi_cmp(k1.priv, k2.priv) == 0 &&
++			gcry_mpi_cmp(k1.pub, k2.pub) == 0,
++			"Keypair copied");
++
++	gcry_mpi_release(k1.priv);
++	gcry_mpi_release(k1.pub);
++	gcry_mpi_release(k2.priv);
++	gcry_mpi_release(k2.pub);
++}
++
++static void test_otrl_dh_session_free()
++{
++	DH_sesskeys sess;
++	DH_keypair kp1, kp2;
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &(kp1));
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &(kp2));
++	otrl_dh_session(&sess, &kp1, kp2.pub);
++
++	otrl_dh_session_free(&sess);
++
++	ok(sess.sendenc == NULL &&
++		sess.sendmac == NULL &&
++		sess.rcvenc == NULL &&
++		sess.rcvmac == NULL &&
++		utils_is_zeroed(sess.sendctr, 16) &&
++		utils_is_zeroed(sess.rcvctr, 16) &&
++		utils_is_zeroed(sess.sendmackey, 16) &&
++		utils_is_zeroed(sess.rcvmackey, 16) &&
++		sess.sendmacused == 0 &&
++		sess.rcvmacused == 0 &&
++		utils_is_zeroed(sess.extrakey, OTRL_EXTRAKEY_BYTES),
++		"Session freed");
++}
++
++
++static void test_otrl_dh_session_blank()
++{
++	DH_sesskeys sess;
++	DH_keypair kp1, kp2;
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &(kp1));
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &(kp2));
++	otrl_dh_session(&sess, &kp1, kp2.pub);
++
++	otrl_dh_session_blank(&sess);
++
++	ok(sess.sendenc == NULL &&
++		sess.sendmac == NULL &&
++		sess.rcvenc == NULL &&
++		sess.rcvmac == NULL &&
++		utils_is_zeroed(sess.sendctr, 16) &&
++		utils_is_zeroed(sess.rcvctr, 16) &&
++		utils_is_zeroed(sess.sendmackey, 16) &&
++		utils_is_zeroed(sess.rcvmackey, 16) &&
++		sess.sendmacused == 0 &&
++		sess.rcvmacused == 0 &&
++		utils_is_zeroed(sess.extrakey, OTRL_EXTRAKEY_BYTES),
++		"Session blanked");
++}
++
++static void test_otrl_dh_gen_keypair(void)
++{
++	DH_keypair kp;
++	gcry_mpi_t pubkey = NULL;
++
++	otrl_dh_keypair_init(&kp);
++
++	ok(otrl_dh_gen_keypair(DH1536_GROUP_ID+1, &kp) ==
++			gcry_error(GPG_ERR_INV_VALUE),
++			"Invalid group detected");
++
++	ok(otrl_dh_gen_keypair(DH1536_GROUP_ID, &kp) ==
++			gcry_error(GPG_ERR_NO_ERROR),
++			"Valid group set");
++	ok(kp.groupid == DH1536_GROUP_ID, "Group set");
++
++	pubkey = gcry_mpi_new(DH1536_MOD_LEN_BITS);
++	gcry_mpi_powm(pubkey, DH1536_GENERATOR, kp.priv, DH1536_MODULUS);
++	ok(gcry_mpi_cmp(pubkey, kp.pub) == 0, "Matching pubkey");
++	otrl_dh_keypair_free(&kp);
++}
++
++static void test_otrl_dh_keypair_free(void)
++{
++	DH_keypair kp;
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &kp);
++	otrl_dh_keypair_free(&kp);
++	ok(kp.pub == NULL && kp.priv == NULL && kp.groupid == DH1536_GROUP_ID,
++			"DH_keypair free'd with success");
++
++}
++
++static void invert_DH_keypair(DH_keypair* kp1, DH_keypair* kp2)
++{
++	DH_keypair tmp;
++	otrl_dh_keypair_copy(&tmp, kp1);
++	otrl_dh_keypair_copy(kp1, kp2);
++	otrl_dh_keypair_copy(kp2, &tmp);
++	otrl_dh_keypair_free(&tmp);
++}
++
++/*
++ * This is an helper function. See the next one.
++ */
++static void _test_ortl_dh_session(const DH_keypair *kp, gcry_mpi_t y)
++{
++	unsigned char *gabdata;
++	unsigned char *hashdata;
++	unsigned char encrypt[32] = {0};
++	unsigned char expected_encrypt[32] = {0};
++	unsigned char sendbyte, rcvbyte;
++	const char test_vector[] = "This is a test vector";
++	DH_sesskeys sess;
++	DH_sesskeys sess_expected;
++	gcry_mpi_t gab;
++	size_t gablen;
++	otrl_dh_session_blank(&sess);
++	otrl_dh_session(&sess, kp, y);
++
++	gab = gcry_mpi_snew(DH1536_MOD_LEN_BITS);
++	gcry_mpi_powm(gab, y, kp->priv, DH1536_MODULUS);
++
++	gcry_mpi_print(GCRYMPI_FMT_USG, NULL, 0, &gablen, gab);
++	gabdata = gcry_malloc_secure(gablen + 5);
++	gabdata[1] = (gablen >> 24) & 0xff;
++	gabdata[2] = (gablen >> 16) & 0xff;
++	gabdata[3] = (gablen >> 8) & 0xff;
++	gabdata[4] = gablen & 0xff;
++	gcry_mpi_print(GCRYMPI_FMT_USG, gabdata + 5, gablen, NULL, gab);
++	gcry_mpi_release(gab);
++
++	hashdata = gcry_malloc_secure(20);
++
++	if (gcry_mpi_cmp(kp->pub, y) > 0 ) {
++		sendbyte = 0x01;
++		rcvbyte = 0x02;
++	} else {
++		sendbyte = 0x02;
++		rcvbyte = 0x01;
++	}
++
++	gabdata[0] = sendbyte;
++	gcry_md_hash_buffer(GCRY_MD_SHA1, hashdata, gabdata, gablen + 5);
++
++	gcry_cipher_open(&(sess_expected.sendenc), GCRY_CIPHER_AES,
++			GCRY_CIPHER_MODE_CTR, GCRY_CIPHER_SECURE);
++	gcry_cipher_setkey(sess_expected.sendenc, hashdata, 16);
++	gcry_cipher_encrypt(sess_expected.sendenc, expected_encrypt,
++			sizeof(expected_encrypt), test_vector, strlen(test_vector));
++	gcry_cipher_encrypt(sess.sendenc, encrypt, sizeof(encrypt), test_vector,
++			strlen(test_vector));
++	ok(memcmp(encrypt, expected_encrypt, sizeof(encrypt)) == 0, "sendenc ok");
++
++	gcry_md_hash_buffer(GCRY_MD_SHA1, sess_expected.sendmackey, hashdata, 16);
++	gcry_md_open(&(sess_expected.sendmac), GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(sess_expected.sendmac, sess_expected.sendmackey, 20);
++	gcry_md_write(sess_expected.sendmac, test_vector, sizeof(test_vector));
++	gcry_md_write(sess.sendmac, test_vector, sizeof(test_vector));
++
++	ok(memcmp(gcry_md_read(sess_expected.sendmac, 0),
++			gcry_md_read(sess.sendmac, 0), 32) == 0,
++			"Sendmac ok");
++
++	gabdata[0] = rcvbyte;
++	gcry_md_hash_buffer(GCRY_MD_SHA1, hashdata, gabdata, gablen + 5);
++	gcry_cipher_open(&(sess_expected.rcvenc), GCRY_CIPHER_AES,
++			GCRY_CIPHER_MODE_CTR, GCRY_CIPHER_SECURE);
++	gcry_cipher_setkey(sess_expected.rcvenc, hashdata, 16);
++	gcry_cipher_encrypt(sess_expected.rcvenc, expected_encrypt,
++			sizeof(expected_encrypt), test_vector, strlen(test_vector));
++	gcry_cipher_encrypt(sess.rcvenc, encrypt, sizeof(encrypt), test_vector,
++			strlen(test_vector));
++	ok(memcmp(encrypt, expected_encrypt, sizeof(encrypt)) == 0, "Sendenc ok");
++
++	gcry_md_hash_buffer(GCRY_MD_SHA1, sess_expected.rcvmackey, hashdata, 16);
++	gcry_md_open(&(sess_expected.rcvmac), GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(sess_expected.rcvmac, sess_expected.rcvmackey, 20);
++	gcry_md_write(sess_expected.rcvmac, test_vector, sizeof(test_vector));
++	gcry_md_write(sess.rcvmac, test_vector, sizeof(test_vector));
++	ok(memcmp(gcry_md_read(sess_expected.sendmac, 0),
++			gcry_md_read(sess.sendmac, 0), 32) == 0,
++			"rcvmac ok");
++
++	gabdata[0] = 0xff;
++
++	gcry_md_hash_buffer(GCRY_MD_SHA256, sess_expected.extrakey, gabdata,
++			gablen + 5);
++	ok(memcmp(sess_expected.extrakey, sess.extrakey, 32) == 0, "extrakey set");
++
++	gcry_free(gabdata);
++	gcry_free(hashdata);
++}
++
++/*
++ * This function is a little bit tricky, since it uses an array of 3
++ * DH_keypair. The first one has a smaller pubkey than the second, which has a
++ * smaller pubkey than the third one.
++ *
++ * The second key is used as "main" key. The two other ones are used to test
++ * the otrl_dh_session, with a biggest and a smallest key than the "main" one.
++ */
++static void test_otrl_dh_session(void)
++{
++	int i;
++	DH_keypair kp[3]; /* kp[0] < kp[1] < kp[2] */
++	DH_sesskeys sess;
++
++	for (i = 0; i < 3; i++) {
++		otrl_dh_gen_keypair(DH1536_GROUP_ID, &(kp[i]));
++	}
++
++	/* Sort the array. */
++	for (i = 0; i < 2; i++) {
++		if (gcry_mpi_cmp(kp[i].pub, kp[i + 1].pub) > 0) {
++			invert_DH_keypair(kp + i, kp + i + 1);
++		}
++	}
++
++	if (gcry_mpi_cmp(kp[0].pub, kp[1].pub) > 0) {
++		invert_DH_keypair(kp, kp + 1);
++	}
++
++	kp[1].groupid++;
++
++	ok(otrl_dh_session(&sess, &(kp[1]), kp[0].pub) ==
++			gcry_error(GPG_ERR_INV_VALUE),
++			"Invalid group detected");
++	kp[1].groupid--;
++
++	_test_ortl_dh_session(&(kp[1]), kp[0].pub);
++	_test_ortl_dh_session(&(kp[1]), kp[2].pub);
++}
++
++static void test_otrl_dh_compute_v2_auth_keys(void)
++{
++	const char test_vector[] = "This is a test vector";
++	size_t slen = 0;
++	size_t sessionidlenp = 0;
++	unsigned char *sdata = NULL;
++	unsigned char *hashdata = NULL;
++	gcry_mpi_t s = NULL;
++	unsigned char ctr[16] = {0};
++
++	DH_keypair our_dh, their_dh;
++	gcry_mpi_t public_key = NULL;
++
++	unsigned char sessionid[8];
++	gcry_md_hd_t mac_m1 = NULL, mac_m1p = NULL, mac_m2 = NULL, mac_m2p = NULL;
++	gcry_cipher_hd_t enc_c = NULL, enc_cp = NULL;
++	unsigned char encrypt[32] = {0};
++
++	unsigned char sessionid_expected[8];
++
++	gcry_md_hd_t mac_m1_expected = NULL, mac_m1p_expected = NULL;
++	gcry_md_hd_t mac_m2_expected = NULL, mac_m2p_expected = NULL;
++	gcry_cipher_hd_t enc_c_expected = NULL, enc_cp_expected = NULL;
++	unsigned char expected_encrypt[32] = {0};
++
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &our_dh);
++	otrl_dh_gen_keypair(DH1536_GROUP_ID, &their_dh);
++
++	our_dh.groupid++;
++	ok(otrl_dh_compute_v2_auth_keys(&our_dh, their_dh.pub,
++			sessionid, &sessionidlenp, &enc_c, &enc_cp,
++			&mac_m1, &mac_m1p, &mac_m2, &mac_m2p)
++			== gcry_error(GPG_ERR_INV_VALUE),
++			"Invalid group detected");
++	our_dh.groupid--;
++
++	gcry_mpi_scan(&public_key, GCRYMPI_FMT_USG, "1", 0, NULL);
++
++	ok(otrl_dh_compute_v2_auth_keys(&our_dh, public_key,
++			sessionid, &sessionidlenp, &enc_c, &enc_cp,
++			&mac_m1, &mac_m1p, &mac_m2, &mac_m2p)
++			== gcry_error(GPG_ERR_INV_VALUE),
++			"Public key too small");
++
++	gcry_mpi_scan(&public_key, GCRYMPI_FMT_HEX,
++			(const unsigned char *) DH1536_MODULUS_S, 0, NULL);
++	gcry_mpi_add_ui(public_key, DH1536_MODULUS, 1);
++
++	ok(otrl_dh_compute_v2_auth_keys(&our_dh, DH1536_MODULUS,
++			sessionid, &sessionidlenp, &enc_c, &enc_cp,
++			&mac_m1, &mac_m1p, &mac_m2, &mac_m2p)
++			== gcry_error(GPG_ERR_INV_VALUE),
++			"Public key too big");
++
++	ok(otrl_dh_compute_v2_auth_keys(&our_dh, their_dh.pub, sessionid,
++			&sessionidlenp, &enc_c, &enc_cp, &mac_m1, &mac_m1p, &mac_m2,
++			&mac_m2p) == gcry_error(GPG_ERR_NO_ERROR),
++			"Auth keys generated");
++
++	ok(sessionidlenp == 8, "Session id len p set to correct value");
++
++	s = gcry_mpi_snew(DH1536_MOD_LEN_BITS);
++	gcry_mpi_powm(s, their_dh.pub, our_dh.priv, DH1536_MODULUS);
++
++	gcry_mpi_print(GCRYMPI_FMT_USG, NULL, 0, &slen, s);
++	sdata = gcry_malloc_secure(slen + 5);
++	sdata[1] = (slen >> 24) & 0xff;
++	sdata[2] = (slen >> 16) & 0xff;
++	sdata[3] = (slen >> 8) & 0xff;
++	sdata[4] = slen & 0xff;
++	gcry_mpi_print(GCRYMPI_FMT_USG, sdata+5, slen, NULL, s);
++	gcry_mpi_release(s);
++
++	hashdata = gcry_malloc_secure(32);
++	sdata[0] = 0x00;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++	memmove(sessionid_expected, hashdata, 8);
++	ok(memcmp(sessionid_expected, sessionid, 8) == 0, "Session id is correct");
++
++	sdata[0] = 0x01;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++
++	gcry_cipher_open(&enc_c_expected, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR,
++			GCRY_CIPHER_SECURE);
++	gcry_cipher_setkey(enc_c_expected, hashdata, 16);
++	gcry_cipher_setctr(enc_c_expected, ctr, 16);
++
++	gcry_cipher_encrypt(enc_c_expected, expected_encrypt,
++			sizeof(expected_encrypt), test_vector, strlen(test_vector));
++	gcry_cipher_encrypt(enc_c, encrypt, sizeof(encrypt), test_vector,
++			strlen(test_vector));
++	ok(memcmp(encrypt, expected_encrypt, sizeof(encrypt)) == 0, "Enc ok");
++
++	gcry_cipher_open(&(enc_cp_expected), GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR,
++			GCRY_CIPHER_SECURE);
++	gcry_cipher_setkey(enc_cp_expected, hashdata+16, 16);
++	gcry_cipher_setctr(enc_cp_expected, ctr, 16);
++	gcry_cipher_encrypt(enc_cp_expected, expected_encrypt,
++			sizeof(expected_encrypt), test_vector, strlen(test_vector));
++	gcry_cipher_encrypt(enc_cp, encrypt, sizeof(encrypt), test_vector,
++			strlen(test_vector));
++	ok(memcmp(encrypt, expected_encrypt, sizeof(encrypt)) == 0, "Encp ok");
++
++	sdata[0] = 0x02;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++	gcry_md_open(&mac_m1_expected, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(mac_m1_expected, hashdata, 32);
++	gcry_md_write(mac_m1_expected, test_vector, sizeof(test_vector));
++	gcry_md_write(mac_m1, test_vector, sizeof(test_vector));
++	ok(memcmp(gcry_md_read(mac_m1_expected, 0),
++			gcry_md_read(mac_m1, 0), 32) == 0,
++			"mac_m1 set");
++
++	sdata[0] = 0x03;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++	gcry_md_open(&mac_m2_expected, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(mac_m2_expected, hashdata, 32);
++	gcry_md_write(mac_m2_expected, test_vector, sizeof(test_vector));
++	gcry_md_write(mac_m2, test_vector, sizeof(test_vector));
++	ok(memcmp(gcry_md_read(mac_m2_expected, 0),
++			gcry_md_read(mac_m2, 0), 32) == 0,
++			"mac_m2 set");
++
++	sdata[0] = 0x04;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++	gcry_md_open(&mac_m1p_expected, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(mac_m1p_expected, hashdata, 32);
++	gcry_md_write(mac_m1p_expected, test_vector, sizeof(test_vector));
++	gcry_md_write(mac_m1p, test_vector, sizeof(test_vector));
++
++	ok(memcmp(gcry_md_read(mac_m1p_expected, 0),
++			gcry_md_read(mac_m1p, 0), 32) == 0,
++			"mac_m1p set");
++
++	sdata[0] = 0x05;
++	gcry_md_hash_buffer(GCRY_MD_SHA256, hashdata, sdata, slen+5);
++	gcry_md_open(&mac_m2p_expected, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
++	gcry_md_setkey(mac_m2p_expected, hashdata, 32);
++	gcry_md_write(mac_m2p_expected, test_vector, sizeof(test_vector));
++	gcry_md_write(mac_m2p, test_vector, sizeof(test_vector));
++
++	ok(memcmp(gcry_md_read(mac_m2p_expected, 0),
++			gcry_md_read(mac_m2p, 0), 32) == 0,
++			"mac_m2p set");
++
++	gcry_free(sdata);
++	gcry_free(hashdata);
++}
++
++static void test_otrl_dh_incctr()
++{
++	unsigned char ctr[8] = {0};
++	otrl_dh_incctr(ctr);
++	ok(ctr[7] == 1 && utils_is_zeroed(ctr, 7), "Counter set");
++	ctr[7] = 255;
++	otrl_dh_incctr(ctr);
++	ok(ctr[7] == 0 && ctr[6] == 1 && utils_is_zeroed(ctr, 5),
++			"Counter set");
++	memset(ctr, 255, sizeof(ctr));
++	otrl_dh_incctr(ctr);
++	ok(utils_is_zeroed(ctr, sizeof(ctr)), "Counter set");
++}
++
++static void test_otrl_dh_cmpctr()
++{
++	unsigned char ctr1[8] = {0}, ctr2[8] = {0};
++	ok(otrl_dh_cmpctr(ctr1, ctr2) == 0, "Null counters are equals");
++	ctr1[1]++;
++	ok(otrl_dh_cmpctr(ctr1, ctr2) > 0, "Ctr1 is bigger than ctr2");
++	ctr2[0]++;
++	ok(otrl_dh_cmpctr(ctr1, ctr2) < 0, "Ctr2 is bigger than ctr1");
++}
++
++int main(int argc, char **argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	otrl_dh_init();
++
++	gcry_mpi_scan(&DH1536_MODULUS, GCRYMPI_FMT_HEX,
++	(const unsigned char *)DH1536_MODULUS_S, 0, NULL);
++	gcry_mpi_scan(&DH1536_GENERATOR, GCRYMPI_FMT_HEX,
++	(const unsigned char *)DH1536_GENERATOR_S, 0, NULL);
++	DH1536_MODULUS_MINUS_2 = gcry_mpi_new(DH1536_MOD_LEN_BITS);
++	gcry_mpi_sub_ui(DH1536_MODULUS_MINUS_2, DH1536_MODULUS, 2);
++
++	test_otrl_dh_gen_keypair();
++	test_otrl_dh_keypair_free();
++	test_otrl_dh_keypair_init();
++	test_otrl_dh_compute_v2_auth_keys();
++	test_otrl_dh_session();
++	test_otrl_dh_keypair_copy();
++	test_otrl_dh_session_blank();
++	test_otrl_dh_session_free();
++	test_otrl_dh_incctr();
++	test_otrl_dh_cmpctr();
++
++	return 0;
++}
+diff --git a/tests/unit/test_instag.c b/tests/unit/test_instag.c
+new file mode 100644
+index 0000000..3758ae2
+--- /dev/null
++++ b/tests/unit/test_instag.c
+@@ -0,0 +1,222 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <limits.h>
++#include <pthread.h>
++#include <unistd.h>
++
++#include <proto.h>
++#include <auth.h>
++#include <context.h>
++
++#include <tap/tap.h>
++#include <utils.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 13
++
++/* Current directory of this executable. */
++static char curdir[PATH_MAX];
++static char instag_filepath[PATH_MAX];
++
++static void test_otrl_instag_forget(void)
++{
++	OtrlInsTag *instag1 = calloc(1, sizeof(OtrlInsTag));
++	OtrlInsTag *instag2 = calloc(1, sizeof(OtrlInsTag));
++
++	instag1->tous = &instag1;
++	instag1->accountname = strdup("name one");
++	instag1->protocol = strdup("protocol one");
++	instag1->next = instag2;
++	instag1->next->tous = &(instag1->next);
++	instag2->accountname = strdup("name two");
++	instag2->protocol = strdup("protocol two");
++
++	otrl_instag_forget(NULL);
++	ok(1, "Forget on NULL didn't segfault");
++
++	otrl_instag_forget(instag2);
++	ok(instag1->next == NULL, "Instag forgotten without segfault");
++}
++
++static void test_otrl_instag_forget_all(void)
++{
++	OtrlUserState us = otrl_userstate_create();
++	OtrlInsTag *p = malloc(sizeof(OtrlInsTag));
++	p->accountname = strdup("account name");
++	p->protocol = strdup("protocol name");
++	p->instag = otrl_instag_get_new();
++
++	otrl_instag_forget_all(us);
++	ok(1, "Forget all on empty user state");
++
++	p->next = us->instag_root;
++	p->tous = &(us->instag_root);
++	us->instag_root = p;
++
++	otrl_instag_forget_all(us);
++	ok(1, "Forget all on a non-empty user state");
++}
++
++static void test_otrl_instag_find(void)
++{
++	OtrlUserState us = otrl_userstate_create();
++	OtrlInsTag *p1 = malloc(sizeof(OtrlInsTag));
++	OtrlInsTag *p2 = malloc(sizeof(OtrlInsTag));
++
++	p1->accountname = strdup("account one");
++	p1->protocol = strdup("protocol one");
++	p1->instag = otrl_instag_get_new();
++	p1->next = us->instag_root;
++	p1->tous = &(us->instag_root);
++	us->instag_root = p1;
++
++	p2->accountname = strdup("account two");
++	p2->protocol = strdup("protocol two");
++	p2->instag = otrl_instag_get_new();
++	p2->next = us->instag_root;
++	p2->next->tous = &(p2->next);
++	p2->tous = &(us->instag_root);
++	us->instag_root = p2;
++
++	ok(otrl_instag_find(us, "account two", "protocol two") == p2,
++			"Found instag");
++	ok(otrl_instag_find(us, "account one", "protocol two") == NULL,
++			"Instag not found");
++	ok(otrl_instag_find(us, "account three", "protocol three") == NULL,
++			"Instag not found");
++}
++
++static void test_otrl_instag_read(void)
++{
++	OtrlUserState us = otrl_userstate_create();
++	OtrlInsTag *one, *two, *three, *four;
++	char sone[9] = {0}, stwo[9] = {0}, sfour[9] = {0};
++	one = two = three = four = NULL;
++	ok(otrl_instag_read(us, "/non_existent_file") ==
++			gcry_error_from_errno(ENOENT),
++			"Non-existent file detected");
++
++	ok(otrl_instag_read(us, instag_filepath) == GPG_ERR_NO_ERROR,
++			"Instag called with success");
++
++	one = otrl_instag_find(us, "alice_xmpp", "XMPP");
++	snprintf(sone, sizeof(sone), "%08x", one->instag);
++
++	two = otrl_instag_find(us, "alice_irc", "IRC");
++	snprintf(stwo, sizeof(stwo), "%08x", two->instag);
++
++	three = otrl_instag_find(us, "alice_inv", "IRC");
++
++	four = otrl_instag_find(us, "alice_icq", "ICQ");
++	snprintf(sfour, sizeof(sfour), "%08x", four->instag);
++
++	ok(one && two && !three && four &&
++			strcmp(sone, "01234567") == 0 &&
++			strcmp(stwo, "9abcdef0") == 0 &&
++			strcmp(sfour, "98765432") == 0,
++			"Instag succesfully read");
++}
++
++static void test_otrl_instag_read_FILEp(void)
++{
++	FILE* instf = fopen(instag_filepath, "rb");
++	OtrlUserState us = otrl_userstate_create();
++	OtrlInsTag* one, *two, *three, *four;
++	char sone[9] = {0}, stwo[9] = {0}, sfour[9] = {0};
++	one = two = three = four = NULL;
++
++	ok(otrl_instag_read_FILEp(us, instf) == gcry_error(GPG_ERR_NO_ERROR),
++			"Instead read from FILEp");
++	fclose(instf);
++
++	one = otrl_instag_find(us, "alice_xmpp", "XMPP");
++	snprintf(sone, sizeof(sone), "%08x", one->instag);
++
++	two = otrl_instag_find(us, "alice_irc", "IRC");
++	snprintf(stwo, sizeof(stwo), "%08x", two->instag);
++
++	three = otrl_instag_find(us, "alice_inv", "IRC");
++
++	four = otrl_instag_find(us, "alice_icq", "ICQ");
++	snprintf(sfour, sizeof(sfour), "%08x", four->instag);
++
++	ok(one && two && !three && four &&
++			strcmp(sone, "01234567") == 0 &&
++			strcmp(stwo, "9abcdef0") == 0 &&
++			strcmp(sfour, "98765432") == 0,
++			"Instag succesfully read");
++}
++
++static void test_otrl_instag_get_new(void)
++{
++	ok(otrl_instag_get_new() != 0, "New instag generated");
++}
++
++static ssize_t get_exe_path(char *buf, size_t len)
++{
++	char *path_end;
++
++	if (readlink("/proc/self/exe", buf, len) < 0) {
++		return -ENOMEM;
++	}
++
++	/*
++	 * Workaround to handle libtool path of the binary that is actually in the
++	 * $(buildir)/.libs. This is to make sure unit test works outside of tree.
++	 */
++	path_end = strstr(buf, ".libs/");
++	if (!path_end) {
++		path_end = strrchr(buf, '/');
++		if (!path_end) {
++			return -errno;
++		}
++		*(++path_end) = '\0';
++	} else {
++		*path_end = '\0';
++	}
++
++	return path_end - buf;
++}
++
++int main(int argc, char **argv)
++{
++	/* Libtap call for the number of tests planned. */
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	if (get_exe_path(curdir, sizeof(curdir)) < 0) {
++		return -ENOMEM;
++	}
++
++	/* Build the full path of the instag.txt file. */
++	(void) snprintf(instag_filepath, sizeof(instag_filepath), "%s%s", curdir,
++			"instag.txt");
++
++	test_otrl_instag_forget();
++	test_otrl_instag_forget_all();
++	test_otrl_instag_find();
++	test_otrl_instag_read();
++	test_otrl_instag_read_FILEp();
++	test_otrl_instag_get_new();
++
++	return 0;
++}
+diff --git a/tests/unit/test_mem.c b/tests/unit/test_mem.c
+new file mode 100644
+index 0000000..24eae20
+--- /dev/null
++++ b/tests/unit/test_mem.c
+@@ -0,0 +1,58 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++
++#include <mem.h>
++#include <proto.h>
++
++#include <tap/tap.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 5
++
++static void test_otrl_mem_differ(void)
++{
++	const unsigned char buf1[] = "\x00" "12" "\x00" "34";
++	const unsigned char buf2[] = "\x00" "13" "\x00" "34";
++	const unsigned char buf3[] = "\x00" "13" "\x00" "345";
++
++	ok(otrl_mem_differ(buf1, buf1, sizeof(buf1)) == 0,
++			"Identical buf are identical");
++	ok(otrl_mem_differ(buf1, buf2, sizeof(buf1)) == 1,
++			"buf1 and buf2 are not identical");
++	ok(otrl_mem_differ(buf2, buf3, sizeof(buf1)) == 1,
++			"buf1 and buf2 are not identical");
++	ok(otrl_mem_differ(buf1, NULL, 0) == 0,
++			"buf1 and NULL are identical");
++	ok(otrl_mem_differ(NULL, NULL, 0) == 0,
++			"NULL and NULL are identical");
++}
++
++int main(int argc, char **argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	test_otrl_mem_differ();
++
++	return 0;
++}
+diff --git a/tests/unit/test_privkey.c b/tests/unit/test_privkey.c
+new file mode 100644
+index 0000000..9e2db46
+--- /dev/null
++++ b/tests/unit/test_privkey.c
+@@ -0,0 +1,264 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++#include <unistd.h>
++
++#include <privkey.h>
++#include <proto.h>
++
++#include <tap/tap.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 13
++
++static OtrlUserState us = NULL;
++static char filename[] = "/tmp/libotr-testing-XXXXXX";
++static FILE* f = NULL;
++
++/*
++ * Create a public key block from a private key
++ */
++static void make_pubkey(unsigned char **pubbufp, size_t *publenp,
++		gcry_sexp_t privkey)
++{
++	gcry_mpi_t p,q,g,y;
++	gcry_sexp_t dsas,ps,qs,gs,ys;
++	size_t np,nq,ng,ny;
++	enum gcry_mpi_format format = GCRYMPI_FMT_USG;
++
++	*pubbufp = NULL;
++	*publenp = 0;
++
++	/* Extract the public parameters */
++	dsas = gcry_sexp_find_token(privkey, "dsa", 0);
++	ps = gcry_sexp_find_token(dsas, "p", 0);
++	qs = gcry_sexp_find_token(dsas, "q", 0);
++	gs = gcry_sexp_find_token(dsas, "g", 0);
++	ys = gcry_sexp_find_token(dsas, "y", 0);
++	gcry_sexp_release(dsas);
++
++	p = gcry_sexp_nth_mpi(ps, 1, GCRYMPI_FMT_USG);
++	gcry_sexp_release(ps);
++	q = gcry_sexp_nth_mpi(qs, 1, GCRYMPI_FMT_USG);
++	gcry_sexp_release(qs);
++	g = gcry_sexp_nth_mpi(gs, 1, GCRYMPI_FMT_USG);
++	gcry_sexp_release(gs);
++	y = gcry_sexp_nth_mpi(ys, 1, GCRYMPI_FMT_USG);
++	gcry_sexp_release(ys);
++
++	*publenp = 0;
++	gcry_mpi_print(format, NULL, 0, &np, p);
++	*publenp += np + 4;
++	gcry_mpi_print(format, NULL, 0, &nq, q);
++	*publenp += nq + 4;
++	gcry_mpi_print(format, NULL, 0, &ng, g);
++	*publenp += ng + 4;
++	gcry_mpi_print(format, NULL, 0, &ny, y);
++	*publenp += ny + 4;
++
++	*pubbufp = malloc(*publenp);
++
++	gcry_mpi_release(p);
++	gcry_mpi_release(q);
++	gcry_mpi_release(g);
++	gcry_mpi_release(y);
++}
++
++static void test_otrl_privkey_generate_FILEp(void)
++{
++	int fd = mkstemp(filename);
++	f = fdopen(fd, "w+b");
++
++	unlink(filename); // The file will be removed on close
++	us = otrl_userstate_create();
++	ok(otrl_privkey_generate_FILEp(us, f, "alice", "irc")
++		== gcry_error(GPG_ERR_NO_ERROR) &&
++		us->privkey_root != NULL,
++		"key generated");
++}
++
++static void test_otrl_privkey_hash_to_human(void)
++{
++	int i;
++	char human[OTRL_PRIVKEY_FPRINT_HUMAN_LEN];
++	unsigned char hash[20];
++
++	for(i = 0; i < 20; i++) {
++		hash[i] = 'A' + i;
++	}
++
++	otrl_privkey_hash_to_human(human, hash);
++	ok(strcmp("41424344 45464748 494A4B4C 4D4E4F50 51525354", human) == 0,
++			"Hash to human ok");
++}
++
++static void test_otrl_privkey_fingerprint(void)
++{
++	char fingerprint[OTRL_PRIVKEY_FPRINT_HUMAN_LEN] = {0};
++	char expected_fingerprint[OTRL_PRIVKEY_FPRINT_HUMAN_LEN] = {0};
++	unsigned char hash[20] = {0};
++	char *fp = otrl_privkey_fingerprint(us, fingerprint, "alice", "irc");
++	const OtrlPrivKey *p = otrl_privkey_find(us, "alice", "irc");
++
++	gcry_md_hash_buffer(GCRY_MD_SHA1, hash, p->pubkey_data, p->pubkey_datalen);
++	otrl_privkey_hash_to_human(expected_fingerprint, hash);
++
++	ok(fp == fingerprint &&
++		memcmp(fingerprint, expected_fingerprint,
++			OTRL_PRIVKEY_FPRINT_HUMAN_LEN) == 0,
++		"Privkey fingerprint ok");
++}
++
++static void test_otrl_privkey_fingerprint_raw(void)
++{
++	unsigned char hash[20] = {0};
++	unsigned char expected_hash[20] = {0};
++	unsigned char *h = otrl_privkey_fingerprint_raw(us, hash, "alice", "irc");
++
++	const OtrlPrivKey *p = otrl_privkey_find(us, "alice", "irc");
++	gcry_md_hash_buffer(GCRY_MD_SHA1, expected_hash, p->pubkey_data,
++			p->pubkey_datalen);
++
++	ok(h == hash && memcmp(hash, expected_hash, 20) == 0,
++		"Raw privkey fingerprint ok");
++}
++
++static void test_otrl_privkey_find(void)
++{
++	OtrlPrivKey *p = NULL;
++
++	ok(otrl_privkey_find(us, "bob", "xmpp") == NULL,
++			"Privkey not found");
++
++	ok(otrl_privkey_find(us, "alice", "xmpp") == NULL,
++			"Privkey not found because of wrong protocol");
++
++	ok(otrl_privkey_find(us, "bob", "irc") == NULL,
++			"Privkey not found because of wrong name");
++
++	p = otrl_privkey_find(us, "alice", "irc");
++	ok(p != NULL && strcmp(p->accountname, "alice") == 0 &&
++		strcmp(p->protocol, "irc") == 0,
++		"Privkey found");
++}
++
++static void test_otrl_privkey_sign(void)
++{
++	unsigned char *sig = NULL;
++	size_t siglen;
++	const char *data = "Some data to sign.";
++	size_t len = strlen(data);
++	OtrlPrivKey *p = otrl_privkey_find(us, "alice", "irc");
++
++	p->pubkey_type = OTRL_PUBKEY_TYPE_DSA + 1;
++
++	ok(otrl_privkey_sign(&sig, &siglen, p,
++			(unsigned char *) data, len) == gcry_error(GPG_ERR_INV_VALUE),
++			"Wrong pubkey type detected");
++	free(sig);
++
++	p->pubkey_type = OTRL_PUBKEY_TYPE_DSA;
++
++	ok(otrl_privkey_sign(&sig, &siglen, p,
++			(unsigned char *) data, len) == gcry_error(GPG_ERR_NO_ERROR),
++			"data signed");
++	free(sig);
++
++	ok(otrl_privkey_sign(&sig, &siglen, p, (unsigned char*)data, 0) ==
++			gcry_error(GPG_ERR_NO_ERROR), "data with len 0 signed");
++	free(sig);
++}
++
++static void test_otrl_privkey_verify(void)
++{
++	unsigned char *sigbuf = NULL;
++	size_t siglen;
++	const char *data = "Some data to sign.";
++	OtrlPrivKey *privkey = otrl_privkey_find(us, "alice", "irc");
++	gcry_mpi_t p,q,g,y;
++	gcry_sexp_t dsas, ps, qs, gs, ys;
++	gcry_sexp_t pubs = NULL;
++	gcry_error_t ret;
++
++	/* Extract pubkey */
++	dsas = gcry_sexp_find_token(privkey->privkey, "dsa", 0);
++	ps = gcry_sexp_find_token(dsas, "p", 0);
++	qs = gcry_sexp_find_token(dsas, "q", 0);
++	gs = gcry_sexp_find_token(dsas, "g", 0);
++	ys = gcry_sexp_find_token(dsas, "y", 0);
++	gcry_sexp_release(dsas);
++	p = gcry_sexp_nth_mpi(ps, 1, GCRYMPI_FMT_USG);
++	q = gcry_sexp_nth_mpi(qs, 1, GCRYMPI_FMT_USG);
++	g = gcry_sexp_nth_mpi(gs, 1, GCRYMPI_FMT_USG);
++	y = gcry_sexp_nth_mpi(ys, 1, GCRYMPI_FMT_USG);
++	gcry_sexp_release(ps);
++	gcry_sexp_release(qs);
++	gcry_sexp_release(gs);
++	gcry_sexp_release(ys);
++
++	gcry_sexp_build(&pubs, NULL, "(public-key (dsa (p %m)(q %m)(g %m)(y %m)))",
++			p, q, g, y);
++
++	gcry_mpi_release(p);
++	gcry_mpi_release(q);
++	gcry_mpi_release(g);
++	gcry_mpi_release(y);
++
++	otrl_privkey_sign(&sigbuf, &siglen, privkey, (unsigned char*)data,
++			strlen(data));
++
++	ok(otrl_privkey_verify(sigbuf, siglen, OTRL_PUBKEY_TYPE_DSA, pubs,
++				(unsigned char *) data, strlen(data)) == 0, "Signature ok");
++
++	ret = otrl_privkey_verify(sigbuf, siglen, OTRL_PUBKEY_TYPE_DSA, pubs,
++			(unsigned char *) data + 1, strlen(data) - 1);
++	ok(gcry_error(ret) == gcry_error(GPG_ERR_BAD_SIGNATURE),
++			"Wrong signature");
++
++	free(sigbuf);
++}
++
++int main(int argc, char **argv)
++{
++	OtrlPrivKey *p;
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	/* Set to quick random so we don't wait on /dev/random. */
++	gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
++
++	test_otrl_privkey_generate_FILEp(); //This must be the first one
++	p = otrl_privkey_find(us, "alice", "irc");
++	make_pubkey(&(p->pubkey_data), &(p->pubkey_datalen), p->privkey);
++
++	test_otrl_privkey_hash_to_human();
++	test_otrl_privkey_fingerprint();
++	test_otrl_privkey_fingerprint_raw();
++	test_otrl_privkey_sign();
++	test_otrl_privkey_verify();
++	test_otrl_privkey_find();
++
++	fclose(f);
++	otrl_userstate_free(us);
++
++	return 0;
++}
+diff --git a/tests/unit/test_proto.c b/tests/unit/test_proto.c
+new file mode 100644
+index 0000000..5b522ef
+--- /dev/null
++++ b/tests/unit/test_proto.c
+@@ -0,0 +1,371 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <limits.h>
++#include <pthread.h>
++
++#include <proto.h>
++
++#include <tap/tap.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 48
++
++static ConnContext *new_context(const char *user, const char *accountname,
++		const char *protocol)
++{
++	ConnContext *context;
++	OtrlSMState *smstate;
++
++	context = malloc(sizeof(ConnContext));
++
++	context->username = strdup(user);
++	context->accountname = strdup(accountname);
++	context->protocol = strdup(protocol);
++
++	context->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	otrl_auth_new(context);
++
++	smstate = malloc(sizeof(OtrlSMState));
++	otrl_sm_state_new(smstate);
++	context->smstate = smstate;
++
++	context->our_instance = 0;
++	context->their_instance = OTRL_INSTAG_MASTER;
++	context->fingerprint_root.fingerprint = NULL;
++	context->fingerprint_root.context = context;
++	context->fingerprint_root.next = NULL;
++	context->fingerprint_root.tous = NULL;
++	context->active_fingerprint = NULL;
++	memset(context->sessionid, 0, 20);
++	context->sessionid_len = 0;
++	context->protocol_version = 0;
++	context->otr_offer = OFFER_NOT;
++	context->app_data = NULL;
++	context->app_data_free = NULL;
++	context->context_priv = otrl_context_priv_new();
++	context->next = NULL;
++	context->m_context = context;
++	context->recent_rcvd_child = NULL;
++	context->recent_sent_child = NULL;
++	context->recent_child = NULL;
++
++	return context;
++}
++
++static void test_otrl_proto_whitespace_bestversion(void)
++{
++	unsigned int ret;
++	const char *start, *end;
++	const char *test1 = OTRL_MESSAGE_TAG_BASE OTRL_MESSAGE_TAG_V2;
++	const char *test2 = OTRL_MESSAGE_TAG_BASE OTRL_MESSAGE_TAG_V3;
++	const char *test3 = OTRL_MESSAGE_TAG_BASE "foobar";
++
++	ret = otrl_proto_whitespace_bestversion(test1, &start, &end,
++			OTRL_POLICY_ALLOW_V2);
++	ok(ret == 2, "Best version whitespace v2");
++
++	ret = otrl_proto_whitespace_bestversion(test1, &start, &end,
++			OTRL_POLICY_ALLOW_V2 | OTRL_POLICY_ALLOW_V3);
++	ok(ret == 2, "Best version whitespace v2 dual policy");
++
++	ret = otrl_proto_whitespace_bestversion(test2, &start, &end,
++			OTRL_POLICY_ALLOW_V3);
++	ok(ret == 3, "Best version whitespace v3");
++
++	ret = otrl_proto_whitespace_bestversion(test2, &start, &end,
++			OTRL_POLICY_ALLOW_V2 | OTRL_POLICY_ALLOW_V3);
++	ok(ret == 3, "Best version whitespace v3 dual policy");
++
++	ret = otrl_proto_whitespace_bestversion(test3, &start, &end,
++			OTRL_POLICY_ALLOW_V2 | OTRL_POLICY_ALLOW_V3);
++	ok(ret == 0, "Best version whitespace invalid");
++}
++
++static void test_otrl_proto_query_bestversion(void)
++{
++	const char *query2 = "?OTRv2?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	const char *query23 = "?OTRv23?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	const char *query3 = "?OTRv3?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	ok(otrl_proto_query_bestversion(query2, OTRL_POLICY_ALLOW_V2) == 2,
++			"The best from query2 is 2");
++	ok(otrl_proto_query_bestversion(query3, OTRL_POLICY_ALLOW_V3) == 3,
++			"The best from query3 is 3");
++	ok(otrl_proto_query_bestversion(query23, OTRL_POLICY_ALLOW_V2) == 2,
++			"The best from query23 is 2");
++	ok(otrl_proto_query_bestversion(query23, OTRL_POLICY_ALLOW_V3) == 3,
++			"The best from query23 is 3");
++}
++
++static void test_otrl_proto_default_query_msg(void)
++{
++	const char *expected2 = "?OTRv2?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	const char *expected23 = "?OTRv23?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	const char *expected3 = "?OTRv3?\n<b>alice</b> has requested an "
++		"<a href=\"https://otr.cypherpunks.ca/\">Off-the-Record "
++		"private conversation</a>.  However, you do not have a plugin "
++		"to support that.\nSee <a href=\"https://otr.cypherpunks.ca/\">"
++		"https://otr.cypherpunks.ca/</a> for more information.";
++
++	const char *msg2 = otrl_proto_default_query_msg("alice",
++			OTRL_POLICY_ALLOW_V2);
++	const char *msg23 = otrl_proto_default_query_msg("alice",
++			OTRL_POLICY_ALLOW_V2 | OTRL_POLICY_ALLOW_V3);
++	const char *msg3 = otrl_proto_default_query_msg("alice",
++			OTRL_POLICY_ALLOW_V3);
++	ok(strcmp(expected2, msg2) == 0, "OTRv2 default query message is valid");
++	ok(strcmp(expected23, msg23) == 0,
++			"OTRv23 default query message is valid");
++	ok(strcmp(expected3, msg3) == 0, "OTRv3 default query message is valid");
++}
++
++void test_otrl_init(void)
++{
++	extern unsigned int otrl_api_version;
++
++	const unsigned int expected = rand();
++	otrl_api_version = expected;
++	ok(otrl_init(OTRL_VERSION_MAJOR+1, 0, 0) == gcry_error(GPG_ERR_INV_VALUE),
++			"Too recent major version");
++	ok(otrl_api_version == expected, "Api number unchanged");
++
++	ok(otrl_init(OTRL_VERSION_MAJOR-1, 0, 0) == gcry_error(GPG_ERR_INV_VALUE),
++			"Too old major version");
++	ok(otrl_api_version == expected, "Api number unchanged");
++
++	ok(otrl_init(OTRL_VERSION_MAJOR, OTRL_VERSION_MINOR+1, 0)
++			== gcry_error(GPG_ERR_INV_VALUE),
++			"Too recent minor version");
++	ok(otrl_api_version = expected, "Api number unchanged");
++
++	ok(otrl_init(OTRL_VERSION_MAJOR, OTRL_VERSION_MINOR?OTRL_VERSION_MINOR-1:0,
++			OTRL_VERSION_SUB) == gcry_error(GPG_ERR_NO_ERROR),
++			"Inferior minor version");
++	ok(otrl_api_version = expected, "Api number unchanged");
++
++	otrl_api_version = 0;
++
++	ok(otrl_init(OTRL_VERSION_MAJOR, OTRL_VERSION_MINOR, OTRL_VERSION_SUB)
++			== gcry_error(GPG_ERR_NO_ERROR), "Exact version");
++	ok(otrl_api_version == (
++				(OTRL_VERSION_MAJOR << 16) |
++				(OTRL_VERSION_MINOR << 8) |
++				(OTRL_VERSION_SUB)
++				), "Api version set for exact version");
++}
++
++static void test_otrl_proto_message_type(void)
++{
++	OtrlMessageType ret;
++
++	const char *test1 = "This is plaintext";
++	ret = otrl_proto_message_type(test1);
++	ok(ret == OTRL_MSGTYPE_NOTOTR, "Proto message type is not OTR");
++
++	const char *test2 = OTRL_MESSAGE_TAG_BASE "This is plaintext";
++	ret = otrl_proto_message_type(test2);
++	ok(ret == OTRL_MSGTYPE_TAGGEDPLAINTEXT,
++			"Proto message type is tagged plaintext");
++
++	const char *test3 = "?OTR:AAIC";
++	ret = otrl_proto_message_type(test3);
++	ok(ret == OTRL_MSGTYPE_DH_COMMIT, "Proto message type v2 is dh commit");
++
++	const char *test4 = "?OTR:AAMC";
++	ret = otrl_proto_message_type(test4);
++	ok(ret == OTRL_MSGTYPE_DH_COMMIT, "Proto message type v3 is dh commit");
++
++	const char *test5 = "?OTR:AAIK";
++	ret = otrl_proto_message_type(test5);
++	ok(ret == OTRL_MSGTYPE_DH_KEY, "Proto message type v2 is DH key");
++
++	const char *test6 = "?OTR:AAMK";
++	ret = otrl_proto_message_type(test6);
++	ok(ret == OTRL_MSGTYPE_DH_KEY, "Proto message type v3 is DH key");
++
++	const char *test7 = "?OTR:AAIR";
++	ret = otrl_proto_message_type(test7);
++	ok(ret == OTRL_MSGTYPE_REVEALSIG, "Proto message type v2 is revealsig");
++
++	const char *test8 = "?OTR:AAMR";
++	ret = otrl_proto_message_type(test8);
++	ok(ret == OTRL_MSGTYPE_REVEALSIG, "Proto message type v3 is revealsig");
++
++	const char *test9 = "?OTR:AAIS";
++	ret = otrl_proto_message_type(test9);
++	ok(ret == OTRL_MSGTYPE_SIGNATURE, "Proto message type v2 is a signature");
++
++	const char *test10 = "?OTR:AAMS";
++	ret = otrl_proto_message_type(test10);
++	ok(ret == OTRL_MSGTYPE_SIGNATURE, "Proto message type v3 is a signature");
++
++	const char *test11 = "?OTR:AAID";
++	ret = otrl_proto_message_type(test11);
++	ok(ret == OTRL_MSGTYPE_DATA, "Proto message type v2 is a data msg");
++
++	const char *test12 = "?OTR:AAMD";
++	ret = otrl_proto_message_type(test12);
++	ok(ret == OTRL_MSGTYPE_DATA, "Proto message type v3 is a data msg");
++
++	const char *test13 = "?OTR?";
++	ret = otrl_proto_message_type(test13);
++	ok(ret == OTRL_MSGTYPE_QUERY, "Proto message type is a query");
++
++	const char *test14 = "?OTR?v";
++	ret = otrl_proto_message_type(test14);
++	ok(ret == OTRL_MSGTYPE_QUERY, "Proto message type is a query");
++
++	const char *test15 = "?OTR Error:";
++	ret = otrl_proto_message_type(test15);
++	ok(ret == OTRL_MSGTYPE_ERROR, "Proto message type is an error");
++
++	const char *test16 = "?OTR: Please verify me";
++	ret = otrl_proto_message_type(test16);
++	ok(ret == OTRL_MSGTYPE_UNKNOWN, "Proto message type is unknown");
++
++	const char *test17 = "?OTR:AAMA";
++	ret = otrl_proto_message_type(test17);
++	ok(ret == OTRL_MSGTYPE_UNKNOWN, "Proto message type is unknown");
++}
++
++static void test_otrl_proto_message_version(void)
++{
++	int ret;
++
++	const char *test1 = "?OTR:AAI";
++	ret = otrl_proto_message_version(test1);
++	ok(ret == 2, "Protocol message version is 2");
++
++	const char *test2 = "?OTR:AAM";
++	ret = otrl_proto_message_version(test2);
++	ok(ret == 3, "Protocol message version is 3");
++
++	const char *test3 = "?OTR:BLAH";
++	ret = otrl_proto_message_version(test3);
++	ok(ret == 0, "Protocol message version is unknown");
++}
++
++static void test_otrl_proto_instance(void)
++{
++	/* Canary that shouldn't get modified on error. */
++	unsigned int inst_from = 42, inst_to = 42;
++	gcry_error_t ret;
++
++	/*
++	 * Instance tags only supported in protocol v3 (AAM in b64).  The msg type
++	 * here is "A" which does not represent a valid one but we don't care
++	 * followed by the Sender Instance set to 1 and Receiver Instance set to 2.
++	 */
++	const char *test1 = "?OTR:AAMAAAAAAQAAAAI==";
++	ret = otrl_proto_instance(test1, &inst_from, &inst_to);
++	ok(ret == gcry_error(GPG_ERR_NO_ERROR)
++		&& inst_from == 1
++		&& inst_to == 2,
++		"Proto instance find for v3");
++
++	/* Reset canary. */
++	inst_from = inst_to = 42;
++
++	/* Len is not enough here. */
++	const char *test2 = "?OTR:AAMAAA=";
++	ret = otrl_proto_instance(test2, &inst_from, &inst_to);
++	ok(ret == gcry_error(GPG_ERR_INV_VALUE)
++		&& inst_from == 42
++		&& inst_to == 42, "Proto instance failed for v3");
++
++	/* Reset canary. */
++	inst_from = inst_to = 42;
++
++	/* Message from protocol v2. */
++	const char *test3 = "?OTR:AAIAAAAAAQAAAAI==";
++	ret = otrl_proto_instance(test3, &inst_from, &inst_to);
++	ok(ret == gcry_error(GPG_ERR_INV_VALUE)
++			&& inst_from == 42
++			&& inst_to == 42, "Proto instance failed for v2");
++}
++
++static void test_otrl_version(void)
++{
++	ok(strcmp(otrl_version(), OTRL_VERSION) == 0, "Otrl version OK");
++}
++
++static void test_otrl_proto_create_data(void)
++{
++	char *encmessagep = NULL, *msg = "HELO";
++	unsigned char flags = 12;
++	unsigned char *extrakey = NULL;
++	OtrlTLV *tlvs = NULL;
++	ConnContext *context =
++		new_context("Alice", "Alice's account", "Secret protocol");
++
++	context->msgstate = OTRL_MSGSTATE_PLAINTEXT;
++	ok(otrl_proto_create_data(&encmessagep, context, msg, tlvs, flags,
++			extrakey) == gcry_error(GPG_ERR_CONFLICT),
++			"Conflict detected for msgstate plaintext");
++
++	context->msgstate = OTRL_MSGSTATE_ENCRYPTED;
++	context->context_priv->their_keyid = 0;
++	ok(otrl_proto_create_data(&encmessagep, context, msg, tlvs, flags,
++			extrakey) == gcry_error(GPG_ERR_CONFLICT),
++			"Conflict detected for msgstate encrypted");
++}
++
++int main(int argc, char **argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	test_otrl_proto_default_query_msg();
++	test_otrl_proto_query_bestversion();
++	test_otrl_init();
++	test_otrl_proto_whitespace_bestversion();
++	test_otrl_proto_message_type();
++	test_otrl_proto_message_version();
++	test_otrl_proto_instance();
++	test_otrl_version();
++	test_otrl_proto_create_data();
++
++	return 0;
++}
+diff --git a/tests/unit/test_sm.c b/tests/unit/test_sm.c
+new file mode 100644
+index 0000000..8f4162a
+--- /dev/null
++++ b/tests/unit/test_sm.c
+@@ -0,0 +1,343 @@
++/*
++ * Copyright (C) 2014 - David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++
++#include <proto.h>
++#include <sm.h>
++
++#include <tap/tap.h>
++#include <utils.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 23
++
++/* Copied from sm.c */
++static const int SM_MOD_LEN_BITS = 1536;
++static const char *SM_GENERATOR_S = "0x02";
++static gcry_mpi_t SM_GENERATOR = NULL;
++
++static const int SM_MSG1_LEN = 6;
++static const int SM_MSG2_LEN = 11;
++static const int SM_MSG3_LEN = 8;
++static const int SM_MSG4_LEN = 3;
++
++/* Alice and Bob SM state for the SMP tests. */
++static OtrlSMState *astate;
++static OtrlSMState *bstate;
++static const char *secret = "truie";
++static unsigned char *alice_output;
++static int alice_output_len;
++static unsigned char *bob_output;
++static int bob_output_len;
++
++/* Stub. */
++void otrl_sm_msg1_init(gcry_mpi_t **msg1);
++void otrl_sm_msg2_init(gcry_mpi_t **msg2);
++void otrl_sm_msg3_init(gcry_mpi_t **msg3);
++void otrl_sm_msg4_init(gcry_mpi_t **msg4);
++void otrl_sm_msg_free(gcry_mpi_t **message, int msglen);
++
++static OtrlSMState *alloc_sm_state(void)
++{
++	OtrlSMState *smst = malloc(sizeof(*smst));
++	ok(smst, "SM State allocated");
++
++	return smst;
++}
++
++static void test_sm_state_new(void)
++{
++	OtrlSMState *smst;
++
++	smst = alloc_sm_state();
++
++	otrl_sm_state_new(smst);
++	ok(!smst->secret &&
++			!smst->x2 &&
++			!smst->x3 &&
++			!smst->g1 &&
++			!smst->g2 &&
++			!smst->g3 &&
++			!smst->g3o &&
++			!smst->p &&
++			!smst->q &&
++			!smst->pab &&
++			!smst->qab &&
++			smst->nextExpected == OTRL_SMP_EXPECT1 &&
++			smst->received_question == 0 &&
++			smst->sm_prog_state == OTRL_SMP_PROG_OK,
++			"SM state new");
++
++	otrl_sm_state_free(smst);
++	free(smst);
++}
++
++static void test_sm_state_init(void)
++{
++	OtrlSMState *smst;
++
++	smst = alloc_sm_state();
++
++	otrl_sm_state_new(smst);
++	otrl_sm_state_init(smst);
++	ok(!gcry_mpi_cmp(smst->secret, gcry_mpi_snew(SM_MOD_LEN_BITS)) &&
++			!smst->x2 &&
++			!smst->x3 &&
++			!gcry_mpi_cmp(smst->g1, gcry_mpi_copy(SM_GENERATOR)) &&
++			!gcry_mpi_cmp(smst->g2, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->g3, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->g3o, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->p, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->q, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->pab, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(smst->qab, gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			smst->nextExpected == OTRL_SMP_EXPECT1 &&
++			smst->received_question == 0 &&
++			smst->sm_prog_state == OTRL_SMP_PROG_OK,
++			"SM state init");
++
++	otrl_sm_state_free(smst);
++	free(smst);
++}
++
++static void test_sm_msg1_init(void)
++{
++	gcry_mpi_t *msg;
++
++	otrl_sm_msg1_init(&msg);
++	ok(msg &&
++			!gcry_mpi_cmp(msg[0], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[1] &&
++			!gcry_mpi_cmp(msg[2], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[3], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[4] &&
++			!gcry_mpi_cmp(msg[5], gcry_mpi_new(SM_MOD_LEN_BITS)),
++			"SM msg1 initialized");
++	otrl_sm_msg_free(&msg, SM_MSG1_LEN);
++	/* Test once here. */
++	ok(!msg, "SM msg1 freed");
++}
++
++static void test_sm_msg2_init(void)
++{
++	gcry_mpi_t *msg;
++
++	otrl_sm_msg2_init(&msg);
++	ok(msg &&
++			!gcry_mpi_cmp(msg[0], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[1] &&
++			!gcry_mpi_cmp(msg[2], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[3], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[4] &&
++			!gcry_mpi_cmp(msg[5], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[6], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[7], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[8] &&
++			!gcry_mpi_cmp(msg[9], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[10], gcry_mpi_new(SM_MOD_LEN_BITS)),
++			"SM msg2 initialized");
++	otrl_sm_msg_free(&msg, SM_MSG2_LEN);
++}
++
++static void test_sm_msg3_init(void)
++{
++	gcry_mpi_t *msg;
++
++	otrl_sm_msg3_init(&msg);
++	ok(msg &&
++			!gcry_mpi_cmp(msg[0], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[1], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[2] &&
++			!gcry_mpi_cmp(msg[3], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[4], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!gcry_mpi_cmp(msg[5], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[6] &&
++			!gcry_mpi_cmp(msg[7], gcry_mpi_new(SM_MOD_LEN_BITS)),
++			"SM msg3 initialized");
++	otrl_sm_msg_free(&msg, SM_MSG3_LEN);
++}
++
++static void test_sm_msg4_init(void)
++{
++	gcry_mpi_t *msg;
++
++	otrl_sm_msg4_init(&msg);
++	ok(msg &&
++			!gcry_mpi_cmp(msg[0], gcry_mpi_new(SM_MOD_LEN_BITS)) &&
++			!msg[1] &&
++			!gcry_mpi_cmp(msg[2], gcry_mpi_new(SM_MOD_LEN_BITS)),
++			"SM msg4 initialized");
++	otrl_sm_msg_free(&msg, SM_MSG4_LEN);
++}
++
++static void test_sm_step1(void)
++{
++	gcry_error_t err;
++	unsigned char hash_secret[SM_DIGEST_SIZE];
++
++	astate = alloc_sm_state();
++	otrl_sm_state_new(astate);
++	otrl_sm_state_init(astate);
++
++	gcry_md_hash_buffer(SM_HASH_ALGORITHM, hash_secret, secret,
++			strlen(secret));
++
++	err = otrl_sm_step1(astate, hash_secret, sizeof(hash_secret),
++			&alice_output, &alice_output_len);
++	ok(err == GPG_ERR_NO_ERROR, "SMP step1 success");
++
++	gcry_mpi_t secret_mpi;
++	gcry_mpi_scan(&secret_mpi, GCRYMPI_FMT_USG, hash_secret,
++			sizeof(hash_secret), NULL);
++	ok(!gcry_mpi_cmp(astate->secret, secret_mpi) &&
++			astate->received_question == 0 &&
++			astate->x2 &&
++			astate->x3 &&
++			astate->sm_prog_state == OTRL_SMP_PROG_OK &&
++			alice_output && alice_output_len > 0,
++			"SMP step 1 validated");
++	gcry_mpi_release(secret_mpi);
++}
++
++static void test_sm_step2a(void)
++{
++	gcry_error_t err;
++
++	bstate = alloc_sm_state();
++	otrl_sm_state_new(bstate);
++	otrl_sm_state_init(bstate);
++
++	err = otrl_sm_step2a(bstate, alice_output, alice_output_len, 1);
++	ok(err == GPG_ERR_NO_ERROR, "SMP step2a success");
++
++	ok(bstate->received_question == 1 &&
++			bstate->sm_prog_state == OTRL_SMP_PROG_OK &&
++			bstate->g3o &&
++			bstate->x2 &&
++			bstate->x3,
++			"SMP step2a validate");
++}
++
++static void test_sm_step2b(void)
++{
++	gcry_error_t err;
++	unsigned char hash_secret[SM_DIGEST_SIZE];
++
++	gcry_md_hash_buffer(SM_HASH_ALGORITHM, hash_secret, secret,
++			strlen(secret));
++
++	err = otrl_sm_step2b(bstate, hash_secret, sizeof(hash_secret), &bob_output,
++			&bob_output_len);
++	ok(err == GPG_ERR_NO_ERROR, "SMP step2b success");
++
++	/* Generate expected data. */
++	gcry_mpi_t secret_mpi;
++	gcry_mpi_scan(&secret_mpi, GCRYMPI_FMT_USG, hash_secret,
++			sizeof(hash_secret), NULL);
++	ok(bob_output && bob_output_len > 0 &&
++			!gcry_mpi_cmp(bstate->secret, secret_mpi) &&
++			bstate->p &&
++			bstate->q,
++			"SMP step2b validate");
++	gcry_mpi_release(secret_mpi);
++}
++
++static void test_sm_step3(void)
++{
++	gcry_error_t err;
++
++	free(alice_output);
++
++	err = otrl_sm_step3(astate, bob_output, bob_output_len, &alice_output,
++			&alice_output_len);
++	ok(err == GPG_ERR_NO_ERROR, "SMP step3 success");
++
++	ok(alice_output && alice_output_len > 0 &&
++			astate->sm_prog_state == OTRL_SMP_PROG_OK &&
++			astate->g3o &&
++			astate->g2 &&
++			astate->g3 &&
++			astate->p &&
++			astate->q &&
++			astate->qab &&
++			astate->pab,
++			"SMP step3 validate");
++}
++
++static void test_sm_step4(void)
++{
++	gcry_error_t err;
++
++	free(bob_output);
++
++	err = otrl_sm_step4(bstate, alice_output, alice_output_len, &bob_output,
++			&bob_output_len);
++	ok(err == gcry_error(GPG_ERR_NO_ERROR), "SMP step4 success");
++
++	ok(bob_output && bob_output_len > 0 &&
++			bstate->sm_prog_state == OTRL_SMP_PROG_SUCCEEDED &&
++			bstate->pab &&
++			bstate->qab,
++			"SMP step4 validate");
++}
++
++static void test_sm_step5(void)
++{
++	gcry_error_t err;
++
++	err = otrl_sm_step5(astate, bob_output, bob_output_len);
++	ok(err == gcry_error(GPG_ERR_NO_ERROR), "SMP step5 success");
++
++	ok(astate && astate->sm_prog_state == OTRL_SMP_PROG_SUCCEEDED,
++			"SMP step5 validate");
++}
++
++int main(int argc, char **argv)
++{
++	/* Libtap call for the number of tests planned. */
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	/* Initialize sm subsystem. We can't really unit test that because every
++	 * value that is being initialized is static to sm.c. */
++	otrl_sm_init();
++
++	/* Init variables we need for testing. */
++	gcry_mpi_scan(&SM_GENERATOR, GCRYMPI_FMT_HEX,
++			(const unsigned char *)SM_GENERATOR_S, 0, NULL);
++
++	test_sm_state_new();
++	test_sm_state_init();
++	test_sm_msg1_init();
++	test_sm_msg2_init();
++	test_sm_msg3_init();
++	test_sm_msg4_init();
++
++	test_sm_step1();
++	test_sm_step2a();
++	test_sm_step2b();
++	test_sm_step3();
++	test_sm_step4();
++	test_sm_step5();
++
++	return 0;
++}
+diff --git a/tests/unit/test_tlv.c b/tests/unit/test_tlv.c
+new file mode 100644
+index 0000000..d05f9b8
+--- /dev/null
++++ b/tests/unit/test_tlv.c
+@@ -0,0 +1,163 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++
++#include <proto.h>
++#include <tlv.h>
++
++#include <tap/tap.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 11
++
++static void test_otrl_tlv_new()
++{
++	const unsigned short type = OTRL_TLV_SMP1Q;
++	const char *data = "This is some test data";
++	const unsigned short len = strlen(data);
++
++	OtrlTLV* tlv = otrl_tlv_new(type, len, (unsigned char*)data);
++	ok(tlv->type == type &&
++			tlv->len == len &&
++			memcmp(tlv->data, data, len) == 0 &&
++			tlv->data[len] == '\0' &&
++			tlv->next == NULL,
++			"TLV created with success");
++	otrl_tlv_free(tlv);
++}
++
++static void test_otrl_tlv_parse()
++{
++	const unsigned char serialized1[] =
++		{'\x01', '\x02', '\x00', '\x03', '1', '2', '3'};
++	const unsigned char serialized2[] = {'\x02', '\x04', '\x00', '\x00'};
++	const unsigned char serialized3[] =
++		{'\x04', '\x02', '\x00', '\x03', '1', '2', '3',
++		'\x02', '\x02', '\xff', '\xff', '1', '3', '3', '7'};
++	const unsigned char serialized4[] =
++		{'\x04', '\x02', '\x00', '\x03', '1', '2', '3',
++		'\x02', '\x02', '\x00', '\x04', '1', '3', '3', '7'};
++
++	OtrlTLV *tlv1 = otrl_tlv_parse(serialized1, sizeof(serialized1));
++	OtrlTLV *tlv2 = otrl_tlv_parse(serialized2, sizeof(serialized2));
++	OtrlTLV *tlv3 = otrl_tlv_parse(serialized3, sizeof(serialized3));
++	OtrlTLV *tlv4 = otrl_tlv_parse(serialized4, sizeof(serialized4));
++
++	ok(tlv1->type == 258 &&
++			tlv1->len == 3 &&
++			tlv1->next == NULL &&
++			memcmp(tlv1->data, "123", tlv1->len) == 0 &&
++			tlv1->data[tlv1->len] == 0,
++			"Single-TLV chain constructed with success");
++	otrl_tlv_free(tlv1);
++
++	ok(tlv2->type == 516 &&
++			tlv2->len == 0 &&
++			tlv2->next == NULL,
++			"tlv2 chain with no data constructed with success");
++	otrl_tlv_free(tlv2);
++
++	ok(tlv3->type == 1026 &&
++			tlv3->len == 3 &&
++			memcmp(tlv3->data, "123", tlv3->len) == 0 &&
++			tlv3->data[tlv3->len] == 0 &&
++			tlv3->next == NULL,
++			"tlv3 chain with overflow constructed with success");
++	otrl_tlv_free(tlv3);
++
++	ok(tlv4->type == 1026 &&
++			tlv4->len == 3 &&
++			memcmp(tlv4->data, "123", tlv4->len) == 0 &&
++			tlv4->data[tlv4->len] == 0 &&
++			tlv4->next != NULL,
++			"First part of the 2-part tlv chain build");
++
++	ok(tlv4->next != NULL &&
++			tlv4->next->type == 514 &&
++			tlv4->next->len == 4 &&
++			memcmp(tlv4->next->data, "1337", tlv4->next->len) == 0 &&
++			tlv4->next->data[tlv4->next->len] == 0 &&
++			tlv4->next->next == NULL,
++			"Second part of the 2-part tlv chain build");
++	otrl_tlv_free(tlv4);
++}
++
++static void test_otrl_tlv_seriallen()
++{
++	const unsigned char serialized[] =
++		{'\x04', '\x02', '\x00', '\x03', '1', '2', '3',
++		'\x02', '\x02', '\x00', '\x04', '1', '3', '3', '7'};
++	OtrlTLV* tlv = otrl_tlv_parse(serialized, sizeof(serialized));
++	ok(otrl_tlv_seriallen(tlv) == 4 + 3 + 4 + 4,
++			"Size correctly guessed");
++	otrl_tlv_free(tlv);
++}
++
++static void test_otrl_tlv_serialize()
++{
++	const unsigned char serialized[] =
++		{'\x04', '\x02', '\x00', '\x03', '1', '2', '3',
++		'\x02', '\x02', '\x00', '\x04', '1', '3', '3', '7'};
++	OtrlTLV *tlv = otrl_tlv_parse(serialized, sizeof(serialized));
++	unsigned char *buf = malloc(otrl_tlv_seriallen(tlv));
++	otrl_tlv_serialize(buf, tlv);
++	ok(memcmp(serialized, buf, sizeof(serialized)) == 0,
++			"tlv correctly serialized");
++	free(tlv);
++
++	tlv = otrl_tlv_parse(buf, sizeof(serialized));
++	otrl_tlv_serialize(buf, tlv);
++	ok(memcmp(serialized, buf, sizeof(serialized)) == 0,
++			"tlv correctly unserialized and serialized again");
++	otrl_tlv_free(tlv);
++}
++
++static void test_otrl_tlv_find()
++{
++	const unsigned char serialized[] =
++		{'\x04', '\x02', '\x00', '\x03', '1', '2', '3',
++		'\x02', '\x02', '\x00', '\x04', '1', '3', '3', '7',
++		'\x01', '\x03', '\x0', '\x01', 'A',
++		'\x01', '\x02', '\x0', '\x01', 'B'};
++	OtrlTLV *tlv = otrl_tlv_parse(serialized, sizeof(serialized));
++	OtrlTLV *result = otrl_tlv_find(tlv, (1<<8) + 3);
++	ok(result == tlv->next->next, "TLV found");
++
++	result = otrl_tlv_find(tlv, 7);
++	ok(result == NULL, "Unexistent TLV not found");
++
++	otrl_tlv_free(tlv);
++}
++
++int main(int argc, char **argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	test_otrl_tlv_new();
++	test_otrl_tlv_parse();
++	test_otrl_tlv_seriallen();
++	test_otrl_tlv_serialize();
++	test_otrl_tlv_find();
++
++	return 0;
++}
+diff --git a/tests/unit/test_userstate.c b/tests/unit/test_userstate.c
+new file mode 100644
+index 0000000..62e996e
+--- /dev/null
++++ b/tests/unit/test_userstate.c
+@@ -0,0 +1,52 @@
++/*
++ * Copyright (C) 2014 - Julien Voisin <julien.voisin at dustri.org>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 <gcrypt.h>
++#include <pthread.h>
++
++#include <userstate.h>
++#include <proto.h>
++
++#include <tap/tap.h>
++
++GCRY_THREAD_OPTION_PTHREAD_IMPL;
++
++#define NUM_TESTS 1
++
++static void test_otrl_userstate_create()
++{
++	OtrlUserState us = otrl_userstate_create();
++	ok(us->context_root == NULL &&
++			us->privkey_root == NULL &&
++			us->instag_root == NULL &&
++			us->pending_root == NULL &&
++			us->timer_running == 0,
++			"OtrlUserState ok");
++	otrl_userstate_free(us);
++}
++
++int main(int argc, char** argv)
++{
++	plan_tests(NUM_TESTS);
++
++	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
++	OTRL_INIT;
++
++	test_otrl_userstate_create();
++
++	return 0;
++}
+diff --git a/tests/utils/Makefile.am b/tests/utils/Makefile.am
+new file mode 100644
+index 0000000..7e4ab05
+--- /dev/null
++++ b/tests/utils/Makefile.am
+@@ -0,0 +1,3 @@
++SUBDIRS = tap
++
++EXTRA_DIST = utils.c utils.h
+diff --git a/tests/utils/tap/Makefile.am b/tests/utils/tap/Makefile.am
+new file mode 100644
+index 0000000..3650e88
+--- /dev/null
++++ b/tests/utils/tap/Makefile.am
+@@ -0,0 +1,7 @@
++AM_CFLAGS = -DHAVE_LIBPTHREAD
++
++noinst_LTLIBRARIES = libtap.la
++libtap_la_SOURCES = tap.c tap.h
++libtap_la_LIBADD = -lpthread
++dist_noinst_SCRIPTS = tap.sh
++EXTRA_DIST = tap.sh
+diff --git a/tests/utils/tap/tap.c b/tests/utils/tap/tap.c
+new file mode 100644
+index 0000000..d52cb03
+--- /dev/null
++++ b/tests/utils/tap/tap.c
+@@ -0,0 +1,433 @@
++/*-
++ * Copyright (c) 2004 Nik Clayton
++ * All rights reserved.
++ *
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 1. Redistributions of source code must retain the above copyright
++ *    notice, this list of conditions and the following disclaimer.
++ * 2. Redistributions in binary form must reproduce the above copyright
++ *    notice, this list of conditions and the following disclaimer in the
++ *    documentation and/or other materials provided with the distribution.
++ *
++ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
++ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
++ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
++ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
++ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
++ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
++ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
++ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
++ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
++ * SUCH DAMAGE.
++ */
++
++#define _GNU_SOURCE
++#include <ctype.h>
++#include <stdarg.h>
++#include <stdio.h>
++#include <stdlib.h>
++
++#include "tap.h"
++
++static int no_plan = 0;
++static int skip_all = 0;
++static int have_plan = 0;
++static unsigned int test_count = 0; /* Number of tests that have been run */
++static unsigned int e_tests = 0; /* Expected number of tests to run */
++static unsigned int failures = 0; /* Number of tests that failed */
++static char *todo_msg = NULL;
++static char *todo_msg_fixed = "libtap malloc issue";
++static int todo = 0;
++static int test_died = 0;
++
++/* Encapsulate the pthread code in a conditional.  In the absence of
++   libpthread the code does nothing */
++#ifdef HAVE_LIBPTHREAD
++#include <pthread.h>
++static pthread_mutex_t M = PTHREAD_MUTEX_INITIALIZER;
++# define LOCK pthread_mutex_lock(&M);
++# define UNLOCK pthread_mutex_unlock(&M);
++#else
++# define LOCK
++# define UNLOCK
++#endif
++
++static void _expected_tests(unsigned int);
++static void _tap_init(void);
++static void _cleanup(void);
++
++/*
++ * Generate a test result.
++ *
++ * ok -- boolean, indicates whether or not the test passed.
++ * test_name -- the name of the test, may be NULL
++ * test_comment -- a comment to print afterwards, may be NULL
++ */
++unsigned int
++_gen_result(int ok, const char *func, char *file, unsigned int line,
++	    char *test_name, ...)
++{
++	va_list ap;
++	char *local_test_name = NULL;
++	char *c;
++	int name_is_digits;
++
++	LOCK;
++
++	test_count++;
++
++	/* Start by taking the test name and performing any printf()
++	   expansions on it */
++	if(test_name != NULL) {
++		va_start(ap, test_name);
++		if (vasprintf(&local_test_name, test_name, ap) == -1) {
++			local_test_name = NULL;
++		}
++		va_end(ap);
++
++		/* Make sure the test name contains more than digits
++		   and spaces.  Emit an error message and exit if it
++		   does */
++		if(local_test_name) {
++			name_is_digits = 1;
++			for(c = local_test_name; *c != '\0'; c++) {
++				if(!isdigit((unsigned char)*c) && !isspace((unsigned char)*c)) {
++					name_is_digits = 0;
++					break;
++				}
++			}
++
++			if(name_is_digits) {
++				diag("    You named your test '%s'.  You shouldn't use numbers for your test names.", local_test_name);
++				diag("    Very confusing.");
++			}
++		}
++	}
++
++	if(!ok) {
++		printf("not ");
++		failures++;
++	}
++
++	printf("ok %d", test_count);
++
++	if(test_name != NULL) {
++		printf(" - ");
++
++		/* Print the test name, escaping any '#' characters it
++		   might contain */
++		if(local_test_name != NULL) {
++			flockfile(stdout);
++			for(c = local_test_name; *c != '\0'; c++) {
++				if(*c == '#')
++					fputc('\\', stdout);
++				fputc((int)*c, stdout);
++			}
++			funlockfile(stdout);
++		} else {	/* vasprintf() failed, use a fixed message */
++			printf("%s", todo_msg_fixed);
++		}
++	}
++
++	/* If we're in a todo_start() block then flag the test as being
++	   TODO.  todo_msg should contain the message to print at this
++	   point.  If it's NULL then asprintf() failed, and we should
++	   use the fixed message.
++
++	   This is not counted as a failure, so decrement the counter if
++	   the test failed. */
++	if(todo) {
++		printf(" # TODO %s", todo_msg ? todo_msg : todo_msg_fixed);
++		if(!ok)
++			failures--;
++	}
++
++	printf("\n");
++
++	if(!ok) {
++		if(getenv("HARNESS_ACTIVE") != NULL)
++			fputs("\n", stderr);
++
++		diag("    Failed %stest (%s:%s() at line %d)",
++		     todo ? "(TODO) " : "", file, func, line);
++	}
++	free(local_test_name);
++
++	UNLOCK;
++
++	/* We only care (when testing) that ok is positive, but here we
++	   specifically only want to return 1 or 0 */
++	return ok ? 1 : 0;
++}
++
++/*
++ * Initialise the TAP library.  Will only do so once, however many times it's
++ * called.
++ */
++void
++_tap_init(void)
++{
++	static int run_once = 0;
++
++	if(!run_once) {
++		atexit(_cleanup);
++
++		/* stdout needs to be unbuffered so that the output appears
++		   in the same place relative to stderr output as it does
++		   with Test::Harness */
++		setbuf(stdout, 0);
++		run_once = 1;
++	}
++}
++
++/*
++ * Note that there's no plan.
++ */
++int
++plan_no_plan(void)
++{
++
++	LOCK;
++
++	_tap_init();
++
++	if(have_plan != 0) {
++		fprintf(stderr, "You tried to plan twice!\n");
++		test_died = 1;
++		UNLOCK;
++		exit(255);
++	}
++
++	have_plan = 1;
++	no_plan = 1;
++
++	UNLOCK;
++
++	return 1;
++}
++
++/*
++ * Note that the plan is to skip all tests
++ */
++int
++plan_skip_all(char *reason)
++{
++
++	LOCK;
++
++	_tap_init();
++
++	skip_all = 1;
++
++	printf("1..0");
++
++	if(reason != NULL)
++		printf(" # Skip %s", reason);
++
++	printf("\n");
++
++	UNLOCK;
++
++	exit(0);
++}
++
++/*
++ * Note the number of tests that will be run.
++ */
++int
++plan_tests(unsigned int tests)
++{
++
++	LOCK;
++
++	_tap_init();
++
++	if(have_plan != 0) {
++		fprintf(stderr, "You tried to plan twice!\n");
++		test_died = 1;
++		UNLOCK;
++		exit(255);
++	}
++
++	if(tests == 0) {
++		fprintf(stderr, "You said to run 0 tests!  You've got to run something.\n");
++		test_died = 1;
++		UNLOCK;
++		exit(255);
++	}
++
++	have_plan = 1;
++
++	_expected_tests(tests);
++
++	UNLOCK;
++
++	return e_tests;
++}
++
++unsigned int
++diag(char *fmt, ...)
++{
++	va_list ap;
++
++	fputs("# ", stderr);
++
++	va_start(ap, fmt);
++	vfprintf(stderr, fmt, ap);
++	va_end(ap);
++
++	fputs("\n", stderr);
++
++	return 0;
++}
++
++void
++_expected_tests(unsigned int tests)
++{
++
++	printf("1..%d\n", tests);
++	e_tests = tests;
++}
++
++int
++skip(unsigned int n, char *fmt, ...)
++{
++	va_list ap;
++	char *skip_msg = NULL;
++
++	LOCK;
++
++	va_start(ap, fmt);
++	if (asprintf(&skip_msg, fmt, ap) == -1) {
++		skip_msg = NULL;
++	}
++	va_end(ap);
++
++	while(n-- > 0) {
++		test_count++;
++		printf("ok %d # skip %s\n", test_count,
++		       skip_msg != NULL ?
++		       skip_msg : "libtap():malloc() failed");
++	}
++
++	free(skip_msg);
++
++	UNLOCK;
++
++	return 1;
++}
++
++void
++todo_start(char *fmt, ...)
++{
++	va_list ap;
++
++	LOCK;
++
++	va_start(ap, fmt);
++	if (vasprintf(&todo_msg, fmt, ap) == -1) {
++		todo_msg = NULL;
++	}
++	va_end(ap);
++
++	todo = 1;
++
++	UNLOCK;
++}
++
++void
++todo_end(void)
++{
++
++	LOCK;
++
++	todo = 0;
++	free(todo_msg);
++
++	UNLOCK;
++}
++
++int
++exit_status(void)
++{
++	int r;
++
++	LOCK;
++
++	/* If there's no plan, just return the number of failures */
++	if(no_plan || !have_plan) {
++		UNLOCK;
++		return failures;
++	}
++
++	/* Ran too many tests?  Return the number of tests that were run
++	   that shouldn't have been */
++	if(e_tests < test_count) {
++		r = test_count - e_tests;
++		UNLOCK;
++		return r;
++	}
++
++	/* Return the number of tests that failed + the number of tests
++	   that weren't run */
++	r = failures + e_tests - test_count;
++	UNLOCK;
++
++	return r;
++}
++
++/*
++ * Cleanup at the end of the run, produce any final output that might be
++ * required.
++ */
++void
++_cleanup(void)
++{
++
++	LOCK;
++
++	/* If plan_no_plan() wasn't called, and we don't have a plan,
++	   and we're not skipping everything, then something happened
++	   before we could produce any output */
++	if(!no_plan && !have_plan && !skip_all) {
++		diag("Looks like your test died before it could output anything.");
++		UNLOCK;
++		return;
++	}
++
++	if(test_died) {
++		diag("Looks like your test died just after %d.", test_count);
++		UNLOCK;
++		return;
++	}
++
++
++	/* No plan provided, but now we know how many tests were run, and can
++	   print the header at the end */
++	if(!skip_all && (no_plan || !have_plan)) {
++		printf("1..%d\n", test_count);
++	}
++
++	if((have_plan && !no_plan) && e_tests < test_count) {
++		diag("Looks like you planned %d %s but ran %d extra.",
++		     e_tests, e_tests == 1 ? "test" : "tests", test_count - e_tests);
++		UNLOCK;
++		return;
++	}
++
++	if((have_plan || !no_plan) && e_tests > test_count) {
++		diag("Looks like you planned %d %s but only ran %d.",
++		     e_tests, e_tests == 1 ? "test" : "tests", test_count);
++		UNLOCK;
++		return;
++	}
++
++	if(failures)
++		diag("Looks like you failed %d %s of %d.",
++		     failures, failures == 1 ? "test" : "tests", test_count);
++
++	UNLOCK;
++}
+diff --git a/tests/utils/tap/tap.h b/tests/utils/tap/tap.h
+new file mode 100644
+index 0000000..0f05943
+--- /dev/null
++++ b/tests/utils/tap/tap.h
+@@ -0,0 +1,89 @@
++/*-
++ * Copyright (c) 2004 Nik Clayton
++ * All rights reserved.
++ *
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 1. Redistributions of source code must retain the above copyright
++ *    notice, this list of conditions and the following disclaimer.
++ * 2. Redistributions in binary form must reproduce the above copyright
++ *    notice, this list of conditions and the following disclaimer in the
++ *    documentation and/or other materials provided with the distribution.
++ *
++ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
++ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
++ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
++ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
++ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
++ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
++ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
++ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
++ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
++ * SUCH DAMAGE.
++ */
++
++/* '## __VA_ARGS__' is a gcc'ism. C99 doesn't allow the token pasting
++   and requires the caller to add the final comma if they've ommitted
++   the optional arguments */
++#ifdef __GNUC__
++# define ok(e, test, ...) ((e) ?					\
++			   _gen_result(1, __func__, __FILE__, __LINE__,	\
++				       test, ## __VA_ARGS__) :		\
++			   _gen_result(0, __func__, __FILE__, __LINE__,	\
++				       test, ## __VA_ARGS__))
++
++# define ok1(e) ((e) ?							\
++		 _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
++		 _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
++
++# define pass(test, ...) ok(1, test, ## __VA_ARGS__);
++# define fail(test, ...) ok(0, test, ## __VA_ARGS__);
++
++# define skip_start(test, n, fmt, ...)			\
++	do {						\
++		if((test)) {				\
++			skip(n, fmt, ## __VA_ARGS__);	\
++			continue;			\
++		}
++#elif __STDC_VERSION__ >= 199901L /* __GNUC__ */
++# define ok(e, ...) ((e) ?						\
++		     _gen_result(1, __func__, __FILE__, __LINE__,	\
++				 __VA_ARGS__) :				\
++		     _gen_result(0, __func__, __FILE__, __LINE__,	\
++				 __VA_ARGS__))
++
++# define ok1(e) ((e) ?							\
++		 _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
++		 _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
++
++# define pass(...) ok(1, __VA_ARGS__);
++# define fail(...) ok(0, __VA_ARGS__);
++
++# define skip_start(test, n, ...)			\
++	do {						\
++		if((test)) {				\
++			skip(n,  __VA_ARGS__);		\
++			continue;			\
++		}
++#else /* __STDC_VERSION__ */
++# error "Needs gcc or C99 compiler for variadic macros."
++#endif /* __STDC_VERSION__ */
++
++#define skip_end() } while(0);
++
++unsigned int _gen_result(int, const char *, char *, unsigned int, char *, ...);
++
++int plan_no_plan(void);
++int plan_skip_all(char *);
++int plan_tests(unsigned int);
++
++unsigned int diag(char *, ...);
++
++int skip(unsigned int, char *, ...);
++
++void todo_start(char *, ...);
++void todo_end(void);
++
++int exit_status(void);
+diff --git a/tests/utils/tap/tap.sh b/tests/utils/tap/tap.sh
+new file mode 100755
+index 0000000..24ac1aa
+--- /dev/null
++++ b/tests/utils/tap/tap.sh
+@@ -0,0 +1,456 @@
++#!/bin/bash
++#
++# Copyright 2010 Patrick LeBoutillier <patrick.leboutillier at gmail.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 3 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, see <http://www.gnu.org/licenses/>.
++
++
++_version='1.01'
++
++_plan_set=0
++_no_plan=0
++_skip_all=0
++_test_died=0
++_expected_tests=0
++_executed_tests=0
++_failed_tests=0
++TODO=
++
++
++usage(){
++    cat <<'USAGE'
++tap-functions: A TAP-producing BASH library
++
++PLAN:
++  plan_no_plan
++  plan_skip_all [REASON]
++  plan_tests NB_TESTS
++
++TEST:
++  ok RESULT [NAME]
++  okx COMMAND
++  is RESULT EXPECTED [NAME]
++  isnt RESULT EXPECTED [NAME]
++  like RESULT PATTERN [NAME]
++  unlike RESULT PATTERN [NAME]
++  pass [NAME]
++  fail [NAME]
++
++SKIP:
++  skip [CONDITION] [REASON] [NB_TESTS=1]
++
++  skip $feature_not_present "feature not present" 2 || {
++      is $a "a"
++      is $b "b"
++  }
++
++TODO:
++  Specify TODO mode by setting $TODO:
++    TODO="not implemented yet"
++    ok $result "some not implemented test"
++    unset TODO
++
++OTHER:
++  diag MSG
++
++EXAMPLE:
++  #!/bin/bash
++
++  . tap-functions
++
++  plan_tests 7
++
++  me=$USER
++  is $USER $me "I am myself"
++  like $HOME $me "My home is mine"
++  like "`id`" $me "My id matches myself"
++
++  /bin/ls $HOME 1>&2
++  ok $? "/bin/ls $HOME"
++  # Same thing using okx shortcut
++  okx /bin/ls $HOME
++
++  [[ "`id -u`" != "0" ]]
++  i_am_not_root=$?
++  skip $i_am_not_root "Must be root" || {
++    okx ls /root
++  }
++
++  TODO="figure out how to become root..."
++  okx [ "$HOME" == "/root" ]
++  unset TODO
++USAGE
++    exit
++}
++
++opt=
++set_u=
++while getopts ":sx" opt ; do
++    case $_opt in
++        u) set_u=1 ;;
++        *) usage ;;
++    esac
++done
++shift $(( OPTIND - 1 ))
++# Don't allow uninitialized variables if requested
++[[ -n "$set_u" ]] && set -u
++unset opt set_u
++
++# Used to call _cleanup on shell exit
++trap _exit EXIT
++
++
++plan_no_plan(){
++    (( _plan_set != 0 )) && "You tried to plan twice!"
++
++    _plan_set=1
++    _no_plan=1
++
++    return 0
++}
++
++
++plan_skip_all(){
++    local reason=${1:-''}
++
++    (( _plan_set != 0 )) && _die "You tried to plan twice!"
++
++    _print_plan 0 "Skip $reason"
++
++    _skip_all=1
++    _plan_set=1
++    _exit 0
++
++    return 0
++}
++
++plan_tests(){
++    local tests=${1:?}
++
++    (( _plan_set != 0 )) && _die "You tried to plan twice!"
++    (( tests == 0 )) && _die "You said to run 0 tests!  You've got to run something."
++
++    _print_plan $tests
++    _expected_tests=$tests
++    _plan_set=1
++
++    return $tests
++}
++
++
++_print_plan(){
++    local tests=${1:?}
++    local directive=${2:-''}
++
++    echo -n "1..$tests"
++    [[ -n "$directive" ]] && echo -n " # $directive"
++    echo
++}
++
++
++pass(){
++    local name=$1
++    ok 0 "$name"
++}
++
++
++fail(){
++    local name=$1
++    ok 1 "$name"
++}
++
++# This is the workhorse method that actually
++# prints the tests result.
++ok(){
++    local result=${1:?}
++    local name=${2:-''}
++
++    (( _plan_set == 0 )) && _die "You tried to run a test without a plan!  Gotta have a plan."
++
++    _executed_tests=$(( $_executed_tests + 1 ))
++
++    if [[ -n "$name" ]] ; then
++        if _matches "$name" "^[0-9]+$" ; then
++            diag "    You named your test '$name'.  You shouldn't use numbers for your test names."
++            diag "    Very confusing."
++        fi
++    fi
++
++    if (( result != 0 )) ; then
++        echo -n "not "
++        _failed_tests=$(( _failed_tests + 1 ))
++    fi
++    echo -n "ok $_executed_tests"
++
++    if [[ -n "$name" ]] ; then
++        local ename=${name//\#/\\#}
++        echo -n " - $ename"
++    fi
++
++    if [[ -n "$TODO" ]] ; then
++        echo -n " # TODO $TODO" ;
++        if (( result != 0 )) ; then
++            _failed_tests=$(( _failed_tests - 1 ))
++        fi
++    fi
++
++    echo
++    if (( result != 0 )) ; then
++        local file='tap-functions'
++        local func=
++        local line=
++
++        local i=0
++        local bt=$(caller $i)
++        while _matches "$bt" "tap-functions$" ; do
++            i=$(( $i + 1 ))
++            bt=$(caller $i)
++        done
++        local backtrace=
++        eval $(caller $i | (read line func file ; echo "backtrace=\"$file:$func() at line $line.\""))
++
++        local t=
++        [[ -n "$TODO" ]] && t="(TODO) "
++
++        if [[ -n "$name" ]] ; then
++            diag "  Failed ${t}test '$name'"
++            diag "  in $backtrace"
++        else
++            diag "  Failed ${t}test in $backtrace"
++        fi
++    fi
++
++    return $result
++}
++
++
++okx(){
++    local command="$@"
++
++    local line=
++    diag "Output of '$command':"
++    "$@" | while read line ; do
++        diag "$line"
++    done
++    ok ${PIPESTATUS[0]} "$command"
++}
++
++
++_equals(){
++    local result=${1:?}
++    local expected=${2:?}
++
++    if [[ "$result" == "$expected" ]] ; then
++        return 0
++    else
++        return 1
++    fi
++}
++
++
++# Thanks to Aaron Kangas for the patch to allow regexp matching
++# under bash < 3.
++ _bash_major_version=${BASH_VERSION%%.*}
++_matches(){
++    local result=${1:?}
++    local pattern=${2:?}
++
++    if [[ -z "$result" || -z "$pattern" ]] ; then
++        return 1
++    else
++        if (( _bash_major_version >= 3 )) ; then
++            [[ "$result" =~ "$pattern" ]]
++        else
++            echo "$result" | egrep -q "$pattern"
++        fi
++    fi
++}
++
++
++_is_diag(){
++    local result=${1:?}
++    local expected=${2:?}
++
++    diag "         got: '$result'"
++    diag "    expected: '$expected'"
++}
++
++
++is(){
++    local result=${1:?}
++    local expected=${2:?}
++    local name=${3:-''}
++
++    _equals "$result" "$expected"
++    (( $? == 0 ))
++    ok $? "$name"
++    local r=$?
++    (( r != 0 )) && _is_diag "$result" "$expected"
++    return $r
++}
++
++
++isnt(){
++    local result=${1:?}
++    local expected=${2:?}
++    local name=${3:-''}
++
++    _equals "$result" "$expected"
++    (( $? != 0 ))
++    ok $? "$name"
++    local r=$?
++    (( r != 0 )) && _is_diag "$result" "$expected"
++    return $r
++}
++
++
++like(){
++    local result=${1:?}
++    local pattern=${2:?}
++    local name=${3:-''}
++
++    _matches "$result" "$pattern"
++    (( $? == 0 ))
++    ok $? "$name"
++    local r=$?
++    (( r != 0 )) && diag "    '$result' doesn't match '$pattern'"
++    return $r
++}
++
++
++unlike(){
++    local result=${1:?}
++    local pattern=${2:?}
++    local name=${3:-''}
++
++    _matches "$result" "$pattern"
++    (( $? != 0 ))
++    ok $? "$name"
++    local r=$?
++    (( r != 0 )) && diag "    '$result' matches '$pattern'"
++    return $r
++}
++
++
++skip(){
++    local condition=${1:?}
++    local reason=${2:-''}
++    local n=${3:-1}
++
++    if (( condition == 0 )) ; then
++        local i=
++        for (( i=0 ; i<$n ; i++ )) ; do
++            _executed_tests=$(( _executed_tests + 1 ))
++            echo "ok $_executed_tests # skip: $reason"
++        done
++        return 0
++    else
++        return
++    fi
++}
++
++
++diag(){
++    local msg=${1:?}
++
++    if [[ -n "$msg" ]] ; then
++        echo "# $msg"
++    fi
++
++    return 1
++}
++
++
++_die(){
++    local reason=${1:-'<unspecified error>'}
++
++    echo "$reason" >&2
++    _test_died=1
++    _exit 255
++}
++
++
++BAIL_OUT(){
++    local reason=${1:-''}
++
++    echo "Bail out! $reason" >&2
++    _exit 255
++}
++
++
++_cleanup(){
++    local rc=0
++
++    if (( _plan_set == 0 )) ; then
++        diag "Looks like your test died before it could output anything."
++        return $rc
++    fi
++
++    if (( _test_died != 0 )) ; then
++        diag "Looks like your test died just after $_executed_tests."
++        return $rc
++    fi
++
++    if (( _skip_all == 0 && _no_plan != 0 )) ; then
++        _print_plan $_executed_tests
++    fi
++
++    local s=
++    if (( _no_plan == 0 && _expected_tests < _executed_tests )) ; then
++        s= ; (( _expected_tests > 1 )) && s=s
++        local extra=$(( _executed_tests - _expected_tests ))
++        diag "Looks like you planned $_expected_tests test$s but ran $extra extra."
++        rc=1 ;
++    fi
++
++    if (( _no_plan == 0 && _expected_tests > _executed_tests )) ; then
++        s= ; (( _expected_tests > 1 )) && s=s
++        diag "Looks like you planned $_expected_tests test$s but only ran $_executed_tests."
++    fi
++
++    if (( _failed_tests > 0 )) ; then
++        s= ; (( _failed_tests > 1 )) && s=s
++        diag "Looks like you failed $_failed_tests test$s of $_executed_tests."
++    fi
++
++    return $rc
++}
++
++
++_exit_status(){
++    if (( _no_plan != 0 || _plan_set == 0 )) ; then
++        return $_failed_tests
++    fi
++
++    if (( _expected_tests < _executed_tests )) ; then
++        return $(( _executed_tests - _expected_tests  ))
++    fi
++
++    return $(( _failed_tests + ( _expected_tests - _executed_tests )))
++}
++
++
++_exit(){
++    local rc=${1:-''}
++    if [[ -z "$rc" ]] ; then
++        _exit_status
++        rc=$?
++    fi
++
++    _cleanup
++    local alt_rc=$?
++    (( alt_rc != 0 )) && rc=$alt_rc
++    trap - EXIT
++    exit $rc
++}
+diff --git a/tests/utils/utils.c b/tests/utils/utils.c
+new file mode 100644
+index 0000000..acc8427
+--- /dev/null
++++ b/tests/utils/utils.c
+@@ -0,0 +1,18 @@
++/*
++ * Copyright (C) 2014 - David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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 "utils.h"
+diff --git a/tests/utils/utils.h b/tests/utils/utils.h
+new file mode 100644
+index 0000000..951ce43
+--- /dev/null
++++ b/tests/utils/utils.h
+@@ -0,0 +1,29 @@
++/*
++ * Copyright (C) 2014 - David Goulet <dgoulet at ev0ke.net>
++ *
++ * This program is free software; you can redistribute it and/or modify it
++ * under the terms of the GNU General Public License, version 2 only, as
++ * published by the Free Software Foundation.
++ *
++ * 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.
++ */
++
++#ifndef TESTS_UTILS_H
++#define TESTS_UTILS_H
++
++/*
++ * Return 1 if the given buffer is zeroed or 0 if not.
++ */
++static inline int utils_is_zeroed(const unsigned char *buf, size_t size)
++{
++	return buf[0] == 0 && !memcmp(buf, buf + 1, size - 1);
++}
++
++#endif /* TESTS_UTILS_H */
diff --git a/debian/patches/series b/debian/patches/series
index 61fc09a..f5dc156 100644
--- a/debian/patches/series
+++ b/debian/patches/series
@@ -1 +1,2 @@
 0001-Do-not-error-out-when-an-application-is-run-against-.patch
+0002-Test-Add-new-test-suite-in-tests.patch

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-privacy/packages/libotr.git



More information about the Pkg-privacy-commits mailing list