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