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