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