-bring set/gns into the fold of non-experimental subsystems
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002--2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file transport/plugin_transport_tcp.c
22  * @brief Implementation of the TCP transport service
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "transport-tcp",__VA_ARGS__)
43
44 #define PLUGIN_NAME "tcp"
45
46 /**
47  * How long until we give up on establishing an NAT connection?
48  * Must be > 4 RTT
49  */
50 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
51
52
53 GNUNET_NETWORK_STRUCT_BEGIN
54
55 /**
56  * Address options
57  */
58 static uint32_t myoptions;
59
60 /**
61  * Initial handshake message for a session.
62  */
63 struct WelcomeMessage
64 {
65   /**
66    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
67    */
68   struct GNUNET_MessageHeader header;
69
70   /**
71    * Identity of the node connecting (TCP client)
72    */
73   struct GNUNET_PeerIdentity clientIdentity;
74
75 };
76
77
78 /**
79  * Basically a WELCOME message, but with the purpose
80  * of giving the waiting peer a client handle to use
81  */
82 struct TCP_NAT_ProbeMessage
83 {
84   /**
85    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
86    */
87   struct GNUNET_MessageHeader header;
88
89   /**
90    * Identity of the sender of the message.
91    */
92   struct GNUNET_PeerIdentity clientIdentity;
93
94 };
95 GNUNET_NETWORK_STRUCT_END
96
97 /**
98  * Context for sending a NAT probe via TCP.
99  */
100 struct TCPProbeContext
101 {
102
103   /**
104    * Active probes are kept in a DLL.
105    */
106   struct TCPProbeContext *next;
107
108   /**
109    * Active probes are kept in a DLL.
110    */
111   struct TCPProbeContext *prev;
112
113   /**
114    * Probe connection.
115    */
116   struct GNUNET_CONNECTION_Handle *sock;
117
118   /**
119    * Message to be sent.
120    */
121   struct TCP_NAT_ProbeMessage message;
122
123   /**
124    * Handle to the transmission.
125    */
126   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
127
128   /**
129    * Transport plugin handle.
130    */
131   struct Plugin *plugin;
132 };
133
134
135 GNUNET_NETWORK_STRUCT_BEGIN
136
137 /**
138  * Network format for IPv4 addresses.
139  */
140 struct IPv4TcpAddress
141 {
142         /**
143          * Optional options and flags for this address
144          */
145         uint32_t options;
146
147   /**
148    * IPv4 address, in network byte order.
149    */
150   uint32_t ipv4_addr GNUNET_PACKED;
151
152   /**
153    * Port number, in network byte order.
154    */
155   uint16_t t4_port GNUNET_PACKED;
156
157 };
158
159
160 /**
161  * Network format for IPv6 addresses.
162  */
163 struct IPv6TcpAddress
164 {
165         /**
166          * Optional flags for this address
167          */
168         uint32_t options;
169
170   /**
171    * IPv6 address.
172    */
173   struct in6_addr ipv6_addr GNUNET_PACKED;
174
175   /**
176    * Port number, in network byte order.
177    */
178   uint16_t t6_port GNUNET_PACKED;
179
180 };
181 GNUNET_NETWORK_STRUCT_END
182
183 /**
184  * Encapsulation of all of the state of the plugin.
185  */
186 struct Plugin;
187
188
189 /**
190  * Information kept for each message that is yet to
191  * be transmitted.
192  */
193 struct PendingMessage
194 {
195
196   /**
197    * This is a doubly-linked list.
198    */
199   struct PendingMessage *next;
200
201   /**
202    * This is a doubly-linked list.
203    */
204   struct PendingMessage *prev;
205
206   /**
207    * The pending message
208    */
209   const char *msg;
210
211   /**
212    * Continuation function to call once the message
213    * has been sent.  Can be NULL if there is no
214    * continuation to call.
215    */
216   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
217
218   /**
219    * Closure for transmit_cont.
220    */
221   void *transmit_cont_cls;
222
223   /**
224    * Timeout value for the pending message.
225    */
226   struct GNUNET_TIME_Absolute timeout;
227
228   /**
229    * So that the gnunet-service-transport can group messages together,
230    * these pending messages need to accept a message buffer and size
231    * instead of just a GNUNET_MessageHeader.
232    */
233   size_t message_size;
234
235 };
236
237
238 /**
239  * Session handle for TCP connections.
240  */
241 struct Session
242 {
243   /**
244    * To whom are we talking to (set to our identity
245    * if we are still waiting for the welcome message)
246    */
247   struct GNUNET_PeerIdentity target;
248
249   /**
250    * API requirement.
251    */
252   struct SessionHeader header;
253
254   /**
255    * Pointer to the global plugin struct.
256    */
257   struct Plugin *plugin;
258
259   /**
260    * The client (used to identify this connection)
261    */
262   struct GNUNET_SERVER_Client *client;
263
264   /**
265    * Task cleaning up a NAT client connection establishment attempt;
266    */
267   GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
268
269   /**
270    * Messages currently pending for transmission
271    * to this peer, if any.
272    */
273   struct PendingMessage *pending_messages_head;
274
275   /**
276    * Messages currently pending for transmission
277    * to this peer, if any.
278    */
279   struct PendingMessage *pending_messages_tail;
280
281   /**
282    * Handle for pending transmission request.
283    */
284   struct GNUNET_SERVER_TransmitHandle *transmit_handle;
285
286   /**
287    * ID of task used to delay receiving more to throttle sender.
288    */
289   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
290
291   /**
292    * Session timeout task
293    */
294   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
295
296   /**
297    * Address of the other peer (either based on our 'connect'
298    * call or on our 'accept' call).
299    *
300    * struct IPv4TcpAddress or struct IPv6TcpAddress
301    *
302    */
303   void *addr;
304
305   /**
306    * Length of connect_addr.
307    */
308   size_t addrlen;
309
310   /**
311    * Last activity on this connection.  Used to select preferred
312    * connection.
313    */
314   struct GNUNET_TIME_Absolute last_activity;
315
316   /**
317    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
318    */
319   int expecting_welcome;
320
321   /**
322    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
323    */
324   int inbound;
325
326   /**
327    * Was this session created using NAT traversal?
328    */
329   int is_nat;
330
331   /**
332    * ATS network type in NBO
333    */
334   uint32_t ats_address_network_type;
335 };
336
337
338 /**
339  * Encapsulation of all of the state of the plugin.
340  */
341 struct Plugin
342 {
343   /**
344    * Our environment.
345    */
346   struct GNUNET_TRANSPORT_PluginEnvironment *env;
347
348   /**
349    * The listen socket.
350    */
351   struct GNUNET_CONNECTION_Handle *lsock;
352
353   /**
354    * Our handle to the NAT module.
355    */
356   struct GNUNET_NAT_Handle *nat;
357
358   /**
359    * Map from peer identities to sessions for the given peer.
360    */
361   struct GNUNET_CONTAINER_MultiHashMap *sessionmap;
362
363   /**
364    * Handle to the network service.
365    */
366   struct GNUNET_SERVICE_Context *service;
367
368   /**
369    * Handle to the server for this service.
370    */
371   struct GNUNET_SERVER_Handle *server;
372
373   /**
374    * Copy of the handler array where the closures are
375    * set to this struct's instance.
376    */
377   struct GNUNET_SERVER_MessageHandler *handlers;
378
379   /**
380    * Map of peers we have tried to contact behind a NAT
381    */
382   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
383
384   /**
385    * List of active TCP probes.
386    */
387   struct TCPProbeContext *probe_head;
388
389   /**
390    * List of active TCP probes.
391    */
392   struct TCPProbeContext *probe_tail;
393
394   /**
395    * Handle for (DYN)DNS lookup of our external IP.
396    */
397   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
398
399   /**
400    * How many more TCP sessions are we allowed to open right now?
401    */
402   unsigned long long max_connections;
403
404   /**
405    * How many more TCP sessions do we have right now?
406    */
407   unsigned long long cur_connections;
408
409   /**
410    * ID of task used to update our addresses when one expires.
411    */
412   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
413
414   /**
415    * Port that we are actually listening on.
416    */
417   uint16_t open_port;
418
419   /**
420    * Port that the user said we would have visible to the
421    * rest of the world.
422    */
423   uint16_t adv_port;
424
425 };
426
427
428 /**
429  * Start session timeout
430  */
431 static void
432 start_session_timeout (struct Session *s);
433
434
435 /**
436  * Increment session timeout due to activity
437  */
438 static void
439 reschedule_session_timeout (struct Session *s);
440
441
442 /**
443  * Cancel timeout
444  */
445 static void
446 stop_session_timeout (struct Session *s);
447
448
449 /* DEBUG CODE */
450 static const char *
451 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
452
453
454 static unsigned int sessions;
455
456
457 static void 
458 inc_sessions (struct Plugin *plugin, struct Session *session, int line)
459 {
460   sessions++;
461   unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
462   if (sessions != size)
463     LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
464         sessions, size);
465   LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
466       line,
467       sessions,
468       size,
469       GNUNET_i2s (&session->target),
470       tcp_address_to_string (NULL, session->addr, session->addrlen));
471 }
472
473
474 static void 
475 dec_sessions (struct Plugin *plugin, struct Session *session, int line)
476 {
477   GNUNET_assert (sessions > 0);
478   unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
479   sessions--;
480   if (sessions != size)
481     LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
482       sessions, size);
483   LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
484       line,
485       sessions,
486       size,
487       GNUNET_i2s (&session->target),
488       tcp_address_to_string (NULL, session->addr, session->addrlen));
489 }
490 /* DEBUG CODE */
491
492
493 /**
494  * Function to check if an inbound connection is acceptable.
495  * Mostly used to limit the total number of open connections
496  * we can have.
497  *
498  * @param cls the 'struct Plugin'
499  * @param ucred credentials, if available, otherwise NULL
500  * @param addr address
501  * @param addrlen length of address
502  * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
503  *   for unknown address family (will be denied).
504  */
505 static int
506 plugin_tcp_access_check (void *cls,
507                          const struct GNUNET_CONNECTION_Credentials *ucred,
508                          const struct sockaddr *addr, socklen_t addrlen)
509 {
510   struct Plugin *plugin = cls;
511   LOG (GNUNET_ERROR_TYPE_DEBUG,
512        "Accepting new incoming TCP connection from `%s'\n",
513        GNUNET_a2s (addr, addrlen));
514   if (plugin->cur_connections >= plugin->max_connections)
515     return GNUNET_NO;
516   plugin->cur_connections ++;
517   return GNUNET_YES;
518 }
519
520
521 /**
522  * Our external IP address/port mapping has changed.
523  *
524  * @param cls closure, the 'struct LocalAddrList'
525  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
526  *     the previous (now invalid) one
527  * @param addr either the previous or the new public IP address
528  * @param addrlen actual lenght of the address
529  */
530 static void
531 tcp_nat_port_map_callback (void *cls, int add_remove,
532                            const struct sockaddr *addr, socklen_t addrlen)
533 {
534   struct Plugin *plugin = cls;
535   struct IPv4TcpAddress t4;
536   struct IPv6TcpAddress t6;
537   void *arg;
538   size_t args;
539
540   LOG (GNUNET_ERROR_TYPE_INFO,
541        "NAT notification to %s address `%s'\n",
542        (GNUNET_YES == add_remove) ? "add" : "remove",
543        GNUNET_a2s (addr, addrlen));
544   /* convert 'addr' to our internal format */
545   switch (addr->sa_family)
546   {
547   case AF_INET:
548     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
549     memset (&t4,0, sizeof (t4));
550     t4.options = htonl (myoptions);
551     t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
552     t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
553     arg = &t4;
554     args = sizeof (t4);
555     break;
556   case AF_INET6:
557     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
558     memset (&t6, 0, sizeof (t6));
559     memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
560             sizeof (struct in6_addr));
561     t6.options = htonl (myoptions);
562     t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
563     arg = &t6;
564     args = sizeof (t6);
565     break;
566   default:
567     GNUNET_break (0);
568     return;
569   }
570   /* modify our published address list */
571   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args, "tcp");
572 }
573
574
575 /**
576  * Function called for a quick conversion of the binary address to
577  * a numeric address.  Note that the caller must not free the
578  * address and that the next call to this function is allowed
579  * to override the address again.
580  *
581  * @param cls closure ('struct Plugin*')
582  * @param addr binary address
583  * @param addrlen length of the address
584  * @return string representing the same address
585  */
586 static const char *
587 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
588 {
589   static char rbuf[INET6_ADDRSTRLEN + 12];
590   char buf[INET6_ADDRSTRLEN];
591   const void *sb;
592   struct in_addr a4;
593   struct in6_addr a6;
594   const struct IPv4TcpAddress *t4;
595   const struct IPv6TcpAddress *t6;
596   int af;
597   uint16_t port;
598   uint32_t options;
599
600   options = 0;
601   switch (addrlen)
602   {
603   case sizeof (struct IPv6TcpAddress):
604     t6 = addr;
605     af = AF_INET6;
606     port = ntohs (t6->t6_port);
607     options = ntohl (t6->options);
608     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
609     sb = &a6;
610     break;
611   case sizeof (struct IPv4TcpAddress): 
612     t4 = addr;
613     af = AF_INET;
614     port = ntohs (t4->t4_port);
615     options = ntohl (t4->options);
616     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
617     sb = &a4;
618     break;
619   case 0:
620     {
621       GNUNET_snprintf (rbuf, sizeof (rbuf), "%s",
622                 TRANSPORT_SESSION_INBOUND_STRING);
623       return rbuf;
624     }
625   default:
626     LOG (GNUNET_ERROR_TYPE_WARNING,
627                 _("Unexpected address length: %u bytes\n"),
628                 (unsigned int) addrlen);
629     return NULL;
630   }
631   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
632   {
633     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
634     return NULL;
635   }
636   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
637                    PLUGIN_NAME, options, buf, port);
638   return rbuf;
639 }
640
641
642 /**
643  * Function called to convert a string address to
644  * a binary address.
645  *
646  * @param cls closure ('struct Plugin*')
647  * @param addr string address
648  * @param addrlen length of the address
649  * @param buf location to store the buffer
650  * @param added location to store the number of bytes in the buffer.
651  *        If the function returns GNUNET_SYSERR, its contents are undefined.
652  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
653  */
654 static int
655 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
656     void **buf, size_t *added)
657 {
658   struct sockaddr_storage socket_address;
659   char *address;
660   char *plugin;
661   char *optionstr;
662   uint32_t options;
663
664   /* Format tcp.options.address:port */
665   address = NULL;
666   plugin = NULL;
667   optionstr = NULL;
668   options = 0;
669   if ((NULL == addr) || (addrlen == 0))
670   {
671     GNUNET_break (0);
672     return GNUNET_SYSERR;
673   }
674   if ('\0' != addr[addrlen - 1])
675   {
676     GNUNET_break (0);
677     return GNUNET_SYSERR;
678   }
679   if (strlen (addr) != addrlen - 1)
680   {
681     GNUNET_break (0);
682     return GNUNET_SYSERR;
683   }
684   plugin = GNUNET_strdup (addr);
685   optionstr = strchr (plugin, '.');
686   if (NULL == optionstr)
687   {
688     GNUNET_break (0);
689     GNUNET_free (plugin);
690     return GNUNET_SYSERR;
691   }
692   optionstr[0] = '\0';
693   optionstr ++;
694   options = atol (optionstr);
695   address = strchr (optionstr, '.');
696   if (NULL == address)
697   {
698     GNUNET_break (0);
699     GNUNET_free (plugin);
700     return GNUNET_SYSERR;
701   }
702   address[0] = '\0';
703   address ++;
704
705   if (GNUNET_OK !=
706       GNUNET_STRINGS_to_address_ip (address, strlen (address),
707                                     &socket_address))
708   {
709     GNUNET_break (0);
710     GNUNET_free (plugin);
711     return GNUNET_SYSERR;
712   }
713
714   GNUNET_free (plugin);
715   switch (socket_address.ss_family)
716   {
717   case AF_INET:
718     {
719       struct IPv4TcpAddress *t4;
720       struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
721       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
722       t4->options =  htonl (options);
723       t4->ipv4_addr = in4->sin_addr.s_addr;
724       t4->t4_port = in4->sin_port;
725       *buf = t4;
726       *added = sizeof (struct IPv4TcpAddress);
727       return GNUNET_OK;
728     }
729   case AF_INET6:  
730     {
731       struct IPv6TcpAddress *t6;
732       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
733       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
734       t6->options = htonl (options);
735       t6->ipv6_addr = in6->sin6_addr;
736       t6->t6_port = in6->sin6_port;
737       *buf = t6;
738       *added = sizeof (struct IPv6TcpAddress);
739       return GNUNET_OK;
740     }
741   default:
742     return GNUNET_SYSERR;
743   }
744 }
745
746
747 struct SessionClientCtx
748 {
749   const struct GNUNET_SERVER_Client *client;
750   struct Session *ret;
751 };
752
753
754 static int 
755 session_lookup_by_client_it (void *cls,
756                              const struct GNUNET_HashCode * key,
757                              void *value)
758 {
759   struct SessionClientCtx *sc_ctx = cls;
760   struct Session *s = value;
761
762   if (s->client == sc_ctx->client)
763   {
764     sc_ctx->ret = s;
765     return GNUNET_NO;
766   }
767   return GNUNET_YES;
768 }
769
770
771 /**
772  * Find the session handle for the given client.
773  *
774  * @param plugin the plugin
775  * @param client which client to find the session handle for
776  * @return NULL if no matching session exists
777  */
778 static struct Session *
779 lookup_session_by_client (struct Plugin *plugin,
780                           const struct GNUNET_SERVER_Client *client)
781 {
782   struct SessionClientCtx sc_ctx;
783
784   sc_ctx.client = client;
785   sc_ctx.ret = NULL;
786   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
787   return sc_ctx.ret;
788 }
789
790
791 /**
792  * Create a new session.  Also queues a welcome message.
793  *
794  * @param plugin the plugin
795  * @param target peer to connect to
796  * @param client client to use, reference counter must have already been increased
797  * @param is_nat this a NAT session, we should wait for a client to
798  *               connect to us from an address, then assign that to
799  *               the session
800  * @return new session object
801  */
802 static struct Session *
803 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
804                 struct GNUNET_SERVER_Client *client, int is_nat)
805 {
806   struct Session *session;
807   struct PendingMessage *pm;
808   struct WelcomeMessage welcome;
809
810   if (GNUNET_YES != is_nat)
811     GNUNET_assert (NULL != client);
812   else
813     GNUNET_assert (NULL == client);
814
815   LOG (GNUNET_ERROR_TYPE_DEBUG, 
816        "Creating new session for peer `%4s'\n",
817        GNUNET_i2s (target));
818   session = GNUNET_malloc (sizeof (struct Session));
819   session->last_activity = GNUNET_TIME_absolute_get ();
820   session->plugin = plugin;
821   session->is_nat = is_nat;
822   session->client = client;
823   session->target = *target;
824   session->expecting_welcome = GNUNET_YES;
825   session->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
826   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
827                       sizeof (struct WelcomeMessage));
828   pm->msg = (const char *) &pm[1];
829   pm->message_size = sizeof (struct WelcomeMessage);
830   welcome.header.size = htons (sizeof (struct WelcomeMessage));
831   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
832   welcome.clientIdentity = *plugin->env->my_identity;
833   memcpy (&pm[1], &welcome, sizeof (welcome));
834   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
835   GNUNET_STATISTICS_update (plugin->env->stats,
836                             gettext_noop ("# bytes currently in TCP buffers"),
837                             pm->message_size, GNUNET_NO);
838   GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
839                                session->pending_messages_tail, pm);
840   if (GNUNET_YES != is_nat)
841   {
842     GNUNET_STATISTICS_update (plugin->env->stats,
843                               gettext_noop ("# TCP sessions active"), 1,
844                               GNUNET_NO);
845   }
846   start_session_timeout (session);
847
848   return session;
849 }
850
851
852 /**
853  * If we have pending messages, ask the server to
854  * transmit them (schedule the respective tasks, etc.)
855  *
856  * @param session for which session should we do this
857  */
858 static void
859 process_pending_messages (struct Session *session);
860
861
862 /**
863  * Function called to notify a client about the socket
864  * being ready to queue more data.  "buf" will be
865  * NULL and "size" zero if the socket was closed for
866  * writing in the meantime.
867  *
868  * @param cls closure
869  * @param size number of bytes available in buf
870  * @param buf where the callee should write the message
871  * @return number of bytes written to buf
872  */
873 static size_t
874 do_transmit (void *cls, size_t size, void *buf)
875 {
876   struct Session *session = cls;
877   struct GNUNET_PeerIdentity pid;
878   struct Plugin *plugin;
879   struct PendingMessage *pos;
880   struct PendingMessage *hd;
881   struct PendingMessage *tl;
882   struct GNUNET_TIME_Absolute now;
883   char *cbuf;
884   size_t ret;
885
886   GNUNET_assert (NULL != session);
887   session->transmit_handle = NULL;
888   plugin = session->plugin;
889   if (NULL == buf)
890   {
891     LOG (GNUNET_ERROR_TYPE_DEBUG, 
892          "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
893          GNUNET_i2s (&session->target));
894     /* timeout; cancel all messages that have already expired */
895     hd = NULL;
896     tl = NULL;
897     ret = 0;
898     now = GNUNET_TIME_absolute_get ();
899     while ((NULL != (pos = session->pending_messages_head)) &&
900            (pos->timeout.abs_value <= now.abs_value))
901     {
902       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
903                                    session->pending_messages_tail, pos);
904       LOG (GNUNET_ERROR_TYPE_DEBUG,
905            "Failed to transmit %u byte message to `%4s'.\n",
906            pos->message_size, GNUNET_i2s (&session->target));
907       ret += pos->message_size;
908       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
909     }
910     /* do this call before callbacks (so that if callbacks destroy
911      * session, they have a chance to cancel actions done by this
912      * call) */
913     process_pending_messages (session);
914     pid = session->target;
915     /* no do callbacks and do not use session again since
916      * the callbacks may abort the session */
917     while (NULL != (pos = hd))
918     {
919       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
920       if (pos->transmit_cont != NULL)
921         pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR, pos->message_size, 0);
922       GNUNET_free (pos);
923     }
924     GNUNET_STATISTICS_update (plugin->env->stats,
925                               gettext_noop ("# bytes currently in TCP buffers"),
926                               -(int64_t) ret, GNUNET_NO);
927     GNUNET_STATISTICS_update (plugin->env->stats,
928                               gettext_noop
929                               ("# bytes discarded by TCP (timeout)"), ret,
930                               GNUNET_NO);
931     return 0;
932   }
933   /* copy all pending messages that would fit */
934   ret = 0;
935   cbuf = buf;
936   hd = NULL;
937   tl = NULL;
938   while (NULL != (pos = session->pending_messages_head))
939   {
940     if (ret + pos->message_size > size)
941       break;
942     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
943                                  session->pending_messages_tail, pos);
944     GNUNET_assert (size >= pos->message_size);
945     LOG (GNUNET_ERROR_TYPE_DEBUG, 
946          "Transmitting message of type %u\n",
947          ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
948     /* FIXME: this memcpy can be up to 7% of our total runtime */
949     memcpy (cbuf, pos->msg, pos->message_size);
950     cbuf += pos->message_size;
951     ret += pos->message_size;
952     size -= pos->message_size;
953     GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
954   }
955   /* schedule 'continuation' before callbacks so that callbacks that
956    * cancel everything don't cause us to use a session that no longer
957    * exists... */
958   process_pending_messages (session);
959   session->last_activity = GNUNET_TIME_absolute_get ();
960   pid = session->target;
961   /* we'll now call callbacks that may cancel the session; hence
962    * we should not use 'session' after this point */
963   while (NULL != (pos = hd))
964   {
965     GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
966     if (pos->transmit_cont != NULL)
967       pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK, pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
968     GNUNET_free (pos);
969   }
970   GNUNET_assert (hd == NULL);
971   GNUNET_assert (tl == NULL);
972   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
973                    ret);
974   GNUNET_STATISTICS_update (plugin->env->stats,
975                             gettext_noop ("# bytes currently in TCP buffers"),
976                             -(int64_t) ret, GNUNET_NO);
977   GNUNET_STATISTICS_update (plugin->env->stats,
978                             gettext_noop ("# bytes transmitted via TCP"), ret,
979                             GNUNET_NO);
980   return ret;
981 }
982
983
984 /**
985  * If we have pending messages, ask the server to
986  * transmit them (schedule the respective tasks, etc.)
987  *
988  * @param session for which session should we do this
989  */
990 static void
991 process_pending_messages (struct Session *session)
992 {
993   struct PendingMessage *pm;
994
995   GNUNET_assert (session->client != NULL);
996   if (session->transmit_handle != NULL)
997     return;
998   if (NULL == (pm = session->pending_messages_head))
999     return;
1000
1001   session->transmit_handle =
1002       GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
1003                                            GNUNET_TIME_absolute_get_remaining
1004                                            (pm->timeout), &do_transmit,
1005                                            session);
1006 }
1007
1008
1009 /**
1010  * Functions with this signature are called whenever we need
1011  * to close a session due to a disconnect or failure to
1012  * establish a connection.
1013  *
1014  * @param session session to close down
1015  */
1016 static void
1017 disconnect_session (struct Session *session)
1018 {
1019   struct PendingMessage *pm;
1020   struct Plugin * plugin = session->plugin;
1021
1022   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1023        "Disconnecting session of peer `%s' address `%s'\n",
1024        GNUNET_i2s (&session->target),
1025        tcp_address_to_string (NULL, session->addr, session->addrlen));
1026
1027   stop_session_timeout (session);
1028
1029   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (plugin->sessionmap, &session->target.hashPubKey, session))
1030   {
1031     GNUNET_STATISTICS_update (session->plugin->env->stats,
1032                               gettext_noop ("# TCP sessions active"), -1,
1033                               GNUNET_NO);
1034     dec_sessions (plugin, session, __LINE__);
1035   }
1036   else GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (plugin->nat_wait_conns, &session->target.hashPubKey, session));
1037
1038   /* clean up state */
1039   if (session->transmit_handle != NULL)
1040   {
1041     GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
1042     session->transmit_handle = NULL;
1043   }
1044   session->plugin->env->session_end (session->plugin->env->cls,
1045                                      &session->target, session);
1046
1047   if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
1048   {
1049     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1050     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1051   }
1052
1053   while (NULL != (pm = session->pending_messages_head))
1054   {
1055     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1056          pm->transmit_cont !=
1057          NULL ? "Could not deliver message to `%4s'.\n" :
1058          "Could not deliver message to `%4s', notifying.\n",
1059          GNUNET_i2s (&session->target));
1060     GNUNET_STATISTICS_update (session->plugin->env->stats,
1061                               gettext_noop ("# bytes currently in TCP buffers"),
1062                               -(int64_t) pm->message_size, GNUNET_NO);
1063     GNUNET_STATISTICS_update (session->plugin->env->stats,
1064                               gettext_noop
1065                               ("# bytes discarded by TCP (disconnect)"),
1066                               pm->message_size, GNUNET_NO);
1067     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1068                                  session->pending_messages_tail, pm);
1069     if (NULL != pm->transmit_cont)
1070       pm->transmit_cont (pm->transmit_cont_cls, &session->target,
1071                          GNUNET_SYSERR, pm->message_size, 0);
1072     GNUNET_free (pm);
1073   }
1074   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
1075   {
1076     GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1077     if (NULL != session->client)
1078       GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
1079   }
1080   if (NULL != session->client)
1081   {
1082     GNUNET_SERVER_client_disconnect (session->client);
1083     GNUNET_SERVER_client_drop (session->client);
1084     session->client = NULL;
1085   }
1086   GNUNET_free_non_null (session->addr);
1087   GNUNET_assert (NULL == session->transmit_handle);
1088   GNUNET_free (session);
1089 }
1090
1091
1092 struct FindSessionContext
1093 {
1094   struct Session *s;
1095   int res;
1096 };
1097
1098 int session_it (void *cls,
1099                const struct GNUNET_HashCode * key,
1100                void *value)
1101 {
1102   struct FindSessionContext *res = cls;
1103   if (res->s == value)
1104   {
1105     res->res = GNUNET_OK;
1106     return GNUNET_NO;
1107   }
1108   else
1109     return GNUNET_YES;
1110 }
1111
1112 int find_session (struct Plugin *plugin, struct Session *session)
1113 {
1114   struct FindSessionContext session_map_res;
1115   struct FindSessionContext nat_map_res;
1116
1117   session_map_res.s = session;
1118   session_map_res.res = GNUNET_SYSERR;
1119   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_it, &session_map_res);
1120
1121   nat_map_res.s = session;
1122   nat_map_res.res = GNUNET_SYSERR;
1123   GNUNET_CONTAINER_multihashmap_iterate (plugin->nat_wait_conns, &session_it, &nat_map_res);
1124
1125   if ((session_map_res.res == GNUNET_SYSERR) && (nat_map_res.res == GNUNET_SYSERR))
1126   {
1127     GNUNET_break (0);
1128     return GNUNET_SYSERR;
1129   }
1130   return GNUNET_OK;
1131 }
1132
1133
1134 /**
1135  * Function that can be used by the transport service to transmit
1136  * a message using the plugin.   Note that in the case of a
1137  * peer disconnecting, the continuation MUST be called
1138  * prior to the disconnect notification itself.  This function
1139  * will be called with this peer's HELLO message to initiate
1140  * a fresh connection to another peer.
1141  *
1142  * @param cls closure
1143  * @param session which session must be used
1144  * @param msgbuf the message to transmit
1145  * @param msgbuf_size number of bytes in 'msgbuf'
1146  * @param priority how important is the message (most plugins will
1147  *                 ignore message priority and just FIFO)
1148  * @param to how long to wait at most for the transmission (does not
1149  *                require plugins to discard the message after the timeout,
1150  *                just advisory for the desired delay; most plugins will ignore
1151  *                this as well)
1152  * @param cont continuation to call once the message has
1153  *        been transmitted (or if the transport is ready
1154  *        for the next transmission call; or if the
1155  *        peer disconnected...); can be NULL
1156  * @param cont_cls closure for cont
1157  * @return number of bytes used (on the physical network, with overheads);
1158  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1159  *         and does NOT mean that the message was not transmitted (DV)
1160  */
1161 static ssize_t
1162 tcp_plugin_send (void *cls,
1163     struct Session *session,
1164     const char *msgbuf, size_t msgbuf_size,
1165     unsigned int priority,
1166     struct GNUNET_TIME_Relative to,
1167     GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1168 {
1169   struct Plugin * plugin = cls;
1170   struct PendingMessage *pm;
1171
1172   GNUNET_assert (NULL != plugin);
1173   GNUNET_assert (NULL != session);
1174
1175   if (GNUNET_SYSERR == find_session(plugin, session))
1176   {
1177       LOG (GNUNET_ERROR_TYPE_ERROR,
1178            _("Trying to send with invalid session %p\n"));
1179       return GNUNET_SYSERR;
1180   }
1181
1182   /* create new message entry */
1183   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1184   pm->msg = (const char *) &pm[1];
1185   memcpy (&pm[1], msgbuf, msgbuf_size);
1186   pm->message_size = msgbuf_size;
1187   pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1188   pm->transmit_cont = cont;
1189   pm->transmit_cont_cls = cont_cls;
1190
1191   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1192        "Asked to transmit %u bytes to `%s', added message to list.\n",
1193        msgbuf_size, GNUNET_i2s (&session->target));
1194
1195   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value (plugin->sessionmap, 
1196                                                                   &session->target.hashPubKey, 
1197                                                                   session))
1198   {
1199     GNUNET_assert (session->client != NULL);
1200     reschedule_session_timeout (session);
1201     GNUNET_SERVER_client_set_timeout (session->client,
1202                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1203     GNUNET_STATISTICS_update (plugin->env->stats,
1204                               gettext_noop ("# bytes currently in TCP buffers"),
1205                               msgbuf_size, GNUNET_NO);
1206
1207     /* append pm to pending_messages list */
1208     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1209                                       session->pending_messages_tail, pm);
1210
1211     process_pending_messages (session);
1212     return msgbuf_size;
1213   }
1214   else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1215   {
1216     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1217          "This NAT WAIT session for peer `%s' is not yet ready!\n",
1218          GNUNET_i2s (&session->target));
1219     reschedule_session_timeout (session);
1220     GNUNET_STATISTICS_update (plugin->env->stats,
1221                               gettext_noop ("# bytes currently in TCP buffers"),
1222                               msgbuf_size, GNUNET_NO);
1223
1224     /* append pm to pending_messages list */
1225     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1226                                       session->pending_messages_tail, pm);
1227     return msgbuf_size;
1228   }
1229   else
1230   {
1231     LOG (GNUNET_ERROR_TYPE_ERROR,
1232          "Invalid session %p\n", session);
1233     if (NULL != cont)
1234       cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1235     GNUNET_break (0);
1236     GNUNET_free (pm);
1237     return GNUNET_SYSERR; /* session does not exist here */
1238   }
1239 }
1240
1241
1242 struct SessionItCtx
1243 {
1244   void *addr;
1245   size_t addrlen;
1246   struct Session *result;
1247 };
1248
1249
1250 static int 
1251 session_lookup_it (void *cls,
1252                    const struct GNUNET_HashCode *key,
1253                    void *value)
1254 {
1255   struct SessionItCtx * si_ctx = cls;
1256   struct Session * session = value;
1257 #if 0
1258   char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1259   char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1260   LOG (GNUNET_ERROR_TYPE_DEBUG,
1261        "Comparing: %s %u <-> %s %u\n",
1262        a1,
1263        session->addrlen,
1264        a2,
1265        si_ctx->addrlen);
1266   GNUNET_free (a1);
1267   GNUNET_free (a2);
1268 #endif
1269   if (session->addrlen != si_ctx->addrlen)
1270   {
1271     return GNUNET_YES;
1272   }
1273   if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1274   {
1275     return GNUNET_YES;
1276   }
1277 #if 0
1278   a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1279   a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1280   LOG (GNUNET_ERROR_TYPE_DEBUG,
1281        "Comparing: %s %u <-> %s %u , OK!\n",
1282        a1,
1283        session->addrlen,
1284        a2,
1285        si_ctx->addrlen);
1286   GNUNET_free (a1);
1287   GNUNET_free (a2);
1288 #endif
1289   /* Found existing session */
1290   si_ctx->result = session;
1291   return GNUNET_NO;
1292 }
1293
1294
1295 /**
1296  * Task cleaning up a NAT connection attempt after timeout
1297  */
1298 static void
1299 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1300 {
1301   struct Session *session = cls;
1302
1303   session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1304   LOG (GNUNET_ERROR_TYPE_DEBUG,
1305        "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1306        GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1307   disconnect_session (session);
1308 }
1309
1310
1311 /**
1312  * Create a new session to transmit data to the target
1313  * This session will used to send data to this peer and the plugin will
1314  * notify us by calling the env->session_end function
1315  *
1316  * @param cls closure
1317  * @param address pointer to the GNUNET_HELLO_Address
1318  * @return the session if the address is valid, NULL otherwise
1319  */
1320 static struct Session *
1321 tcp_plugin_get_session (void *cls,
1322                         const struct GNUNET_HELLO_Address *address)
1323 {
1324   struct Plugin *plugin = cls;
1325   struct Session *session = NULL;
1326   int af;
1327   const void *sb;
1328   size_t sbs;
1329   struct GNUNET_CONNECTION_Handle *sa;
1330   struct sockaddr_in a4;
1331   struct sockaddr_in6 a6;
1332   const struct IPv4TcpAddress *t4;
1333   const struct IPv6TcpAddress *t6;
1334   struct GNUNET_ATS_Information ats;
1335   unsigned int is_natd = GNUNET_NO;
1336   size_t addrlen;
1337
1338   GNUNET_assert (plugin != NULL);
1339   GNUNET_assert (address != NULL);
1340   addrlen = address->address_length;
1341   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1342        "Trying to get session for `%s' address of peer `%s'\n",
1343        tcp_address_to_string(NULL, address->address, address->address_length),
1344        GNUNET_i2s (&address->peer));
1345
1346   /* look for existing session */
1347   if (GNUNET_YES == 
1348       GNUNET_CONTAINER_multihashmap_contains (plugin->sessionmap, 
1349                                               &address->peer.hashPubKey))
1350   {
1351     struct SessionItCtx si_ctx;
1352
1353     si_ctx.addr = (void *) address->address;
1354     si_ctx.addrlen = address->address_length;
1355
1356     si_ctx.result = NULL;
1357
1358     GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, 
1359                                                 &address->peer.hashPubKey, 
1360                                                 &session_lookup_it, &si_ctx);
1361     if (si_ctx.result != NULL)
1362     {
1363       session = si_ctx.result;
1364       LOG (GNUNET_ERROR_TYPE_DEBUG,
1365            "Found existing session for `%s' address `%s' session %p\n",
1366            GNUNET_i2s (&address->peer),
1367            tcp_address_to_string(NULL, address->address, address->address_length),
1368            session);
1369       return session;
1370     }
1371     LOG (GNUNET_ERROR_TYPE_DEBUG,
1372          "Existing sessions did not match address `%s' or peer `%s'\n",
1373          tcp_address_to_string(NULL, address->address, address->address_length),
1374          GNUNET_i2s (&address->peer));
1375   }
1376
1377   if (addrlen == sizeof (struct IPv6TcpAddress))
1378   {
1379     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1380     t6 = address->address;
1381     af = AF_INET6;
1382     memset (&a6, 0, sizeof (a6));
1383 #if HAVE_SOCKADDR_IN_SIN_LEN
1384     a6.sin6_len = sizeof (a6);
1385 #endif
1386     a6.sin6_family = AF_INET6;
1387     a6.sin6_port = t6->t6_port;
1388     if (t6->t6_port == 0)
1389       is_natd = GNUNET_YES;
1390     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1391     sb = &a6;
1392     sbs = sizeof (a6);
1393   }
1394   else if (addrlen == sizeof (struct IPv4TcpAddress))
1395   {
1396     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1397     t4 = address->address;
1398     af = AF_INET;
1399     memset (&a4, 0, sizeof (a4));
1400 #if HAVE_SOCKADDR_IN_SIN_LEN
1401     a4.sin_len = sizeof (a4);
1402 #endif
1403     a4.sin_family = AF_INET;
1404     a4.sin_port = t4->t4_port;
1405     if (t4->t4_port == 0)
1406       is_natd = GNUNET_YES;
1407     a4.sin_addr.s_addr = t4->ipv4_addr;
1408     sb = &a4;
1409     sbs = sizeof (a4);
1410   }
1411   else
1412   {
1413     LOG (GNUNET_ERROR_TYPE_WARNING,
1414         _("Trying to create session for address of unexpected length %u (should be %u or %u)\n"),
1415                   addrlen, sizeof (struct IPv4TcpAddress), sizeof (struct IPv6TcpAddress));
1416     return NULL;
1417   }
1418
1419   ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1420
1421   if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1422   {
1423     /* NAT client only works with IPv4 addresses */
1424     return NULL;
1425   }
1426
1427   if (plugin->cur_connections >= plugin->max_connections)
1428   {
1429     /* saturated */
1430     return NULL;
1431   }
1432
1433   if ((is_natd == GNUNET_YES) &&
1434       (GNUNET_YES ==
1435        GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1436                                                &address->peer.hashPubKey)))
1437   {
1438     /* Only do one NAT punch attempt per peer identity */
1439      return NULL;
1440   }
1441
1442   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1443       (GNUNET_NO ==
1444        GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1445                                                &address->peer.hashPubKey)))
1446   {
1447     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1448          "Found valid IPv4 NAT address (creating session)!\n") ;
1449     session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1450     session->addrlen = 0;
1451     session->addr = NULL;
1452     session->ats_address_network_type = ats.value;
1453     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1454                                                                     &nat_connect_timeout,
1455                                                                     session);
1456     GNUNET_assert (session != NULL);
1457     GNUNET_assert (GNUNET_OK ==
1458                    GNUNET_CONTAINER_multihashmap_put (plugin->nat_wait_conns, 
1459                                                       &session->target.hashPubKey, 
1460                                                       session,
1461                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1462
1463     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1464          "Created NAT WAIT connection to `%4s' at `%s'\n",
1465          GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1466
1467     if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1468       return session;
1469     else
1470     {
1471       LOG (GNUNET_ERROR_TYPE_DEBUG, 
1472            "Running NAT client for `%4s' at `%s' failed\n",
1473            GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1474       disconnect_session (session);
1475       return NULL;
1476     }
1477   }
1478
1479   /* create new outbound session */
1480   GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
1481   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1482   if (sa == NULL)
1483   {
1484     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1485          "Failed to create connection to `%4s' at `%s'\n",
1486          GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1487     return NULL;
1488   }
1489   plugin->cur_connections++;
1490   if (plugin->cur_connections == plugin->max_connections)
1491         GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1492
1493   LOG (GNUNET_ERROR_TYPE_DEBUG,
1494        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1495        GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1496
1497   session = create_session (plugin,
1498                             &address->peer,
1499                             GNUNET_SERVER_connect_socket (plugin->server, sa),
1500                             GNUNET_NO);
1501   session->addr = GNUNET_malloc (addrlen);
1502   memcpy (session->addr, address->address, addrlen);
1503   session->addrlen = addrlen;
1504   session->ats_address_network_type = ats.value;
1505
1506   GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap, 
1507                                      &session->target.hashPubKey, 
1508                                      session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1509   inc_sessions (plugin, session, __LINE__);
1510   LOG (GNUNET_ERROR_TYPE_DEBUG,
1511        "Creating new session for `%s' address `%s' session %p\n",
1512        GNUNET_i2s (&address->peer),
1513        tcp_address_to_string(NULL, address->address, address->address_length),
1514        session);
1515   /* Send TCP Welcome */
1516   process_pending_messages (session);
1517
1518   return session;
1519 }
1520
1521
1522 static int 
1523 session_disconnect_it (void *cls,
1524                        const struct GNUNET_HashCode * key,
1525                        void *value)
1526 {
1527   struct Session *session = value;
1528
1529   GNUNET_STATISTICS_update (session->plugin->env->stats,
1530                             gettext_noop
1531                             ("# transport-service disconnect requests for TCP"),
1532                             1, GNUNET_NO);
1533   disconnect_session (session);
1534   return GNUNET_YES;
1535 }
1536
1537
1538 /**
1539  * Function that can be called to force a disconnect from the
1540  * specified neighbour.  This should also cancel all previously
1541  * scheduled transmissions.  Obviously the transmission may have been
1542  * partially completed already, which is OK.  The plugin is supposed
1543  * to close the connection (if applicable) and no longer call the
1544  * transmit continuation(s).
1545  *
1546  * Finally, plugin MUST NOT call the services's receive function to
1547  * notify the service that the connection to the specified target was
1548  * closed after a getting this call.
1549  *
1550  * @param cls closure
1551  * @param target peer for which the last transmission is
1552  *        to be cancelled
1553  */
1554 static void
1555 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1556 {
1557   struct Plugin *plugin = cls;
1558
1559   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1560        "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1561   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, &session_disconnect_it, plugin);
1562   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->nat_wait_conns, &target->hashPubKey, &session_disconnect_it, plugin);
1563 }
1564
1565
1566 /**
1567  * Context for address to string conversion.
1568  */
1569 struct PrettyPrinterContext
1570 {
1571   /**
1572    * Function to call with the result.
1573    */
1574   GNUNET_TRANSPORT_AddressStringCallback asc;
1575
1576   /**
1577    * Clsoure for 'asc'.
1578    */
1579   void *asc_cls;
1580
1581   /**
1582    * Port to add after the IP address.
1583    */
1584   uint16_t port;
1585
1586   /**
1587    * IPv6 address
1588    */
1589   int ipv6;
1590
1591   /**
1592    * Options
1593    */
1594   uint32_t options;
1595 };
1596
1597
1598 /**
1599  * Append our port and forward the result.
1600  *
1601  * @param cls the 'struct PrettyPrinterContext*'
1602  * @param hostname hostname part of the address
1603  */
1604 static void
1605 append_port (void *cls, const char *hostname)
1606 {
1607   struct PrettyPrinterContext *ppc = cls;
1608   char *ret;
1609
1610   if (hostname == NULL)
1611   {
1612     ppc->asc (ppc->asc_cls, NULL);
1613     GNUNET_free (ppc);
1614     return;
1615   }
1616   if (GNUNET_YES == ppc->ipv6)
1617     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1618   else
1619     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1620   ppc->asc (ppc->asc_cls, ret);
1621   GNUNET_free (ret);
1622 }
1623
1624
1625 /**
1626  * Convert the transports address to a nice, human-readable
1627  * format.
1628  *
1629  * @param cls closure
1630  * @param type name of the transport that generated the address
1631  * @param addr one of the addresses of the host, NULL for the last address
1632  *        the specific address format depends on the transport
1633  * @param addrlen length of the address
1634  * @param numeric should (IP) addresses be displayed in numeric form?
1635  * @param timeout after how long should we give up?
1636  * @param asc function to call on each string
1637  * @param asc_cls closure for asc
1638  */
1639 static void
1640 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1641                                    const void *addr, size_t addrlen,
1642                                    int numeric,
1643                                    struct GNUNET_TIME_Relative timeout,
1644                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1645                                    void *asc_cls)
1646 {
1647   struct PrettyPrinterContext *ppc;
1648   const void *sb;
1649   size_t sbs;
1650   struct sockaddr_in a4;
1651   struct sockaddr_in6 a6;
1652   const struct IPv4TcpAddress *t4;
1653   const struct IPv6TcpAddress *t6;
1654   uint16_t port;
1655   uint32_t options;
1656
1657
1658   options = 0;
1659   if (addrlen == sizeof (struct IPv6TcpAddress))
1660   {
1661     t6 = addr;
1662     memset (&a6, 0, sizeof (a6));
1663     a6.sin6_family = AF_INET6;
1664     a6.sin6_port = t6->t6_port;
1665     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1666     port = ntohs (t6->t6_port);
1667     options = ntohl (t6->options);
1668     sb = &a6;
1669     sbs = sizeof (a6);
1670   }
1671   else if (addrlen == sizeof (struct IPv4TcpAddress))
1672   {
1673     t4 = addr;
1674     memset (&a4, 0, sizeof (a4));
1675     a4.sin_family = AF_INET;
1676     a4.sin_port = t4->t4_port;
1677     a4.sin_addr.s_addr = t4->ipv4_addr;
1678     port = ntohs (t4->t4_port);
1679     options = ntohl (t4->options);
1680     sb = &a4;
1681     sbs = sizeof (a4);
1682   }
1683   else if (0 == addrlen)
1684   {
1685     asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1686     asc (asc_cls, NULL);
1687     return;
1688   }
1689   else
1690   {
1691     /* invalid address */
1692     GNUNET_break_op (0);
1693     asc (asc_cls, NULL);
1694     return;
1695   }
1696   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1697   if (addrlen == sizeof (struct IPv6TcpAddress))
1698     ppc->ipv6 = GNUNET_YES;
1699   else
1700     ppc->ipv6 = GNUNET_NO;
1701   ppc->asc = asc;
1702   ppc->asc_cls = asc_cls;
1703   ppc->port = port;
1704   ppc->options = options;
1705   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1706 }
1707
1708
1709 /**
1710  * Check if the given port is plausible (must be either our listen
1711  * port or our advertised port), or any port if we are behind NAT
1712  * and do not have a port open.  If it is neither, we return
1713  * GNUNET_SYSERR.
1714  *
1715  * @param plugin global variables
1716  * @param in_port port number to check
1717  * @return GNUNET_OK if port is either open_port or adv_port
1718  */
1719 static int
1720 check_port (struct Plugin *plugin, uint16_t in_port)
1721 {
1722   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1723     return GNUNET_OK;
1724   return GNUNET_SYSERR;
1725 }
1726
1727
1728 /**
1729  * Function that will be called to check if a binary address for this
1730  * plugin is well-formed and corresponds to an address for THIS peer
1731  * (as per our configuration).  Naturally, if absolutely necessary,
1732  * plugins can be a bit conservative in their answer, but in general
1733  * plugins should make sure that the address does not redirect
1734  * traffic to a 3rd party that might try to man-in-the-middle our
1735  * traffic.
1736  *
1737  * @param cls closure, our 'struct Plugin*'
1738  * @param addr pointer to the address
1739  * @param addrlen length of addr
1740  * @return GNUNET_OK if this is a plausible address for this peer
1741  *         and transport, GNUNET_SYSERR if not
1742  */
1743 static int
1744 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1745 {
1746   struct Plugin *plugin = cls;
1747   struct IPv4TcpAddress *v4;
1748   struct IPv6TcpAddress *v6;
1749
1750   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1751       (addrlen != sizeof (struct IPv6TcpAddress)))
1752   {
1753     GNUNET_break_op (0);
1754     return GNUNET_SYSERR;
1755   }
1756
1757
1758   if (addrlen == sizeof (struct IPv4TcpAddress))
1759   {
1760     v4 = (struct IPv4TcpAddress *) addr;
1761     if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
1762     {
1763         GNUNET_break (0);
1764         return GNUNET_SYSERR;
1765     }
1766     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1767       return GNUNET_SYSERR;
1768     if (GNUNET_OK !=
1769         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1770                                  sizeof (struct in_addr)))
1771       return GNUNET_SYSERR;
1772   }
1773   else
1774   {
1775     v6 = (struct IPv6TcpAddress *) addr;
1776     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1777     {
1778       GNUNET_break_op (0);
1779       return GNUNET_SYSERR;
1780     }
1781     if (0 != memcmp (&v6->options, &myoptions, sizeof (myoptions)))
1782     {
1783         GNUNET_break (0);
1784         return GNUNET_SYSERR;
1785     }
1786     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1787       return GNUNET_SYSERR;
1788     if (GNUNET_OK !=
1789         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1790                                  sizeof (struct in6_addr)))
1791       return GNUNET_SYSERR;
1792   }
1793   return GNUNET_OK;
1794 }
1795
1796
1797 /**
1798  * We've received a nat probe from this peer via TCP.  Finish
1799  * creating the client session and resume sending of queued
1800  * messages.
1801  *
1802  * @param cls closure
1803  * @param client identification of the client
1804  * @param message the actual message
1805  */
1806 static void
1807 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1808                       const struct GNUNET_MessageHeader *message)
1809 {
1810   struct Plugin *plugin = cls;
1811   struct Session *session;
1812   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1813   size_t alen;
1814   void *vaddr;
1815   struct IPv4TcpAddress *t4;
1816   struct IPv6TcpAddress *t6;
1817   const struct sockaddr_in *s4;
1818   const struct sockaddr_in6 *s6;
1819
1820   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
1821
1822   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1823    * a connection to this peer by running gnunet-nat-client.  This peer
1824    * received the punch message and now wants us to use the new connection
1825    * as the default for that peer.  Do so and then send a WELCOME message
1826    * so we can really be connected!
1827    */
1828   if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1829   {
1830     GNUNET_break_op (0);
1831     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1832     return;
1833   }
1834
1835   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1836   if (0 ==
1837       memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1838               sizeof (struct GNUNET_PeerIdentity)))
1839   {
1840     /* refuse connections from ourselves */
1841     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1842     return;
1843   }
1844
1845   session =
1846       GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1847                                          &tcp_nat_probe->
1848                                          clientIdentity.hashPubKey);
1849   if (session == NULL)
1850   {
1851     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1852          "Did NOT find session for NAT probe!\n");
1853     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1854     return;
1855   }
1856   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1857        "Found session for NAT probe!\n");
1858
1859   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1860   {
1861     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1862     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1863   }
1864
1865   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1866   {
1867     GNUNET_break (0);
1868     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1869     disconnect_session (session);
1870     return;
1871   }
1872   GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1873                  (plugin->nat_wait_conns,
1874                   &tcp_nat_probe->clientIdentity.hashPubKey,
1875                   session) == GNUNET_YES);
1876   GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap,
1877                                      &session->target.hashPubKey, session, 
1878                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);  
1879   session->last_activity = GNUNET_TIME_absolute_get ();
1880   session->inbound = GNUNET_NO;
1881   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1882        "Found address `%s' for incoming connection\n",
1883        GNUNET_a2s (vaddr, alen));
1884   switch (((const struct sockaddr *) vaddr)->sa_family)
1885   {
1886   case AF_INET:
1887     s4 = vaddr;
1888     t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1889     t4->options = 0;
1890     t4->t4_port = s4->sin_port;
1891     t4->ipv4_addr = s4->sin_addr.s_addr;
1892     session->addr = t4;
1893     session->addrlen = sizeof (struct IPv4TcpAddress);
1894     break;
1895   case AF_INET6:
1896     s6 = vaddr;
1897     t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1898     t6->options = 0;
1899     t6->t6_port = s6->sin6_port;
1900     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1901     session->addr = t6;
1902     session->addrlen = sizeof (struct IPv6TcpAddress);
1903     break;
1904   default:
1905     GNUNET_break_op (0);
1906     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1907          "Bad address for incoming connection!\n");
1908     GNUNET_free (vaddr);
1909     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1910     disconnect_session (session);
1911     return;
1912   }
1913   GNUNET_free (vaddr);
1914   GNUNET_break (NULL == session->client);
1915   GNUNET_SERVER_client_keep (client);
1916   session->client = client;
1917   inc_sessions (plugin, session, __LINE__);
1918   GNUNET_STATISTICS_update (plugin->env->stats,
1919                             gettext_noop ("# TCP sessions active"), 1,
1920                             GNUNET_NO);
1921   process_pending_messages (session);
1922   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1923 }
1924
1925
1926 /**
1927  * We've received a welcome from this peer via TCP.  Possibly create a
1928  * fresh client record and send back our welcome.
1929  *
1930  * @param cls closure
1931  * @param client identification of the client
1932  * @param message the actual message
1933  */
1934 static void
1935 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1936                     const struct GNUNET_MessageHeader *message)
1937 {
1938   struct Plugin *plugin = cls;
1939   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1940   struct Session *session;
1941   size_t alen;
1942   void *vaddr;
1943   struct IPv4TcpAddress *t4;
1944   struct IPv6TcpAddress *t6;
1945   const struct sockaddr_in *s4;
1946   const struct sockaddr_in6 *s6;
1947   struct GNUNET_ATS_Information ats;
1948
1949   if (0 ==
1950       memcmp (&wm->clientIdentity, plugin->env->my_identity,
1951               sizeof (struct GNUNET_PeerIdentity)))
1952   {
1953     /* refuse connections from ourselves */
1954     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1955     GNUNET_break (0);
1956     return;
1957   }
1958   LOG (GNUNET_ERROR_TYPE_DEBUG,
1959        "Received %s message from `%4s' %p\n", "WELCOME",
1960        GNUNET_i2s (&wm->clientIdentity), client);
1961   GNUNET_STATISTICS_update (plugin->env->stats,
1962                             gettext_noop ("# TCP WELCOME messages received"), 1,
1963                             GNUNET_NO);
1964   session = lookup_session_by_client (plugin, client);
1965   if (session != NULL)
1966   {
1967     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1968     {
1969       LOG (GNUNET_ERROR_TYPE_DEBUG,
1970            "Found existing session %p for peer `%s'\n",
1971            session,
1972            GNUNET_a2s (vaddr, alen));
1973       GNUNET_free (vaddr);
1974     }
1975   }
1976   else
1977   {
1978     GNUNET_SERVER_client_keep (client);
1979     if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
1980         plugin->cur_connections++;
1981     if (plugin->cur_connections == plugin->max_connections)
1982         GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1983
1984     session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1985     session->inbound = GNUNET_YES;
1986     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1987     {
1988       if (alen == sizeof (struct sockaddr_in))
1989       {
1990         s4 = vaddr;
1991         t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1992         t4->options = htonl (0);
1993         t4->t4_port = s4->sin_port;
1994         t4->ipv4_addr = s4->sin_addr.s_addr;
1995         session->addr = t4;
1996         session->addrlen = sizeof (struct IPv4TcpAddress);
1997       }
1998       else if (alen == sizeof (struct sockaddr_in6))
1999       {
2000         s6 = vaddr;
2001         t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
2002         t6->options = htonl (0);
2003         t6->t6_port = s6->sin6_port;
2004         memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2005         session->addr = t6;
2006         session->addrlen = sizeof (struct IPv6TcpAddress);
2007       }
2008
2009       ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
2010       session->ats_address_network_type = ats.value;
2011       LOG (GNUNET_ERROR_TYPE_DEBUG,
2012      "Creating new session %p for peer `%s'\n",
2013      session,
2014      GNUNET_a2s (vaddr, alen));
2015       GNUNET_free (vaddr);
2016       GNUNET_CONTAINER_multihashmap_put (plugin->sessionmap,
2017                                        &session->target.hashPubKey,
2018                                        session,
2019                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2020       inc_sessions (plugin, session, __LINE__);
2021     }
2022     else
2023     {
2024       LOG (GNUNET_ERROR_TYPE_DEBUG, 
2025            "Did not obtain TCP socket address for incoming connection\n");
2026       GNUNET_break (0);
2027     }
2028   }
2029
2030   if (session->expecting_welcome != GNUNET_YES)
2031   {
2032     GNUNET_break_op (0);
2033     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2034     GNUNET_break (0);
2035     return;
2036   }
2037   session->last_activity = GNUNET_TIME_absolute_get ();
2038   session->expecting_welcome = GNUNET_NO;
2039
2040   /* Notify transport and ATS about new session */
2041   if (GNUNET_YES == session->inbound)
2042   {
2043         plugin->env->session_start (NULL, &wm->clientIdentity, PLUGIN_NAME,
2044                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2045                   (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2046                   session, &ats, 1);
2047   }
2048
2049   process_pending_messages (session);
2050
2051   GNUNET_SERVER_client_set_timeout (client,
2052                                     GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2053   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2054 }
2055
2056
2057 /**
2058  * Task to signal the server that we can continue
2059  * receiving from the TCP client now.
2060  *
2061  * @param cls the 'struct Session*'
2062  * @param tc task context (unused)
2063  */
2064 static void
2065 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2066 {
2067   struct Session *session = cls;
2068
2069   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2070   reschedule_session_timeout (session);
2071
2072   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2073 }
2074
2075
2076 /**
2077  * We've received data for this peer via TCP.  Unbox,
2078  * compute latency and forward.
2079  *
2080  * @param cls closure
2081  * @param client identification of the client
2082  * @param message the actual message
2083  */
2084 static void
2085 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2086                  const struct GNUNET_MessageHeader *message)
2087 {
2088   struct Plugin *plugin = cls;
2089   struct Session *session;
2090   struct GNUNET_TIME_Relative delay;
2091   uint16_t type;
2092
2093   type = ntohs (message->type);
2094   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
2095       (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2096   {
2097     /* We don't want to propagate WELCOME and NAT Probe messages up! */
2098     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2099     return;
2100   }
2101   session = lookup_session_by_client (plugin, client);
2102   if (NULL == session)
2103   {
2104     /* No inbound session found */
2105     void *vaddr;
2106     size_t alen;
2107     
2108     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2109     LOG (GNUNET_ERROR_TYPE_ERROR, 
2110          "Received unexpected %u bytes of type %u from `%s'\n",
2111          (unsigned int) ntohs (message->size),
2112          (unsigned int) ntohs (message->type),
2113          GNUNET_a2s(vaddr, alen));
2114     GNUNET_break_op (0);
2115     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2116     GNUNET_free_non_null(vaddr);
2117     return;
2118   }
2119   else if (GNUNET_YES == session->expecting_welcome)
2120   {
2121     /* Session is expecting WELCOME message */
2122     void *vaddr;
2123     size_t alen;
2124
2125     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2126     LOG (GNUNET_ERROR_TYPE_ERROR, 
2127          "Received unexpected %u bytes of type %u from `%s'\n",
2128          (unsigned int) ntohs (message->size),
2129          (unsigned int) ntohs (message->type),
2130          GNUNET_a2s(vaddr, alen));
2131     GNUNET_break_op (0);
2132     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2133     GNUNET_free_non_null(vaddr);
2134     return;
2135   }
2136
2137   session->last_activity = GNUNET_TIME_absolute_get ();
2138   LOG (GNUNET_ERROR_TYPE_DEBUG, 
2139                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2140                    (unsigned int) ntohs (message->size),
2141                    (unsigned int) ntohs (message->type),
2142                    GNUNET_i2s (&session->target));
2143
2144   GNUNET_STATISTICS_update (plugin->env->stats,
2145                             gettext_noop ("# bytes received via TCP"),
2146                             ntohs (message->size), GNUNET_NO);
2147   struct GNUNET_ATS_Information distance;
2148
2149   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2150   distance.value = session->ats_address_network_type;
2151   GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
2152
2153   GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains_value (plugin->sessionmap,
2154       &session->target.hashPubKey,
2155       session));
2156
2157   delay = plugin->env->receive (plugin->env->cls,
2158                                 &session->target,
2159                                 message,
2160                                 session,
2161                                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2162                                 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
2163   plugin->env->update_address_metrics (plugin->env->cls,
2164                 &session->target,
2165                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2166                   (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2167                   session, &distance, 1);
2168
2169   reschedule_session_timeout (session);
2170
2171   if (delay.rel_value == 0)
2172   {
2173     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2174   }
2175   else
2176   {
2177     LOG (GNUNET_ERROR_TYPE_DEBUG, 
2178          "Throttling receiving from `%s' for %llu ms\n",
2179          GNUNET_i2s (&session->target),
2180          (unsigned long long) delay.rel_value);
2181     GNUNET_SERVER_disable_receive_done_warning (client);
2182     session->receive_delay_task =
2183         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2184   }
2185 }
2186
2187
2188 /**
2189  * Functions with this signature are called whenever a peer
2190  * is disconnected on the network level.
2191  *
2192  * @param cls closure
2193  * @param client identification of the client
2194  */
2195 static void
2196 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2197 {
2198   struct Plugin *plugin = cls;
2199   struct Session *session;
2200
2201   if (client == NULL)
2202     return;
2203   session = lookup_session_by_client (plugin, client);
2204   if (session == NULL)
2205     return;                     /* unknown, nothing to do */
2206   LOG (GNUNET_ERROR_TYPE_DEBUG,
2207        "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2208        GNUNET_i2s (&session->target),
2209        (session->addr !=
2210         NULL) ? tcp_address_to_string (session->plugin,
2211                                        session->addr,
2212                                        session->addrlen) :
2213        "*");
2214
2215   if (plugin->cur_connections == plugin->max_connections)
2216         GNUNET_SERVER_resume (plugin->server); /* Resume server  */
2217
2218   if (plugin->cur_connections < 1)
2219         GNUNET_break (0);
2220   else
2221         plugin->cur_connections--;
2222
2223   GNUNET_STATISTICS_update (session->plugin->env->stats,
2224                             gettext_noop
2225                             ("# network-level TCP disconnect events"), 1,
2226                             GNUNET_NO);
2227   disconnect_session (session);
2228 }
2229
2230
2231 /**
2232  * We can now send a probe message, copy into buffer to really send.
2233  *
2234  * @param cls closure, a struct TCPProbeContext
2235  * @param size max size to copy
2236  * @param buf buffer to copy message to
2237  * @return number of bytes copied into buf
2238  */
2239 static size_t
2240 notify_send_probe (void *cls, size_t size, void *buf)
2241 {
2242   struct TCPProbeContext *tcp_probe_ctx = cls;
2243   struct Plugin *plugin = tcp_probe_ctx->plugin;
2244   size_t ret;
2245
2246   tcp_probe_ctx->transmit_handle = NULL;
2247   GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2248                                tcp_probe_ctx);
2249   if (buf == NULL)
2250   {
2251     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2252     GNUNET_free (tcp_probe_ctx);
2253     return 0;
2254   }
2255   GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2256   memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2257   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2258                                 tcp_probe_ctx->sock);
2259   ret = sizeof (tcp_probe_ctx->message);
2260   GNUNET_free (tcp_probe_ctx);
2261   return ret;
2262 }
2263
2264
2265 /**
2266  * Function called by the NAT subsystem suggesting another peer wants
2267  * to connect to us via connection reversal.  Try to connect back to the
2268  * given IP.
2269  *
2270  * @param cls closure
2271  * @param addr address to try
2272  * @param addrlen number of bytes in addr
2273  */
2274 static void
2275 try_connection_reversal (void *cls, const struct sockaddr *addr,
2276                          socklen_t addrlen)
2277 {
2278   struct Plugin *plugin = cls;
2279   struct GNUNET_CONNECTION_Handle *sock;
2280   struct TCPProbeContext *tcp_probe_ctx;
2281
2282   /**
2283    * We have received an ICMP response, ostensibly from a peer
2284    * that wants to connect to us! Send a message to establish a connection.
2285    */
2286   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2287   if (sock == NULL)
2288   {
2289     /* failed for some odd reason (out of sockets?); ignore attempt */
2290     return;
2291   }
2292
2293   /* FIXME: do we need to track these probe context objects so that
2294    * we can clean them up on plugin unload? */
2295   tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2296   tcp_probe_ctx->message.header.size =
2297       htons (sizeof (struct TCP_NAT_ProbeMessage));
2298   tcp_probe_ctx->message.header.type =
2299       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2300   memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2301           sizeof (struct GNUNET_PeerIdentity));
2302   tcp_probe_ctx->plugin = plugin;
2303   tcp_probe_ctx->sock = sock;
2304   GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2305                                tcp_probe_ctx);
2306   tcp_probe_ctx->transmit_handle =
2307       GNUNET_CONNECTION_notify_transmit_ready (sock,
2308                                                ntohs (tcp_probe_ctx->
2309                                                       message.header.size),
2310                                                GNUNET_TIME_UNIT_FOREVER_REL,
2311                                                &notify_send_probe,
2312                                                tcp_probe_ctx);
2313
2314 }
2315
2316
2317 /**
2318  * Session was idle, so disconnect it
2319  */
2320 static void
2321 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2322 {
2323   GNUNET_assert (NULL != cls);
2324   struct Session *s = cls;
2325
2326   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328               "Session %p was idle for %llu ms, disconnecting\n",
2329               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
2330   /* call session destroy function */
2331   disconnect_session(s);
2332 }
2333
2334
2335 /**
2336  * Start session timeout
2337  */
2338 static void
2339 start_session_timeout (struct Session *s)
2340 {
2341   GNUNET_assert (NULL != s);
2342   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2343   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2344                                                    &session_timeout,
2345                                                    s);
2346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347               "Timeout for session %p set to %llu ms\n",
2348               s,  (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
2349 }
2350
2351
2352 /**
2353  * Increment session timeout due to activity
2354  */
2355 static void
2356 reschedule_session_timeout (struct Session *s)
2357 {
2358   GNUNET_assert (NULL != s);
2359   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2360
2361   GNUNET_SCHEDULER_cancel (s->timeout_task);
2362   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2363                                                    &session_timeout,
2364                                                    s);
2365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366               "Timeout rescheduled for session %p set to %llu ms\n",
2367               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
2368 }
2369
2370
2371 /**
2372  * Cancel timeout
2373  */
2374 static void
2375 stop_session_timeout (struct Session *s)
2376 {
2377   GNUNET_assert (NULL != s);
2378
2379   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
2380   {
2381     GNUNET_SCHEDULER_cancel (s->timeout_task);
2382     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2383     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2384                 "Timeout stopped for session %p canceled\n",
2385                 s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
2386   }
2387 }
2388
2389 /**
2390  * Function obtain the network type for a session
2391  *
2392  * @param cls closure ('struct Plugin*')
2393  * @param session the session
2394  * @return the network type in HBO or GNUNET_SYSERR
2395  */
2396 static enum GNUNET_ATS_Network_Type
2397 tcp_get_network (void *cls,
2398                  struct Session *session)
2399 {
2400   GNUNET_assert (NULL != session);
2401   return ntohl (session->ats_address_network_type);
2402 }
2403
2404
2405 /**
2406  * Entry point for the plugin.
2407  *
2408  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2409  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2410  */
2411 void *
2412 libgnunet_plugin_transport_tcp_init (void *cls)
2413 {
2414   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2415     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2416      sizeof (struct WelcomeMessage)},
2417     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2418      sizeof (struct TCP_NAT_ProbeMessage)},
2419     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2420     {NULL, NULL, 0, 0}
2421   };
2422   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2423   struct GNUNET_TRANSPORT_PluginFunctions *api;
2424   struct Plugin *plugin;
2425   struct GNUNET_SERVICE_Context *service;
2426   unsigned long long aport;
2427   unsigned long long bport;
2428   unsigned long long max_connections;
2429   unsigned int i;
2430   struct GNUNET_TIME_Relative idle_timeout;
2431   int ret;
2432   int ret_s;
2433   struct sockaddr **addrs;
2434   socklen_t *addrlens;
2435
2436
2437   if (NULL == env->receive)
2438   {
2439     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2440        initialze the plugin or the API */
2441     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2442     api->cls = NULL;
2443     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2444     api->address_to_string = &tcp_address_to_string;
2445     api->string_to_address = &tcp_string_to_address;
2446     return api;
2447   }
2448
2449   GNUNET_assert (NULL != env->cfg);
2450   if (GNUNET_OK !=
2451       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2452                                              "MAX_CONNECTIONS",
2453                                              &max_connections))
2454     max_connections = 128;
2455
2456   aport = 0;
2457   if ((GNUNET_OK !=
2458        GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2459                                               &bport)) || (bport > 65535) ||
2460       ((GNUNET_OK ==
2461         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2462                                                "ADVERTISED-PORT", &aport)) &&
2463        (aport > 65535)))
2464   {
2465     LOG (GNUNET_ERROR_TYPE_ERROR, 
2466          _
2467          ("Require valid port number for service `%s' in configuration!\n"),
2468          "transport-tcp");
2469     return NULL;
2470   }
2471   if (aport == 0)
2472     aport = bport;
2473   if (bport == 0)
2474     aport = 0;
2475   if (bport != 0)
2476   {
2477     service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2478     if (service == NULL)
2479     {
2480       LOG (GNUNET_ERROR_TYPE_WARNING,
2481            _("Failed to start service.\n"));
2482       return NULL;
2483     }
2484   }
2485   else
2486     service = NULL;
2487
2488   /* Initialize my flags */
2489   myoptions = 0;
2490
2491   plugin = GNUNET_malloc (sizeof (struct Plugin));
2492   plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create (max_connections, GNUNET_YES);
2493   plugin->max_connections = max_connections;
2494   plugin->cur_connections = 0;
2495   plugin->open_port = bport;
2496   plugin->adv_port = aport;
2497   plugin->env = env;
2498   plugin->lsock = NULL;
2499   if ((service != NULL) &&
2500       (GNUNET_SYSERR !=
2501        (ret_s =
2502         GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2503                                              &addrlens))))
2504   {
2505     for (ret = ret_s-1; ret >= 0; ret--)
2506       LOG (GNUNET_ERROR_TYPE_INFO,
2507            "Binding to address `%s'\n", 
2508            GNUNET_a2s (addrs[ret], addrlens[ret]));
2509     plugin->nat =
2510         GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2511                              (const struct sockaddr **) addrs, addrlens,
2512                              &tcp_nat_port_map_callback,
2513                              &try_connection_reversal, plugin);
2514     for (ret = ret_s -1; ret >= 0; ret--)
2515     {
2516       GNUNET_assert (addrs[ret] != NULL);
2517       GNUNET_free (addrs[ret]);
2518     }
2519     GNUNET_free_non_null (addrs);
2520     GNUNET_free_non_null (addrlens);
2521   }
2522   else
2523   {
2524     plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2525                                        GNUNET_YES, 0, 0, NULL, NULL, NULL,
2526                                        &try_connection_reversal, plugin);
2527   }
2528   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2529   api->cls = plugin;
2530   api->send = &tcp_plugin_send;
2531   api->get_session = &tcp_plugin_get_session;
2532
2533   api->disconnect = &tcp_plugin_disconnect;
2534   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2535   api->check_address = &tcp_plugin_check_address;
2536   api->address_to_string = &tcp_address_to_string;
2537   api->string_to_address = &tcp_string_to_address;
2538   api->get_network = &tcp_get_network;
2539   plugin->service = service;
2540   if (service != NULL)
2541   {
2542     plugin->server = GNUNET_SERVICE_get_server (service);
2543   }
2544   else
2545   {
2546     if (GNUNET_OK !=
2547         GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2548                                              "TIMEOUT", &idle_timeout))
2549     {
2550       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2551                                  "transport-tcp", "TIMEOUT");
2552       if (plugin->nat != NULL)
2553         GNUNET_NAT_unregister (plugin->nat);
2554       GNUNET_free (plugin);
2555       GNUNET_free (api);
2556       return NULL;
2557     }
2558     plugin->server =
2559         GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2560                                            NULL, idle_timeout, GNUNET_YES);
2561   }
2562   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2563   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2564   for (i = 0;
2565        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2566        i++)
2567     plugin->handlers[i].callback_cls = plugin;
2568
2569   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2570   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2571   plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_YES);
2572   if (bport != 0)
2573     LOG (GNUNET_ERROR_TYPE_INFO, 
2574          _("TCP transport listening on port %llu\n"), bport);
2575   else
2576     LOG (GNUNET_ERROR_TYPE_INFO, 
2577          _
2578          ("TCP transport not listening on any port (client only)\n"));
2579   if (aport != bport)
2580     LOG (GNUNET_ERROR_TYPE_INFO, 
2581                      _
2582                      ("TCP transport advertises itself as being on port %llu\n"),
2583                      aport);
2584   /* Initially set connections to 0 */
2585   GNUNET_assert (NULL != plugin->env->stats);
2586   GNUNET_STATISTICS_set (plugin->env->stats,
2587                         gettext_noop ("# TCP sessions active"), 0,
2588                         GNUNET_NO);
2589   return api;
2590 }
2591
2592
2593 /**
2594  * Exit point from the plugin.
2595  */
2596 void *
2597 libgnunet_plugin_transport_tcp_done (void *cls)
2598 {
2599   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2600   struct Plugin *plugin = api->cls;
2601   struct TCPProbeContext *tcp_probe;
2602
2603   if (NULL == plugin)
2604   {
2605     GNUNET_free (api);
2606     return NULL;
2607   }
2608   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down TCP plugin\n");
2609
2610   /* Removing leftover sessions */
2611   GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2612   /* Removing leftover NAT sessions */
2613   GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2614
2615   if (plugin->service != NULL)
2616     GNUNET_SERVICE_stop (plugin->service);
2617   else
2618     GNUNET_SERVER_destroy (plugin->server);
2619   GNUNET_free (plugin->handlers);
2620   if (plugin->nat != NULL)
2621     GNUNET_NAT_unregister (plugin->nat);
2622   while (NULL != (tcp_probe = plugin->probe_head))
2623   {
2624     GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2625                                  tcp_probe);
2626     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2627     GNUNET_free (tcp_probe);
2628   }
2629   GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2630   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2631   GNUNET_free (plugin);
2632   GNUNET_free (api);
2633   return NULL;
2634 }
2635
2636 /* end of plugin_transport_tcp.c */