- fix error messages
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
index f377392c60b43fdef787b935f0c0d37586620fce..a969bdd2271502dcf61e02daae7b090077b1085a 100644 (file)
@@ -1,6 +1,6 @@
 /*
      This file is part of GNUnet
-     (C) 2002--2012 Christian Grothoff (and other contributing authors)
+     (C) 2002--2013 Christian Grothoff (and other contributing authors)
 
      GNUnet is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
 #include "platform.h"
 #include "gnunet_hello_lib.h"
 #include "gnunet_constants.h"
-#include "gnunet_connection_lib.h"
-#include "gnunet_container_lib.h"
+#include "gnunet_util_lib.h"
 #include "gnunet_nat_lib.h"
-#include "gnunet_os_lib.h"
 #include "gnunet_protocols.h"
 #include "gnunet_resolver_service.h"
-#include "gnunet_server_lib.h"
-#include "gnunet_service_lib.h"
 #include "gnunet_signatures.h"
 #include "gnunet_statistics_service.h"
 #include "gnunet_transport_service.h"
@@ -43,6 +39,8 @@
 
 #define PLUGIN_NAME "tcp"
 
+#define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
+
 /**
  * How long until we give up on establishing an NAT connection?
  * Must be > 4 RTT
@@ -63,7 +61,7 @@ static uint32_t myoptions;
 struct WelcomeMessage
 {
   /**
-   * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
+   * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
    */
   struct GNUNET_MessageHeader header;
 
@@ -82,7 +80,7 @@ struct WelcomeMessage
 struct TCP_NAT_ProbeMessage
 {
   /**
-   * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
+   * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
    */
   struct GNUNET_MessageHeader header;
 
@@ -139,10 +137,10 @@ GNUNET_NETWORK_STRUCT_BEGIN
  */
 struct IPv4TcpAddress
 {
-       /**
-        * Optional options and flags for this address
-        */
-       uint32_t options;
+  /**
+   * Optional options and flags for this address
+   */
+  uint32_t options;
 
   /**
    * IPv4 address, in network byte order.
@@ -162,10 +160,10 @@ struct IPv4TcpAddress
  */
 struct IPv6TcpAddress
 {
-       /**
-        * Optional flags for this address
-        */
-       uint32_t options;
+  /**
+   * Optional flags for this address
+   */
+  uint32_t options;
 
   /**
    * IPv6 address.
@@ -298,12 +296,11 @@ struct Session
    * call or on our 'accept' call).
    *
    * struct IPv4TcpAddress or struct IPv6TcpAddress
-   *
    */
   void *addr;
 
   /**
-   * Length of connect_addr.
+   * Length of @e addr.
    */
   size_t addrlen;
 
@@ -314,12 +311,12 @@ struct Session
   struct GNUNET_TIME_Absolute last_activity;
 
   /**
-   * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
+   * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
    */
   int expecting_welcome;
 
   /**
-   * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
+   * Was this a connection that was inbound (we accepted)? (#GNUNET_YES/#GNUNET_NO)
    */
   int inbound;
 
@@ -331,7 +328,7 @@ struct Session
   /**
    * ATS network type in NBO
    */
-  uint32_t ats_address_network_type;
+  enum GNUNET_ATS_Network_Type ats_address_network_type;
 };
 
 
@@ -358,7 +355,7 @@ struct Plugin
   /**
    * Map from peer identities to sessions for the given peer.
    */
-  struct GNUNET_CONTAINER_MultiHashMap *sessionmap;
+  struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
 
   /**
    * Handle to the network service.
@@ -379,7 +376,7 @@ struct Plugin
   /**
    * Map of peers we have tried to contact behind a NAT
    */
-  struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
+  struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
 
   /**
    * List of active TCP probes.
@@ -426,68 +423,20 @@ struct Plugin
 
 
 /**
- * Start session timeout
- */
-static void
-start_session_timeout (struct Session *s);
-
-
-/**
- * Increment session timeout due to activity
- */
-static void
-reschedule_session_timeout (struct Session *s);
-
-
-/**
- * Cancel timeout
+ * Function called for a quick conversion of the binary address to
+ * a numeric address.  Note that the caller must not free the
+ * address and that the next call to this function is allowed
+ * to override the address again.
+ *
+ * @param cls closure ('struct Plugin*')
+ * @param addr binary address
+ * @param addrlen length of the address
+ * @return string representing the same address
  */
-static void
-stop_session_timeout (struct Session *s);
-
-
-/* DEBUG CODE */
 static const char *
-tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
-
-
-static unsigned int sessions;
-
-
-static void 
-inc_sessions (struct Plugin *plugin, struct Session *session, int line)
-{
-  sessions++;
-  unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
-  if (sessions != size)
-    LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
-        sessions, size);
-  LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
-      line,
-      sessions,
-      size,
-      GNUNET_i2s (&session->target),
-      tcp_address_to_string (NULL, session->addr, session->addrlen));
-}
-
-
-static void 
-dec_sessions (struct Plugin *plugin, struct Session *session, int line)
-{
-  GNUNET_assert (sessions > 0);
-  unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
-  sessions--;
-  if (sessions != size)
-    LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
-      sessions, size);
-  LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
-      line,
-      sessions,
-      size,
-      GNUNET_i2s (&session->target),
-      tcp_address_to_string (NULL, session->addr, session->addrlen));
-}
-/* DEBUG CODE */
+tcp_address_to_string (void *cls,
+                       const void *addr,
+                       size_t addrlen);
 
 
 /**
@@ -495,11 +444,11 @@ dec_sessions (struct Plugin *plugin, struct Session *session, int line)
  * Mostly used to limit the total number of open connections
  * we can have.
  *
- * @param cls the 'struct Plugin'
+ * @param cls the `struct Plugin`
  * @param ucred credentials, if available, otherwise NULL
  * @param addr address
  * @param addrlen length of address
- * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
+ * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
  *   for unknown address family (will be denied).
  */
 static int
@@ -521,15 +470,16 @@ plugin_tcp_access_check (void *cls,
 /**
  * Our external IP address/port mapping has changed.
  *
- * @param cls closure, the 'struct LocalAddrList'
- * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
+ * @param cls closure, the 'struct Plugin'
+ * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
  *     the previous (now invalid) one
  * @param addr either the previous or the new public IP address
  * @param addrlen actual lenght of the address
  */
 static void
 tcp_nat_port_map_callback (void *cls, int add_remove,
-                           const struct sockaddr *addr, socklen_t addrlen)
+                           const struct sockaddr *addr,
+                           socklen_t addrlen)
 {
   struct Plugin *plugin = cls;
   struct IPv4TcpAddress t4;
@@ -578,7 +528,7 @@ tcp_nat_port_map_callback (void *cls, int add_remove,
  * address and that the next call to this function is allowed
  * to override the address again.
  *
- * @param cls closure ('struct Plugin*')
+ * @param cls closure (`struct Plugin*`)
  * @param addr binary address
  * @param addrlen length of the address
  * @return string representing the same address
@@ -597,7 +547,6 @@ tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
   uint16_t port;
   uint32_t options;
 
-  options = 0;
   switch (addrlen)
   {
   case sizeof (struct IPv6TcpAddress):
@@ -608,7 +557,7 @@ tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
     sb = &a6;
     break;
-  case sizeof (struct IPv4TcpAddress): 
+  case sizeof (struct IPv4TcpAddress):
     t4 = addr;
     af = AF_INET;
     port = ntohs (t4->t4_port);
@@ -616,6 +565,12 @@ tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
     sb = &a4;
     break;
+  case 0:
+    {
+      GNUNET_snprintf (rbuf, sizeof (rbuf), "%s",
+               TRANSPORT_SESSION_INBOUND_STRING);
+      return rbuf;
+    }
   default:
     LOG (GNUNET_ERROR_TYPE_WARNING,
                _("Unexpected address length: %u bytes\n"),
@@ -627,8 +582,15 @@ tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
     return NULL;
   }
-  GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
-                   PLUGIN_NAME, options, buf, port);
+  GNUNET_snprintf (rbuf,
+                   sizeof (rbuf),
+                   (af == AF_INET6)
+                   ? "%s.%u.[%s]:%u"
+                   : "%s.%u.%s:%u",
+                   PLUGIN_NAME,
+                   options,
+                   buf,
+                   port);
   return rbuf;
 }
 
@@ -637,17 +599,19 @@ tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
  * Function called to convert a string address to
  * a binary address.
  *
- * @param cls closure ('struct Plugin*')
+ * @param cls closure (`struct Plugin*`)
  * @param addr string address
  * @param addrlen length of the address
  * @param buf location to store the buffer
  * @param added location to store the number of bytes in the buffer.
- *        If the function returns GNUNET_SYSERR, its contents are undefined.
- * @return GNUNET_OK on success, GNUNET_SYSERR on failure
+ *        If the function returns #GNUNET_SYSERR, its contents are undefined.
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
  */
 static int
-tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
-    void **buf, size_t *added)
+tcp_string_to_address (void *cls,
+                       const char *addr,
+                       uint16_t addrlen,
+                       void **buf, size_t *added)
 {
   struct sockaddr_storage socket_address;
   char *address;
@@ -659,7 +623,6 @@ tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
   address = NULL;
   plugin = NULL;
   optionstr = NULL;
-  options = 0;
   if ((NULL == addr) || (addrlen == 0))
   {
     GNUNET_break (0);
@@ -712,7 +675,7 @@ tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
     {
       struct IPv4TcpAddress *t4;
       struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
-      t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
+      t4 = GNUNET_new (struct IPv4TcpAddress);
       t4->options =  htonl (options);
       t4->ipv4_addr = in4->sin_addr.s_addr;
       t4->t4_port = in4->sin_port;
@@ -720,11 +683,11 @@ tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
       *added = sizeof (struct IPv4TcpAddress);
       return GNUNET_OK;
     }
-  case AF_INET6:  
+  case AF_INET6:
     {
       struct IPv6TcpAddress *t6;
       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
-      t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
+      t6 = GNUNET_new (struct IPv6TcpAddress);
       t6->options = htonl (options);
       t6->ipv6_addr = in6->sin6_addr;
       t6->t6_port = in6->sin6_port;
@@ -738,16 +701,26 @@ tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
 }
 
 
+/**
+ * Closure for #session_lookup_by_client_it().
+ */
 struct SessionClientCtx
 {
+  /**
+   * Client we are looking for.
+   */
   const struct GNUNET_SERVER_Client *client;
+
+  /**
+   * Session that was found.
+   */
   struct Session *ret;
 };
 
 
-static int 
+static int
 session_lookup_by_client_it (void *cls,
-                            const struct GNUNET_HashCode * key,
+                            const struct GNUNET_PeerIdentity *key,
                             void *value)
 {
   struct SessionClientCtx *sc_ctx = cls;
@@ -764,6 +737,9 @@ session_lookup_by_client_it (void *cls,
 
 /**
  * Find the session handle for the given client.
+ * Currently uses both the hashmap and the client
+ * context, as the client context is new and the
+ * logic still needs to be tested.
  *
  * @param plugin the plugin
  * @param client which client to find the session handle for
@@ -771,17 +747,183 @@ session_lookup_by_client_it (void *cls,
  */
 static struct Session *
 lookup_session_by_client (struct Plugin *plugin,
-                         const struct GNUNET_SERVER_Client *client)
+                         struct GNUNET_SERVER_Client *client)
 {
+  struct Session *ret;
   struct SessionClientCtx sc_ctx;
 
+  ret = GNUNET_SERVER_client_get_user_context (client, struct Session);
   sc_ctx.client = client;
   sc_ctx.ret = NULL;
-  GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
+  GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
+                                         &session_lookup_by_client_it, &sc_ctx);
+  /* check both methods yield the same result */
+  GNUNET_break (ret == sc_ctx.ret);
   return sc_ctx.ret;
 }
 
 
+/**
+ * Functions with this signature are called whenever we need
+ * to close a session due to a disconnect or failure to
+ * establish a connection.
+ *
+ * @param cls the `struct Plugin`
+ * @param session session to close down
+ * @return #GNUNET_OK on success
+ */
+static int
+tcp_disconnect_session (void *cls,
+                        struct Session *session)
+{
+  struct Plugin *plugin = cls;
+  struct PendingMessage *pm;
+
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Disconnecting session of peer `%s' address `%s'\n",
+       GNUNET_i2s (&session->target),
+       tcp_address_to_string (NULL, session->addr, session->addrlen));
+
+  if (GNUNET_SCHEDULER_NO_TASK != session->timeout_task)
+  {
+    GNUNET_SCHEDULER_cancel (session->timeout_task);
+    session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
+  }
+
+  if (GNUNET_YES ==
+      GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
+                                            &session->target,
+                                            session))
+  {
+    GNUNET_STATISTICS_update (session->plugin->env->stats,
+                             gettext_noop ("# TCP sessions active"), -1,
+                             GNUNET_NO);
+  }
+  else
+  {
+    GNUNET_assert (GNUNET_YES ==
+                   GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
+                                                         &session->target,
+                                                         session));
+  }
+  if (NULL != session->client)
+    GNUNET_SERVER_client_set_user_context (session->client,
+                                           (void *) NULL);
+
+  /* clean up state */
+  if (NULL != session->transmit_handle)
+  {
+    GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
+    session->transmit_handle = NULL;
+  }
+  session->plugin->env->session_end (session->plugin->env->cls,
+                                     &session->target, session);
+
+  if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
+  {
+    GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
+    session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
+  }
+
+  while (NULL != (pm = session->pending_messages_head))
+  {
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        pm->transmit_cont !=
+        NULL ? "Could not deliver message to `%4s'.\n" :
+        "Could not deliver message to `%4s', notifying.\n",
+        GNUNET_i2s (&session->target));
+    GNUNET_STATISTICS_update (session->plugin->env->stats,
+                              gettext_noop ("# bytes currently in TCP buffers"),
+                              -(int64_t) pm->message_size, GNUNET_NO);
+    GNUNET_STATISTICS_update (session->plugin->env->stats,
+                              gettext_noop
+                              ("# bytes discarded by TCP (disconnect)"),
+                              pm->message_size, GNUNET_NO);
+    GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
+                                 session->pending_messages_tail, pm);
+    if (NULL != pm->transmit_cont)
+      pm->transmit_cont (pm->transmit_cont_cls, &session->target,
+                         GNUNET_SYSERR, pm->message_size, 0);
+    GNUNET_free (pm);
+  }
+  if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
+  {
+    GNUNET_SCHEDULER_cancel (session->receive_delay_task);
+    if (NULL != session->client)
+      GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
+  }
+  if (NULL != session->client)
+  {
+    GNUNET_SERVER_client_disconnect (session->client);
+    GNUNET_SERVER_client_drop (session->client);
+    session->client = NULL;
+  }
+  GNUNET_free_non_null (session->addr);
+  GNUNET_assert (NULL == session->transmit_handle);
+  GNUNET_free (session);
+  return GNUNET_OK;
+}
+
+
+/**
+ * Function that is called to get the keepalive factor.
+ * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
+ * calculate the interval between keepalive packets.
+ *
+ * @param cls closure with the `struct Plugin`
+ * @return keepalive factor
+ */
+static unsigned int
+tcp_query_keepalive_factor (void *cls)
+{
+  return 3;
+}
+
+
+/**
+ * Session was idle, so disconnect it
+ *
+ * @param cls the `struct Session` of the idle session
+ * @param tc scheduler context
+ */
+static void
+session_timeout (void *cls,
+                 const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct Session *s = cls;
+
+  s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+             "Session %p was idle for %s, disconnecting\n",
+             s,
+             GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
+                                                     GNUNET_YES));
+  /* call session destroy function */
+  tcp_disconnect_session (s->plugin, s);
+}
+
+
+/**
+ * Increment session timeout due to activity
+ *
+ * @param s session to increment timeout for
+ */
+static void
+reschedule_session_timeout (struct Session *s)
+{
+  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
+  GNUNET_SCHEDULER_cancel (s->timeout_task);
+  s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
+                                                  &session_timeout,
+                                                  s);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Timeout rescheduled for session %p set to %s\n",
+             s,
+             GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
+                                                     GNUNET_YES));
+}
+
+
 /**
  * Create a new session.  Also queues a welcome message.
  *
@@ -794,7 +936,8 @@ lookup_session_by_client (struct Plugin *plugin,
  * @return new session object
  */
 static struct Session *
-create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
+create_session (struct Plugin *plugin,
+                const struct GNUNET_PeerIdentity *target,
                 struct GNUNET_SERVER_Client *client, int is_nat)
 {
   struct Session *session;
@@ -806,17 +949,17 @@ create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
   else
     GNUNET_assert (NULL == client);
 
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Creating new session for peer `%4s'\n",
        GNUNET_i2s (target));
-  session = GNUNET_malloc (sizeof (struct Session));
+  session = GNUNET_new (struct Session);
   session->last_activity = GNUNET_TIME_absolute_get ();
   session->plugin = plugin;
   session->is_nat = is_nat;
   session->client = client;
   session->target = *target;
   session->expecting_welcome = GNUNET_YES;
-  session->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
+  session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
                       sizeof (struct WelcomeMessage));
   pm->msg = (const char *) &pm[1];
@@ -837,8 +980,9 @@ create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
                               gettext_noop ("# TCP sessions active"), 1,
                               GNUNET_NO);
   }
-  start_session_timeout (session);
-
+  session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
+                                                        &session_timeout,
+                                                        session);
   return session;
 }
 
@@ -877,12 +1021,11 @@ do_transmit (void *cls, size_t size, void *buf)
   char *cbuf;
   size_t ret;
 
-  GNUNET_assert (NULL != session);
   session->transmit_handle = NULL;
   plugin = session->plugin;
   if (NULL == buf)
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
         GNUNET_i2s (&session->target));
     /* timeout; cancel all messages that have already expired */
@@ -891,7 +1034,7 @@ do_transmit (void *cls, size_t size, void *buf)
     ret = 0;
     now = GNUNET_TIME_absolute_get ();
     while ((NULL != (pos = session->pending_messages_head)) &&
-           (pos->timeout.abs_value <= now.abs_value))
+           (pos->timeout.abs_value_us <= now.abs_value_us))
     {
       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
                                    session->pending_messages_tail, pos);
@@ -936,7 +1079,7 @@ do_transmit (void *cls, size_t size, void *buf)
     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
                                  session->pending_messages_tail, pos);
     GNUNET_assert (size >= pos->message_size);
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Transmitting message of type %u\n",
         ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
     /* FIXME: this memcpy can be up to 7% of our total runtime */
@@ -986,8 +1129,8 @@ process_pending_messages (struct Session *session)
 {
   struct PendingMessage *pm;
 
-  GNUNET_assert (session->client != NULL);
-  if (session->transmit_handle != NULL)
+  GNUNET_assert (NULL != session->client);
+  if (NULL != session->transmit_handle)
     return;
   if (NULL == (pm = session->pending_messages_head))
     return;
@@ -1000,129 +1143,80 @@ process_pending_messages (struct Session *session)
 }
 
 
+#if EXTRA_CHECKS
 /**
- * Functions with this signature are called whenever we need
- * to close a session due to a disconnect or failure to
- * establish a connection.
- *
- * @param session session to close down
+ * Closure for #session_it().
  */
-static void
-disconnect_session (struct Session *session)
-{
-  struct PendingMessage *pm;
-  struct Plugin * plugin = session->plugin;
-
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
-       "Disconnecting session of peer `%s' address `%s'\n",
-       GNUNET_i2s (&session->target),
-       tcp_address_to_string (NULL, session->addr, session->addrlen));
-
-  stop_session_timeout (session);
-
-  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (plugin->sessionmap, &session->target.hashPubKey, session))
-  {
-    GNUNET_STATISTICS_update (session->plugin->env->stats,
-                             gettext_noop ("# TCP sessions active"), -1,
-                             GNUNET_NO);
-    dec_sessions (plugin, session, __LINE__);
-  }
-  else GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (plugin->nat_wait_conns, &session->target.hashPubKey, session));
-
-  /* clean up state */
-  if (session->transmit_handle != NULL)
-  {
-    GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
-    session->transmit_handle = NULL;
-  }
-  session->plugin->env->session_end (session->plugin->env->cls,
-                                     &session->target, session);
-
-  if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
-  {
-    GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
-    session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
-  }
-
-  while (NULL != (pm = session->pending_messages_head))
-  {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
-        pm->transmit_cont !=
-        NULL ? "Could not deliver message to `%4s'.\n" :
-        "Could not deliver message to `%4s', notifying.\n",
-        GNUNET_i2s (&session->target));
-    GNUNET_STATISTICS_update (session->plugin->env->stats,
-                              gettext_noop ("# bytes currently in TCP buffers"),
-                              -(int64_t) pm->message_size, GNUNET_NO);
-    GNUNET_STATISTICS_update (session->plugin->env->stats,
-                              gettext_noop
-                              ("# bytes discarded by TCP (disconnect)"),
-                              pm->message_size, GNUNET_NO);
-    GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
-                                 session->pending_messages_tail, pm);
-    if (NULL != pm->transmit_cont)
-      pm->transmit_cont (pm->transmit_cont_cls, &session->target,
-                         GNUNET_SYSERR, pm->message_size, 0);
-    GNUNET_free (pm);
-  }
-  if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
-  {
-    GNUNET_SCHEDULER_cancel (session->receive_delay_task);
-    if (NULL != session->client)
-      GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
-  }
-  if (NULL != session->client)
-  {
-    GNUNET_SERVER_client_disconnect (session->client);
-    GNUNET_SERVER_client_drop (session->client);
-    session->client = NULL;
-  }
-  GNUNET_free_non_null (session->addr);
-  GNUNET_assert (NULL == session->transmit_handle);
-  GNUNET_free (session);
-}
-
-
 struct FindSessionContext
 {
+  /**
+   * Session we are looking for.
+   */
   struct Session *s;
+
+  /**
+   * Set to #GNUNET_OK if we found the session.
+   */
   int res;
 };
 
-int session_it (void *cls,
-               const struct GNUNET_HashCode * key,
-               void *value)
+
+/**
+ * Function called to check if a session is in our maps.
+ *
+ * @param cls the `struct FindSessionContext`
+ * @param key peer identity
+ * @param value session in the map
+ * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
+ */
+static int
+session_it (void *cls,
+           const struct GNUNET_PeerIdentity *key,
+           void *value)
 {
   struct FindSessionContext *res = cls;
-  if (res->s == value)
+  struct Session *session = value;
+
+  if (res->s == session)
   {
     res->res = GNUNET_OK;
     return GNUNET_NO;
   }
-  else
-    return GNUNET_YES;
+  return GNUNET_YES;
 }
 
-int find_session (struct Plugin *plugin, struct Session *session)
+
+/**
+ * Check that the given session is known to the plugin and
+ * is in one of our maps.
+ *
+ * @param plugin the plugin to check against
+ * @param session the session to check
+ * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
+ */
+static int
+find_session (struct Plugin *plugin,
+              struct Session *session)
 {
   struct FindSessionContext session_map_res;
   struct FindSessionContext nat_map_res;
 
   session_map_res.s = session;
   session_map_res.res = GNUNET_SYSERR;
-  GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_it, &session_map_res);
-
+  GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
+                                         &session_it, &session_map_res);
+  if (GNUNET_SYSERR != session_map_res.res)
+    return GNUNET_OK;
   nat_map_res.s = session;
   nat_map_res.res = GNUNET_SYSERR;
-  GNUNET_CONTAINER_multihashmap_iterate (plugin->nat_wait_conns, &session_it, &nat_map_res);
-
-  if ((session_map_res.res == GNUNET_SYSERR) && (nat_map_res.res == GNUNET_SYSERR))
-  {
-    GNUNET_break (0);
-    return GNUNET_SYSERR;
-  }
-  return GNUNET_OK;
+  GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
+                                         &session_it, &nat_map_res);
+  if (GNUNET_SYSERR != nat_map_res.res)
+    return GNUNET_OK;
+  GNUNET_break (0);
+  return GNUNET_SYSERR;
 }
+#endif
 
 
 /**
@@ -1147,32 +1241,31 @@ int find_session (struct Plugin *plugin, struct Session *session)
  *        been transmitted (or if the transport is ready
  *        for the next transmission call; or if the
  *        peer disconnected...); can be NULL
- * @param cont_cls closure for cont
+ * @param cont_cls closure for @a cont
  * @return number of bytes used (on the physical network, with overheads);
  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
  *         and does NOT mean that the message was not transmitted (DV)
  */
 static ssize_t
 tcp_plugin_send (void *cls,
-    struct Session *session,
-    const char *msgbuf, size_t msgbuf_size,
-    unsigned int priority,
-    struct GNUNET_TIME_Relative to,
-    GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
+                 struct Session *session,
+                 const char *msgbuf, size_t msgbuf_size,
+                 unsigned int priority,
+                 struct GNUNET_TIME_Relative to,
+                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
 {
   struct Plugin * plugin = cls;
   struct PendingMessage *pm;
 
-  GNUNET_assert (NULL != plugin);
-  GNUNET_assert (NULL != session);
-
-  if (GNUNET_SYSERR == find_session(plugin, session))
+#if EXTRA_CHECKS
+  if (GNUNET_SYSERR == find_session (plugin, session))
   {
-      LOG (GNUNET_ERROR_TYPE_ERROR,
-           _("Trying to send with invalid session %p\n"));
-      return GNUNET_SYSERR;
+    LOG (GNUNET_ERROR_TYPE_ERROR,
+         _("Trying to send with invalid session %p\n"));
+    GNUNET_assert (0);
+    return GNUNET_SYSERR;
   }
-
+#endif
   /* create new message entry */
   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
   pm->msg = (const char *) &pm[1];
@@ -1182,16 +1275,16 @@ tcp_plugin_send (void *cls,
   pm->transmit_cont = cont;
   pm->transmit_cont_cls = cont_cls;
 
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Asked to transmit %u bytes to `%s', added message to list.\n",
        msgbuf_size, GNUNET_i2s (&session->target));
 
-  if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value (plugin->sessionmap, 
-                                                                 &session->target.hashPubKey, 
-                                                                 session))
+  if (GNUNET_YES ==
+      GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
+                                                    &session->target,
+                                                    session))
   {
-    GNUNET_assert (session->client != NULL);
-    reschedule_session_timeout (session);
+    GNUNET_assert (NULL != session->client);
     GNUNET_SERVER_client_set_timeout (session->client,
                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
     GNUNET_STATISTICS_update (plugin->env->stats,
@@ -1205,12 +1298,14 @@ tcp_plugin_send (void *cls,
     process_pending_messages (session);
     return msgbuf_size;
   }
-  else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
+  else if (GNUNET_YES ==
+           GNUNET_CONTAINER_multipeermap_contains_value(plugin->nat_wait_conns,
+                                                        &session->target,
+                                                        session))
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "This NAT WAIT session for peer `%s' is not yet ready!\n",
         GNUNET_i2s (&session->target));
-    reschedule_session_timeout (session);
     GNUNET_STATISTICS_update (plugin->env->stats,
                               gettext_noop ("# bytes currently in TCP buffers"),
                               msgbuf_size, GNUNET_NO);
@@ -1225,7 +1320,11 @@ tcp_plugin_send (void *cls,
     LOG (GNUNET_ERROR_TYPE_ERROR,
          "Invalid session %p\n", session);
     if (NULL != cont)
-      cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
+      cont (cont_cls,
+            &session->target,
+            GNUNET_SYSERR,
+            pm->message_size,
+            0);
     GNUNET_break (0);
     GNUNET_free (pm);
     return GNUNET_SYSERR; /* session does not exist here */
@@ -1233,53 +1332,48 @@ tcp_plugin_send (void *cls,
 }
 
 
+/**
+ * Closure for #session_lookup_it().
+ */
 struct SessionItCtx
 {
+  /**
+   * Address we are looking for.
+   */
   void *addr;
+
+  /**
+   * Number of bytes in @e addr.
+   */
   size_t addrlen;
+
+  /**
+   * Where to store the session (if we found it).
+   */
   struct Session *result;
 };
 
 
-static int 
+/**
+ * Look for a session by address.
+ *
+ * @param cls the `struct SessionItCtx`
+ * @param key unused
+ * @param value a `struct Session`
+ * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
+ */
+static int
 session_lookup_it (void *cls,
-                  const struct GNUNET_HashCode *key,
+                  const struct GNUNET_PeerIdentity *key,
                   void *value)
 {
   struct SessionItCtx * si_ctx = cls;
   struct Session * session = value;
-#if 0
-  char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
-  char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
-  LOG (GNUNET_ERROR_TYPE_DEBUG,
-       "Comparing: %s %u <-> %s %u\n",
-       a1,
-       session->addrlen,
-       a2,
-       si_ctx->addrlen);
-  GNUNET_free (a1);
-  GNUNET_free (a2);
-#endif
+
   if (session->addrlen != si_ctx->addrlen)
-  {
     return GNUNET_YES;
-  }
   if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
-  {
     return GNUNET_YES;
-  }
-#if 0
-  a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
-  a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
-  LOG (GNUNET_ERROR_TYPE_DEBUG,
-       "Comparing: %s %u <-> %s %u , OK!\n",
-       a1,
-       session->addrlen,
-       a2,
-       si_ctx->addrlen);
-  GNUNET_free (a1);
-  GNUNET_free (a2);
-#endif
   /* Found existing session */
   si_ctx->result = session;
   return GNUNET_NO;
@@ -1288,17 +1382,37 @@ session_lookup_it (void *cls,
 
 /**
  * Task cleaning up a NAT connection attempt after timeout
+ *
+ * @param cls the `struct Session`
+ * @param tc scheduler context (unused)
  */
 static void
-nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+nat_connect_timeout (void *cls,
+                     const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct Session *session = cls;
 
   session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
   LOG (GNUNET_ERROR_TYPE_DEBUG,
        "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
-       GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
-  disconnect_session (session);
+       GNUNET_i2s (&session->target),
+       tcp_address_to_string (NULL,
+                              session->addr, session->addrlen));
+  tcp_disconnect_session (session->plugin,
+                          session);
+}
+
+
+static void
+tcp_plugin_update_session_timeout (void *cls,
+                                  const struct GNUNET_PeerIdentity *peer,
+                                  struct Session *session)
+{
+  struct Plugin *plugin = cls;
+
+  if (GNUNET_SYSERR == find_session (plugin, session))
+    return;
+  reschedule_session_timeout (session);
 }
 
 
@@ -1308,7 +1422,7 @@ nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
  * notify us by calling the env->session_end function
  *
  * @param cls closure
- * @param address pointer to the GNUNET_HELLO_Address
+ * @param address the address to use
  * @return the session if the address is valid, NULL otherwise
  */
 static struct Session *
@@ -1329,18 +1443,16 @@ tcp_plugin_get_session (void *cls,
   unsigned int is_natd = GNUNET_NO;
   size_t addrlen;
 
-  GNUNET_assert (plugin != NULL);
-  GNUNET_assert (address != NULL);
   addrlen = address->address_length;
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Trying to get session for `%s' address of peer `%s'\n",
        tcp_address_to_string(NULL, address->address, address->address_length),
        GNUNET_i2s (&address->peer));
 
   /* look for existing session */
-  if (GNUNET_YES == 
-      GNUNET_CONTAINER_multihashmap_contains (plugin->sessionmap, 
-                                             &address->peer.hashPubKey))
+  if (GNUNET_YES ==
+      GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
+                                             &address->peer))
   {
     struct SessionItCtx si_ctx;
 
@@ -1349,13 +1461,13 @@ tcp_plugin_get_session (void *cls,
 
     si_ctx.result = NULL;
 
-    GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, 
-                                               &address->peer.hashPubKey, 
+    GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
+                                               &address->peer,
                                                &session_lookup_it, &si_ctx);
     if (si_ctx.result != NULL)
     {
       session = si_ctx.result;
-      LOG (GNUNET_ERROR_TYPE_DEBUG, 
+      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Found existing session for `%s' address `%s' session %p\n",
           GNUNET_i2s (&address->peer),
           tcp_address_to_string(NULL, address->address, address->address_length),
@@ -1404,13 +1516,14 @@ tcp_plugin_get_session (void *cls,
   }
   else
   {
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-       _("Trying to create session for address of unexpected length %u (should be %u or %u)\n"),
-                 addrlen, sizeof (struct IPv4TcpAddress), sizeof (struct IPv6TcpAddress));
+    GNUNET_STATISTICS_update (plugin->env->stats,
+                              gettext_noop
+                              ("# requests to create session with invalid address"),
+                              1, GNUNET_NO);
     return NULL;
   }
 
-  ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
+  ats = plugin->env->get_address_type (plugin->env->cls, sbsbs);
 
   if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
   {
@@ -1426,8 +1539,8 @@ tcp_plugin_get_session (void *cls,
 
   if ((is_natd == GNUNET_YES) &&
       (GNUNET_YES ==
-       GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
-                                               &address->peer.hashPubKey)))
+       GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
+                                               &address->peer)))
   {
     /* Only do one NAT punch attempt per peer identity */
      return NULL;
@@ -1435,26 +1548,30 @@ tcp_plugin_get_session (void *cls,
 
   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
       (GNUNET_NO ==
-       GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
-                                               &address->peer.hashPubKey)))
+       GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
+                                               &address->peer)))
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Found valid IPv4 NAT address (creating session)!\n") ;
-    session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
+    session = create_session (plugin,
+                              &address->peer,
+                              NULL,
+                              GNUNET_YES);
     session->addrlen = 0;
     session->addr = NULL;
-    session->ats_address_network_type = ats.value;
+    session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
+    GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
                                                                    &nat_connect_timeout,
                                                                    session);
     GNUNET_assert (session != NULL);
     GNUNET_assert (GNUNET_OK ==
-                  GNUNET_CONTAINER_multihashmap_put (plugin->nat_wait_conns, 
-                                                     &session->target.hashPubKey, 
+                  GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
+                                                     &session->target,
                                                      session,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
 
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Created NAT WAIT connection to `%4s' at `%s'\n",
         GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
 
@@ -1462,10 +1579,10 @@ tcp_plugin_get_session (void *cls,
       return session;
     else
     {
-      LOG (GNUNET_ERROR_TYPE_DEBUG, 
+      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Running NAT client for `%4s' at `%s' failed\n",
           GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
-      disconnect_session (session);
+      tcp_disconnect_session (plugin, session);
       return NULL;
     }
   }
@@ -1473,20 +1590,21 @@ tcp_plugin_get_session (void *cls,
   /* create new outbound session */
   GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
-  if (sa == NULL)
+  if (NULL == sa)
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Failed to create connection to `%4s' at `%s'\n",
         GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
     return NULL;
   }
   plugin->cur_connections++;
   if (plugin->cur_connections == plugin->max_connections)
-       GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
+    GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
 
   LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
-       GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
+       GNUNET_i2s (&address->peer),
+       GNUNET_a2s (sb, sbs));
 
   session = create_session (plugin,
                             &address->peer,
@@ -1495,12 +1613,13 @@ tcp_plugin_get_session (void *cls,
   session->addr = GNUNET_malloc (addrlen);
   memcpy (session->addr, address->address, addrlen);
   session->addrlen = addrlen;
-  session->ats_address_network_type = ats.value;
-
-  GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap, 
-                                    &session->target.hashPubKey, 
-                                    session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
-  inc_sessions (plugin, session, __LINE__);
+  session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
+  GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
+  GNUNET_SERVER_client_set_user_context (session->client, session);
+  GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
+                                    &session->target,
+                                    session,
+                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
   LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Creating new session for `%s' address `%s' session %p\n",
        GNUNET_i2s (&address->peer),
@@ -1513,18 +1632,20 @@ tcp_plugin_get_session (void *cls,
 }
 
 
-static int 
+static int
 session_disconnect_it (void *cls,
-                      const struct GNUNET_HashCode * key,
+                      const struct GNUNET_PeerIdentity *key,
                       void *value)
 {
+  struct Plugin *plugin = cls;
   struct Session *session = value;
 
   GNUNET_STATISTICS_update (session->plugin->env->stats,
                             gettext_noop
                             ("# transport-service disconnect requests for TCP"),
                             1, GNUNET_NO);
-  disconnect_session (session);
+  tcp_disconnect_session (plugin,
+                          session);
   return GNUNET_YES;
 }
 
@@ -1546,22 +1667,56 @@ session_disconnect_it (void *cls,
  *        to be cancelled
  */
 static void
-tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
+tcp_plugin_disconnect (void *cls,
+                       const struct GNUNET_PeerIdentity *target)
 {
   struct Plugin *plugin = cls;
 
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
-       "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
-  GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, &session_disconnect_it, plugin);
-  GNUNET_CONTAINER_multihashmap_get_multiple (plugin->nat_wait_conns, &target->hashPubKey, &session_disconnect_it, plugin);
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Disconnecting peer `%4s'\n",
+       GNUNET_i2s (target));
+  GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
+                                             &session_disconnect_it, plugin);
+  GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
+                                             &session_disconnect_it, plugin);
 }
 
 
+/**
+ * Running pretty printers: head
+ */
+static struct PrettyPrinterContext *ppc_dll_head;
+
+/**
+ * Running pretty printers: tail
+ */
+static struct PrettyPrinterContext *ppc_dll_tail;
+
 /**
  * Context for address to string conversion.
  */
 struct PrettyPrinterContext
 {
+  /**
+   * DLL
+   */
+  struct PrettyPrinterContext *next;
+
+  /**
+   * DLL
+   */
+  struct PrettyPrinterContext *prev;
+
+  /**
+   * Timeout task
+   */
+  GNUNET_SCHEDULER_TaskIdentifier timeout_task;
+
+  /**
+   * Resolver handle
+   */
+  struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
+
   /**
    * Function to call with the result.
    */
@@ -1589,6 +1744,23 @@ struct PrettyPrinterContext
 };
 
 
+static void
+ppc_cancel_task (void *cls,
+                 const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct PrettyPrinterContext *ppc = cls;
+
+  ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
+  if (NULL != ppc->resolver_handle)
+  {
+    GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
+    ppc->resolver_handle = NULL;
+  }
+  GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
+  GNUNET_free (ppc);
+}
+
+
 /**
  * Append our port and forward the result.
  *
@@ -1599,18 +1771,42 @@ static void
 append_port (void *cls, const char *hostname)
 {
   struct PrettyPrinterContext *ppc = cls;
+  struct PrettyPrinterContext *cur;
   char *ret;
 
-  if (hostname == NULL)
+  if (NULL == hostname)
   {
     ppc->asc (ppc->asc_cls, NULL);
+    GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
+    GNUNET_SCHEDULER_cancel (ppc->timeout_task);
+    ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
+    ppc->resolver_handle = NULL;
     GNUNET_free (ppc);
     return;
   }
+  for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
+    if (cur == ppc)
+      break;
+  if (NULL == cur)
+  {
+    GNUNET_break (0);
+    return;
+  }
+
   if (GNUNET_YES == ppc->ipv6)
-    GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
+    GNUNET_asprintf (&ret,
+                     "%s.%u.[%s]:%d",
+                     PLUGIN_NAME,
+                     ppc->options,
+                     hostname,
+                     ppc->port);
   else
-    GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
+    GNUNET_asprintf (&ret,
+                     "%s.%u.%s:%d",
+                     PLUGIN_NAME,
+                     ppc->options,
+                     hostname,
+                     ppc->port);
   ppc->asc (ppc->asc_cls, ret);
   GNUNET_free (ret);
 }
@@ -1648,8 +1844,6 @@ tcp_plugin_address_pretty_printer (void *cls, const char *type,
   uint16_t port;
   uint32_t options;
 
-
-  options = 0;
   if (addrlen == sizeof (struct IPv6TcpAddress))
   {
     t6 = addr;
@@ -1676,7 +1870,7 @@ tcp_plugin_address_pretty_printer (void *cls, const char *type,
   }
   else if (0 == addrlen)
   {
-    asc (asc_cls, "<inbound connection>");
+    asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
     asc (asc_cls, NULL);
     return;
   }
@@ -1687,7 +1881,7 @@ tcp_plugin_address_pretty_printer (void *cls, const char *type,
     asc (asc_cls, NULL);
     return;
   }
-  ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
+  ppc = GNUNET_new (struct PrettyPrinterContext);
   if (addrlen == sizeof (struct IPv6TcpAddress))
     ppc->ipv6 = GNUNET_YES;
   else
@@ -1696,7 +1890,21 @@ tcp_plugin_address_pretty_printer (void *cls, const char *type,
   ppc->asc_cls = asc_cls;
   ppc->port = port;
   ppc->options = options;
-  GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
+  ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(timeout, 2),
+                                                    &ppc_cancel_task, ppc);
+  ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
+                                                       timeout,
+                                                       &append_port, ppc);
+  if (NULL != ppc->resolver_handle)
+  {
+    //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
+    GNUNET_CONTAINER_DLL_insert (ppc_dll_head, ppc_dll_tail, ppc);
+  }
+  else
+  {
+    GNUNET_break (0);
+    GNUNET_free (ppc);
+  }
 }
 
 
@@ -1704,11 +1912,11 @@ tcp_plugin_address_pretty_printer (void *cls, const char *type,
  * Check if the given port is plausible (must be either our listen
  * port or our advertised port), or any port if we are behind NAT
  * and do not have a port open.  If it is neither, we return
- * GNUNET_SYSERR.
+ * #GNUNET_SYSERR.
  *
  * @param plugin global variables
  * @param in_port port number to check
- * @return GNUNET_OK if port is either open_port or adv_port
+ * @return #GNUNET_OK if port is either open_port or adv_port
  */
 static int
 check_port (struct Plugin *plugin, uint16_t in_port)
@@ -1728,11 +1936,11 @@ check_port (struct Plugin *plugin, uint16_t in_port)
  * traffic to a 3rd party that might try to man-in-the-middle our
  * traffic.
  *
- * @param cls closure, our 'struct Plugin*'
+ * @param cls closure, our `struct Plugin *`
  * @param addr pointer to the address
  * @param addrlen length of addr
- * @return GNUNET_OK if this is a plausible address for this peer
- *         and transport, GNUNET_SYSERR if not
+ * @return #GNUNET_OK if this is a plausible address for this peer
+ *         and transport, #GNUNET_SYSERR if not
  */
 static int
 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
@@ -1748,14 +1956,13 @@ tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
     return GNUNET_SYSERR;
   }
 
-
   if (addrlen == sizeof (struct IPv4TcpAddress))
   {
     v4 = (struct IPv4TcpAddress *) addr;
     if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
     {
-       GNUNET_break (0);
-       return GNUNET_SYSERR;
+      GNUNET_break (0);
+      return GNUNET_SYSERR;
     }
     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
       return GNUNET_SYSERR;
@@ -1798,7 +2005,8 @@ tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
  * @param message the actual message
  */
 static void
-handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
+handle_tcp_nat_probe (void *cls,
+                      struct GNUNET_SERVER_Client *client,
                       const struct GNUNET_MessageHeader *message)
 {
   struct Plugin *plugin = cls;
@@ -1811,8 +2019,8 @@ handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
   const struct sockaddr_in *s4;
   const struct sockaddr_in6 *s6;
 
-  LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
-
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Received NAT probe\n");
   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
    * a connection to this peer by running gnunet-nat-client.  This peer
    * received the punch message and now wants us to use the new connection
@@ -1837,17 +2045,16 @@ handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
   }
 
   session =
-      GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
-                                         &tcp_nat_probe->
-                                         clientIdentity.hashPubKey);
+    GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
+                                       &tcp_nat_probe->clientIdentity);
   if (session == NULL)
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Did NOT find session for NAT probe!\n");
     GNUNET_SERVER_receive_done (client, GNUNET_OK);
     return;
   }
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Found session for NAT probe!\n");
 
   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
@@ -1860,26 +2067,27 @@ handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
   {
     GNUNET_break (0);
     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
-    disconnect_session (session);
+    tcp_disconnect_session (plugin, session);
     return;
   }
-  GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
+  GNUNET_assert (GNUNET_CONTAINER_multipeermap_remove
                  (plugin->nat_wait_conns,
-                  &tcp_nat_probe->clientIdentity.hashPubKey,
+                  &tcp_nat_probe->clientIdentity,
                   session) == GNUNET_YES);
-  GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap,
-                                    &session->target.hashPubKey, session, 
-                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
+  GNUNET_SERVER_client_set_user_context (client, session);
+  GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
+                                    &session->target, session,
+                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
   session->last_activity = GNUNET_TIME_absolute_get ();
   session->inbound = GNUNET_NO;
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Found address `%s' for incoming connection\n",
        GNUNET_a2s (vaddr, alen));
   switch (((const struct sockaddr *) vaddr)->sa_family)
   {
   case AF_INET:
     s4 = vaddr;
-    t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
+    t4 = GNUNET_new (struct IPv4TcpAddress);
     t4->options = 0;
     t4->t4_port = s4->sin_port;
     t4->ipv4_addr = s4->sin_addr.s_addr;
@@ -1888,7 +2096,7 @@ handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
     break;
   case AF_INET6:
     s6 = vaddr;
-    t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
+    t6 = GNUNET_new (struct IPv6TcpAddress);
     t6->options = 0;
     t6->t6_port = s6->sin6_port;
     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
@@ -1897,18 +2105,17 @@ handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
     break;
   default:
     GNUNET_break_op (0);
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Bad address for incoming connection!\n");
     GNUNET_free (vaddr);
     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
-    disconnect_session (session);
+    tcp_disconnect_session (plugin, session);
     return;
   }
   GNUNET_free (vaddr);
   GNUNET_break (NULL == session->client);
   GNUNET_SERVER_client_keep (client);
   session->client = client;
-  inc_sessions (plugin, session, __LINE__);
   GNUNET_STATISTICS_update (plugin->env->stats,
                             gettext_noop ("# TCP sessions active"), 1,
                             GNUNET_NO);
@@ -1946,7 +2153,14 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
   {
     /* refuse connections from ourselves */
     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
-    GNUNET_break (0);
+    if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
+    {
+       LOG (GNUNET_ERROR_TYPE_WARNING,
+         "Received %s message from my own identity `%4s' on address `%s'\n",
+         "WELCOME", GNUNET_i2s (&wm->clientIdentity), GNUNET_a2s (vaddr, alen));
+       GNUNET_free (vaddr);
+    }
+    GNUNET_break_op (0);
     return;
   }
   LOG (GNUNET_ERROR_TYPE_DEBUG,
@@ -1956,9 +2170,10 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
                             gettext_noop ("# TCP WELCOME messages received"), 1,
                             GNUNET_NO);
   session = lookup_session_by_client (plugin, client);
-  if (session != NULL)
+  if (NULL != session)
   {
-    if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
+    if (GNUNET_OK ==
+        GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
     {
       LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Found existing session %p for peer `%s'\n",
@@ -1970,7 +2185,7 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
   else
   {
     GNUNET_SERVER_client_keep (client);
-    if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
+    if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
        plugin->cur_connections++;
     if (plugin->cur_connections == plugin->max_connections)
        GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
@@ -1982,7 +2197,7 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
       if (alen == sizeof (struct sockaddr_in))
       {
         s4 = vaddr;
-        t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
+        t4 = GNUNET_new (struct IPv4TcpAddress);
         t4->options = htonl (0);
         t4->t4_port = s4->sin_port;
         t4->ipv4_addr = s4->sin_addr.s_addr;
@@ -1992,7 +2207,7 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
       else if (alen == sizeof (struct sockaddr_in6))
       {
         s6 = vaddr;
-        t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
+        t6 = GNUNET_new (struct IPv6TcpAddress);
         t6->options = htonl (0);
         t6->t6_port = s6->sin6_port;
         memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
@@ -2001,21 +2216,21 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
       }
 
       ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
-      session->ats_address_network_type = ats.value;
+      session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
       LOG (GNUNET_ERROR_TYPE_DEBUG,
-     "Creating new session %p for peer `%s'\n",
-     session,
-     GNUNET_a2s (vaddr, alen));
+           "Creating new session %p for peer `%s'\n",
+           session,
+           GNUNET_a2s (vaddr, alen));
       GNUNET_free (vaddr);
-      GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap,
-                                      &session->target.hashPubKey,
-                                      session,
-                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
-      inc_sessions (plugin, session, __LINE__);
+      GNUNET_SERVER_client_set_user_context (session->client, session);
+      GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
+                                         &session->target,
+                                         session,
+                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
     }
     else
     {
-      LOG (GNUNET_ERROR_TYPE_DEBUG, 
+      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Did not obtain TCP socket address for incoming connection\n");
       GNUNET_break (0);
     }
@@ -2031,14 +2246,17 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
   session->last_activity = GNUNET_TIME_absolute_get ();
   session->expecting_welcome = GNUNET_NO;
 
-
   /* Notify transport and ATS about new session */
-  plugin->env->session_start (NULL, &wm->clientIdentity,
-               PLUGIN_NAME, session->addr, session->addrlen, session, &ats, 1);
-
-
+  if (GNUNET_YES == session->inbound)
+  {
+    plugin->env->session_start (NULL,
+                                &wm->clientIdentity,
+                                PLUGIN_NAME,
+                                (GNUNET_YES == session->inbound) ? NULL : session->addr,
+                                (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
+                                session, &ats, 1);
+  }
   process_pending_messages (session);
-
   GNUNET_SERVER_client_set_timeout (client,
                                     GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
   GNUNET_SERVER_receive_done (client, GNUNET_OK);
@@ -2049,11 +2267,12 @@ handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
  * Task to signal the server that we can continue
  * receiving from the TCP client now.
  *
- * @param cls the 'struct Session*'
+ * @param cls the `struct Session*`
  * @param tc task context (unused)
  */
 static void
-delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+delayed_done (void *cls,
+              const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct Session *session = cls;
 
@@ -2095,9 +2314,9 @@ handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
     /* No inbound session found */
     void *vaddr;
     size_t alen;
-    
+
     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
-    LOG (GNUNET_ERROR_TYPE_ERROR, 
+    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Received unexpected %u bytes of type %u from `%s'\n",
         (unsigned int) ntohs (message->size),
         (unsigned int) ntohs (message->type),
@@ -2114,7 +2333,7 @@ handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
     size_t alen;
 
     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
-    LOG (GNUNET_ERROR_TYPE_ERROR, 
+    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Received unexpected %u bytes of type %u from `%s'\n",
         (unsigned int) ntohs (message->size),
         (unsigned int) ntohs (message->type),
@@ -2126,7 +2345,7 @@ handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
   }
 
   session->last_activity = GNUNET_TIME_absolute_get ();
-  LOG (GNUNET_ERROR_TYPE_DEBUG, 
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
                    (unsigned int) ntohs (message->size),
                    (unsigned int) ntohs (message->type),
@@ -2138,12 +2357,12 @@ handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
   struct GNUNET_ATS_Information distance;
 
   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
-  distance.value = session->ats_address_network_type;
-  GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
+  distance.value = htonl ((uint32_t) session->ats_address_network_type);
+  GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
 
-  GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains_value (plugin->sessionmap,
-      &session->target.hashPubKey,
-      session));
+  GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
+                                                              &session->target,
+                                                              session));
 
   delay = plugin->env->receive (plugin->env->cls,
                                 &session->target,
@@ -2152,28 +2371,24 @@ handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
                                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
                                 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
   plugin->env->update_address_metrics (plugin->env->cls,
-               &session->target,
-               (GNUNET_YES == session->inbound) ? NULL : session->addr,
-                                      (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
-                                      session,
-                                      &distance,
-                                      1);
-
+                                       &session->target,
+                                       (GNUNET_YES == session->inbound) ? NULL : session->addr,
+                                       (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
+                                       session, &distance, 1);
   reschedule_session_timeout (session);
-
-  if (delay.rel_value == 0)
+  if (0 == delay.rel_value_us)
   {
     GNUNET_SERVER_receive_done (client, GNUNET_OK);
   }
   else
   {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, 
-        "Throttling receiving from `%s' for %llu ms\n",
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        "Throttling receiving from `%s' for %s\n",
         GNUNET_i2s (&session->target),
-        (unsigned long long) delay.rel_value);
+        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
     GNUNET_SERVER_disable_receive_done_warning (client);
     session->receive_delay_task =
-        GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
+      GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
   }
 }
 
@@ -2206,18 +2421,18 @@ disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
        "*");
 
   if (plugin->cur_connections == plugin->max_connections)
-       GNUNET_SERVER_resume (plugin->server); /* Resume server  */
+    GNUNET_SERVER_resume (plugin->server); /* Resume server  */
 
   if (plugin->cur_connections < 1)
-       GNUNET_break (0);
+    GNUNET_break (0);
   else
-       plugin->cur_connections--;
+    plugin->cur_connections--;
 
   GNUNET_STATISTICS_update (session->plugin->env->stats,
                             gettext_noop
                             ("# network-level TCP disconnect events"), 1,
                             GNUNET_NO);
-  disconnect_session (session);
+  tcp_disconnect_session (plugin, session);
 }
 
 
@@ -2262,7 +2477,7 @@ notify_send_probe (void *cls, size_t size, void *buf)
  *
  * @param cls closure
  * @param addr address to try
- * @param addrlen number of bytes in addr
+ * @param addrlen number of bytes in @a addr
  */
 static void
 try_connection_reversal (void *cls, const struct sockaddr *addr,
@@ -2285,7 +2500,7 @@ try_connection_reversal (void *cls, const struct sockaddr *addr,
 
   /* FIXME: do we need to track these probe context objects so that
    * we can clean them up on plugin unload? */
-  tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
+  tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
   tcp_probe_ctx->message.header.size =
       htons (sizeof (struct TCP_NAT_ProbeMessage));
   tcp_probe_ctx->message.header.type =
@@ -2307,90 +2522,19 @@ try_connection_reversal (void *cls, const struct sockaddr *addr,
 }
 
 
-/**
- * Session was idle, so disconnect it
- */
-static void
-session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
-  GNUNET_assert (NULL != cls);
-  struct Session *s = cls;
-
-  s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-             "Session %p was idle for %llu ms, disconnecting\n",
-             s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
-  /* call session destroy function */
-  disconnect_session(s);
-}
-
-
-/**
- * Start session timeout
- */
-static void
-start_session_timeout (struct Session *s)
-{
-  GNUNET_assert (NULL != s);
-  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
-  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
-                                                   &session_timeout,
-                                                   s);
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-             "Timeout for session %p set to %llu ms\n",
-             s,  (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
-}
-
-
-/**
- * Increment session timeout due to activity
- */
-static void
-reschedule_session_timeout (struct Session *s)
-{
-  GNUNET_assert (NULL != s);
-  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
-
-  GNUNET_SCHEDULER_cancel (s->timeout_task);
-  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
-                                                   &session_timeout,
-                                                   s);
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-              "Timeout rescheduled for session %p set to %llu ms\n",
-             s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
-}
-
-
-/**
- * Cancel timeout
- */
-static void
-stop_session_timeout (struct Session *s)
-{
-  GNUNET_assert (NULL != s);
-
-  if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
-  {
-    GNUNET_SCHEDULER_cancel (s->timeout_task);
-    s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                "Timeout stopped for session %p canceled\n",
-                s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
-  }
-}
-
 /**
  * Function obtain the network type for a session
  *
  * @param cls closure ('struct Plugin*')
  * @param session the session
- * @return the network type in HBO or GNUNET_SYSERR
+ * @return the network type in HBO or #GNUNET_SYSERR
  */
-int tcp_get_network (void *cls,
-                     void *session)
+static enum GNUNET_ATS_Network_Type
+tcp_get_network (void *cls,
+                struct Session *session)
 {
-       struct Session *s = (struct Session *) session;
-       return s->ats_address_network_type;
+  GNUNET_assert (NULL != session);
+  return session->ats_address_network_type;
 }
 
 
@@ -2430,7 +2574,7 @@ libgnunet_plugin_transport_tcp_init (void *cls)
   {
     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
        initialze the plugin or the API */
-    api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
+    api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
     api->cls = NULL;
     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
     api->address_to_string = &tcp_address_to_string;
@@ -2454,9 +2598,8 @@ libgnunet_plugin_transport_tcp_init (void *cls)
                                                "ADVERTISED-PORT", &aport)) &&
        (aport > 65535)))
   {
-    LOG (GNUNET_ERROR_TYPE_ERROR, 
-        _
-        ("Require valid port number for service `%s' in configuration!\n"),
+    LOG (GNUNET_ERROR_TYPE_ERROR,
+        _("Require valid port number for service `%s' in configuration!\n"),
         "transport-tcp");
     return NULL;
   }
@@ -2480,8 +2623,8 @@ libgnunet_plugin_transport_tcp_init (void *cls)
   /* Initialize my flags */
   myoptions = 0;
 
-  plugin = GNUNET_malloc (sizeof (struct Plugin));
-  plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create (max_connections, GNUNET_YES);
+  plugin = GNUNET_new (struct Plugin);
+  plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections, GNUNET_YES);
   plugin->max_connections = max_connections;
   plugin->cur_connections = 0;
   plugin->open_port = bport;
@@ -2496,7 +2639,7 @@ libgnunet_plugin_transport_tcp_init (void *cls)
   {
     for (ret = ret_s-1; ret >= 0; ret--)
       LOG (GNUNET_ERROR_TYPE_INFO,
-          "Binding to address `%s'\n", 
+          "Binding to address `%s'\n",
           GNUNET_a2s (addrs[ret], addrlens[ret]));
     plugin->nat =
         GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
@@ -2517,19 +2660,22 @@ libgnunet_plugin_transport_tcp_init (void *cls)
                                       GNUNET_YES, 0, 0, NULL, NULL, NULL,
                                       &try_connection_reversal, plugin);
   }
-  api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
+  api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
   api->cls = plugin;
   api->send = &tcp_plugin_send;
   api->get_session = &tcp_plugin_get_session;
 
-  api->disconnect = &tcp_plugin_disconnect;
+  api->disconnect_session = &tcp_disconnect_session;
+  api->query_keepalive_factor = &tcp_query_keepalive_factor;
+  api->disconnect_peer = &tcp_plugin_disconnect;
   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
   api->check_address = &tcp_plugin_check_address;
   api->address_to_string = &tcp_address_to_string;
   api->string_to_address = &tcp_string_to_address;
   api->get_network = &tcp_get_network;
+  api->update_session_timeout = &tcp_plugin_update_session_timeout;
   plugin->service = service;
-  if (service != NULL)
+  if (NULL != service)
   {
     plugin->server = GNUNET_SERVICE_get_server (service);
   }
@@ -2560,30 +2706,31 @@ libgnunet_plugin_transport_tcp_init (void *cls)
 
   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
-  plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_YES);
+  plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
   if (bport != 0)
-    LOG (GNUNET_ERROR_TYPE_INFO, 
+    LOG (GNUNET_ERROR_TYPE_INFO,
         _("TCP transport listening on port %llu\n"), bport);
   else
-    LOG (GNUNET_ERROR_TYPE_INFO, 
-        _
-        ("TCP transport not listening on any port (client only)\n"));
+    LOG (GNUNET_ERROR_TYPE_INFO,
+        _("TCP transport not listening on any port (client only)\n"));
   if (aport != bport)
-    LOG (GNUNET_ERROR_TYPE_INFO, 
-                     _
-                     ("TCP transport advertises itself as being on port %llu\n"),
-                     aport);
+    LOG (GNUNET_ERROR_TYPE_INFO,
+         _("TCP transport advertises itself as being on port %llu\n"),
+         aport);
   /* Initially set connections to 0 */
   GNUNET_assert (NULL != plugin->env->stats);
   GNUNET_STATISTICS_set (plugin->env->stats,
-                        gettext_noop ("# TCP sessions active"), 0,
-                        GNUNET_NO);
+                         gettext_noop ("# TCP sessions active"), 0,
+                         GNUNET_NO);
   return api;
 }
 
 
 /**
  * Exit point from the plugin.
+ *
+ * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
+ * @return NULL
  */
 void *
 libgnunet_plugin_transport_tcp_done (void *cls)
@@ -2591,18 +2738,35 @@ libgnunet_plugin_transport_tcp_done (void *cls)
   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
   struct Plugin *plugin = api->cls;
   struct TCPProbeContext *tcp_probe;
+  struct PrettyPrinterContext *cur;
+  struct PrettyPrinterContext *next;
 
   if (NULL == plugin)
   {
     GNUNET_free (api);
     return NULL;
   }
-  LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down TCP plugin\n");
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Shutting down TCP plugin\n");
 
   /* Removing leftover sessions */
-  GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
+  GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
+                                         &session_disconnect_it, plugin);
   /* Removing leftover NAT sessions */
-  GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
+  GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
+                                         &session_disconnect_it, plugin);
+
+  next = ppc_dll_head;
+  for (cur = next; NULL != cur; cur = next)
+  {
+    next = cur->next;
+    GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
+    if (NULL != cur->resolver_handle)
+      GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
+    GNUNET_SCHEDULER_cancel (cur->timeout_task);
+    GNUNET_free (cur);
+    GNUNET_break (0);
+  }
 
   if (plugin->service != NULL)
     GNUNET_SERVICE_stop (plugin->service);
@@ -2618,8 +2782,8 @@ libgnunet_plugin_transport_tcp_done (void *cls)
     GNUNET_CONNECTION_destroy (tcp_probe->sock);
     GNUNET_free (tcp_probe);
   }
-  GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
-  GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
+  GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
+  GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
   GNUNET_free (plugin);
   GNUNET_free (api);
   return NULL;