Index: freeDiameter/CMakeLists.txt
===================================================================
--- freeDiameter/CMakeLists.txt	(revision 13)
+++ freeDiameter/CMakeLists.txt	(revision 16)
@@ -27,4 +27,8 @@
 	)
 
+# Require GNU TLS for building the daemon
+FIND_PACKAGE(GNUTLS REQUIRED)
+INCLUDE_DIRECTORIES(${GNUTLS_INCLUDE_DIRS})
+SET(FD_LIBS ${FD_LIBS} ${GNUTLS_LIBRARIES})
 
 # Building the executable
Index: freeDiameter/fD.h
===================================================================
--- freeDiameter/fD.h	(revision 14)
+++ freeDiameter/fD.h	(revision 16)
@@ -151,9 +151,9 @@
 /* Events codespace for struct fd_peer->p_events */
 enum {
+	/* Dump all info about this peer in the debug log */
+	 FDEVP_DUMP_ALL = 2000
+	
 	/* request to terminate this peer : disconnect, requeue all messages */
-	 FDEVP_TERMINATE = 2000
-	
-	/* Dump all info about this peer in the debug log */
-	,FDEVP_DUMP_ALL
+	,FDEVP_TERMINATE
 	
 	/* A message was received in the peer */
@@ -164,4 +164,6 @@
 };
 const char * fd_pev_str(int event);
+#define CHECK_EVENT( _e ) \
+	(((int)(_e) >= FDEVP_DUMP_ALL) && ((int)(_e) <= FDEVP_PSM_TIMEOUT))
 
 /* Structure to store a sent request */
@@ -174,4 +176,7 @@
 int fd_peer_fini();
 void fd_peer_dump_list(int details);
+void fd_peer_dump(struct fd_peer * peer, int details);
+int fd_peer_alloc(struct fd_peer ** ptr);
+int fd_peer_free(struct fd_peer ** ptr);
 /* fd_peer_add declared in freeDiameter.h */
 
Index: freeDiameter/main.c
===================================================================
--- freeDiameter/main.c	(revision 14)
+++ freeDiameter/main.c	(revision 16)
@@ -38,4 +38,10 @@
 #include <signal.h>
 #include <getopt.h>
+#include <locale.h>
+
+#ifdef GCRY_THREAD_OPTION_PTHREAD_IMPL
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+#endif /* GCRY_THREAD_OPTION_PTHREAD_IMPL */
+
 
 /* forward declarations */
@@ -62,4 +68,5 @@
 	/* Initialize the library */
 	CHECK_FCT( fd_lib_init() );
+	TRACE_DEBUG(INFO, "libfreeDiameter initialized.");
 	
 	/* Name this thread */
@@ -71,4 +78,13 @@
 	/* Parse the command-line */
 	CHECK_FCT(  main_cmdline(argc, argv)  );
+	
+	/* Initialize gnutls */
+	CHECK_GNUTLS_DO( gnutls_global_init(), return EINVAL );
+	if ( ! gnutls_check_version(GNUTLS_VERSION) ) {
+		fprintf(stderr, "The GNUTLS library is too old; found '%s', need '" GNUTLS_VERSION "'\n", gnutls_check_version(NULL));
+		return EINVAL;
+	} else {
+		TRACE_DEBUG(INFO, "GNUTLS library '%s' initialized.", gnutls_check_version(NULL));
+	}
 	
 	/* Allow SIGINT and SIGTERM from this point */
@@ -141,4 +157,6 @@
 	
 	CHECK_FCT_DO( fd_thr_term(&sig_th), /* continue */ );
+	
+	gnutls_global_deinit();
 	
 	return ret;
@@ -168,12 +186,14 @@
 	int c;
 	int option_index = 0;
+	char * locale;
 	
       	struct option long_options[] = {
-		{ "help",	0, NULL, 'h' },
-		{ "version",	0, NULL, 'V' },
-		{ "config",	1, NULL, 'c' },
-		{ "debug",	0, NULL, 'd' },
-		{ "quiet",	0, NULL, 'q' },
-		{ NULL,	0, NULL, 0 }
+		{ "help",	no_argument, 		NULL, 'h' },
+		{ "version",	no_argument, 		NULL, 'V' },
+		{ "config",	required_argument, 	NULL, 'c' },
+		{ "debug",	no_argument, 		NULL, 'd' },
+		{ "quiet",	no_argument, 		NULL, 'q' },
+		{ "dbglocale",	optional_argument, 	NULL, 'l' },
+		{ NULL,		0, 			NULL, 0 }
 	};
 	
@@ -182,5 +202,5 @@
 	/* Loop on arguments */
 	while (1) {
-		c = getopt_long (argc, argv, "hVc:dq", long_options, &option_index);
+		c = getopt_long (argc, argv, "hVc:dql:", long_options, &option_index);
 		if (c == -1) 
 			break;	/* Exit from the loop.  */
@@ -200,4 +220,14 @@
 				break;
 
+			case 'l':	/* Change the locale.  */
+				locale = setlocale(LC_ALL, optarg?:"");
+				if (locale) {
+					TRACE_DEBUG(INFO, "Locale set to: %s", optarg ?: locale);
+				} else {
+					TRACE_DEBUG(INFO, "Unable to set locale (%s)", optarg);
+					return EINVAL;
+				}
+				break;
+
 			case 'd':	/* Increase verbosity of debug messages.  */
 				fd_g_debug_lvl++;
@@ -210,9 +240,9 @@
 			case '?':	/* Invalid option.  */
 				/* `getopt_long' already printed an error message.  */
-				TRACE_DEBUG(INFO, "getopt_long found an invalid character\n");
+				TRACE_DEBUG(INFO, "getopt_long found an invalid character");
 				return EINVAL;
 
 			default:	/* bug: option not considered.  */
-				TRACE_DEBUG(INFO, "A command-line option is missing in parser: %c\n", c);
+				TRACE_DEBUG(INFO, "A command-line option is missing in parser: %c", c);
 				ASSERT(0);
 				return EINVAL;
@@ -267,4 +297,5 @@
  	printf( "\nDebug:\n"
   		"  These options are mostly useful for developers\n"
+  		"  -l, --dbglocale        Set the locale for error messages\n"
   		"  -d, --debug            Increase verbosity of debug messages\n"
   		"  -q, --quiet            Decrease verbosity then remove debug messages\n");
Index: freeDiameter/p_expiry.c
===================================================================
--- freeDiameter/p_expiry.c	(revision 14)
+++ freeDiameter/p_expiry.c	(revision 16)
@@ -36,8 +36,60 @@
 #include "fD.h"
 
+/* Delay for garbage collection of expired threads, in seconds */
+#define GC_TIME		60
+
 static pthread_t       exp_thr;
+static pthread_t       gc_thr;
 static struct fd_list  exp_list = FD_LIST_INITIALIZER( exp_list );
 static pthread_cond_t  exp_cnd  = PTHREAD_COND_INITIALIZER;
 static pthread_mutex_t exp_mtx  = PTHREAD_MUTEX_INITIALIZER;
+
+static void * gc_th_fct(void * arg)
+{
+	fd_log_threadname ( "Peers/garbage" );
+	TRACE_ENTRY( "" );
+	
+	do {
+		struct fd_list * li, purge = FD_LIST_INITIALIZER(purge);
+		
+		pthread_testcancel();
+		sleep(GC_TIME);
+		
+		/* Now check in the peers list if any peer can be deleted */
+		CHECK_FCT_DO( pthread_rwlock_wrlock(&fd_g_peers_rw), goto error );
+		
+		for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
+			struct fd_peer * peer = (struct fd_peer *)li;
+			
+			if (peer->p_hdr.info.pi_state != STATE_ZOMBIE)
+				continue;
+			
+			if (peer->p_hdr.info.pi_flags.exp == PI_EXP_NONE)
+				continue; /* This peer was not supposed to expire, keep it in the list */
+			
+			/* Ok, the peer was expired, let's remove it */
+			li = li->prev; /* to avoid breaking the loop */
+			fd_list_unlink(&peer->p_hdr.chain);
+			fd_list_insert_before(&purge, &peer->p_hdr.chain);
+		}
+
+		CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), goto error );
+		
+		/* Now delete peers that are in the purge list */
+		while (!FD_IS_LIST_EMPTY(&purge)) {
+			struct fd_peer * peer = (struct fd_peer *)(purge.next);
+			fd_list_unlink(&peer->p_hdr.chain);
+			TRACE_DEBUG(INFO, "Garbage Collect: delete zombie peer '%s'", peer->p_hdr.info.pi_diamid);
+			CHECK_FCT_DO( fd_peer_free(&peer), /* Continue... what else to do ? */ );
+		}
+	} while (1);
+	
+error:
+	TRACE_DEBUG(INFO, "An error occurred in peers module! GC thread is terminating...");
+	ASSERT(0);
+	CHECK_FCT_DO(fd_event_send(fd_g_config->cnf_main_ev, FDEV_TERMINATE, NULL), );
+	return NULL;
+}
+
 
 static void * exp_th_fct(void * arg)
@@ -98,4 +150,5 @@
 	TRACE_ENTRY();
 	CHECK_FCT( pthread_create( &exp_thr, NULL, exp_th_fct, NULL ) );
+	CHECK_FCT( pthread_create( &gc_thr,  NULL, gc_th_fct,  NULL ) );
 	return 0;
 }
@@ -113,4 +166,5 @@
 	
 	CHECK_POSIX( pthread_mutex_unlock(&exp_mtx) );
+	CHECK_FCT_DO( fd_thr_term(&gc_thr), );
 	return 0;
 }
Index: freeDiameter/p_psm.c
===================================================================
--- freeDiameter/p_psm.c	(revision 14)
+++ freeDiameter/p_psm.c	(revision 16)
@@ -37,5 +37,5 @@
 
 const char *peer_state_str[] = { 
-	  "STATE_ZOMBIE"
+	  "STATE_NEW"
 	, "STATE_OPEN"
 	, "STATE_CLOSED"
@@ -46,4 +46,5 @@
 	, "STATE_SUSPECT"
 	, "STATE_REOPEN"
+	, "STATE_ZOMBIE"
 	};
 
@@ -123,4 +124,5 @@
 }
 
+/* Wait for the next event in the PSM, or timeout */
 static int psm_ev_timedget(struct fd_peer * peer, int *code, void ** data)
 {
@@ -142,11 +144,13 @@
 	
 	return 0;
-}	
-
-/* The state machine thread */
+}
+
+/* The state machine thread (controler) */
 static void * p_psm_th( void * arg )
 {
 	struct fd_peer * peer = (struct fd_peer *)arg;
 	int created_started = started;
+	int event;
+	void * ev_data;
 	
 	CHECK_PARAMS_DO( CHECK_PEER(peer), ASSERT(0) );
@@ -161,9 +165,9 @@
 	}
 	
-	/* Wait that the PSM are authorized to start in the daemon */
-	CHECK_FCT_DO( fd_psm_waitstart(), goto end );
-	
 	/* The state machine starts in CLOSED state */
 	peer->p_hdr.info.pi_state = STATE_CLOSED;
+	
+	/* Wait that the PSM are authorized to start in the daemon */
+	CHECK_FCT_DO( fd_psm_waitstart(), goto psm_end );
 	
 	/* Initialize the timer */
@@ -174,25 +178,66 @@
 	}
 	
-psm:
-	do {
-		int event;
-		void * ev_data;
-		
-		/* Get next event */
-		CHECK_FCT_DO( psm_ev_timedget(peer, &event, &ev_data), goto end );
-		TRACE_DEBUG(FULL, "'%s'\t<-- '%s'\t(%p)\t'%s'",
-				STATE_STR(peer->p_hdr.info.pi_state),
-				fd_pev_str(event), ev_data,
-				peer->p_hdr.info.pi_diamid);
-		
-		/* Now, the action depends on the current state and the incoming event */
-		
-	
-	} while (1);	
-	
-	
-end:	
-	/* set STATE_ZOMBIE */
-	pthread_cleanup_pop(1);
+psm_loop:
+	/* Get next event */
+	CHECK_FCT_DO( psm_ev_timedget(peer, &event, &ev_data), goto psm_end );
+	TRACE_DEBUG(FULL, "'%s'\t<-- '%s'\t(%p)\t'%s'",
+			STATE_STR(peer->p_hdr.info.pi_state),
+			fd_pev_str(event), ev_data,
+			peer->p_hdr.info.pi_diamid);
+
+	/* Now, the action depends on the current state and the incoming event */
+
+	/* The following two states are impossible */
+	ASSERT( peer->p_hdr.info.pi_state != STATE_NEW );
+	ASSERT( peer->p_hdr.info.pi_state != STATE_ZOMBIE );
+
+	/* Purge invalid events */
+	if (!CHECK_EVENT(event)) {
+		TRACE_DEBUG(INFO, "Invalid event received in PSM '%s' : %d", peer->p_hdr.info.pi_diamid, event);
+		goto psm_loop;
+	}
+
+	/* Handle the (easy) debug event now */
+	if (event == FDEVP_DUMP_ALL) {
+		fd_peer_dump(peer, ANNOYING);
+		goto psm_loop;
+	}
+
+	/* Requests to terminate the peer object */
+	if (event == FDEVP_TERMINATE) {
+		switch (peer->p_hdr.info.pi_state) {
+			case STATE_CLOSING:
+			case STATE_WAITCNXACK:
+			case STATE_WAITCNXACK_ELEC:
+			case STATE_WAITCEA:
+			case STATE_SUSPECT:
+				/* In these cases, we just cleanup the peer object and terminate now */
+				TODO("Cleanup the PSM: terminate connection object, ...");
+			case STATE_CLOSED:
+				/* Then we just terminate the PSM */
+				goto psm_end;
+				
+			case STATE_OPEN:
+			case STATE_REOPEN:
+				/* We cannot just close the conenction, we have to send a DPR first */
+				TODO("Send DPR, mark the peer as CLOSING");
+				goto psm_loop;
+		}
+	}
+	
+	/* MSG_RECEIVED: fd_p_expi_update(struct fd_peer * peer ) */
+	/* If timeout or OPEN : call cb if defined */
+
+	/* Default action : the handling has not yet been implemented. */
+	TODO("Missing handler in PSM : '%s'\t<-- '%s'", STATE_STR(peer->p_hdr.info.pi_state), fd_pev_str(event));
+	if (event == FDEVP_PSM_TIMEOUT) {
+		/* We have not handled timeout in this state, let's postpone next alert */
+		psm_next_timeout(peer, 0, 60);
+	}
+	
+	goto psm_loop;
+	
+psm_end:
+	pthread_cleanup_pop(1); /* set STATE_ZOMBIE */
 	return NULL;
 }	
@@ -205,6 +250,13 @@
 {
 	TRACE_ENTRY("%p", peer);
-	TODO("");
-	return ENOTSUP;
+	
+	/* Check the peer and state are OK */
+	CHECK_PARAMS( CHECK_PEER(peer) && (peer->p_hdr.info.pi_state == STATE_NEW) );
+	
+	/* Create the PSM controler thread */
+	CHECK_POSIX( pthread_create( &peer->p_psm, NULL, p_psm_th, peer ) );
+	
+	/* We're done */
+	return 0;
 }
 
@@ -214,5 +266,9 @@
 	TRACE_ENTRY("%p", peer);
 	CHECK_PARAMS( CHECK_PEER(peer) );
-	CHECK_FCT( fd_event_send(peer->p_events, FDEVP_TERMINATE, NULL) );
+	if (peer->p_hdr.info.pi_state != STATE_ZOMBIE) {
+		CHECK_FCT( fd_event_send(peer->p_events, FDEVP_TERMINATE, NULL) );
+	} else {
+		TRACE_DEBUG(FULL, "Peer '%s' was already terminated", peer->p_hdr.info.pi_diamid);
+	}
 	return 0;
 }
@@ -225,5 +281,6 @@
 	TODO("Cancel IN thread");
 	TODO("Cancel OUT thread");
-	TODO("Cleanup the connection");
+	TODO("Cleanup the peer connection object");
+	TODO("Cleanup the message queues (requeue)");
 	return;
 }
Index: freeDiameter/peers.c
===================================================================
--- freeDiameter/peers.c	(revision 14)
+++ freeDiameter/peers.c	(revision 16)
@@ -36,61 +36,11 @@
 #include "fD.h"
 
+/* Global list of peers */
 struct fd_list   fd_g_peers = FD_LIST_INITIALIZER(fd_g_peers);
 pthread_rwlock_t fd_g_peers_rw = PTHREAD_RWLOCK_INITIALIZER;
 
-/* Terminate peer module (destroy all peers) */
-int fd_peer_fini()
-{
-	struct fd_list * li;
-	TRACE_ENTRY();
-	
-	CHECK_FCT_DO(fd_p_expi_fini(), /* continue */);
-	
-	TRACE_DEBUG(INFO, "Sending signal to terminate to all peer connections");
-	
-	CHECK_FCT_DO( pthread_rwlock_rdlock(&fd_g_peers_rw), /* continue */ );
-	/* For each peer in the list, ... */
-	for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
-		struct fd_peer * np = (struct fd_peer *)li;
-		CHECK_FCT_DO( fd_psm_terminate(np), /* continue */ );
-	}
-	CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
-	
-	TODO("Give some time to all PSM, then destroy remaining threads");
-	/* fd_psm_abord(struct fd_peer * peer ) */
-	
-	return 0;
-}
-
-/* Dump the list of peers */
-void fd_peer_dump_list(int details)
-{
-	struct fd_list * li;
-	
-	fd_log_debug("Dumping list of peers :\n");
-	CHECK_FCT_DO( pthread_rwlock_rdlock(&fd_g_peers_rw), /* continue */ );
-	
-	for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
-		struct fd_peer * np = (struct fd_peer *)li;
-		if (np->p_eyec != EYEC_PEER) {
-			fd_log_debug("  Invalid entry @%p !\n", li);
-			continue;
-		}
-		
-		fd_log_debug("   %s\t%s", STATE_STR(np->p_hdr.info.pi_state), np->p_hdr.info.pi_diamid);
-		if (details > INFO) {
-			fd_log_debug("\t(rlm:%s)", np->p_hdr.info.pi_realm);
-			if (np->p_hdr.info.pi_prodname)
-				fd_log_debug("\t['%s' %u]", np->p_hdr.info.pi_prodname, np->p_hdr.info.pi_firmrev);
-			fd_log_debug("\t(from %s)", np->p_dbgorig);
-		}
-		fd_log_debug("\n");
-	}
-	
-	CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
-}
 
 /* Alloc / reinit a peer structure. if *ptr is not NULL, it must already point to a valid struct fd_peer. */
-static int fd_sp_reinit(struct fd_peer ** ptr)
+int fd_peer_alloc(struct fd_peer ** ptr)
 {
 	struct fd_peer *p;
@@ -126,89 +76,4 @@
 }
 
-#define free_null( _v ) 	\
-	if (_v) {		\
-		free(_v);	\
-		(_v) = NULL;	\
-	}
-	
-#define free_list( _l ) 						\
-	while (!FD_IS_LIST_EMPTY(_l)) {					\
-		struct fd_list * __li = ((struct fd_list *)(_l))->next;	\
-		fd_list_unlink(__li);					\
-		free(__li);						\
-	}
-
-/* Destroy a structure once all cleanups have been performed */
-static int fd_sp_destroy(struct fd_peer ** ptr)
-{
-	struct fd_peer *p;
-	void * t;
-	
-	TRACE_ENTRY("%p", ptr);
-	CHECK_PARAMS(ptr);
-	p = *ptr;
-	*ptr = NULL;
-	CHECK_PARAMS(p);
-	
-	CHECK_PARAMS( FD_IS_LIST_EMPTY(&p->p_hdr.chain) );
-	
-	free_null(p->p_hdr.info.pi_diamid); 
-	free_null(p->p_hdr.info.pi_realm); 
-	free_list( &p->p_hdr.info.pi_endpoints );
-	/* Assume the security data is already freed */
-	free_null(p->p_hdr.info.pi_prodname);
-	free_list( &p->p_hdr.info.pi_apps );
-	
-	free_null(p->p_dbgorig);
-	ASSERT(FD_IS_LIST_EMPTY(&p->p_expiry));
-	ASSERT(FD_IS_LIST_EMPTY(&p->p_actives));
-	
-	CHECK_FCT( fd_thr_term(&p->p_psm) );
-	while ( fd_fifo_tryget(p->p_events, &t) == 0 ) {
-		struct fd_event * ev = t;
-		TRACE_DEBUG(FULL, "Found event %d(%p) in queue of peer %p being destroyed", ev->code, ev->data, p);
-		free(ev);
-	}
-	CHECK_FCT( fd_fifo_del(&p->p_events) );
-	
-	CHECK_FCT( fd_thr_term(&p->p_inthr) );
-	while ( fd_fifo_tryget(p->p_recv, &t) == 0 ) {
-		struct msg * m = t;
-		TRACE_DEBUG(FULL, "Found message %p in incoming queue of peer %p being destroyed", m, p);
-		/* We simply destroy, the remote peer will re-send to someone else...*/
-		CHECK_FCT(fd_msg_free(m));
-	}
-	CHECK_FCT( fd_fifo_del(&p->p_recv) );
-	
-	CHECK_FCT( fd_thr_term(&p->p_outthr) );
-	while ( fd_fifo_tryget(p->p_tosend, &t) == 0 ) {
-		struct msg * m = t;
-		TRACE_DEBUG(FULL, "Found message %p in outgoing queue of peer %p being destroyed, requeue", m, p);
-		/* We simply requeue in global, the routing thread will re-handle it. */
-		
-	}
-	CHECK_FCT( fd_fifo_del(&p->p_tosend) );
-	
-	while (!FD_IS_LIST_EMPTY(&p->p_sentreq)) {
-		struct sentreq * sr = (struct sentreq *)(p->p_sentreq.next);
-		fd_list_unlink(&sr->chain);
-		TRACE_DEBUG(FULL, "Found message %p in list of sent requests to peer %p being destroyed, requeue (fallback)", sr->req, p);
-		CHECK_FCT(fd_fifo_post(fd_g_outgoing, &sr->req));
-		free(sr);
-	}
-	
-	if (p->p_cnxctx) {
-		TODO("destroy p->p_cnxctx");
-	}
-	
-	if (p->p_cb)
-		(*p->p_cb)(NULL, p->p_cb_data);
-	
-	free(p);
-	
-	return 0;
-}
-
-
 /* Add a new peer entry */
 int fd_peer_add ( struct peer_info * info, char * orig_dbg, void (*cb)(struct peer_info *, void *), void * cb_data )
@@ -221,5 +86,5 @@
 	
 	/* Create a structure to contain the new peer information */
-	CHECK_FCT( fd_sp_reinit(&p) );
+	CHECK_FCT( fd_peer_alloc(&p) );
 	
 	/* Copy the informations from the parameters received */
@@ -248,7 +113,4 @@
 			fd_list_insert_before(&p->p_hdr.info.pi_endpoints, li);
 		}
-	
-	p->p_hdr.info.pi_sec_module = info->pi_sec_module;
-	memcpy(&p->p_hdr.info.pi_sec_data, &info->pi_sec_data, sizeof(info->pi_sec_data));
 	
 	/* The internal data */
@@ -286,5 +148,5 @@
 	CHECK_POSIX( pthread_rwlock_unlock(&fd_g_peers_rw) );
 	if (ret) {
-		CHECK_FCT( fd_sp_destroy(&p) );
+		CHECK_FCT( fd_peer_free(&p) );
 	} else {
 		CHECK_FCT( fd_psm_begin(p) );
@@ -292,2 +154,218 @@
 	return ret;
 }
+
+
+#define free_null( _v ) 	\
+	if (_v) {		\
+		free(_v);	\
+		(_v) = NULL;	\
+	}
+	
+#define free_list( _l ) 						\
+	while (!FD_IS_LIST_EMPTY(_l)) {					\
+		struct fd_list * __li = ((struct fd_list *)(_l))->next;	\
+		fd_list_unlink(__li);					\
+		free(__li);						\
+	}
+
+/* Destroy a structure once all cleanups have been performed */
+int fd_peer_free(struct fd_peer ** ptr)
+{
+	struct fd_peer *p;
+	void * t;
+	
+	TRACE_ENTRY("%p", ptr);
+	CHECK_PARAMS(ptr);
+	p = *ptr;
+	*ptr = NULL;
+	CHECK_PARAMS(p);
+	
+	CHECK_PARAMS( FD_IS_LIST_EMPTY(&p->p_hdr.chain) );
+	
+	free_null(p->p_hdr.info.pi_diamid); 
+	free_null(p->p_hdr.info.pi_realm); 
+	free_list( &p->p_hdr.info.pi_endpoints );
+	/* Assume the security data is already freed */
+	free_null(p->p_hdr.info.pi_prodname);
+	free_list( &p->p_hdr.info.pi_apps );
+	
+	free_null(p->p_dbgorig);
+	ASSERT(FD_IS_LIST_EMPTY(&p->p_expiry));
+	ASSERT(FD_IS_LIST_EMPTY(&p->p_actives));
+	
+	CHECK_FCT( fd_thr_term(&p->p_psm) );
+	while ( fd_fifo_tryget(p->p_events, &t) == 0 ) {
+		struct fd_event * ev = t;
+		TRACE_DEBUG(FULL, "Found event %d(%p) in queue of peer %p being destroyed", ev->code, ev->data, p);
+		free(ev);
+	}
+	CHECK_FCT( fd_fifo_del(&p->p_events) );
+	
+	CHECK_FCT( fd_thr_term(&p->p_inthr) );
+	while ( fd_fifo_tryget(p->p_recv, &t) == 0 ) {
+		struct msg * m = t;
+		TRACE_DEBUG(FULL, "Found message %p in incoming queue of peer %p being destroyed", m, p);
+		/* We simply destroy, the remote peer will re-send to someone else...*/
+		CHECK_FCT(fd_msg_free(m));
+	}
+	CHECK_FCT( fd_fifo_del(&p->p_recv) );
+	
+	CHECK_FCT( fd_thr_term(&p->p_outthr) );
+	while ( fd_fifo_tryget(p->p_tosend, &t) == 0 ) {
+		struct msg * m = t;
+		TRACE_DEBUG(FULL, "Found message %p in outgoing queue of peer %p being destroyed, requeue", m, p);
+		/* We simply requeue in global, the routing thread will re-handle it. */
+		
+	}
+	CHECK_FCT( fd_fifo_del(&p->p_tosend) );
+	
+	while (!FD_IS_LIST_EMPTY(&p->p_sentreq)) {
+		struct sentreq * sr = (struct sentreq *)(p->p_sentreq.next);
+		fd_list_unlink(&sr->chain);
+		TRACE_DEBUG(FULL, "Found message %p in list of sent requests to peer %p being destroyed, requeue (fallback)", sr->req, p);
+		CHECK_FCT(fd_fifo_post(fd_g_outgoing, &sr->req));
+		free(sr);
+	}
+	
+	if (p->p_cnxctx) {
+		TODO("destroy p->p_cnxctx");
+	}
+	
+	if (p->p_cb)
+		(*p->p_cb)(NULL, p->p_cb_data);
+	
+	free(p);
+	
+	return 0;
+}
+
+/* Terminate peer module (destroy all peers) */
+int fd_peer_fini()
+{
+	struct fd_list * li;
+	struct fd_list purge = FD_LIST_INITIALIZER(purge); /* Store zombie peers here */
+	int list_empty;
+	struct timespec	wait_until, now;
+	
+	TRACE_ENTRY();
+	
+	CHECK_FCT_DO(fd_p_expi_fini(), /* continue */);
+	
+	TRACE_DEBUG(INFO, "Sending terminate signal to all peer connections");
+	
+	CHECK_FCT_DO( pthread_rwlock_wrlock(&fd_g_peers_rw), /* continue */ );
+	for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
+		struct fd_peer * peer = (struct fd_peer *)li;
+		
+		if (peer->p_hdr.info.pi_state != STATE_ZOMBIE) {
+			CHECK_FCT_DO( fd_psm_terminate(peer), /* continue */ );
+		} else {
+			li = li->prev; /* to avoid breaking the loop */
+			fd_list_unlink(&peer->p_hdr.chain);
+			fd_list_insert_before(&purge, &peer->p_hdr.chain);
+		}
+	}
+	list_empty = FD_IS_LIST_EMPTY(&fd_g_peers);
+	CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
+	
+	if (!list_empty) {
+		CHECK_SYS(  clock_gettime(CLOCK_REALTIME, &now)  );
+		TRACE_DEBUG(INFO, "Waiting for connections shutdown... (%d sec max)", DPR_TIMEOUT);
+		wait_until.tv_sec  = now.tv_sec + DPR_TIMEOUT;
+		wait_until.tv_nsec = now.tv_nsec;
+	}
+	
+	while ((!list_empty) && (TS_IS_INFERIOR(&now, &wait_until))) {
+		
+		/* Allow the PSM(s) to execute */
+		pthread_yield();
+		
+		/* Remove zombie peers */
+		CHECK_FCT_DO( pthread_rwlock_wrlock(&fd_g_peers_rw), /* continue */ );
+		for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
+			struct fd_peer * peer = (struct fd_peer *)li;
+			if (peer->p_hdr.info.pi_state == STATE_ZOMBIE) {
+				li = li->prev; /* to avoid breaking the loop */
+				fd_list_unlink(&peer->p_hdr.chain);
+				fd_list_insert_before(&purge, &peer->p_hdr.chain);
+			}
+		}
+		list_empty = FD_IS_LIST_EMPTY(&fd_g_peers);
+		CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
+	}
+	
+	if (!list_empty) {
+		TRACE_DEBUG(INFO, "Forcing connections shutdown");
+		CHECK_FCT_DO( pthread_rwlock_wrlock(&fd_g_peers_rw), /* continue */ );
+		while (!FD_IS_LIST_EMPTY(&fd_g_peers)) {
+			struct fd_peer * peer = (struct fd_peer *)(fd_g_peers.next);
+			fd_psm_abord(peer);
+			fd_list_unlink(&peer->p_hdr.chain);
+			fd_list_insert_before(&purge, &peer->p_hdr.chain);
+		}
+		CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
+	}
+	
+	/* Free memory objects of all peers */
+	while (!FD_IS_LIST_EMPTY(&purge)) {
+		struct fd_peer * peer = (struct fd_peer *)(purge.next);
+		fd_list_unlink(&peer->p_hdr.chain);
+		fd_peer_free(&peer);
+	}
+	
+	return 0;
+}
+
+/* Dump info of one peer */
+void fd_peer_dump(struct fd_peer * peer, int details)
+{
+	if (peer->p_eyec != EYEC_PEER) {
+		fd_log_debug("  Invalid peer @ %p !\n", peer);
+		return;
+	}
+
+	fd_log_debug(">  %s\t%s", STATE_STR(peer->p_hdr.info.pi_state), peer->p_hdr.info.pi_diamid);
+	if (details > INFO) {
+		fd_log_debug("\t(rlm:%s)", peer->p_hdr.info.pi_realm);
+		if (peer->p_hdr.info.pi_prodname)
+			fd_log_debug("\t['%s' %u]", peer->p_hdr.info.pi_prodname, peer->p_hdr.info.pi_firmrev);
+	}
+	fd_log_debug("\n");
+	if (details > FULL) {
+		/* Dump all info */
+		fd_log_debug("\tEntry origin : %s\n", peer->p_dbgorig);
+		fd_log_debug("\tFlags : %s%s%s%s%s - %s%s%s\n", 
+				peer->p_hdr.info.pi_flags.pro3 == PI_P3_DEFAULT ? "" :
+					(peer->p_hdr.info.pi_flags.pro3 == PI_P3_IP ? "IP." : "IPv6."),
+				peer->p_hdr.info.pi_flags.pro4 == PI_P4_DEFAULT ? "" :
+					(peer->p_hdr.info.pi_flags.pro4 == PI_P4_TCP ? "TCP." : "SCTP."),
+				peer->p_hdr.info.pi_flags.alg ? "PrefTCP." : "",
+				peer->p_hdr.info.pi_flags.sec == PI_SEC_DEFAULT ? "" :
+					(peer->p_hdr.info.pi_flags.sec == PI_SEC_NONE ? "IPSec." : "InbandTLS."),
+				peer->p_hdr.info.pi_flags.exp ? "Expire." : "",
+				peer->p_hdr.info.pi_flags.inband & PI_INB_NONE ? "InbandIPsecOK." : "",
+				peer->p_hdr.info.pi_flags.inband & PI_INB_TLS ?  "InbandTLSOK." : "",
+				peer->p_hdr.info.pi_flags.relay ? "Relay (0xffffff)" : "No relay"
+				);
+		fd_log_debug("\tLifetime : %d sec\n", peer->p_hdr.info.pi_lft);
+		
+		TODO("Dump remaining useful information");
+	}
+}
+
+/* Dump the list of peers */
+void fd_peer_dump_list(int details)
+{
+	struct fd_list * li;
+	
+	fd_log_debug("Dumping list of peers :\n");
+	CHECK_FCT_DO( pthread_rwlock_rdlock(&fd_g_peers_rw), /* continue */ );
+	
+	for (li = fd_g_peers.next; li != &fd_g_peers; li = li->next) {
+		struct fd_peer * np = (struct fd_peer *)li;
+		fd_peer_dump(np, details);
+	}
+	
+	CHECK_FCT_DO( pthread_rwlock_unlock(&fd_g_peers_rw), /* continue */ );
+}
+
Index: include/freeDiameter/freeDiameter.h
===================================================================
--- include/freeDiameter/freeDiameter.h	(revision 14)
+++ include/freeDiameter/freeDiameter.h	(revision 16)
@@ -39,4 +39,22 @@
 
 #include <freeDiameter/libfreeDiameter.h>
+#include <gnutls/gnutls.h>
+#include <gnutls/x509.h>
+
+/* GNUTLS version */
+#ifndef GNUTLS_VERSION
+#define GNUTLS_VERSION LIBGNUTLS_VERSION
+#endif /* GNUTLS_VERSION */
+
+/* Check the return value of a GNUTLS function, log and propagate */
+#define CHECK_GNUTLS_DO( __call__, __fallback__ ) {						\
+	int __ret__;										\
+	TRACE_DEBUG_ALL( "Check FCT: " #__call__ );						\
+	__ret__ = (__call__);									\
+	if (__ret__ < 0) {									\
+		TRACE_DEBUG(INFO, "Error in '" #__call__ "':\t%s", gnutls_strerror(__ret__));	\
+		__fallback__;									\
+	}											\
+}
 
 
@@ -70,4 +88,9 @@
 		unsigned tls_alg: 1;	/* TLS algorithm for initiated cnx. 0: separate port. 1: inband-security (old) */
 	} 		 cnf_flags;
+	
+	struct {
+			/* GNUTLS global state */
+			/* Server credential(s) */
+	} 		 cnf_sec_data;
 	
 	uint32_t	 cnf_orstateid;	/* The value to use in Origin-State-Id, default to random value */
@@ -151,5 +174,5 @@
 enum peer_state {
 	/* Stable states */
-	STATE_ZOMBIE = 0,	/* The threads handling the peer are not running for some reason */
+	STATE_NEW = 0,		/* The peer has been just been created, PSM thread not started yet */
 	STATE_OPEN,		/* Connexion established */
 	
@@ -168,8 +191,12 @@
 	STATE_SUSPECT,		/* A DWR was sent and not answered within TwTime. Failover in progress. */
 	STATE_REOPEN,		/* Connection has been re-established, waiting for 3 DWR/DWA exchanges before putting back to service */
+	
+	/* Error state */
+	STATE_ZOMBIE		/* The PSM thread is not running anymore; it must be re-started or peer should be deleted. */
+#define STATE_MAX STATE_ZOMBIE
 };
 extern const char *peer_state_str[];
 #define STATE_STR(state) \
-	(((unsigned)(state)) <= STATE_REOPEN ? peer_state_str[((unsigned)(state)) ] : "<Invalid>")
+	(((unsigned)(state)) <= STATE_MAX ? peer_state_str[((unsigned)(state)) ] : "<Invalid>")
 
 /* Information about a remote peer. Same structure is used for creating a new entry, but not all fields are meaningful in that case */
@@ -220,21 +247,4 @@
 	
 	struct fd_list	pi_endpoints;	/* Endpoint(s) of the remote peer (configured, discovered, or advertized). list of struct fd_endpoint. DNS resolved if empty. */
-	
-	/* TLS specific data -- the exact data pointed here depends on the security module in use (ex: gnutls, ...) */
-	enum {
-		PI_SEC_GNUTLS = 0,	/* The security module is GNUTLS, this is the default */
-		PI_SEC_OTHER		/* Another security module (TBD) */
-	}		pi_sec_module;
-	union {
-		/* Security data when pi_sec_module == PI_SEC_GNUTLS */
-		struct {
-			void *	CA;	/* Authority to use to validate this peer credentials (a CA or root certificate) -- use default if NULL */
-			void *	cred;	/* The (valid) credentials that the peer has presented */
-		} 	gnutls;
-		/* Security data when pi_sec_module == PI_SEC_OTHER */
-		struct {
-			void * dummy;	/* Something meaningful for the other security module */
-		} 	other;
-	} 		pi_sec_data;
 	
 	/* The remaining information must not be modified, and is not used for peer creation */
@@ -245,4 +255,9 @@
 	uint32_t	pi_firmrev;	/* Content of the Firmware-Revision AVP */
 	struct fd_list	pi_apps;	/* applications advertised by the remote peer, except relay (pi_flags.relay) */
+	struct {
+		/* This is inspired from http://www.gnu.org/software/gnutls/manual/gnutls.html#ex_003ax509_002dinfo */
+		const gnutls_datum_t 	*cert_list; 	/* The (valid) credentials that the peer has presented */
+		unsigned int 		 cert_list_size;/* Number of certificates in the list */
+	} 		pi_sec_data;
 };
 
