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