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