Index: libfdproto/CMakeLists.txt
===================================================================
--- libfdproto/CMakeLists.txt	(revision 836)
+++ libfdproto/CMakeLists.txt	(revision 922)
@@ -6,4 +6,5 @@
 	fdproto-internal.h
 	dictionary.c
+	dictionary_functions.c
 	dispatch.c
 	fifo.c
Index: libfdproto/dictionary_functions.c
===================================================================
--- libfdproto/dictionary_functions.c	(revision 923)
+++ libfdproto/dictionary_functions.c	(revision 923)
@@ -0,0 +1,331 @@
+/*********************************************************************************************************
+* Software License Agreement (BSD License)                                                               *
+* Author: Sebastien Decugis <sdecugis@freediameter.net>							 *
+*													 *
+* Copyright (c) 2013, WIDE Project and NICT								 *
+* All rights reserved.											 *
+* 													 *
+* Redistribution and use of this software in source and binary forms, with or without modification, are  *
+* permitted provided that the following conditions are met:						 *
+* 													 *
+* * Redistributions of source code must retain the above 						 *
+*   copyright notice, this list of conditions and the 							 *
+*   following disclaimer.										 *
+*    													 *
+* * 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.								 *
+* 													 *
+* * Neither the name of the WIDE Project or NICT nor the 						 *
+*   names of its contributors may be used to endorse or 						 *
+*   promote products derived from this software without 						 *
+*   specific prior written permission of WIDE Project and 						 *
+*   NICT.												 *
+* 													 *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.								 *
+*********************************************************************************************************/
+
+#include "fdproto-internal.h"
+
+/* This file contains helpers functions to be reused as callbacks in the struct dict_type_data structure.
+There are three callbacks there:
+
+ - type_encode    :
+ - type_interpret :
+ 	  Those two callbacks allow to manipulate more natural structures of data in the code, and to 
+	map transparently these natural structures with the AVP-encoded format by calling the functions
+	msg_avp_value_encode or msg_avp_value_interpret.
+ - type_dump : 
+ 	  This callback if provided gives a more human-readable debug information.
+
+ */
+
+/****************************/
+/*    Address  AVP  type    */
+/****************************/
+
+/* The interpret and encode functions work with a "struct sockaddr_storage" pointer for mapping 
+the contents of the AVP */
+
+int fd_dictfct_Address_encode(void * data, union avp_value * avp_value)
+{
+	sSS * ss = (sSS *) data;
+	uint16_t AddressType = 0;
+	size_t	size = 0;
+	unsigned char * buf = NULL;
+	
+	TRACE_ENTRY("%p %p", data, avp_value);
+	CHECK_PARAMS( data && avp_value  );
+	
+	switch (ss->ss_family) {
+		case AF_INET:
+			{
+				/* We are encoding an IP address */
+				sSA4 * sin = (sSA4 *)ss;
+				
+				AddressType = 1;/* see http://www.iana.org/assignments/address-family-numbers/ */
+				size = 6;	/* 2 for AddressType + 4 for data */
+				
+				CHECK_MALLOC(  buf = malloc(size)  );
+				
+				/* may not work because of alignment: *(uint32_t *)(buf+2) = htonl(sin->sin_addr.s_addr); */
+				memcpy(buf + 2, &sin->sin_addr.s_addr, 4);
+			}
+			break;
+				
+		case AF_INET6:
+			{
+				/* We are encoding an IPv6 address */
+				sSA6 * sin6 = (sSA6 *)ss;
+				
+				AddressType = 2;/* see http://www.iana.org/assignments/address-family-numbers/ */
+				size = 18;	/* 2 for AddressType + 16 for data */
+				
+				CHECK_MALLOC(  buf = malloc(size)  );
+				
+				/* The order is already good here */
+				memcpy(buf + 2, &sin6->sin6_addr.s6_addr, 16);
+			}
+			break;
+				
+		default:
+			CHECK_PARAMS( AddressType = 0 );
+	}
+	
+	*(uint16_t *)buf = htons(AddressType);
+
+	avp_value->os.len = size;
+	avp_value->os.data = buf;
+	
+	return 0;
+}
+
+int fd_dictfct_Address_interpret(union avp_value * avp_value, void * interpreted)
+{
+	uint16_t AddressType = 0;
+	unsigned char * buf;
+	
+	TRACE_ENTRY("%p %p", avp_value, interpreted);
+	
+	CHECK_PARAMS( avp_value && interpreted && (avp_value->os.len >= 2)  );
+	
+	AddressType = ntohs(*(uint16_t *)avp_value->os.data);
+	buf = &avp_value->os.data[2];
+	
+	switch (AddressType) {
+		case 1 /* IP */:
+			{
+				sSA4 * sin = (sSA4 *)interpreted;
+				
+				CHECK_PARAMS(  avp_value->os.len == 6  );
+				
+				sin->sin_family = AF_INET;
+				/* sin->sin_addr.s_addr = ntohl( * (uint32_t *) buf); -- may not work because of bad alignment */
+				memcpy(&sin->sin_addr.s_addr, buf, 4);
+			}
+			break;
+				
+		case 2 /* IP6 */:
+			{
+				sSA6 * sin6 = (sSA6 *)interpreted;
+				
+				CHECK_PARAMS(  avp_value->os.len == 18  );
+				
+				sin6->sin6_family = AF_INET6;
+				memcpy(&sin6->sin6_addr.s6_addr, buf, 16);
+			}
+			break;
+				
+		default:
+			CHECK_PARAMS( AddressType = 0 );
+	}
+	
+	return 0;
+}
+
+/* Dump the content of an Address AVP */
+char * fd_dictfct_Address_dump(union avp_value * avp_value)
+{
+	char * ret;
+	#define STR_LEN	1024
+	union {
+		sSA	sa;
+		sSS	ss;
+		sSA4	sin;
+		sSA6	sin6;
+	} s;
+	uint16_t fam;
+	
+	memset(&s, 0, sizeof(s));
+	
+	CHECK_MALLOC_DO( ret = malloc(STR_LEN), return NULL );
+	
+	/* The first two octets represent the address family, http://www.iana.org/assignments/address-family-numbers/ */
+	if (avp_value->os.len < 2) {
+		snprintf(ret, STR_LEN, "[invalid length: %zd]", avp_value->os.len);
+		return ret;
+	}
+	
+	/* Following octets are the address in network byte order already */
+	fam = avp_value->os.data[0] << 8 | avp_value->os.data[1];
+	switch (fam) {
+		case 1:
+			/* IP */
+			s.sa.sa_family = AF_INET;
+			if (avp_value->os.len != 6) {
+				snprintf(ret, STR_LEN, "[invalid IP length: %zd]", avp_value->os.len);
+				return ret;
+			}
+			memcpy(&s.sin.sin_addr.s_addr, avp_value->os.data + 2, 4);
+			break;
+		case 2:
+			/* IP6 */
+			s.sa.sa_family = AF_INET6;
+			if (avp_value->os.len != 18) {
+				snprintf(ret, STR_LEN, "[invalid IP6 length: %zd]", avp_value->os.len);
+				return ret;
+			}
+			memcpy(&s.sin6.sin6_addr.s6_addr, avp_value->os.data + 2, 16);
+			break;
+		default:
+			snprintf(ret, STR_LEN, "[unsupported family: 0x%hx]", fam);
+			return ret;
+	}
+	
+	{
+		int rc = getnameinfo(&s.sa, sSAlen(&s.sa), ret, STR_LEN, NULL, 0, NI_NUMERICHOST);
+		if (rc)
+			snprintf(ret, STR_LEN, "%s", (char *)gai_strerror(rc));
+	}
+	
+	return ret;
+}
+
+
+
+/*******************************/
+/*    UTF8String  AVP  type    */
+/*******************************/
+
+/* Dump the AVP in a natural human-readable format */
+char * fd_dictfct_UTF8String_dump(union avp_value * avp_value)
+{
+#define TRUNC_LEN	42 /* avoid very long strings */
+	char * ret = strndup((char *)avp_value->os.data, TRUNC_LEN); 
+	if (ret && (*ret != '\0')) {
+		/* We sanitize the returned string to avoid UTF8 boundary problem.
+		We do this whether the string is trucated at TRUNC_LEN or not, to avoid potential problem
+		with malformed AVP */
+
+		char * end = strchr(ret, '\0');
+		
+		while (end > ret) {
+			end--;
+			char b = *end;
+			/* after the position pointed by end, we have only \0s */
+			if ((b & 0x80) == 0) {
+				break; /* this is a single byte char, no problem */
+			} else {
+				/* this byte is start or cont. of multibyte sequence, as we do not know the next byte we need to delete it. */
+				*end = '\0';
+				if (b & 0x40)
+					break; /* This was a start byte, we can stop the loop */
+			}
+		}
+	}	
+	return ret;
+}
+
+
+/*******************************/
+/*    Time  AVP  type    */
+/*******************************/
+
+/* The interpret and encode functions work with a "time_t" pointer for mapping 
+the contents of the AVP */
+
+/* Unix Epoch starts 1970-01-01, NTP 0 is at 1900-01-01 */
+#define DIFF_EPOCH_TO_NTP ((365*(1970-1900) + 17ul) * 24 * 60 * 60)
+
+static int diameter_string_to_time_t(const char *str, size_t len, time_t *result) {
+    time_t time_stamp;
+    CHECK_PARAMS(len == 4);
+   
+    time_stamp = (((unsigned long)(str[0]&0xff))<<24) + ((str[1]&0xff)<<16) + ((str[2]&0xff)<<8) + ((str[3]&0xff));
+    time_stamp -= DIFF_EPOCH_TO_NTP;
+#ifdef FIX__NEEDED_FOR_YEAR_2036_AND_LATER
+/* NTP overflows in 2036; after that, values start at zero again */
+#define NTP_OVERFLOW_CORRECTION (0x100000000ull)
+    /* XXX: debug and find correct conversion */
+    if (str[0] & 0x80 == 0x00) {
+        time_stamp += NTP_OVERFLOW_CORRECTION;
+    }
+#endif
+    *result = time_stamp;
+    return 0;
+}
+
+static int time_t_to_diameter_string(time_t time_stamp, char **result) {
+    uint64_t out = time_stamp;
+    char *conv;
+    /* XXX: 2036 fix */
+    out += DIFF_EPOCH_TO_NTP;
+    CHECK_PARAMS( (out & 0xffffffff00000000) == 0);
+
+    CHECK_MALLOC(conv=(char *)malloc(5));
+    
+    conv[0] = (out>>24) & 0xff;
+    conv[1] = (out>>16) & 0xff;
+    conv[2] = (out>> 8) & 0xff;
+    conv[3] =  out      & 0xff;
+    conv[4] = '\0';
+    *result = conv;
+    return 0;
+}
+
+int fd_dictfct_Time_encode(void * data, union avp_value * avp_value)
+{
+	char * buf;
+	size_t len;
+	
+	TRACE_ENTRY("%p %p", data, avp_value);
+	CHECK_PARAMS( data && avp_value  );
+	
+	CHECK_FCT( time_t_to_diameter_string( *((time_t *)data), &buf) );
+	/* FIXME: return len from the function above? */ len = 4;
+	
+	avp_value->os.len = len;
+	avp_value->os.data = buf;
+	return 0;
+}
+
+int fd_dictfct_Time_interpret(union avp_value * avp_value, void * interpreted)
+{
+	TRACE_ENTRY("%p %p", avp_value, interpreted);
+	
+	CHECK_PARAMS( avp_value && interpreted );
+	
+	return diameter_string_to_time_t(avp_value->os.data, avp_value->os.len, interpreted);
+}
+
+char * fd_dictfct_Time_dump(union avp_value * avp_value)
+{
+	char * ret;
+	CHECK_MALLOC_DO( ret = malloc(STR_LEN), return NULL );
+	if (avp_value->os.len != 4) {
+		snprintf(ret, STR_LEN, "[invalid length: %zd]", avp_value->os.len);
+		return ret;
+	}
+	/* TODO: display the time as human-readable */
+	snprintf(ret, STR_LEN, "[TODO Time dump: 0x%02hhx%02hhx%02hhx%02hhx]", avp_value->os.data[0], avp_value->os.data[1], avp_value->os.data[2], avp_value->os.data[3]);
+	return ret;
+}
+
Index: libfdproto/fdproto-internal.h
===================================================================
--- libfdproto/fdproto-internal.h	(revision 909)
+++ libfdproto/fdproto-internal.h	(revision 924)
@@ -70,4 +70,5 @@
 int fd_sess_reclaim_msg ( struct session ** session );
 
+
 /* For dump routines into string buffers */
 #include <stdarg.h>
Index: libfdproto/messages.c
===================================================================
--- libfdproto/messages.c	(revision 903)
+++ libfdproto/messages.c	(revision 951)
@@ -106,5 +106,5 @@
 #define _A(_x) ((struct avp *)(_x))
 /* Check the type and eyecatcher */
-#define CHECK_AVP(_x) ((_C(_x)->type == MSG_AVP) && (_A(_x)->avp_eyec == MSG_AVP_EYEC))
+#define CHECK_AVP(_x) ((_x) && (_C(_x)->type == MSG_AVP) && (_A(_x)->avp_eyec == MSG_AVP_EYEC))
 
 /* The following structure represents an instance of a message (command and children AVPs). */
@@ -239,5 +239,5 @@
 		if (new->avp_rawlen) {
 			CHECK_MALLOC(  new->avp_rawdata = malloc(new->avp_rawlen)  );
-			memset(new->avp_rawdata, 0xFF, new->avp_rawlen);
+			memset(new->avp_rawdata, 0x00, new->avp_rawlen);
 		}
 	}
@@ -683,8 +683,8 @@
 	struct tm tm;
 	
-	CHECK_FCT( dump_add_str(outstr, offset, outlen, "%*sMSG: %p\n", INOBJHDRVAL, msg) );
+	CHECK_FCT( dump_add_str(outstr, offset, outlen, "%*sMSG: %p|", INOBJHDRVAL, msg) );
 	
 	if (!CHECK_MSG(msg)) {
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "INVALID!\n", INOBJHDRVAL) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "INVALID!", INOBJHDRVAL) );
 		return 0;
 	}
@@ -693,15 +693,15 @@
 		tsoffset += strftime(buftime + tsoffset, sizeof(buftime) - tsoffset, "%D,%T", localtime_r( &msg->msg_ts_rcv.tv_sec , &tm ));
 		tsoffset += snprintf(buftime + tsoffset, sizeof(buftime) - tsoffset, ".%6.6ld", msg->msg_ts_rcv.tv_nsec / 1000);
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "Received: %s\n", INOBJHDRVAL, buftime) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "Received: %s|", INOBJHDRVAL, buftime) );
 	}
 	if ((msg->msg_ts_sent.tv_sec != 0) || (msg->msg_ts_sent.tv_nsec != 0)) {
 		tsoffset += strftime(buftime + tsoffset, sizeof(buftime) - tsoffset, "%D,%T", localtime_r( &msg->msg_ts_sent.tv_sec , &tm ));
 		tsoffset += snprintf(buftime + tsoffset, sizeof(buftime) - tsoffset, ".%6.6ld", msg->msg_ts_sent.tv_nsec / 1000);
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "Sent    : %s\n", INOBJHDRVAL, buftime) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "Sent    : %s|", INOBJHDRVAL, buftime) );
 	}
 	
 	if (!msg->msg_model) {
 		
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(no model)\n", INOBJHDRVAL) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(no model)|", INOBJHDRVAL) );
 		
 	} else {
@@ -711,17 +711,17 @@
 		ret = fd_dict_gettype(msg->msg_model, &dicttype);
 		if (ret || (dicttype != DICT_COMMAND)) {
-			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(invalid model: %d %d)\n", INOBJHDRVAL, ret, dicttype) );
+			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(invalid model: %d %d)|", INOBJHDRVAL, ret, dicttype) );
 			goto public;
 		}
 		ret = fd_dict_getval(msg->msg_model, &dictdata);
 		if (ret != 0) {
-			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(error getting model data: %s)\n", INOBJHDRVAL, strerror(ret)) );
+			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(error getting model data: %s)|", INOBJHDRVAL, strerror(ret)) );
 			goto public;
 		}
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "model : v/m:" DUMP_CMDFL_str "/" DUMP_CMDFL_str ", %u \"%s\"\n", INOBJHDRVAL, 
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "model : v/m:" DUMP_CMDFL_str "/" DUMP_CMDFL_str ", %u \"%s\"|", INOBJHDRVAL, 
 			DUMP_CMDFL_val(dictdata.cmd_flag_val), DUMP_CMDFL_val(dictdata.cmd_flag_mask), dictdata.cmd_code, dictdata.cmd_name) );
 	}
 public:	
-	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "public: V:%d L:%d fl:" DUMP_CMDFL_str " CC:%u A:%d hi:%x ei:%x\n", INOBJHDRVAL, 
+	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "public: V:%d L:%d fl:" DUMP_CMDFL_str " CC:%u A:%d hi:%x ei:%x|", INOBJHDRVAL, 
 		msg->msg_public.msg_version,
 		msg->msg_public.msg_length,
@@ -732,5 +732,5 @@
 		msg->msg_public.msg_eteid
 		) );
-	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "intern: rwb:%p rt:%d cb:%p(%p) qry:%p asso:%d sess:%p src:%s(%zd)\n", 
+	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "intern: rwb:%p rt:%d cb:%p(%p) qry:%p asso:%d sess:%p src:%s(%zd)|", 
 			INOBJHDRVAL, msg->msg_rawbuffer, msg->msg_routable, msg->msg_cb.fct, msg->msg_cb.data, msg->msg_query, msg->msg_associated, msg->msg_sess, msg->msg_src_id?:"(nil)", msg->msg_src_id_len) );
 	return 0;
@@ -743,5 +743,5 @@
 	
 	if (!CHECK_AVP(avp)) {
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "INVALID!\n", INOBJHDRVAL) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "INVALID!", INOBJHDRVAL) );
 		return 0;
 	}
@@ -749,5 +749,5 @@
 	if (!avp->avp_model) {
 		
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(no model resolved)\n", INOBJHDRVAL) );
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(no model resolved)|", INOBJHDRVAL) );
 		
 	} else {
@@ -757,13 +757,13 @@
 		ret = fd_dict_gettype(avp->avp_model, &dicttype);
 		if (ret || (dicttype != DICT_AVP)) {
-			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(invalid model: %d %d)\n", INOBJHDRVAL, ret, dicttype) );
+			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(invalid model: %d %d)|", INOBJHDRVAL, ret, dicttype) );
 			goto public;
 		}
 		ret = fd_dict_getval(avp->avp_model, &dictdata);
 		if (ret != 0) {
-			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(error getting model data: %s)\n", INOBJHDRVAL, strerror(ret)) );
+			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(error getting model data: %s)|", INOBJHDRVAL, strerror(ret)) );
 			goto public;
 		}
-		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "model : v/m:" DUMP_AVPFL_str "/" DUMP_AVPFL_str ", %12s, %u \"%s\"\n", INOBJHDRVAL, 
+		CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "model : v/m:" DUMP_AVPFL_str "/" DUMP_AVPFL_str ", %12s, %u \"%s\"|", INOBJHDRVAL, 
 			DUMP_AVPFL_val(dictdata.avp_flag_val), 
 			DUMP_AVPFL_val(dictdata.avp_flag_mask), 
@@ -773,5 +773,5 @@
 	}
 public:	
-	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "public: C:%u fl:" DUMP_AVPFL_str " L:%d V:%u  data:@%p\n", INOBJHDRVAL, 
+	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "public: C:%u fl:" DUMP_AVPFL_str " L:%d V:%u  data:@%p|", INOBJHDRVAL, 
 		avp->avp_public.avp_code,
 		DUMP_AVPFL_val(avp->avp_public.avp_flags),
@@ -783,5 +783,5 @@
 	if (avp->avp_public.avp_value) {
 		if (!avp->avp_model) {
-			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(data set but no model: ERROR)\n", INOBJHDRVAL) );
+			CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "(data set but no model: ERROR)|", INOBJHDRVAL) );
 		} else {
 			CHECK_FCT( fd_dict_dump_avp_value(avp->avp_public.avp_value, avp->avp_model, indent, outstr, offset, outlen) );
@@ -789,5 +789,5 @@
 	}
 
-	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "intern: src:%p mf:%d raw:%p(%d)\n", INOBJHDRVAL, avp->avp_source, avp->avp_mustfreeos, avp->avp_rawdata, avp->avp_rawlen) );
+	CHECK_FCT( dump_add_str(outstr, offset, outlen, INOBJHDR "intern: src:%p mf:%d raw:%p(%d)|", INOBJHDRVAL, avp->avp_source, avp->avp_mustfreeos, avp->avp_rawdata, avp->avp_rawlen) );
 	return 0;
 }
@@ -880,5 +880,5 @@
 	/* now really output this in one shot, so it is not interrupted */
 	TRACE_DEBUG(level, "------ Dumping object %p (w)-------", obj);
-	fd_log_debug_fstr(fd_g_debug_fstr, "%s", outstr);
+	TRACE_DEBUG(level, "%s", outstr);
 	TRACE_DEBUG(level, "------ /end of object %p -------", obj);
 	
@@ -896,5 +896,5 @@
 			fd_log_debug_fstr(fd_g_debug_fstr, "Error while dumping %p\n", obj) );
 	TRACE_DEBUG(level, "------ Dumping object %p (s)-------", obj);
-	fd_log_debug_fstr(fd_g_debug_fstr, "%s", outstr);
+	TRACE_DEBUG(level, "%s", outstr);
 	TRACE_DEBUG(level, "------ /end of object %p -------", obj);
 	free(outstr);
@@ -1213,4 +1213,18 @@
 	
 	memcpy(ts, &msg->msg_ts_sent, sizeof(struct timespec));
+	return 0;
+}
+
+/* Associate a session with a message, use only when the session was just created */
+int fd_msg_sess_set(struct msg * msg, struct session * session)
+{
+	TRACE_ENTRY("%p %p", msg, session);
+	
+	/* Check we received valid parameters */
+	CHECK_PARAMS( CHECK_MSG(msg) );
+	CHECK_PARAMS( session );
+	CHECK_PARAMS( msg->msg_sess == NULL );
+	
+	msg->msg_sess = session;
 	return 0;
 }
@@ -1261,6 +1275,11 @@
 	
 	/* Resolve the session and we are done */
-	CHECK_FCT( fd_sess_fromsid_msg ( avp->avp_public.avp_value->os.data, avp->avp_public.avp_value->os.len, &msg->msg_sess, new) );
-	*session = msg->msg_sess;
+	if (avp->avp_public.avp_value->os.len > 0) {
+		CHECK_FCT( fd_sess_fromsid_msg ( avp->avp_public.avp_value->os.data, avp->avp_public.avp_value->os.len, &msg->msg_sess, new) );
+		*session = msg->msg_sess;
+	} else {
+		TRACE_DEBUG(FULL, "Session-Id AVP with 0-byte length found in message %p", msg);
+		*session = NULL;
+	}
 	
 	return 0;
@@ -1648,5 +1667,5 @@
 		struct avp * avp;
 		
-		if (buflen - offset <= AVPHDRSZ_NOVEND) {
+		if (buflen - offset < AVPHDRSZ_NOVEND) {
 			TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes", buflen - offset);
 			return EBADMSG;
@@ -1666,5 +1685,5 @@
 		
 		if (avp->avp_public.avp_flags & AVP_FLAG_VENDOR) {
-			if (buflen - offset <= 4) {
+			if (buflen - offset < 4) {
 				TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes for vendor and data", buflen - offset);
 				free(avp);
@@ -1676,5 +1695,6 @@
 		
 		/* Check there is enough remaining data in the buffer */
-		if (buflen - offset < avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags)) {
+		if ( (avp->avp_public.avp_len > GETAVPHDRSZ(avp->avp_public.avp_flags))
+		&& (buflen - offset < avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags))) {
 			TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes for data, and avp data size is %d", 
 					buflen - offset, 
Index: libfdproto/sessions.c
===================================================================
--- libfdproto/sessions.c	(revision 788)
+++ libfdproto/sessions.c	(revision 924)
@@ -360,5 +360,5 @@
 
 
-/* Create a new session object with the default timeout value, and link it */
+/* Create a new session object with the default timeout value, and link it. The refcount is increased by 1, whether the session existed or not */
 int fd_sess_new ( struct session ** session, DiamId_t diamid, size_t diamidlen, uint8_t * opt, size_t optlen )
 {
@@ -461,6 +461,12 @@
 	
 		fd_list_insert_before(li, &sess->chain_h); /* hash table */
+		sess->msg_cnt++;
 	} else {
 		free(sid);
+		
+		CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) ); 
+		(*session)->msg_cnt++;
+		CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) ); 
+		
 		/* it was found: was it previously destroyed? */
 		if ((*session)->is_destroyed == 0) {
@@ -469,6 +475,6 @@
 		} else {
 			/* the session was marked destroyed, let's re-activate it. */
-			TODO("Re-creating a deleted session. Should investigate if this can lead to an issue... (need more feedback)");
 			sess = *session;
+			sess->is_destroyed = 0;
 			
 			/* update the expiry time */
@@ -501,5 +507,5 @@
 
 out:
-	;	
+	;
 	pthread_cleanup_pop(0);
 	CHECK_POSIX( pthread_mutex_unlock( H_LOCK(hash) ) );
@@ -512,6 +518,6 @@
 }
 
-/* Find or create a session */
-int fd_sess_fromsid ( uint8_t * sid, size_t len, struct session ** session, int * new)
+/* Find or create a session -- the msg refcount is increased */
+int fd_sess_fromsid_msg ( uint8_t * sid, size_t len, struct session ** session, int * new)
 {
 	int ret;
@@ -802,5 +808,5 @@
 
 /* For the messages module */
-int fd_sess_fromsid_msg ( uint8_t * sid, size_t len, struct session ** session, int * new)
+int fd_sess_fromsid ( uint8_t * sid, size_t len, struct session ** session, int * new)
 {
 	TRACE_ENTRY("%p %zd %p %p", sid, len, session, new);
@@ -808,9 +814,11 @@
 	
 	/* Get the session object */
-	CHECK_FCT( fd_sess_fromsid ( sid, len, session, new) );
-	
-	/* Increase count */
-	CHECK_FCT( fd_sess_ref_msg ( *session ) );
-	
+	CHECK_FCT( fd_sess_fromsid_msg ( sid, len, session, new) );
+	
+	/* Decrease the refcount */
+	CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) );
+	(*session)->msg_cnt--; /* was increased in fd_sess_new */
+	CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) );
+		
 	/* Done */
 	return 0;
@@ -833,8 +841,14 @@
 {
 	int reclaim;
+	uint32_t hash;
 	
 	TRACE_ENTRY("%p", session);
 	CHECK_PARAMS( session && VALIDATE_SI(*session) );
 	
+	/* Lock the hash line to avoid possibility that session is freed while we are reclaiming */
+	hash = (*session)->hash;
+	CHECK_POSIX( pthread_mutex_lock( H_LOCK(hash)) );
+	pthread_cleanup_push( fd_cleanup_mutex, H_LOCK(hash) ); 
+
 	/* Update the msg refcount */
 	CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) );
@@ -843,4 +857,9 @@
 	CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) );
 	
+	/* Ok, now unlock the hash line */
+	pthread_cleanup_pop( 0 );
+	CHECK_POSIX( pthread_mutex_unlock( H_LOCK(hash) ) );
+	
+	/* and reclaim if no message references the session anymore */
 	if (reclaim == 1) {
 		CHECK_FCT(fd_sess_reclaim ( session ));
