- check task (could be in the middle of transmission loop and be 0)
[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   plugin->env->unregister_quota_notification (plugin->env->cls,
783       &session->target, PLUGIN_NAME, session);
784   session->plugin->env->session_end (session->plugin->env->cls,
785       &session->target, session);
786
787   if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
788   {
789     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
790     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
791   }
792
793   while (NULL != (pm = session->pending_messages_head))
794   {
795     LOG(GNUNET_ERROR_TYPE_DEBUG,
796         pm->transmit_cont != NULL ? "Could not deliver message to `%4s'.\n" : "Could not deliver message to `%4s', notifying.\n",
797         GNUNET_i2s (&session->target));
798     GNUNET_STATISTICS_update (session->plugin->env->stats,
799         gettext_noop ("# bytes currently in TCP buffers"),
800         -(int64_t) pm->message_size, GNUNET_NO);
801     GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
802     ("# bytes discarded by TCP (disconnect)"), pm->message_size, GNUNET_NO);
803     GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
804         session->pending_messages_tail, pm);
805     if (NULL != pm->transmit_cont)
806       pm->transmit_cont (pm->transmit_cont_cls, &session->target, GNUNET_SYSERR,
807           pm->message_size, 0);
808     GNUNET_free(pm);
809   }
810   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK )
811   {
812     GNUNET_SCHEDULER_cancel (session->receive_delay_task);
813     if (NULL != session->client)
814       GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
815   }
816   if (NULL != session->client)
817   {
818     GNUNET_SERVER_client_disconnect (session->client);
819     GNUNET_SERVER_client_drop (session->client);
820     session->client = NULL;
821   }
822   GNUNET_HELLO_address_free (session->address);
823   GNUNET_assert(NULL == session->transmit_handle);
824   GNUNET_free(session);
825   return GNUNET_OK;
826 }
827
828 /**
829  * Function that is called to get the keepalive factor.
830  * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
831  * calculate the interval between keepalive packets.
832  *
833  * @param cls closure with the `struct Plugin`
834  * @return keepalive factor
835  */
836 static unsigned int
837 tcp_query_keepalive_factor (void *cls)
838 {
839   return 3;
840 }
841
842 /**
843  * Session was idle, so disconnect it
844  *
845  * @param cls the `struct Session` of the idle session
846  * @param tc scheduler context
847  */
848 static void
849 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
850 {
851   struct Session *s = cls;
852
853   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
854   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
855       "Session %p was idle for %s, disconnecting\n", s,
856       GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, GNUNET_YES));
857   /* call session destroy function */
858   tcp_disconnect_session (s->plugin, s);
859 }
860
861 /**
862  * Increment session timeout due to activity
863  *
864  * @param s session to increment timeout for
865  */
866 static void
867 reschedule_session_timeout (struct Session *s)
868 {
869   GNUNET_assert(GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
870   GNUNET_SCHEDULER_cancel (s->timeout_task);
871   s->timeout_task = GNUNET_SCHEDULER_add_delayed (
872       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, s);
873   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
874       "Timeout rescheduled for session %p set to %s\n", s,
875       GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, GNUNET_YES));
876 }
877
878 /**
879  * Create a new session.  Also queues a welcome message.
880  *
881  * @param plugin the plugin
882  * @param address the address to create the session for
883  * @param client client to use, reference counter must have already been increased
884  * @param is_nat this a NAT session, we should wait for a client to
885  *               connect to us from an address, then assign that to
886  *               the session
887  * @return new session object
888  */
889 static struct Session *
890 create_session (struct Plugin *plugin,
891                 const struct GNUNET_HELLO_Address *address,
892                 struct GNUNET_SERVER_Client *client,
893                 int is_nat)
894 {
895   struct Session *session;
896   struct PendingMessage *pm;
897   struct WelcomeMessage welcome;
898
899   if (GNUNET_YES != is_nat)
900     GNUNET_assert(NULL != client);
901   else
902     GNUNET_assert(NULL == client);
903
904   LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new session for peer `%4s'\n",
905       GNUNET_i2s (&address->peer));
906   session = GNUNET_new (struct Session);
907   session->last_activity = GNUNET_TIME_absolute_get ();
908   session->plugin = plugin;
909   session->is_nat = is_nat;
910   session->client = client;
911   session->address = GNUNET_HELLO_address_copy (address);
912   session->target = address->peer;
913   session->expecting_welcome = GNUNET_YES;
914   session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
915   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
916       sizeof (struct WelcomeMessage));
917   pm->msg = (const char *) &pm[1];
918   pm->message_size = sizeof(struct WelcomeMessage);
919   welcome.header.size = htons (sizeof(struct WelcomeMessage));
920   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
921   welcome.clientIdentity = *plugin->env->my_identity;
922   memcpy (&pm[1], &welcome, sizeof(welcome));
923   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
924   GNUNET_STATISTICS_update (plugin->env->stats,
925       gettext_noop ("# bytes currently in TCP buffers"), pm->message_size,
926       GNUNET_NO);
927   GNUNET_CONTAINER_DLL_insert(session->pending_messages_head,
928       session->pending_messages_tail, pm);
929   if (GNUNET_YES != is_nat)
930   {
931     GNUNET_STATISTICS_update (plugin->env->stats,
932         gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
933   }
934   plugin->env->register_quota_notification (plugin->env->cls,
935       &address->peer, PLUGIN_NAME, session);
936   session->timeout_task = GNUNET_SCHEDULER_add_delayed (
937       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
938   return session;
939 }
940
941 /**
942  * If we have pending messages, ask the server to
943  * transmit them (schedule the respective tasks, etc.)
944  *
945  * @param session for which session should we do this
946  */
947 static void
948 process_pending_messages (struct Session *session);
949
950 /**
951  * Function called to notify a client about the socket
952  * being ready to queue more data.  "buf" will be
953  * NULL and "size" zero if the socket was closed for
954  * writing in the meantime.
955  *
956  * @param cls closure
957  * @param size number of bytes available in buf
958  * @param buf where the callee should write the message
959  * @return number of bytes written to buf
960  */
961 static size_t
962 do_transmit (void *cls, size_t size, void *buf)
963 {
964   struct Session *session = cls;
965   struct GNUNET_PeerIdentity pid;
966   struct Plugin *plugin;
967   struct PendingMessage *pos;
968   struct PendingMessage *hd;
969   struct PendingMessage *tl;
970   struct GNUNET_TIME_Absolute now;
971   char *cbuf;
972   size_t ret;
973
974   session->transmit_handle = NULL;
975   plugin = session->plugin;
976   if (NULL == buf)
977   {
978     LOG(GNUNET_ERROR_TYPE_DEBUG,
979         "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
980         GNUNET_i2s (&session->target));
981     /* timeout; cancel all messages that have already expired */
982     hd = NULL;
983     tl = NULL;
984     ret = 0;
985     now = GNUNET_TIME_absolute_get ();
986     while ((NULL != (pos = session->pending_messages_head))
987         && (pos->timeout.abs_value_us <= now.abs_value_us))
988     {
989       GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
990           session->pending_messages_tail, pos);
991       LOG(GNUNET_ERROR_TYPE_DEBUG,
992           "Failed to transmit %u byte message to `%4s'.\n", pos->message_size,
993           GNUNET_i2s (&session->target));
994       ret += pos->message_size;
995       GNUNET_CONTAINER_DLL_insert_after(hd, tl, tl, pos);
996     }
997     /* do this call before callbacks (so that if callbacks destroy
998      * session, they have a chance to cancel actions done by this
999      * call) */
1000     process_pending_messages (session);
1001     pid = session->target;
1002     /* no do callbacks and do not use session again since
1003      * the callbacks may abort the session */
1004     while (NULL != (pos = hd))
1005     {
1006       GNUNET_CONTAINER_DLL_remove(hd, tl, pos);
1007       if (pos->transmit_cont != NULL )
1008         pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR,
1009             pos->message_size, 0);
1010       GNUNET_free(pos);
1011     }
1012     GNUNET_STATISTICS_update (plugin->env->stats,
1013         gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1014         GNUNET_NO);
1015     GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1016     ("# bytes discarded by TCP (timeout)"), ret, GNUNET_NO);
1017     return 0;
1018   }
1019   /* copy all pending messages that would fit */
1020   ret = 0;
1021   cbuf = buf;
1022   hd = NULL;
1023   tl = NULL;
1024   while (NULL != (pos = session->pending_messages_head))
1025   {
1026     if (ret + pos->message_size > size)
1027       break;
1028     GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
1029         session->pending_messages_tail, pos);
1030     GNUNET_assert(size >= pos->message_size);
1031     LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting message of type %u\n",
1032         ntohs (((struct GNUNET_MessageHeader * ) pos->msg)->type));
1033     /* FIXME: this memcpy can be up to 7% of our total runtime */
1034     memcpy (cbuf, pos->msg, pos->message_size);
1035     cbuf += pos->message_size;
1036     ret += pos->message_size;
1037     size -= pos->message_size;
1038     GNUNET_CONTAINER_DLL_insert_tail(hd, tl, pos);
1039   }
1040   /* schedule 'continuation' before callbacks so that callbacks that
1041    * cancel everything don't cause us to use a session that no longer
1042    * exists... */
1043   process_pending_messages (session);
1044   session->last_activity = GNUNET_TIME_absolute_get ();
1045   pid = session->target;
1046   /* we'll now call callbacks that may cancel the session; hence
1047    * we should not use 'session' after this point */
1048   while (NULL != (pos = hd))
1049   {
1050     GNUNET_CONTAINER_DLL_remove(hd, tl, pos);
1051     if (pos->transmit_cont != NULL )
1052       pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK,
1053           pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
1054     GNUNET_free(pos);
1055   }
1056   GNUNET_assert(hd == NULL);
1057   GNUNET_assert(tl == NULL);
1058   LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n", ret);
1059   GNUNET_STATISTICS_update (plugin->env->stats,
1060       gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1061       GNUNET_NO);
1062   GNUNET_STATISTICS_update (plugin->env->stats,
1063       gettext_noop ("# bytes transmitted via TCP"), ret, GNUNET_NO);
1064   return ret;
1065 }
1066
1067 /**
1068  * If we have pending messages, ask the server to
1069  * transmit them (schedule the respective tasks, etc.)
1070  *
1071  * @param session for which session should we do this
1072  */
1073 static void
1074 process_pending_messages (struct Session *session)
1075 {
1076   struct PendingMessage *pm;
1077
1078   GNUNET_assert(NULL != session->client);
1079   if (NULL != session->transmit_handle)
1080     return;
1081   if (NULL == (pm = session->pending_messages_head))
1082     return;
1083
1084   session->transmit_handle = GNUNET_SERVER_notify_transmit_ready (
1085       session->client, pm->message_size,
1086       GNUNET_TIME_absolute_get_remaining (pm->timeout), &do_transmit, session);
1087 }
1088
1089 #if EXTRA_CHECKS
1090 /**
1091  * Closure for #session_it().
1092  */
1093 struct FindSessionContext
1094 {
1095   /**
1096    * Session we are looking for.
1097    */
1098   struct Session *s;
1099
1100   /**
1101    * Set to #GNUNET_OK if we found the session.
1102    */
1103   int res;
1104 };
1105
1106 /**
1107  * Function called to check if a session is in our maps.
1108  *
1109  * @param cls the `struct FindSessionContext`
1110  * @param key peer identity
1111  * @param value session in the map
1112  * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1113  */
1114 static int
1115 session_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1116 {
1117   struct FindSessionContext *res = cls;
1118   struct Session *session = value;
1119
1120   if (res->s == session)
1121   {
1122     res->res = GNUNET_OK;
1123     return GNUNET_NO;
1124   }
1125   return GNUNET_YES;
1126 }
1127
1128 /**
1129  * Check that the given session is known to the plugin and
1130  * is in one of our maps.
1131  *
1132  * @param plugin the plugin to check against
1133  * @param session the session to check
1134  * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1135  */
1136 static int
1137 find_session (struct Plugin *plugin, struct Session *session)
1138 {
1139   struct FindSessionContext session_map_res;
1140   struct FindSessionContext nat_map_res;
1141
1142   session_map_res.s = session;
1143   session_map_res.res = GNUNET_SYSERR;
1144   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_it,
1145       &session_map_res);
1146   if (GNUNET_SYSERR != session_map_res.res)
1147     return GNUNET_OK;
1148   nat_map_res.s = session;
1149   nat_map_res.res = GNUNET_SYSERR;
1150   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns, &session_it,
1151       &nat_map_res);
1152   if (GNUNET_SYSERR != nat_map_res.res)
1153     return GNUNET_OK;
1154   GNUNET_break(0);
1155   return GNUNET_SYSERR;
1156 }
1157 #endif
1158
1159 /**
1160  * Function that can be used by the transport service to transmit
1161  * a message using the plugin.   Note that in the case of a
1162  * peer disconnecting, the continuation MUST be called
1163  * prior to the disconnect notification itself.  This function
1164  * will be called with this peer's HELLO message to initiate
1165  * a fresh connection to another peer.
1166  *
1167  * @param cls closure
1168  * @param session which session must be used
1169  * @param msgbuf the message to transmit
1170  * @param msgbuf_size number of bytes in 'msgbuf'
1171  * @param priority how important is the message (most plugins will
1172  *                 ignore message priority and just FIFO)
1173  * @param to how long to wait at most for the transmission (does not
1174  *                require plugins to discard the message after the timeout,
1175  *                just advisory for the desired delay; most plugins will ignore
1176  *                this as well)
1177  * @param cont continuation to call once the message has
1178  *        been transmitted (or if the transport is ready
1179  *        for the next transmission call; or if the
1180  *        peer disconnected...); can be NULL
1181  * @param cont_cls closure for @a cont
1182  * @return number of bytes used (on the physical network, with overheads);
1183  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1184  *         and does NOT mean that the message was not transmitted (DV)
1185  */
1186 static ssize_t
1187 tcp_plugin_send (void *cls, struct Session *session, const char *msgbuf,
1188     size_t msgbuf_size, unsigned int priority, struct GNUNET_TIME_Relative to,
1189     GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1190 {
1191   struct Plugin * plugin = cls;
1192   struct PendingMessage *pm;
1193
1194 #if EXTRA_CHECKS
1195   if (GNUNET_SYSERR == find_session (plugin, session))
1196   {
1197     LOG(GNUNET_ERROR_TYPE_ERROR, _("Trying to send with invalid session %p\n"));
1198     GNUNET_assert(0);
1199     return GNUNET_SYSERR;
1200   }
1201 #endif
1202   /* create new message entry */
1203   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1204   pm->msg = (const char *) &pm[1];
1205   memcpy (&pm[1], msgbuf, msgbuf_size);
1206   pm->message_size = msgbuf_size;
1207   pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1208   pm->transmit_cont = cont;
1209   pm->transmit_cont_cls = cont_cls;
1210
1211   LOG(GNUNET_ERROR_TYPE_DEBUG,
1212       "Asked to transmit %u bytes to `%s', added message to list.\n",
1213       msgbuf_size, GNUNET_i2s (&session->target));
1214
1215   if (GNUNET_YES
1216       == GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1217           &session->target, session))
1218   {
1219     GNUNET_assert(NULL != session->client);
1220     GNUNET_SERVER_client_set_timeout (session->client,
1221         GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1222     GNUNET_STATISTICS_update (plugin->env->stats,
1223         gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1224         GNUNET_NO);
1225
1226     /* append pm to pending_messages list */
1227     GNUNET_CONTAINER_DLL_insert_tail(session->pending_messages_head,
1228         session->pending_messages_tail, pm);
1229
1230     process_pending_messages (session);
1231     return msgbuf_size;
1232   }
1233   else if (GNUNET_YES
1234       == GNUNET_CONTAINER_multipeermap_contains_value (plugin->nat_wait_conns,
1235           &session->target, session))
1236   {
1237     LOG(GNUNET_ERROR_TYPE_DEBUG,
1238         "This NAT WAIT session for peer `%s' is not yet ready!\n",
1239         GNUNET_i2s (&session->target));
1240     GNUNET_STATISTICS_update (plugin->env->stats,
1241         gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1242         GNUNET_NO);
1243
1244     /* append pm to pending_messages list */
1245     GNUNET_CONTAINER_DLL_insert_tail(session->pending_messages_head,
1246         session->pending_messages_tail, pm);
1247     return msgbuf_size;
1248   }
1249   else
1250   {
1251     LOG(GNUNET_ERROR_TYPE_ERROR, "Invalid session %p\n", session);
1252     if (NULL != cont)
1253       cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1254     GNUNET_break(0);
1255     GNUNET_free(pm);
1256     return GNUNET_SYSERR; /* session does not exist here */
1257   }
1258 }
1259
1260 /**
1261  * Closure for #session_lookup_it().
1262  */
1263 struct SessionItCtx
1264 {
1265   /**
1266    * Address we are looking for.
1267    */
1268   const struct GNUNET_HELLO_Address *address;
1269
1270   /**
1271    * Where to store the session (if we found it).
1272    */
1273   struct Session *result;
1274
1275 };
1276
1277 /**
1278  * Look for a session by address.
1279  *
1280  * @param cls the `struct SessionItCtx`
1281  * @param key unused
1282  * @param value a `struct Session`
1283  * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1284  */
1285 static int
1286 session_lookup_it (void *cls, const struct GNUNET_PeerIdentity *key,
1287     void *value)
1288 {
1289   struct SessionItCtx * si_ctx = cls;
1290   struct Session * session = value;
1291
1292   if (0 != GNUNET_HELLO_address_cmp (si_ctx->address, session->address))
1293     return GNUNET_YES;
1294   /* Found existing session */
1295   si_ctx->result = session;
1296   return GNUNET_NO;
1297 }
1298
1299 /**
1300  * Task cleaning up a NAT connection attempt after timeout
1301  *
1302  * @param cls the `struct Session`
1303  * @param tc scheduler context (unused)
1304  */
1305 static void
1306 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1307 {
1308   struct Session *session = cls;
1309
1310   session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1311   LOG(GNUNET_ERROR_TYPE_DEBUG,
1312       "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1313       GNUNET_i2s (&session->target),
1314       tcp_address_to_string (NULL, session->address->address, session->address->address_length));
1315   tcp_disconnect_session (session->plugin, session);
1316 }
1317
1318 static void
1319 tcp_plugin_update_session_timeout (void *cls,
1320     const struct GNUNET_PeerIdentity *peer, struct Session *session)
1321 {
1322   struct Plugin *plugin = cls;
1323
1324   if (GNUNET_SYSERR == find_session (plugin, session))
1325     return;
1326   reschedule_session_timeout (session);
1327 }
1328
1329 /**
1330  * Task to signal the server that we can continue
1331  * receiving from the TCP client now.
1332  *
1333  * @param cls the `struct Session*`
1334  * @param tc task context (unused)
1335  */
1336 static void
1337 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1338 {
1339   struct Session *session = cls;
1340
1341   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1342   reschedule_session_timeout (session);
1343
1344   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1345 }
1346
1347 static void tcp_plugin_update_inbound_delay (void *cls,
1348                                       const struct GNUNET_PeerIdentity *peer,
1349                                       struct Session *session,
1350                                       struct GNUNET_TIME_Relative delay)
1351 {
1352   if (GNUNET_SCHEDULER_NO_TASK == session->receive_delay_task)
1353     return;
1354
1355   LOG(GNUNET_ERROR_TYPE_DEBUG,
1356       "New inbound delay %llu us\n",delay.rel_value_us);
1357
1358   GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1359   session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
1360       &delayed_done, session);
1361 }
1362
1363
1364 /**
1365  * Create a new session to transmit data to the target
1366  * This session will used to send data to this peer and the plugin will
1367  * notify us by calling the env->session_end function
1368  *
1369  * @param cls closure
1370  * @param address the address to use
1371  * @return the session if the address is valid, NULL otherwise
1372  */
1373 static struct Session *
1374 tcp_plugin_get_session (void *cls, const struct GNUNET_HELLO_Address *address)
1375 {
1376   struct Plugin *plugin = cls;
1377   struct Session *session = NULL;
1378   int af;
1379   const void *sb;
1380   size_t sbs;
1381   struct GNUNET_CONNECTION_Handle *sa;
1382   struct sockaddr_in a4;
1383   struct sockaddr_in6 a6;
1384   const struct IPv4TcpAddress *t4;
1385   const struct IPv6TcpAddress *t6;
1386   struct GNUNET_ATS_Information ats;
1387   unsigned int is_natd = GNUNET_NO;
1388   size_t addrlen;
1389
1390   addrlen = address->address_length;
1391   LOG(GNUNET_ERROR_TYPE_DEBUG,
1392       "Trying to get session for `%s' address of peer `%s'\n",
1393       tcp_address_to_string(NULL, address->address, address->address_length),
1394       GNUNET_i2s (&address->peer));
1395
1396   if (GNUNET_HELLO_address_check_option(address, GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1397   {
1398     GNUNET_break (0);
1399     return NULL;
1400   }
1401
1402   /* look for existing session */
1403   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1404           &address->peer))
1405   {
1406     struct SessionItCtx si_ctx;
1407
1408     si_ctx.address = address;
1409     si_ctx.result = NULL;
1410
1411     GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1412         &address->peer, &session_lookup_it, &si_ctx);
1413     if (si_ctx.result != NULL )
1414     {
1415       session = si_ctx.result;
1416       LOG(GNUNET_ERROR_TYPE_DEBUG,
1417           "Found existing session for `%s' address `%s' session %p\n",
1418           GNUNET_i2s (&address->peer),
1419           tcp_address_to_string(NULL, address->address, address->address_length),
1420           session);
1421       return session;
1422     }
1423     LOG(GNUNET_ERROR_TYPE_DEBUG,
1424         "Existing sessions did not match address `%s' or peer `%s'\n",
1425         tcp_address_to_string(NULL, address->address, address->address_length),
1426         GNUNET_i2s (&address->peer));
1427   }
1428
1429   if (addrlen == sizeof(struct IPv6TcpAddress))
1430   {
1431     GNUNET_assert(NULL != address->address); /* make static analysis happy */
1432     t6 = address->address;
1433     af = AF_INET6;
1434     memset (&a6, 0, sizeof(a6));
1435 #if HAVE_SOCKADDR_IN_SIN_LEN
1436     a6.sin6_len = sizeof (a6);
1437 #endif
1438     a6.sin6_family = AF_INET6;
1439     a6.sin6_port = t6->t6_port;
1440     if (t6->t6_port == 0)
1441       is_natd = GNUNET_YES;
1442     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1443     sb = &a6;
1444     sbs = sizeof(a6);
1445   }
1446   else if (addrlen == sizeof(struct IPv4TcpAddress))
1447   {
1448     GNUNET_assert(NULL != address->address); /* make static analysis happy */
1449     t4 = address->address;
1450     af = AF_INET;
1451     memset (&a4, 0, sizeof(a4));
1452 #if HAVE_SOCKADDR_IN_SIN_LEN
1453     a4.sin_len = sizeof (a4);
1454 #endif
1455     a4.sin_family = AF_INET;
1456     a4.sin_port = t4->t4_port;
1457     if (t4->t4_port == 0)
1458       is_natd = GNUNET_YES;
1459     a4.sin_addr.s_addr = t4->ipv4_addr;
1460     sb = &a4;
1461     sbs = sizeof(a4);
1462   }
1463   else
1464   {
1465     GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1466     ("# requests to create session with invalid address"), 1, GNUNET_NO);
1467     return NULL ;
1468   }
1469
1470   ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1471
1472   if ((is_natd == GNUNET_YES) && (addrlen == sizeof(struct IPv6TcpAddress)))
1473   {
1474     /* NAT client only works with IPv4 addresses */
1475     return NULL ;
1476   }
1477
1478   if (plugin->cur_connections >= plugin->max_connections)
1479   {
1480     /* saturated */
1481     return NULL ;
1482   }
1483
1484   if ((is_natd == GNUNET_YES)
1485       && (GNUNET_YES
1486           == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1487               &address->peer)))
1488   {
1489     /* Only do one NAT punch attempt per peer identity */
1490     return NULL ;
1491   }
1492
1493   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1494       (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1495               &address->peer)))
1496   {
1497     LOG (GNUNET_ERROR_TYPE_DEBUG,
1498         "Found valid IPv4 NAT address (creating session)!\n");
1499     session = create_session (plugin, address, NULL, GNUNET_YES);
1500     session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1501         ats.value);
1502     GNUNET_break(
1503         session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1504     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1505         &nat_connect_timeout, session);
1506     GNUNET_assert(session != NULL);
1507     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1508         &session->target, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1509
1510     LOG(GNUNET_ERROR_TYPE_DEBUG,
1511         "Created NAT WAIT connection to `%4s' at `%s'\n",
1512         GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1513
1514     if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1515       return session;
1516     else
1517     {
1518       LOG(GNUNET_ERROR_TYPE_DEBUG,
1519           "Running NAT client for `%4s' at `%s' failed\n",
1520           GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1521       tcp_disconnect_session (plugin, session);
1522       return NULL ;
1523     }
1524   }
1525
1526   /* create new outbound session */
1527   GNUNET_assert(plugin->cur_connections <= plugin->max_connections);
1528   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1529   if (NULL == sa)
1530   {
1531     LOG(GNUNET_ERROR_TYPE_DEBUG,
1532         "Failed to create connection to `%4s' at `%s'\n",
1533         GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1534     return NULL ;
1535   }
1536   plugin->cur_connections++;
1537   if (plugin->cur_connections == plugin->max_connections)
1538     GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1539
1540   LOG(GNUNET_ERROR_TYPE_DEBUG,
1541       "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1542       GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1543
1544   session = create_session (plugin, address,
1545       GNUNET_SERVER_connect_socket (plugin->server, sa), GNUNET_NO);
1546   session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1547       ats.value);
1548   GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1549   GNUNET_SERVER_client_set_user_context(session->client, session);
1550   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1551       session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1552   LOG(GNUNET_ERROR_TYPE_DEBUG,
1553       "Creating new session for `%s' address `%s' session %p\n",
1554       GNUNET_i2s (&address->peer),
1555       tcp_address_to_string(NULL, address->address, address->address_length),
1556       session);
1557   /* Send TCP Welcome */
1558   process_pending_messages (session);
1559
1560   return session;
1561 }
1562
1563 static int
1564 session_disconnect_it (void *cls, const struct GNUNET_PeerIdentity *key,
1565     void *value)
1566 {
1567   struct Plugin *plugin = cls;
1568   struct Session *session = value;
1569
1570   GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
1571   ("# transport-service disconnect requests for TCP"), 1, GNUNET_NO);
1572   tcp_disconnect_session (plugin, session);
1573   return GNUNET_YES;
1574 }
1575
1576 /**
1577  * Function that can be called to force a disconnect from the
1578  * specified neighbour.  This should also cancel all previously
1579  * scheduled transmissions.  Obviously the transmission may have been
1580  * partially completed already, which is OK.  The plugin is supposed
1581  * to close the connection (if applicable) and no longer call the
1582  * transmit continuation(s).
1583  *
1584  * Finally, plugin MUST NOT call the services's receive function to
1585  * notify the service that the connection to the specified target was
1586  * closed after a getting this call.
1587  *
1588  * @param cls closure
1589  * @param target peer for which the last transmission is
1590  *        to be cancelled
1591  */
1592 static void
1593 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1594 {
1595   struct Plugin *plugin = cls;
1596
1597   LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s'\n",
1598       GNUNET_i2s (target));
1599   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1600       &session_disconnect_it, plugin);
1601   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1602       &session_disconnect_it, plugin);
1603 }
1604
1605 /**
1606  * Running pretty printers: head
1607  */
1608 static struct PrettyPrinterContext *ppc_dll_head;
1609
1610 /**
1611  * Running pretty printers: tail
1612  */
1613 static struct PrettyPrinterContext *ppc_dll_tail;
1614
1615 /**
1616  * Context for address to string conversion.
1617  */
1618 struct PrettyPrinterContext
1619 {
1620   /**
1621    * DLL
1622    */
1623   struct PrettyPrinterContext *next;
1624
1625   /**
1626    * DLL
1627    */
1628   struct PrettyPrinterContext *prev;
1629
1630   /**
1631    * Timeout task
1632    */
1633   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1634
1635   /**
1636    * Resolver handle
1637    */
1638   struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1639
1640   /**
1641    * Function to call with the result.
1642    */
1643   GNUNET_TRANSPORT_AddressStringCallback asc;
1644
1645   /**
1646    * Clsoure for 'asc'.
1647    */
1648   void *asc_cls;
1649
1650   /**
1651    * Port to add after the IP address.
1652    */
1653   uint16_t port;
1654
1655   /**
1656    * IPv6 address
1657    */
1658   int ipv6;
1659
1660   /**
1661    * Options
1662    */
1663   uint32_t options;
1664 };
1665
1666 static void
1667 ppc_cancel_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1668 {
1669   struct PrettyPrinterContext *ppc = cls;
1670
1671   ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1672   if (NULL != ppc->resolver_handle)
1673   {
1674     GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1675     ppc->resolver_handle = NULL;
1676   }
1677   GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
1678   GNUNET_free(ppc);
1679 }
1680
1681 /**
1682  * Append our port and forward the result.
1683  *
1684  * @param cls the 'struct PrettyPrinterContext*'
1685  * @param hostname hostname part of the address
1686  */
1687 static void
1688 append_port (void *cls, const char *hostname)
1689 {
1690   struct PrettyPrinterContext *ppc = cls;
1691   struct PrettyPrinterContext *cur;
1692   char *ret;
1693
1694   if (NULL == hostname)
1695   {
1696     ppc->asc (ppc->asc_cls, NULL );
1697     GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
1698     GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1699     ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1700     ppc->resolver_handle = NULL;
1701     GNUNET_free(ppc);
1702     return;
1703   }
1704   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1705     if (cur == ppc)
1706       break;
1707   if (NULL == cur)
1708   {
1709     GNUNET_break(0);
1710     return;
1711   }
1712
1713   if (GNUNET_YES == ppc->ipv6)
1714     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname,
1715         ppc->port);
1716   else
1717     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname,
1718         ppc->port);
1719   ppc->asc (ppc->asc_cls, ret);
1720   GNUNET_free(ret);
1721 }
1722
1723 /**
1724  * Convert the transports address to a nice, human-readable
1725  * format.
1726  *
1727  * @param cls closure
1728  * @param type name of the transport that generated the address
1729  * @param addr one of the addresses of the host, NULL for the last address
1730  *        the specific address format depends on the transport
1731  * @param addrlen length of the address
1732  * @param numeric should (IP) addresses be displayed in numeric form?
1733  * @param timeout after how long should we give up?
1734  * @param asc function to call on each string
1735  * @param asc_cls closure for asc
1736  */
1737 static void
1738 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1739     const void *addr, size_t addrlen, int numeric,
1740     struct GNUNET_TIME_Relative timeout,
1741     GNUNET_TRANSPORT_AddressStringCallback asc, void *asc_cls)
1742 {
1743   struct PrettyPrinterContext *ppc;
1744   const void *sb;
1745   size_t sbs;
1746   struct sockaddr_in a4;
1747   struct sockaddr_in6 a6;
1748   const struct IPv4TcpAddress *t4;
1749   const struct IPv6TcpAddress *t6;
1750   uint16_t port;
1751   uint32_t options;
1752
1753   if (addrlen == sizeof(struct IPv6TcpAddress))
1754   {
1755     t6 = addr;
1756     memset (&a6, 0, sizeof(a6));
1757     a6.sin6_family = AF_INET6;
1758     a6.sin6_port = t6->t6_port;
1759     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1760     port = ntohs (t6->t6_port);
1761     options = ntohl (t6->options);
1762     sb = &a6;
1763     sbs = sizeof(a6);
1764   }
1765   else if (addrlen == sizeof(struct IPv4TcpAddress))
1766   {
1767     t4 = addr;
1768     memset (&a4, 0, sizeof(a4));
1769     a4.sin_family = AF_INET;
1770     a4.sin_port = t4->t4_port;
1771     a4.sin_addr.s_addr = t4->ipv4_addr;
1772     port = ntohs (t4->t4_port);
1773     options = ntohl (t4->options);
1774     sb = &a4;
1775     sbs = sizeof(a4);
1776   }
1777   else if (0 == addrlen)
1778   {
1779     asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1780     asc (asc_cls, NULL );
1781     return;
1782   }
1783   else
1784   {
1785     /* invalid address */
1786     GNUNET_break_op(0);
1787     asc (asc_cls, NULL );
1788     return;
1789   }
1790   ppc = GNUNET_new (struct PrettyPrinterContext);
1791   if (addrlen == sizeof(struct IPv6TcpAddress))
1792     ppc->ipv6 = GNUNET_YES;
1793   else
1794     ppc->ipv6 = GNUNET_NO;
1795   ppc->asc = asc;
1796   ppc->asc_cls = asc_cls;
1797   ppc->port = port;
1798   ppc->options = options;
1799   ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (
1800       GNUNET_TIME_relative_multiply (timeout, 2), &ppc_cancel_task, ppc);
1801   ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1802       timeout, &append_port, ppc);
1803   if (NULL != ppc->resolver_handle)
1804   {
1805     //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1806     GNUNET_CONTAINER_DLL_insert(ppc_dll_head, ppc_dll_tail, ppc);
1807   }
1808   else
1809   {
1810     GNUNET_break(0);
1811     GNUNET_free(ppc);
1812   }
1813 }
1814
1815 /**
1816  * Check if the given port is plausible (must be either our listen
1817  * port or our advertised port), or any port if we are behind NAT
1818  * and do not have a port open.  If it is neither, we return
1819  * #GNUNET_SYSERR.
1820  *
1821  * @param plugin global variables
1822  * @param in_port port number to check
1823  * @return #GNUNET_OK if port is either open_port or adv_port
1824  */
1825 static int
1826 check_port (struct Plugin *plugin, uint16_t in_port)
1827 {
1828   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1829     return GNUNET_OK;
1830   return GNUNET_SYSERR;
1831 }
1832
1833 /**
1834  * Function that will be called to check if a binary address for this
1835  * plugin is well-formed and corresponds to an address for THIS peer
1836  * (as per our configuration).  Naturally, if absolutely necessary,
1837  * plugins can be a bit conservative in their answer, but in general
1838  * plugins should make sure that the address does not redirect
1839  * traffic to a 3rd party that might try to man-in-the-middle our
1840  * traffic.
1841  *
1842  * @param cls closure, our `struct Plugin *`
1843  * @param addr pointer to the address
1844  * @param addrlen length of addr
1845  * @return #GNUNET_OK if this is a plausible address for this peer
1846  *         and transport, #GNUNET_SYSERR if not
1847  */
1848 static int
1849 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1850 {
1851   struct Plugin *plugin = cls;
1852   struct IPv4TcpAddress *v4;
1853   struct IPv6TcpAddress *v6;
1854
1855   if ((addrlen != sizeof(struct IPv4TcpAddress))
1856       && (addrlen != sizeof(struct IPv6TcpAddress)))
1857   {
1858     GNUNET_break_op(0);
1859     return GNUNET_SYSERR;
1860   }
1861
1862   if (addrlen == sizeof(struct IPv4TcpAddress))
1863   {
1864     v4 = (struct IPv4TcpAddress *) addr;
1865     if (0 != memcmp (&v4->options, &myoptions, sizeof(myoptions)))
1866     {
1867       GNUNET_break(0);
1868       return GNUNET_SYSERR;
1869     }
1870     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1871       return GNUNET_SYSERR;
1872     if (GNUNET_OK
1873         != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1874             sizeof(struct in_addr)))
1875       return GNUNET_SYSERR;
1876   }
1877   else
1878   {
1879     v6 = (struct IPv6TcpAddress *) addr;
1880     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1881     {
1882       GNUNET_break_op(0);
1883       return GNUNET_SYSERR;
1884     }
1885     if (0 != memcmp (&v6->options, &myoptions, sizeof(myoptions)))
1886     {
1887       GNUNET_break(0);
1888       return GNUNET_SYSERR;
1889     }
1890     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1891       return GNUNET_SYSERR;
1892     if (GNUNET_OK
1893         != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1894             sizeof(struct in6_addr)))
1895       return GNUNET_SYSERR;
1896   }
1897   return GNUNET_OK;
1898 }
1899
1900 /**
1901  * We've received a nat probe from this peer via TCP.  Finish
1902  * creating the client session and resume sending of queued
1903  * messages.
1904  *
1905  * @param cls closure
1906  * @param client identification of the client
1907  * @param message the actual message
1908  */
1909 static void
1910 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1911     const struct GNUNET_MessageHeader *message)
1912 {
1913   struct Plugin *plugin = cls;
1914   struct Session *session;
1915   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1916   size_t alen;
1917   void *vaddr;
1918   struct IPv4TcpAddress *t4;
1919   struct IPv6TcpAddress *t6;
1920   const struct sockaddr_in *s4;
1921   const struct sockaddr_in6 *s6;
1922
1923   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
1924   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1925    * a connection to this peer by running gnunet-nat-client.  This peer
1926    * received the punch message and now wants us to use the new connection
1927    * as the default for that peer.  Do so and then send a WELCOME message
1928    * so we can really be connected!
1929    */
1930   if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1931   {
1932     GNUNET_break_op(0);
1933     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1934     return;
1935   }
1936
1937   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1938   if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1939           sizeof(struct GNUNET_PeerIdentity)))
1940   {
1941     /* refuse connections from ourselves */
1942     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1943     return;
1944   }
1945
1946   session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
1947       &tcp_nat_probe->clientIdentity);
1948   if (session == NULL )
1949   {
1950     LOG(GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1951     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1952     return;
1953   }
1954   LOG(GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1955
1956   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK )
1957   {
1958     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1959     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1960   }
1961
1962   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1963   {
1964     GNUNET_break(0);
1965     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1966     tcp_disconnect_session (plugin, session);
1967     return;
1968   }
1969   GNUNET_assert(
1970       GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity, session) == GNUNET_YES);
1971   GNUNET_SERVER_client_set_user_context(client, session);
1972   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1973       session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1974   session->last_activity = GNUNET_TIME_absolute_get ();
1975   LOG(GNUNET_ERROR_TYPE_DEBUG, "Found address `%s' for incoming connection\n",
1976       GNUNET_a2s (vaddr, alen));
1977   switch (((const struct sockaddr *) vaddr)->sa_family)
1978   {
1979   case AF_INET:
1980     s4 = vaddr;
1981     t4 = GNUNET_new (struct IPv4TcpAddress);
1982     t4->options = 0;
1983     t4->t4_port = s4->sin_port;
1984     t4->ipv4_addr = s4->sin_addr.s_addr;
1985     session->address = GNUNET_HELLO_address_allocate (
1986         &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t4,
1987         sizeof(struct IPv4TcpAddress), GNUNET_HELLO_ADDRESS_INFO_NONE);
1988     break;
1989   case AF_INET6:
1990     s6 = vaddr;
1991     t6 = GNUNET_new (struct IPv6TcpAddress);
1992     t6->options = 0;
1993     t6->t6_port = s6->sin6_port;
1994     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
1995     session->address = GNUNET_HELLO_address_allocate (
1996         &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t6,
1997         sizeof(struct IPv6TcpAddress), GNUNET_HELLO_ADDRESS_INFO_NONE);
1998     break;
1999   default:
2000     GNUNET_break_op(0);
2001     LOG(GNUNET_ERROR_TYPE_DEBUG, "Bad address for incoming connection!\n");
2002     GNUNET_free(vaddr);
2003     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2004     tcp_disconnect_session (plugin, session);
2005     return;
2006   }
2007   GNUNET_free(vaddr);
2008   GNUNET_break(NULL == session->client);
2009   GNUNET_SERVER_client_keep (client);
2010   session->client = client;
2011   GNUNET_STATISTICS_update (plugin->env->stats,
2012       gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
2013   process_pending_messages (session);
2014   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2015 }
2016
2017 /**
2018  * We've received a welcome from this peer via TCP.  Possibly create a
2019  * fresh client record and send back our welcome.
2020  *
2021  * @param cls closure
2022  * @param client identification of the client
2023  * @param message the actual message
2024  */
2025 static void
2026 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2027     const struct GNUNET_MessageHeader *message)
2028 {
2029   struct Plugin *plugin = cls;
2030   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2031   struct GNUNET_HELLO_Address *address;
2032   struct Session *session;
2033   size_t alen;
2034   void *vaddr;
2035   struct IPv4TcpAddress t4;
2036   struct IPv6TcpAddress t6;
2037   const struct sockaddr_in *s4;
2038   const struct sockaddr_in6 *s6;
2039   struct GNUNET_ATS_Information ats;
2040
2041
2042   if (0 == memcmp (&wm->clientIdentity, plugin->env->my_identity,
2043           sizeof(struct GNUNET_PeerIdentity)))
2044   {
2045     /* refuse connections from ourselves */
2046     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2047     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2048     {
2049       LOG(GNUNET_ERROR_TYPE_WARNING,
2050           "Received %s message from my own identity `%4s' on address `%s'\n",
2051           "WELCOME", GNUNET_i2s (&wm->clientIdentity),
2052           GNUNET_a2s (vaddr, alen));
2053       GNUNET_free(vaddr);
2054     }
2055     GNUNET_break_op(0);
2056     return;
2057   }
2058
2059   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received %s message from `%4s' %p\n", "WELCOME",
2060       GNUNET_i2s (&wm->clientIdentity), client);
2061   GNUNET_STATISTICS_update (plugin->env->stats,
2062       gettext_noop ("# TCP WELCOME messages received"), 1, GNUNET_NO);
2063   session = lookup_session_by_client (plugin, client);
2064   if (NULL != session)
2065   {
2066     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2067     {
2068       LOG(GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p for peer `%s'\n",
2069           session, GNUNET_a2s (vaddr, alen));
2070       GNUNET_free(vaddr);
2071     }
2072   }
2073   else
2074   {
2075     GNUNET_SERVER_client_keep (client);
2076     if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
2077       plugin->cur_connections++;
2078     if (plugin->cur_connections == plugin->max_connections)
2079       GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2080
2081     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2082     {
2083       if (alen == sizeof(struct sockaddr_in))
2084       {
2085         s4 = vaddr;
2086         memset (&t4, '\0', sizeof (t4));
2087         t4.options = htonl (0);
2088         t4.t4_port = s4->sin_port;
2089         t4.ipv4_addr = s4->sin_addr.s_addr;
2090         address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2091             PLUGIN_NAME, &t4, sizeof(t4),
2092             GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2093       }
2094       else if (alen == sizeof(struct sockaddr_in6))
2095       {
2096         s6 = vaddr;
2097         memset (&t6, '\0', sizeof (t6));
2098         t6.options = htonl (0);
2099         t6.t6_port = s6->sin6_port;
2100         memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2101         address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2102             PLUGIN_NAME, &t6, sizeof (t6),
2103             GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2104       }
2105       session = create_session (plugin, address, client, GNUNET_NO);
2106       GNUNET_HELLO_address_free (address);
2107       ats = plugin->env->get_address_type (plugin->env->cls, vaddr, alen);
2108       session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
2109           ats.value);
2110       LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new%s session %p for peer `%s' client %p \n",
2111           GNUNET_HELLO_address_check_option (session->address,
2112               GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? " inbound" : "", session,
2113           tcp_address_to_string(NULL, (void *) session->address->address,
2114               session->address->address_length),
2115           client);
2116       GNUNET_free(vaddr);
2117       GNUNET_SERVER_client_set_user_context(session->client, session);
2118       GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2119           session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2120
2121       /* Notify transport and ATS about new session */
2122       plugin->env->session_start (NULL, session->address, session, &ats, 1);
2123     }
2124     else
2125     {
2126       LOG(GNUNET_ERROR_TYPE_DEBUG,
2127           "Did not obtain TCP socket address for incoming connection\n");
2128       GNUNET_break(0);
2129       return;
2130     }
2131   }
2132
2133   if (session->expecting_welcome != GNUNET_YES)
2134   {
2135     GNUNET_break_op(0);
2136     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2137     GNUNET_break(0);
2138     return;
2139   }
2140   session->last_activity = GNUNET_TIME_absolute_get ();
2141   session->expecting_welcome = GNUNET_NO;
2142
2143   process_pending_messages (session);
2144   GNUNET_SERVER_client_set_timeout (client,
2145       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2146   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2147 }
2148
2149
2150 /**
2151  * We've received data for this peer via TCP.  Unbox,
2152  * compute latency and forward.
2153  *
2154  * @param cls closure
2155  * @param client identification of the client
2156  * @param message the actual message
2157  */
2158 static void
2159 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2160     const struct GNUNET_MessageHeader *message)
2161 {
2162   struct Plugin *plugin = cls;
2163   struct Session *session;
2164   struct GNUNET_TIME_Relative delay;
2165   uint16_t type;
2166
2167   type = ntohs (message->type);
2168   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type)
2169       || (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2170   {
2171     /* We don't want to propagate WELCOME and NAT Probe messages up! */
2172     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2173     return;
2174   }
2175   session = lookup_session_by_client (plugin, client);
2176   if (NULL == session)
2177   {
2178     /* No inbound session found */
2179     void *vaddr;
2180     size_t alen;
2181
2182     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2183     LOG(GNUNET_ERROR_TYPE_ERROR,
2184         "Received unexpected %u bytes of type %u from `%s'\n",
2185         (unsigned int ) ntohs (message->size),
2186         (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2187     GNUNET_break_op(0);
2188     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2189     GNUNET_free_non_null(vaddr);
2190     return;
2191   }
2192   else if (GNUNET_YES == session->expecting_welcome)
2193   {
2194     /* Session is expecting WELCOME message */
2195     void *vaddr;
2196     size_t alen;
2197
2198     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2199     LOG(GNUNET_ERROR_TYPE_ERROR,
2200         "Received unexpected %u bytes of type %u from `%s'\n",
2201         (unsigned int ) ntohs (message->size),
2202         (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2203     GNUNET_break_op(0);
2204     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2205     GNUNET_free_non_null(vaddr);
2206     return;
2207   }
2208
2209   session->last_activity = GNUNET_TIME_absolute_get ();
2210   LOG(GNUNET_ERROR_TYPE_DEBUG,
2211       "Passing %u bytes of type %u from `%4s' to transport service.\n",
2212       (unsigned int ) ntohs (message->size),
2213       (unsigned int ) ntohs (message->type), GNUNET_i2s (&session->target));
2214
2215   GNUNET_STATISTICS_update (plugin->env->stats,
2216       gettext_noop ("# bytes received via TCP"), ntohs (message->size),
2217       GNUNET_NO);
2218   struct GNUNET_ATS_Information distance;
2219
2220   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2221   distance.value = htonl ((uint32_t) session->ats_address_network_type);
2222   GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2223
2224   GNUNET_assert(
2225       GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2226           &session->target, session));
2227
2228   delay = plugin->env->receive (plugin->env->cls, session->address, session, message);
2229   plugin->env->update_address_metrics (plugin->env->cls, session->address,
2230       session, &distance, 1);
2231   reschedule_session_timeout (session);
2232   if (0 == delay.rel_value_us)
2233   {
2234     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2235   }
2236   else
2237   {
2238     LOG(GNUNET_ERROR_TYPE_DEBUG, "Throttling receiving from `%s' for %s\n",
2239         GNUNET_i2s (&session->target),
2240         GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2241     GNUNET_SERVER_disable_receive_done_warning (client);
2242     session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2243         &delayed_done, session);
2244   }
2245 }
2246
2247 /**
2248  * Functions with this signature are called whenever a peer
2249  * is disconnected on the network level.
2250  *
2251  * @param cls closure
2252  * @param client identification of the client
2253  */
2254 static void
2255 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2256 {
2257   struct Plugin *plugin = cls;
2258   struct Session *session;
2259
2260   if (client == NULL )
2261     return;
2262   session = lookup_session_by_client (plugin, client);
2263   if (session == NULL )
2264     return; /* unknown, nothing to do */
2265   LOG(GNUNET_ERROR_TYPE_DEBUG,
2266       "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2267       GNUNET_i2s (&session->target),
2268       tcp_address_to_string (session->plugin, session->address->address,
2269           session->address->address_length));
2270
2271   if (plugin->cur_connections == plugin->max_connections)
2272     GNUNET_SERVER_resume (plugin->server); /* Resume server  */
2273
2274   if (plugin->cur_connections < 1)
2275     GNUNET_break(0);
2276   else
2277     plugin->cur_connections--;
2278
2279   GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
2280   ("# network-level TCP disconnect events"), 1, GNUNET_NO);
2281   tcp_disconnect_session (plugin, session);
2282 }
2283
2284 /**
2285  * We can now send a probe message, copy into buffer to really send.
2286  *
2287  * @param cls closure, a struct TCPProbeContext
2288  * @param size max size to copy
2289  * @param buf buffer to copy message to
2290  * @return number of bytes copied into buf
2291  */
2292 static size_t
2293 notify_send_probe (void *cls, size_t size, void *buf)
2294 {
2295   struct TCPProbeContext *tcp_probe_ctx = cls;
2296   struct Plugin *plugin = tcp_probe_ctx->plugin;
2297   size_t ret;
2298
2299   tcp_probe_ctx->transmit_handle = NULL;
2300   GNUNET_CONTAINER_DLL_remove(plugin->probe_head, plugin->probe_tail,
2301       tcp_probe_ctx);
2302   if (buf == NULL )
2303   {
2304     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2305     GNUNET_free(tcp_probe_ctx);
2306     return 0;
2307   }
2308   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2309   memcpy (buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2310   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2311       tcp_probe_ctx->sock);
2312   ret = sizeof(tcp_probe_ctx->message);
2313   GNUNET_free(tcp_probe_ctx);
2314   return ret;
2315 }
2316
2317 /**
2318  * Function called by the NAT subsystem suggesting another peer wants
2319  * to connect to us via connection reversal.  Try to connect back to the
2320  * given IP.
2321  *
2322  * @param cls closure
2323  * @param addr address to try
2324  * @param addrlen number of bytes in @a addr
2325  */
2326 static void
2327 try_connection_reversal (void *cls, const struct sockaddr *addr,
2328     socklen_t addrlen)
2329 {
2330   struct Plugin *plugin = cls;
2331   struct GNUNET_CONNECTION_Handle *sock;
2332   struct TCPProbeContext *tcp_probe_ctx;
2333
2334   /**
2335    * We have received an ICMP response, ostensibly from a peer
2336    * that wants to connect to us! Send a message to establish a connection.
2337    */
2338   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2339   if (sock == NULL )
2340   {
2341     /* failed for some odd reason (out of sockets?); ignore attempt */
2342     return;
2343   }
2344
2345   /* FIXME: do we need to track these probe context objects so that
2346    * we can clean them up on plugin unload? */
2347   tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
2348   tcp_probe_ctx->message.header.size = htons (
2349       sizeof(struct TCP_NAT_ProbeMessage));
2350   tcp_probe_ctx->message.header.type = htons (
2351       GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2352   memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2353       sizeof(struct GNUNET_PeerIdentity));
2354   tcp_probe_ctx->plugin = plugin;
2355   tcp_probe_ctx->sock = sock;
2356   GNUNET_CONTAINER_DLL_insert(plugin->probe_head, plugin->probe_tail,
2357       tcp_probe_ctx);
2358   tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (
2359       sock, ntohs (tcp_probe_ctx->message.header.size),
2360       GNUNET_TIME_UNIT_FOREVER_REL, &notify_send_probe, tcp_probe_ctx);
2361
2362 }
2363
2364 /**
2365  * Function obtain the network type for a session
2366  *
2367  * @param cls closure ('struct Plugin*')
2368  * @param session the session
2369  * @return the network type in HBO or #GNUNET_SYSERR
2370  */
2371 static enum GNUNET_ATS_Network_Type
2372 tcp_get_network (void *cls, struct Session *session)
2373 {
2374   GNUNET_assert(NULL != session);
2375   return session->ats_address_network_type;
2376 }
2377
2378 /**
2379  * Entry point for the plugin.
2380  *
2381  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2382  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2383  */
2384 void *
2385 libgnunet_plugin_transport_tcp_init (void *cls)
2386 {
2387   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = { {
2388       &handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2389       sizeof(struct WelcomeMessage) }, { &handle_tcp_nat_probe, NULL,
2390       GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2391       sizeof(struct TCP_NAT_ProbeMessage) }, { &handle_tcp_data, NULL,
2392       GNUNET_MESSAGE_TYPE_ALL, 0 }, { NULL, NULL, 0, 0 } };
2393   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2394   struct GNUNET_TRANSPORT_PluginFunctions *api;
2395   struct Plugin *plugin;
2396   struct GNUNET_SERVICE_Context *service;
2397   unsigned long long aport;
2398   unsigned long long bport;
2399   unsigned long long max_connections;
2400   unsigned int i;
2401   struct GNUNET_TIME_Relative idle_timeout;
2402   int ret;
2403   int ret_s;
2404   struct sockaddr **addrs;
2405   socklen_t *addrlens;
2406
2407   if (NULL == env->receive)
2408   {
2409     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2410      initialze the plugin or the API */
2411     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2412     api->cls = NULL;
2413     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2414     api->address_to_string = &tcp_address_to_string;
2415     api->string_to_address = &tcp_string_to_address;
2416     return api;
2417   }
2418
2419   GNUNET_assert(NULL != env->cfg);
2420   if (GNUNET_OK
2421       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2422           "MAX_CONNECTIONS", &max_connections))
2423     max_connections = 128;
2424
2425   aport = 0;
2426   if ((GNUNET_OK
2427       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2428           "PORT", &bport)) || (bport > 65535)
2429       || ((GNUNET_OK
2430           == GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2431               "ADVERTISED-PORT", &aport)) && (aport > 65535)))
2432   {
2433     LOG(GNUNET_ERROR_TYPE_ERROR,
2434         _("Require valid port number for service `%s' in configuration!\n"),
2435         "transport-tcp");
2436     return NULL ;
2437   }
2438   if (aport == 0)
2439     aport = bport;
2440   if (bport == 0)
2441     aport = 0;
2442   if (bport != 0)
2443   {
2444     service = GNUNET_SERVICE_start ("transport-tcp", env->cfg,
2445         GNUNET_SERVICE_OPTION_NONE);
2446     if (service == NULL )
2447     {
2448       LOG(GNUNET_ERROR_TYPE_WARNING, _("Failed to start service.\n"));
2449       return NULL ;
2450     }
2451   }
2452   else
2453     service = NULL;
2454
2455   /* Initialize my flags */
2456   myoptions = 0;
2457
2458   plugin = GNUNET_new (struct Plugin);
2459   plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
2460       GNUNET_YES);
2461   plugin->max_connections = max_connections;
2462   plugin->cur_connections = 0;
2463   plugin->open_port = bport;
2464   plugin->adv_port = aport;
2465   plugin->env = env;
2466   plugin->lsock = NULL;
2467   if ((service != NULL )&&
2468   (GNUNET_SYSERR !=
2469       (ret_s =
2470           GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2471               &addrlens)))){
2472   for (ret = ret_s-1; ret >= 0; ret--)
2473   LOG (GNUNET_ERROR_TYPE_INFO,
2474       "Binding to address `%s'\n",
2475       GNUNET_a2s (addrs[ret], addrlens[ret]));
2476   plugin->nat =
2477   GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2478       (const struct sockaddr **) addrs, addrlens,
2479       &tcp_nat_port_map_callback,
2480       &try_connection_reversal, plugin);
2481   for (ret = ret_s -1; ret >= 0; ret--)
2482   {
2483     GNUNET_assert (addrs[ret] != NULL);
2484     GNUNET_free (addrs[ret]);
2485   }
2486   GNUNET_free_non_null (addrs);
2487   GNUNET_free_non_null (addrlens);
2488 }
2489 else
2490 {
2491   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2492       GNUNET_YES, 0, 0, NULL, NULL, NULL,
2493       &try_connection_reversal, plugin);
2494 }
2495   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2496   api->cls = plugin;
2497   api->send = &tcp_plugin_send;
2498   api->get_session = &tcp_plugin_get_session;
2499
2500   api->disconnect_session = &tcp_disconnect_session;
2501   api->query_keepalive_factor = &tcp_query_keepalive_factor;
2502   api->disconnect_peer = &tcp_plugin_disconnect;
2503   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2504   api->check_address = &tcp_plugin_check_address;
2505   api->address_to_string = &tcp_address_to_string;
2506   api->string_to_address = &tcp_string_to_address;
2507   api->get_network = &tcp_get_network;
2508   api->update_session_timeout = &tcp_plugin_update_session_timeout;
2509   api->update_inbound_delay = &tcp_plugin_update_inbound_delay;
2510   plugin->service = service;
2511   if (NULL != service)
2512   {
2513     plugin->server = GNUNET_SERVICE_get_server (service);
2514   }
2515   else
2516   {
2517     if (GNUNET_OK
2518         != GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2519             "TIMEOUT", &idle_timeout))
2520     {
2521       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "transport-tcp",
2522           "TIMEOUT");
2523       if (plugin->nat != NULL )
2524         GNUNET_NAT_unregister (plugin->nat);
2525       GNUNET_free(plugin);
2526       GNUNET_free(api);
2527       return NULL ;
2528     }
2529     plugin->server = GNUNET_SERVER_create_with_sockets (
2530         &plugin_tcp_access_check, plugin, NULL, idle_timeout, GNUNET_YES);
2531   }
2532   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2533   memcpy (plugin->handlers, my_handlers, sizeof(my_handlers));
2534   for (i = 0;
2535       i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);
2536       i++)
2537     plugin->handlers[i].callback_cls = plugin;
2538
2539   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2540   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2541   plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
2542       GNUNET_YES);
2543   if (bport != 0)
2544     LOG(GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"),
2545         bport);
2546   else
2547     LOG(GNUNET_ERROR_TYPE_INFO,
2548         _("TCP transport not listening on any port (client only)\n"));
2549   if (aport != bport)
2550     LOG(GNUNET_ERROR_TYPE_INFO,
2551         _("TCP transport advertises itself as being on port %llu\n"), aport);
2552   /* Initially set connections to 0 */
2553   GNUNET_assert(NULL != plugin->env->stats);
2554   GNUNET_STATISTICS_set (plugin->env->stats,
2555       gettext_noop ("# TCP sessions active"), 0, GNUNET_NO);
2556   return api;
2557 }
2558
2559 /**
2560  * Exit point from the plugin.
2561  *
2562  * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
2563  * @return NULL
2564  */
2565 void *
2566 libgnunet_plugin_transport_tcp_done (void *cls)
2567 {
2568   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2569   struct Plugin *plugin = api->cls;
2570   struct TCPProbeContext *tcp_probe;
2571   struct PrettyPrinterContext *cur;
2572   struct PrettyPrinterContext *next;
2573
2574   if (NULL == plugin)
2575   {
2576     GNUNET_free(api);
2577     return NULL ;
2578   }
2579   LOG(GNUNET_ERROR_TYPE_DEBUG, "Shutting down TCP plugin\n");
2580
2581   /* Removing leftover sessions */
2582   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2583       &session_disconnect_it, plugin);
2584   /* Removing leftover NAT sessions */
2585   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2586       &session_disconnect_it, plugin);
2587
2588   next = ppc_dll_head;
2589   for (cur = next; NULL != cur; cur = next)
2590   {
2591     next = cur->next;
2592     GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, cur);
2593     if (NULL != cur->resolver_handle)
2594       GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2595     GNUNET_SCHEDULER_cancel (cur->timeout_task);
2596     GNUNET_free(cur);
2597     GNUNET_break(0);
2598   }
2599
2600   if (plugin->service != NULL )
2601     GNUNET_SERVICE_stop (plugin->service);
2602   else
2603     GNUNET_SERVER_destroy (plugin->server);
2604   GNUNET_free(plugin->handlers);
2605   if (plugin->nat != NULL )
2606     GNUNET_NAT_unregister (plugin->nat);
2607   while (NULL != (tcp_probe = plugin->probe_head))
2608   {
2609     GNUNET_CONTAINER_DLL_remove(plugin->probe_head, plugin->probe_tail,
2610         tcp_probe);
2611     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2612     GNUNET_free(tcp_probe);
2613   }
2614   GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2615   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2616   GNUNET_free(plugin);
2617   GNUNET_free(api);
2618   return NULL ;
2619 }
2620
2621 /* end of plugin_transport_tcp.c */