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