Index: INSTALL.FreeBSD
===================================================================
--- INSTALL.FreeBSD	(revision 707)
+++ INSTALL.FreeBSD	(revision 921)
@@ -9,5 +9,5 @@
 
 Then the cmake command had to look like:
- cmake -DFLEX_EXECUTABLE:FILEPATH=/usr/local/bin/flex ...
+ cmake -DFLEX_EXECUTABLE:FILEPATH=/usr/local/bin/flex -DSCTP_USE_MAPPED_ADDRESSES:BOOL=ON ...
 
 
@@ -46,5 +46,5 @@
    
 7) Run cmake for freeDiameter (add other flags as you see fit, see INSTALL for more details)
-   # /usr/local/bin/cmake -DFLEX_EXECUTABLE:FILEPATH=/usr/local/bin/flex ../freeDiameter
+   # /usr/local/bin/cmake -DFLEX_EXECUTABLE:FILEPATH=/usr/local/bin/flex -DSCTP_USE_MAPPED_ADDRESSES:BOOL=ON ../freeDiameter
 
 8) Compile, optionnaly test
Index: extensions/app_radgw/rgwx_auth.c
===================================================================
--- extensions/app_radgw/rgwx_auth.c	(revision 740)
+++ extensions/app_radgw/rgwx_auth.c	(revision 924)
@@ -458,5 +458,5 @@
 		if (si_len) {
 			/* We already have the Session-Id, just use it */
-			CHECK_FCT( fd_sess_fromsid ( si, si_len, session, NULL) );
+			CHECK_FCT( fd_sess_fromsid_msg ( si, si_len, session, NULL) );
 		} else {
 			/* Create a new Session-Id string */
@@ -496,4 +496,5 @@
 		CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
 		CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_FIRST_CHILD, avp) );
+		CHECK_FCT( fd_msg_sess_set( *diam_fw, *session) );
 	}
 	
Index: extensions/app_radgw/rgwx_sip.c
===================================================================
--- extensions/app_radgw/rgwx_sip.c	(revision 816)
+++ extensions/app_radgw/rgwx_sip.c	(revision 924)
@@ -480,4 +480,5 @@
 	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
 	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_FIRST_CHILD, avp) );
+	CHECK_FCT( fd_msg_sess_set( *diam_fw, *session) );
 	
 	/*
Index: extensions/app_sip/registrationtermination.c
===================================================================
--- extensions/app_sip/registrationtermination.c	(revision 706)
+++ extensions/app_sip/registrationtermination.c	(revision 924)
@@ -148,13 +148,5 @@
 	{
 		#define APP_SIP_SID_OPT  "app_sip"
-		CHECK_FCT( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)APP_SIP_SID_OPT, CONSTSTRLEN(APP_SIP_SID_OPT) ));
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT( fd_sess_getsid ( sess, &sid, &sidlen ));
-		CHECK_FCT( fd_msg_avp_new ( sip_dict.Session_Id, 0, &avp ));
-		value.os.data = sid;
-		value.os.len  = sidlen;
-		CHECK_FCT( fd_msg_avp_setvalue( avp, &value ));
-		CHECK_FCT( fd_msg_avp_add( message, MSG_BRW_FIRST_CHILD, avp ));
+		CHECK_FCT( fd_msg_new_session( message, (os0_t)APP_SIP_SID_OPT, CONSTSTRLEN(APP_SIP_SID_OPT) ) );
 	}
 	
Index: extensions/test_app/ta_bench.c
===================================================================
--- extensions/test_app/ta_bench.c	(revision 879)
+++ extensions/test_app/ta_bench.c	(revision 924)
@@ -122,5 +122,4 @@
 	union avp_value val;
 	struct ta_mess_info * mi = NULL;
-	struct session *sess = NULL;
 	
 	TRACE_DEBUG(FULL, "Creating a new message for sending.");
@@ -131,5 +130,5 @@
 	/* Create a new session */
 	#define TEST_APP_SID_OPT  "app_testb"
-	CHECK_FCT_DO( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)TEST_APP_SID_OPT, CONSTSTRLEN(TEST_APP_SID_OPT) ), goto out );
+	CHECK_FCT_DO( fd_msg_new_session( req, (os0_t)TEST_APP_SID_OPT, CONSTSTRLEN(TEST_APP_SID_OPT) ), goto out );
 	
 	/* Create the random value to store with the session */
@@ -143,17 +142,4 @@
 	
 	/* Now set all AVPs values */
-	
-	/* Session-Id */
-	{
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT_DO( fd_sess_getsid ( sess, &sid, &sidlen ), goto out );
-		CHECK_FCT_DO( fd_msg_avp_new ( ta_sess_id, 0, &avp ), goto out );
-		val.os.data = sid;
-		val.os.len  = sidlen;
-		CHECK_FCT_DO( fd_msg_avp_setvalue( avp, &val ), goto out );
-		CHECK_FCT_DO( fd_msg_avp_add( req, MSG_BRW_FIRST_CHILD, avp ), goto out );
-		
-	}
 	
 	/* Set the Destination-Realm AVP */
Index: extensions/test_app/ta_cli.c
===================================================================
--- extensions/test_app/ta_cli.c	(revision 740)
+++ extensions/test_app/ta_cli.c	(revision 924)
@@ -151,5 +151,6 @@
 	/* Create a new session */
 	#define TEST_APP_SID_OPT  "app_test"
-	CHECK_FCT_DO( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)TEST_APP_SID_OPT, CONSTSTRLEN(TEST_APP_SID_OPT) ), goto out );
+	CHECK_FCT_DO( fd_msg_new_session( req, (os0_t)TEST_APP_SID_OPT, CONSTSTRLEN(TEST_APP_SID_OPT) ), goto out );
+	CHECK_FCT_DO( fd_msg_sess_get(fd_g_config->cnf_dict, req, &sess, NULL), goto out );
 	
 	/* Create the random value to store with the session */
@@ -164,17 +165,4 @@
 	/* Now set all AVPs values */
 	
-	/* Session-Id */
-	{
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT_DO( fd_sess_getsid ( sess, &sid, &sidlen ), goto out );
-		CHECK_FCT_DO( fd_msg_avp_new ( ta_sess_id, 0, &avp ), goto out );
-		val.os.data = sid;
-		val.os.len  = sidlen;
-		CHECK_FCT_DO( fd_msg_avp_setvalue( avp, &val ), goto out );
-		CHECK_FCT_DO( fd_msg_avp_add( req, MSG_BRW_FIRST_CHILD, avp ), goto out );
-		
-	}
-	
 	/* Set the Destination-Realm AVP */
 	{
Index: extensions/test_sip/locationinfo.c
===================================================================
--- extensions/test_sip/locationinfo.c	(revision 706)
+++ extensions/test_sip/locationinfo.c	(revision 924)
@@ -42,5 +42,4 @@
 	struct msg * message=NULL;
 	struct avp *avp=NULL;
-	struct session *sess=NULL;
 	union avp_value value;
 	
@@ -62,13 +61,5 @@
 	// Create a new session 
 	{
-		CHECK_FCT( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)"appsip", 6 ));
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT( fd_sess_getsid ( sess, &sid, &sidlen ));
-		CHECK_FCT( fd_msg_avp_new ( sip_dict.Session_Id, 0, &avp ));
-		value.os.data = sid;
-		value.os.len  = sidlen;
-		CHECK_FCT( fd_msg_avp_setvalue( avp, &value ));
-		CHECK_FCT( fd_msg_avp_add( message, MSG_BRW_FIRST_CHILD, avp ));
+		CHECK_FCT( fd_msg_new_session( message, (os0_t)"appsip", CONSTSTRLEN("appsip") ) );
 	}
 	
Index: extensions/test_sip/locationinfosl.c
===================================================================
--- extensions/test_sip/locationinfosl.c	(revision 706)
+++ extensions/test_sip/locationinfosl.c	(revision 924)
@@ -42,5 +42,4 @@
 	struct msg * message=NULL;
 	struct avp *avp=NULL;
-	struct session *sess=NULL;
 	union avp_value value;
 	
@@ -62,13 +61,5 @@
 	// Create a new session 
 	{
-		CHECK_FCT( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)"appsip", 6 ));
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT( fd_sess_getsid ( sess, &sid, &sidlen ));
-		CHECK_FCT( fd_msg_avp_new ( sip_dict.Session_Id, 0, &avp ));
-		value.os.data = sid;
-		value.os.len  = sidlen;
-		CHECK_FCT( fd_msg_avp_setvalue( avp, &value ));
-		CHECK_FCT( fd_msg_avp_add( message, MSG_BRW_FIRST_CHILD, avp ));
+		CHECK_FCT( fd_msg_new_session( message, (os0_t)"appsip", CONSTSTRLEN("appsip") ) );
 	}
 	
Index: extensions/test_sip/serverassignment.c
===================================================================
--- extensions/test_sip/serverassignment.c	(revision 706)
+++ extensions/test_sip/serverassignment.c	(revision 924)
@@ -42,5 +42,4 @@
 	struct msg * message=NULL;
 	struct avp *avp=NULL;
-	struct session *sess=NULL;
 	union avp_value value;
 	
@@ -71,13 +70,5 @@
 	// Create a new session 
 	{
-		CHECK_FCT( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)"appsip", 6 ));
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT( fd_sess_getsid ( sess, &sid, &sidlen ));
-		CHECK_FCT( fd_msg_avp_new ( sip_dict.Session_Id, 0, &avp ));
-		value.os.data = sid;
-		value.os.len  = sidlen;
-		CHECK_FCT( fd_msg_avp_setvalue( avp, &value ));
-		CHECK_FCT( fd_msg_avp_add( message, MSG_BRW_FIRST_CHILD, avp ));
+		CHECK_FCT( fd_msg_new_session( message, (os0_t)"appsip", CONSTSTRLEN("appsip") ) );
 	}
 	
Index: extensions/test_sip/userauthorization.c
===================================================================
--- extensions/test_sip/userauthorization.c	(revision 706)
+++ extensions/test_sip/userauthorization.c	(revision 924)
@@ -42,5 +42,4 @@
 	struct msg * message=NULL;
 	struct avp *avp=NULL;
-	struct session *sess=NULL;
 	union avp_value value;
 	
@@ -67,13 +66,5 @@
 	// Create a new session 
 	{
-		CHECK_FCT( fd_sess_new( &sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t)"appsip", 6 ));
-		os0_t sid;
-		size_t sidlen;
-		CHECK_FCT( fd_sess_getsid ( sess, &sid, &sidlen ));
-		CHECK_FCT( fd_msg_avp_new ( sip_dict.Session_Id, 0, &avp ));
-		value.os.data = sid;
-		value.os.len  = sidlen;
-		CHECK_FCT( fd_msg_avp_setvalue( avp, &value ));
-		CHECK_FCT( fd_msg_avp_add( message, MSG_BRW_FIRST_CHILD, avp ));
+		CHECK_FCT( fd_msg_new_session( message, (os0_t)"appsip", CONSTSTRLEN("appsip") ) );
 	}
 	
Index: include/freeDiameter/libfdproto.h
===================================================================
--- include/freeDiameter/libfdproto.h	(revision 946)
+++ include/freeDiameter/libfdproto.h	(revision 950)
@@ -1158,4 +1158,24 @@
 };
 
+/****
+ Callbacks defined in libfdproto/dictionary_functions.c file -- see that file for usage. 
+ */
+
+/* Convert an Address type AVP into a struct sockaddr_storage */
+int fd_dictfct_Address_encode(void * data, union avp_value * avp_value);
+int fd_dictfct_Address_interpret(union avp_value * avp_value, void * interpreted);
+char * fd_dictfct_Address_dump(union avp_value * avp_value);
+
+/* Display the content of an AVP of type UTF8String in the log file */
+char * fd_dictfct_UTF8String_dump(union avp_value * avp_value);
+
+/* For Time AVPs, map with time_t value directly */
+int fd_dictfct_Time_encode(void * data, union avp_value * avp_value);
+int fd_dictfct_Time_interpret(union avp_value * avp_value, void * interpreted);
+char * fd_dictfct_Time_dump(union avp_value * avp_value);
+
+
+
+/****/
 
 /***
@@ -1188,5 +1208,5 @@
  
 */
-	 
+
 /*
  ***************************************************************************
@@ -1790,7 +1810,7 @@
  *
  * RETURN VALUE:
- *  0      	: The session is created.
- *  EINVAL 	: A parameter is invalid.
- *  EALREADY	: A session with the same name already exists (returned in *session)
+ *  0      	: The session is created, the initial msg refcount is 1.
+ *  EINVAL 	: A parameter is invalid.
+ *  EALREADY	: A session with the same name already exists (returned in *session), the msg refcount is increased.
  *  ENOMEM	: Not enough memory to complete the operation
  */
@@ -2479,4 +2499,8 @@
 int fd_msg_sess_get(struct dictionary * dict, struct msg * msg, struct session ** session, int * isnew);
 
+/* This one is used by the libfdcore, you should use fd_msg_new_session rather than fd_sess_new, when possible */
+int fd_msg_sess_set(struct msg * msg, struct session * session);
+
+
 /***************************************/
 /*   Manage AVP values                 */
Index: libfdcore/dict_base_proto.c
===================================================================
--- libfdcore/dict_base_proto.c	(revision 838)
+++ libfdcore/dict_base_proto.c	(revision 922)
@@ -45,167 +45,4 @@
 struct dictionary * fd_g_dict = NULL;
 
-/* The functions to encode and interpret the derived types defined in the base protocol */
-
-/* Address AVP <-> struct sockaddr_storage */
-static int 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;
-}
-
-static int 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 */
-static char * 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;
-}
-
-static char * UTF8String_dump(union avp_value * avp_value)
-{
-	return strndup((char *)avp_value->os.data, 42); /* avoid very long strings */
-}
-
-
 
 
@@ -295,5 +132,5 @@
 				the content and format of the remaining octets.
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"Address"		, Address_interpret	, Address_encode,	Address_dump	};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"Address"		, fd_dictfct_Address_interpret	, fd_dictfct_Address_encode,	fd_dictfct_Address_dump	};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
@@ -314,5 +151,5 @@
 				This procedure MUST be supported by all DIAMETER nodes.
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"Time"			, NULL			, NULL		, NULL		};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"Time"			, fd_dictfct_Time_interpret	, fd_dictfct_Time_encode, 	fd_dictfct_Time_dump		};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
@@ -352,5 +189,5 @@
 				octets, not characters.
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"UTF8String"		, NULL			, NULL	, UTF8String_dump	};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"UTF8String"		, NULL			, NULL	, fd_dictfct_UTF8String_dump	};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
@@ -381,5 +218,5 @@
 				Domain Name (IDNs).
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"DiameterIdentity"	, NULL			, NULL		, UTF8String_dump	};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"DiameterIdentity"	, NULL			, NULL		, fd_dictfct_UTF8String_dump	};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
@@ -436,5 +273,5 @@
 				aaa://host.example.com:1813;transport=udp;protocol=radius
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"DiameterURI"		, NULL			, NULL		, UTF8String_dump	};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"DiameterURI"		, NULL			, NULL		, fd_dictfct_UTF8String_dump	};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
@@ -498,5 +335,5 @@
 				infrastructure.
 			*/
-			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"IPFilterRule"		, NULL			, NULL		, UTF8String_dump	};
+			struct dict_type_data data = { AVP_TYPE_OCTETSTRING,	"IPFilterRule"		, NULL			, NULL		, fd_dictfct_UTF8String_dump	};
 			CHECK_dict_new( DICT_TYPE, &data , NULL, NULL);
 		}
Index: libfdcore/fdd.l
===================================================================
--- libfdcore/fdd.l	(revision 944)
+++ libfdcore/fdd.l	(revision 950)
@@ -52,5 +52,6 @@
 	yylloc->first_column = yylloc->last_column + 1; 		\
 	yylloc->last_column = yylloc->first_column + yyleng - 1;	\
-	TRACE_DEBUG_ERROR("(%d:%d-%d:%d) matched rule %d, length=%d, txt='%s'\n",	\
+	TRACE_DEBUG_ERROR( 						\
+		"(%d:%d-%d:%d) matched rule %d, length=%d, txt='%s'\n",	\
 		yylloc->first_line, yylloc->first_column, 		\
 		yylloc->last_line, yylloc->last_column, 		\
@@ -145,5 +146,5 @@
 <*>[[:alnum:]]+		|	/* This rule is only useful to print a complete token in error messages */
 	/* Unrecognized character */
-<*>.			{ 
+<*>.			{
 				TRACE_DEBUG_ERROR("Unrecognized text on line %d col %d: '%s'.\n", yylloc->first_line, yylloc->first_column, yytext);
 			 	return LEX_ERROR; 
Index: libfdcore/fdd.y
===================================================================
--- libfdcore/fdd.y	(revision 944)
+++ libfdcore/fdd.y	(revision 950)
@@ -328,5 +328,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open extension file %s for reading: %s\n", fname, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open extension file %s for reading: %s\n", fname, strerror(ret));
 					yyerror (&yylloc, conf, "Error adding extension"); 
 					YYERROR;
@@ -502,5 +502,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open certificate file %s for reading: %s\n", $3, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open certificate file %s for reading: %s\n", $3, strerror(ret));
 					yyerror (&yylloc, conf, "Error on file name"); 
 					YYERROR;
@@ -510,5 +510,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open private key file %s for reading: %s\n", $5, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open private key file %s for reading: %s\n", $5, strerror(ret));
 					yyerror (&yylloc, conf, "Error on file name"); 
 					YYERROR;
@@ -533,5 +533,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open CA file %s for reading: %s\n", $3, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open CA file %s for reading: %s\n", $3, strerror(ret));
 					yyerror (&yylloc, conf, "Error on file name"); 
 					YYERROR;
@@ -573,5 +573,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open CRL file %s for reading: %s\n", $3, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open CRL file %s for reading: %s\n", $3, strerror(ret));
 					yyerror (&yylloc, conf, "Error on file name"); 
 					YYERROR;
@@ -616,5 +616,5 @@
 							&err_pos),
 						{ yyerror (&yylloc, conf, "Error setting Priority parameter.");
-						  fprintf(stderr, "Error at position : %s\n", err_pos);
+						  TRACE_DEBUG_ERROR("Error at position : %s\n", err_pos);
 						  YYERROR; } );
 			}
@@ -633,5 +633,5 @@
 				if (fd == NULL) {
 					int ret = errno;
-					TRACE_DEBUG(INFO, "Unable to open DH file %s for reading: %s\n", $3, strerror(ret));
+					TRACE_DEBUG_ERROR("Unable to open DH file %s for reading: %s\n", $3, strerror(ret));
 					yyerror (&yylloc, conf, "Error on file name"); 
 					YYERROR;
Index: libfdcore/messages.c
===================================================================
--- libfdcore/messages.c	(revision 892)
+++ libfdcore/messages.c	(revision 924)
@@ -159,4 +159,7 @@
 	CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_FIRST_CHILD, avp ) );
 	
+	/* Save the session associated with the message */
+	CHECK_FCT( fd_msg_sess_set( msg, sess) );
+	
 	/* Done! */
 	return 0;
@@ -284,5 +287,5 @@
 			hdr->msg_flags |= CMD_FLAG_ERROR;
 		else
-			hdr->msg_flags &= ! CMD_FLAG_ERROR;
+			hdr->msg_flags &= ~ CMD_FLAG_ERROR;
 	}
 	
Index: libfdcore/peers.c
===================================================================
--- libfdcore/peers.c	(revision 947)
+++ libfdcore/peers.c	(revision 950)
@@ -549,5 +549,5 @@
 	ev_data->validate = !found;
 	
-	CHECK_FCT_DO( ret = fd_event_send(peer->p_events, FDEVP_CNX_INCOMING, sizeof(ev_data), ev_data), goto out );
+	CHECK_FCT_DO( ret = fd_event_send(peer->p_events, FDEVP_CNX_INCOMING, sizeof(*ev_data), ev_data), goto out );
 	
 out:	
Index: libfdcore/sctp.c
===================================================================
--- libfdcore/sctp.c	(revision 946)
+++ libfdcore/sctp.c	(revision 950)
@@ -654,5 +654,5 @@
 		if (ep->sa.sa_family == AF_INET6)
 		#else /* SCTP_USE_MAPPED_ADDRESSES */
-		if (target_family == AF_INET6) {
+		if (target_family == AF_INET6)
 		#endif /* SCTP_USE_MAPPED_ADDRESSES */
 			sz = sizeof(sSA6);
@@ -1087,5 +1087,5 @@
 	/* We will loop while all data is not received. */
 incomplete:
-	if (datasize == bufsz - sizeof(struct timespec)) {
+	while (datasize + sizeof(struct timespec) >= bufsz ) {
 		/* The buffer is full, enlarge it */
 		bufsz += mempagesz;
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 924)
@@ -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);
 		}
 	}
@@ -1216,4 +1216,18 @@
 }
 
+/* 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;
+}
+
 
 /* Retrieve the session of the message */
@@ -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 ));
