session timeouts for tcp
[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   GNUNET_assert (NULL != session);
1024   session->transmit_handle = NULL;
1025   plugin = session->plugin;
1026   if (NULL == buf)
1027   {
1028     LOG (GNUNET_ERROR_TYPE_DEBUG,
1029          "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
1030          GNUNET_i2s (&session->target));
1031     /* timeout; cancel all messages that have already expired */
1032     hd = NULL;
1033     tl = NULL;
1034     ret = 0;
1035     now = GNUNET_TIME_absolute_get ();
1036     while ((NULL != (pos = session->pending_messages_head)) &&
1037            (pos->timeout.abs_value_us <= now.abs_value_us))
1038     {
1039       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1040                                    session->pending_messages_tail, pos);
1041       LOG (GNUNET_ERROR_TYPE_DEBUG,
1042            "Failed to transmit %u byte message to `%4s'.\n",
1043            pos->message_size, GNUNET_i2s (&session->target));
1044       ret += pos->message_size;
1045       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
1046     }
1047     /* do this call before callbacks (so that if callbacks destroy
1048      * session, they have a chance to cancel actions done by this
1049      * call) */
1050     process_pending_messages (session);
1051     pid = session->target;
1052     /* no do callbacks and do not use session again since
1053      * the callbacks may abort the session */
1054     while (NULL != (pos = hd))
1055     {
1056       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1057       if (pos->transmit_cont != NULL)
1058         pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR, pos->message_size, 0);
1059       GNUNET_free (pos);
1060     }
1061     GNUNET_STATISTICS_update (plugin->env->stats,
1062                               gettext_noop ("# bytes currently in TCP buffers"),
1063                               -(int64_t) ret, GNUNET_NO);
1064     GNUNET_STATISTICS_update (plugin->env->stats,
1065                               gettext_noop
1066                               ("# bytes discarded by TCP (timeout)"), ret,
1067                               GNUNET_NO);
1068     return 0;
1069   }
1070   /* copy all pending messages that would fit */
1071   ret = 0;
1072   cbuf = buf;
1073   hd = NULL;
1074   tl = NULL;
1075   while (NULL != (pos = session->pending_messages_head))
1076   {
1077     if (ret + pos->message_size > size)
1078       break;
1079     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1080                                  session->pending_messages_tail, pos);
1081     GNUNET_assert (size >= pos->message_size);
1082     LOG (GNUNET_ERROR_TYPE_DEBUG,
1083          "Transmitting message of type %u\n",
1084          ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
1085     /* FIXME: this memcpy can be up to 7% of our total runtime */
1086     memcpy (cbuf, pos->msg, pos->message_size);
1087     cbuf += pos->message_size;
1088     ret += pos->message_size;
1089     size -= pos->message_size;
1090     GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
1091   }
1092   /* schedule 'continuation' before callbacks so that callbacks that
1093    * cancel everything don't cause us to use a session that no longer
1094    * exists... */
1095   process_pending_messages (session);
1096   session->last_activity = GNUNET_TIME_absolute_get ();
1097   pid = session->target;
1098   /* we'll now call callbacks that may cancel the session; hence
1099    * we should not use 'session' after this point */
1100   while (NULL != (pos = hd))
1101   {
1102     GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1103     if (pos->transmit_cont != NULL)
1104       pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK, pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
1105     GNUNET_free (pos);
1106   }
1107   GNUNET_assert (hd == NULL);
1108   GNUNET_assert (tl == NULL);
1109   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
1110                    ret);
1111   GNUNET_STATISTICS_update (plugin->env->stats,
1112                             gettext_noop ("# bytes currently in TCP buffers"),
1113                             -(int64_t) ret, GNUNET_NO);
1114   GNUNET_STATISTICS_update (plugin->env->stats,
1115                             gettext_noop ("# bytes transmitted via TCP"), ret,
1116                             GNUNET_NO);
1117   return ret;
1118 }
1119
1120
1121 /**
1122  * If we have pending messages, ask the server to
1123  * transmit them (schedule the respective tasks, etc.)
1124  *
1125  * @param session for which session should we do this
1126  */
1127 static void
1128 process_pending_messages (struct Session *session)
1129 {
1130   struct PendingMessage *pm;
1131
1132   GNUNET_assert (session->client != NULL);
1133   if (session->transmit_handle != NULL)
1134     return;
1135   if (NULL == (pm = session->pending_messages_head))
1136     return;
1137
1138   session->transmit_handle =
1139       GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
1140                                            GNUNET_TIME_absolute_get_remaining
1141                                            (pm->timeout), &do_transmit,
1142                                            session);
1143 }
1144
1145
1146 #if EXTRA_CHECKS
1147 /**
1148  * Closure for #session_it().
1149  */
1150 struct FindSessionContext
1151 {
1152   /**
1153    * Session we are looking for.
1154    */
1155   struct Session *s;
1156
1157   /**
1158    * Set to #GNUNET_OK if we found the session.
1159    */
1160   int res;
1161 };
1162
1163
1164 /**
1165  * Function called to check if a session is in our maps.
1166  *
1167  * @param cls the `struct FindSessionContext`
1168  * @param key peer identity
1169  * @param value session in the map
1170  * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1171  */
1172 static int
1173 session_it (void *cls,
1174             const struct GNUNET_PeerIdentity *key,
1175             void *value)
1176 {
1177   struct FindSessionContext *res = cls;
1178   struct Session *session = value;
1179
1180   if (res->s == session)
1181   {
1182     res->res = GNUNET_OK;
1183     return GNUNET_NO;
1184   }
1185   return GNUNET_YES;
1186 }
1187
1188
1189 /**
1190  * Check that the given session is known to the plugin and
1191  * is in one of our maps.
1192  *
1193  * @param plugin the plugin to check against
1194  * @param session the session to check
1195  * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1196  */
1197 static int
1198 find_session (struct Plugin *plugin,
1199               struct Session *session)
1200 {
1201   struct FindSessionContext session_map_res;
1202   struct FindSessionContext nat_map_res;
1203
1204   session_map_res.s = session;
1205   session_map_res.res = GNUNET_SYSERR;
1206   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
1207                                          &session_it, &session_map_res);
1208   if (GNUNET_SYSERR != session_map_res.res)
1209     return GNUNET_OK;
1210   nat_map_res.s = session;
1211   nat_map_res.res = GNUNET_SYSERR;
1212   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
1213                                          &session_it, &nat_map_res);
1214   if (GNUNET_SYSERR != nat_map_res.res)
1215     return GNUNET_OK;
1216   GNUNET_break (0);
1217   return GNUNET_SYSERR;
1218 }
1219 #endif
1220
1221
1222 /**
1223  * Function that can be used by the transport service to transmit
1224  * a message using the plugin.   Note that in the case of a
1225  * peer disconnecting, the continuation MUST be called
1226  * prior to the disconnect notification itself.  This function
1227  * will be called with this peer's HELLO message to initiate
1228  * a fresh connection to another peer.
1229  *
1230  * @param cls closure
1231  * @param session which session must be used
1232  * @param msgbuf the message to transmit
1233  * @param msgbuf_size number of bytes in 'msgbuf'
1234  * @param priority how important is the message (most plugins will
1235  *                 ignore message priority and just FIFO)
1236  * @param to how long to wait at most for the transmission (does not
1237  *                require plugins to discard the message after the timeout,
1238  *                just advisory for the desired delay; most plugins will ignore
1239  *                this as well)
1240  * @param cont continuation to call once the message has
1241  *        been transmitted (or if the transport is ready
1242  *        for the next transmission call; or if the
1243  *        peer disconnected...); can be NULL
1244  * @param cont_cls closure for @a cont
1245  * @return number of bytes used (on the physical network, with overheads);
1246  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1247  *         and does NOT mean that the message was not transmitted (DV)
1248  */
1249 static ssize_t
1250 tcp_plugin_send (void *cls,
1251                  struct Session *session,
1252                  const char *msgbuf, size_t msgbuf_size,
1253                  unsigned int priority,
1254                  struct GNUNET_TIME_Relative to,
1255                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1256 {
1257   struct Plugin * plugin = cls;
1258   struct PendingMessage *pm;
1259
1260 #if EXTRA_CHECKS
1261   if (GNUNET_SYSERR == find_session (plugin, session))
1262   {
1263     LOG (GNUNET_ERROR_TYPE_ERROR,
1264          _("Trying to send with invalid session %p\n"));
1265     GNUNET_assert (0);
1266     return GNUNET_SYSERR;
1267   }
1268 #endif
1269   /* create new message entry */
1270   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1271   pm->msg = (const char *) &pm[1];
1272   memcpy (&pm[1], msgbuf, msgbuf_size);
1273   pm->message_size = msgbuf_size;
1274   pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1275   pm->transmit_cont = cont;
1276   pm->transmit_cont_cls = cont_cls;
1277
1278   LOG (GNUNET_ERROR_TYPE_DEBUG,
1279        "Asked to transmit %u bytes to `%s', added message to list.\n",
1280        msgbuf_size, GNUNET_i2s (&session->target));
1281
1282   if (GNUNET_YES ==
1283       GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1284                                                     &session->target,
1285                                                     session))
1286   {
1287     GNUNET_assert (session->client != NULL);
1288     GNUNET_SERVER_client_set_timeout (session->client,
1289                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1290     GNUNET_STATISTICS_update (plugin->env->stats,
1291                               gettext_noop ("# bytes currently in TCP buffers"),
1292                               msgbuf_size, GNUNET_NO);
1293
1294     /* append pm to pending_messages list */
1295     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1296                                       session->pending_messages_tail, pm);
1297
1298     process_pending_messages (session);
1299     return msgbuf_size;
1300   }
1301   else if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains_value(plugin->nat_wait_conns, &session->target, session))
1302   {
1303     LOG (GNUNET_ERROR_TYPE_DEBUG,
1304          "This NAT WAIT session for peer `%s' is not yet ready!\n",
1305          GNUNET_i2s (&session->target));
1306     GNUNET_STATISTICS_update (plugin->env->stats,
1307                               gettext_noop ("# bytes currently in TCP buffers"),
1308                               msgbuf_size, GNUNET_NO);
1309
1310     /* append pm to pending_messages list */
1311     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1312                                       session->pending_messages_tail, pm);
1313     return msgbuf_size;
1314   }
1315   else
1316   {
1317     LOG (GNUNET_ERROR_TYPE_ERROR,
1318          "Invalid session %p\n", session);
1319     if (NULL != cont)
1320       cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1321     GNUNET_break (0);
1322     GNUNET_free (pm);
1323     return GNUNET_SYSERR; /* session does not exist here */
1324   }
1325 }
1326
1327
1328 /**
1329  * Closure for #session_lookup_it().
1330  */
1331 struct SessionItCtx
1332 {
1333   /**
1334    * Address we are looking for.
1335    */
1336   void *addr;
1337
1338   /**
1339    * Number of bytes in @e addr.
1340    */
1341   size_t addrlen;
1342
1343   /**
1344    * Where to store the session (if we found it).
1345    */
1346   struct Session *result;
1347 };
1348
1349
1350 /**
1351  * Look for a session by address.
1352  *
1353  * @param cls the `struct SessionItCtx`
1354  * @param key unused
1355  * @param value a `struct Session`
1356  * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1357  */
1358 static int
1359 session_lookup_it (void *cls,
1360                    const struct GNUNET_PeerIdentity *key,
1361                    void *value)
1362 {
1363   struct SessionItCtx * si_ctx = cls;
1364   struct Session * session = value;
1365 #if 0
1366   char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1367   char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1368   LOG (GNUNET_ERROR_TYPE_DEBUG,
1369        "Comparing: %s %u <-> %s %u\n",
1370        a1,
1371        session->addrlen,
1372        a2,
1373        si_ctx->addrlen);
1374   GNUNET_free (a1);
1375   GNUNET_free (a2);
1376 #endif
1377   if (session->addrlen != si_ctx->addrlen)
1378     return GNUNET_YES;
1379   if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1380     return GNUNET_YES;
1381 #if 0
1382   a1 = strdup (tcp_address_to_string (NULL, session->addr, session->addrlen));
1383   a2 = strdup (tcp_address_to_string (NULL, si_ctx->addr, si_ctx->addrlen));
1384   LOG (GNUNET_ERROR_TYPE_DEBUG,
1385        "Comparing: %s %u <-> %s %u , OK!\n",
1386        a1,
1387        session->addrlen,
1388        a2,
1389        si_ctx->addrlen);
1390   GNUNET_free (a1);
1391   GNUNET_free (a2);
1392 #endif
1393   /* Found existing session */
1394   si_ctx->result = session;
1395   return GNUNET_NO;
1396 }
1397
1398
1399 /**
1400  * Task cleaning up a NAT connection attempt after timeout
1401  *
1402  * @param cls the `struct Session`
1403  * @param tc scheduler context (unused)
1404  */
1405 static void
1406 nat_connect_timeout (void *cls,
1407                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1408 {
1409   struct Session *session = cls;
1410
1411   session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1412   LOG (GNUNET_ERROR_TYPE_DEBUG,
1413        "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1414        GNUNET_i2s (&session->target),
1415        tcp_address_to_string (NULL,
1416                               session->addr, session->addrlen));
1417   tcp_disconnect_session (session->plugin,
1418                           session);
1419 }
1420
1421 static void
1422 tcp_plugin_update_session_timeout (void *cls,
1423                                   const struct GNUNET_PeerIdentity *peer,
1424                                   struct Session *session)
1425 {
1426   struct Plugin *plugin = cls;
1427   if (GNUNET_SYSERR == find_session (plugin, session))
1428     return;
1429
1430   reschedule_session_timeout (session);
1431 }
1432
1433
1434 /**
1435  * Create a new session to transmit data to the target
1436  * This session will used to send data to this peer and the plugin will
1437  * notify us by calling the env->session_end function
1438  *
1439  * @param cls closure
1440  * @param address the address to use
1441  * @return the session if the address is valid, NULL otherwise
1442  */
1443 static struct Session *
1444 tcp_plugin_get_session (void *cls,
1445                         const struct GNUNET_HELLO_Address *address)
1446 {
1447   struct Plugin *plugin = cls;
1448   struct Session *session = NULL;
1449   int af;
1450   const void *sb;
1451   size_t sbs;
1452   struct GNUNET_CONNECTION_Handle *sa;
1453   struct sockaddr_in a4;
1454   struct sockaddr_in6 a6;
1455   const struct IPv4TcpAddress *t4;
1456   const struct IPv6TcpAddress *t6;
1457   struct GNUNET_ATS_Information ats;
1458   unsigned int is_natd = GNUNET_NO;
1459   size_t addrlen;
1460
1461   addrlen = address->address_length;
1462   LOG (GNUNET_ERROR_TYPE_DEBUG,
1463        "Trying to get session for `%s' address of peer `%s'\n",
1464        tcp_address_to_string(NULL, address->address, address->address_length),
1465        GNUNET_i2s (&address->peer));
1466
1467   /* look for existing session */
1468   if (GNUNET_YES ==
1469       GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1470                                               &address->peer))
1471   {
1472     struct SessionItCtx si_ctx;
1473
1474     si_ctx.addr = (void *) address->address;
1475     si_ctx.addrlen = address->address_length;
1476
1477     si_ctx.result = NULL;
1478
1479     GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1480                                                 &address->peer,
1481                                                 &session_lookup_it, &si_ctx);
1482     if (si_ctx.result != NULL)
1483     {
1484       session = si_ctx.result;
1485       LOG (GNUNET_ERROR_TYPE_DEBUG,
1486            "Found existing session for `%s' address `%s' session %p\n",
1487            GNUNET_i2s (&address->peer),
1488            tcp_address_to_string(NULL, address->address, address->address_length),
1489            session);
1490       return session;
1491     }
1492     LOG (GNUNET_ERROR_TYPE_DEBUG,
1493          "Existing sessions did not match address `%s' or peer `%s'\n",
1494          tcp_address_to_string(NULL, address->address, address->address_length),
1495          GNUNET_i2s (&address->peer));
1496   }
1497
1498   if (addrlen == sizeof (struct IPv6TcpAddress))
1499   {
1500     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1501     t6 = address->address;
1502     af = AF_INET6;
1503     memset (&a6, 0, sizeof (a6));
1504 #if HAVE_SOCKADDR_IN_SIN_LEN
1505     a6.sin6_len = sizeof (a6);
1506 #endif
1507     a6.sin6_family = AF_INET6;
1508     a6.sin6_port = t6->t6_port;
1509     if (t6->t6_port == 0)
1510       is_natd = GNUNET_YES;
1511     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1512     sb = &a6;
1513     sbs = sizeof (a6);
1514   }
1515   else if (addrlen == sizeof (struct IPv4TcpAddress))
1516   {
1517     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1518     t4 = address->address;
1519     af = AF_INET;
1520     memset (&a4, 0, sizeof (a4));
1521 #if HAVE_SOCKADDR_IN_SIN_LEN
1522     a4.sin_len = sizeof (a4);
1523 #endif
1524     a4.sin_family = AF_INET;
1525     a4.sin_port = t4->t4_port;
1526     if (t4->t4_port == 0)
1527       is_natd = GNUNET_YES;
1528     a4.sin_addr.s_addr = t4->ipv4_addr;
1529     sb = &a4;
1530     sbs = sizeof (a4);
1531   }
1532   else
1533   {
1534     GNUNET_STATISTICS_update (plugin->env->stats,
1535                               gettext_noop
1536                               ("# requests to create session with invalid address"),
1537                               1, GNUNET_NO);
1538     return NULL;
1539   }
1540
1541   ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1542
1543   if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1544   {
1545     /* NAT client only works with IPv4 addresses */
1546     return NULL;
1547   }
1548
1549   if (plugin->cur_connections >= plugin->max_connections)
1550   {
1551     /* saturated */
1552     return NULL;
1553   }
1554
1555   if ((is_natd == GNUNET_YES) &&
1556       (GNUNET_YES ==
1557        GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1558                                                &address->peer)))
1559   {
1560     /* Only do one NAT punch attempt per peer identity */
1561      return NULL;
1562   }
1563
1564   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1565       (GNUNET_NO ==
1566        GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1567                                                &address->peer)))
1568   {
1569     LOG (GNUNET_ERROR_TYPE_DEBUG,
1570          "Found valid IPv4 NAT address (creating session)!\n") ;
1571     session = create_session (plugin,
1572                               &address->peer,
1573                               NULL,
1574                               GNUNET_YES);
1575     session->addrlen = 0;
1576     session->addr = NULL;
1577     session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value)
1578 ;
1579     GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1580     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1581                                                                     &nat_connect_timeout,
1582                                                                     session);
1583     GNUNET_assert (session != NULL);
1584     GNUNET_assert (GNUNET_OK ==
1585                    GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1586                                                       &session->target,
1587                                                       session,
1588                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1589
1590     LOG (GNUNET_ERROR_TYPE_DEBUG,
1591          "Created NAT WAIT connection to `%4s' at `%s'\n",
1592          GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1593
1594     if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1595       return session;
1596     else
1597     {
1598       LOG (GNUNET_ERROR_TYPE_DEBUG,
1599            "Running NAT client for `%4s' at `%s' failed\n",
1600            GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1601       tcp_disconnect_session (plugin, session);
1602       return NULL;
1603     }
1604   }
1605
1606   /* create new outbound session */
1607   GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
1608   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1609   if (sa == NULL)
1610   {
1611     LOG (GNUNET_ERROR_TYPE_DEBUG,
1612          "Failed to create connection to `%4s' at `%s'\n",
1613          GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1614     return NULL;
1615   }
1616   plugin->cur_connections++;
1617   if (plugin->cur_connections == plugin->max_connections)
1618     GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1619
1620   LOG (GNUNET_ERROR_TYPE_DEBUG,
1621        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1622        GNUNET_i2s (&address->peer),
1623        GNUNET_a2s (sb, sbs));
1624
1625   session = create_session (plugin,
1626                             &address->peer,
1627                             GNUNET_SERVER_connect_socket (plugin->server, sa),
1628                             GNUNET_NO);
1629   session->addr = GNUNET_malloc (addrlen);
1630   memcpy (session->addr, address->address, addrlen);
1631   session->addrlen = addrlen;
1632   session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
1633   GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1634   GNUNET_SERVER_client_set_user_context (session->client, session);
1635   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
1636                                      &session->target,
1637                                      session,
1638                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1639   LOG (GNUNET_ERROR_TYPE_DEBUG,
1640        "Creating new session for `%s' address `%s' session %p\n",
1641        GNUNET_i2s (&address->peer),
1642        tcp_address_to_string(NULL, address->address, address->address_length),
1643        session);
1644   /* Send TCP Welcome */
1645   process_pending_messages (session);
1646
1647   return session;
1648 }
1649
1650
1651 static int
1652 session_disconnect_it (void *cls,
1653                        const struct GNUNET_PeerIdentity *key,
1654                        void *value)
1655 {
1656   struct Plugin *plugin = cls;
1657   struct Session *session = value;
1658
1659   GNUNET_STATISTICS_update (session->plugin->env->stats,
1660                             gettext_noop
1661                             ("# transport-service disconnect requests for TCP"),
1662                             1, GNUNET_NO);
1663   tcp_disconnect_session (plugin,
1664                           session);
1665   return GNUNET_YES;
1666 }
1667
1668
1669 /**
1670  * Function that can be called to force a disconnect from the
1671  * specified neighbour.  This should also cancel all previously
1672  * scheduled transmissions.  Obviously the transmission may have been
1673  * partially completed already, which is OK.  The plugin is supposed
1674  * to close the connection (if applicable) and no longer call the
1675  * transmit continuation(s).
1676  *
1677  * Finally, plugin MUST NOT call the services's receive function to
1678  * notify the service that the connection to the specified target was
1679  * closed after a getting this call.
1680  *
1681  * @param cls closure
1682  * @param target peer for which the last transmission is
1683  *        to be cancelled
1684  */
1685 static void
1686 tcp_plugin_disconnect (void *cls,
1687                        const struct GNUNET_PeerIdentity *target)
1688 {
1689   struct Plugin *plugin = cls;
1690
1691   LOG (GNUNET_ERROR_TYPE_DEBUG,
1692        "Disconnecting peer `%4s'\n",
1693        GNUNET_i2s (target));
1694   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1695                                               &session_disconnect_it, plugin);
1696   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1697                                               &session_disconnect_it, plugin);
1698 }
1699
1700
1701 /**
1702  * Running pretty printers: head
1703  */
1704 static struct PrettyPrinterContext *ppc_dll_head;
1705
1706 /**
1707  * Running pretty printers: tail
1708  */
1709 static struct PrettyPrinterContext *ppc_dll_tail;
1710
1711 /**
1712  * Context for address to string conversion.
1713  */
1714 struct PrettyPrinterContext
1715 {
1716   /**
1717    * DLL
1718    */
1719   struct PrettyPrinterContext *next;
1720
1721   /**
1722    * DLL
1723    */
1724   struct PrettyPrinterContext *prev;
1725
1726   /**
1727    * Timeout task
1728    */
1729   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1730
1731   /**
1732    * Resolver handle
1733    */
1734   struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1735
1736   /**
1737    * Function to call with the result.
1738    */
1739   GNUNET_TRANSPORT_AddressStringCallback asc;
1740
1741   /**
1742    * Clsoure for 'asc'.
1743    */
1744   void *asc_cls;
1745
1746   /**
1747    * Port to add after the IP address.
1748    */
1749   uint16_t port;
1750
1751   /**
1752    * IPv6 address
1753    */
1754   int ipv6;
1755
1756   /**
1757    * Options
1758    */
1759   uint32_t options;
1760 };
1761
1762
1763 static void
1764 ppc_cancel_task (void *cls,
1765                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1766 {
1767   int count = 0;
1768   struct PrettyPrinterContext *ppc = cls;
1769   struct PrettyPrinterContext *cur;
1770
1771   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1772   {
1773     if (cur != ppc)
1774       count++;
1775   }
1776
1777   // GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cancel request %p, %u pending\n", ppc, count);
1778   ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1779   if (NULL != ppc->resolver_handle)
1780   {
1781     GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1782     ppc->resolver_handle = NULL;
1783   }
1784   GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1785   GNUNET_free (ppc);
1786 }
1787
1788
1789 /**
1790  * Append our port and forward the result.
1791  *
1792  * @param cls the 'struct PrettyPrinterContext*'
1793  * @param hostname hostname part of the address
1794  */
1795 static void
1796 append_port (void *cls, const char *hostname)
1797 {
1798   struct PrettyPrinterContext *ppc = cls;
1799   struct PrettyPrinterContext *cur;
1800   char *ret;
1801   int count = 0;
1802
1803   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1804   {
1805     if (cur != ppc)
1806       count++;
1807   }
1808   //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Callback request %p == %s, %u pending\n", ppc, hostname, count);
1809   if (hostname == NULL)
1810   {
1811     ppc->asc (ppc->asc_cls, NULL);
1812     GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1813     GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1814     ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1815     ppc->resolver_handle = NULL;
1816     //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Done request %p, %u pending\n", ppc, count);
1817     GNUNET_free (ppc);
1818     return;
1819   }
1820   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1821   {
1822         if (cur == ppc)
1823                 break;
1824   }
1825   if (NULL == cur)
1826   {
1827         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
1828         return;
1829   }
1830
1831   if (GNUNET_YES == ppc->ipv6)
1832     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1833   else
1834     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1835   ppc->asc (ppc->asc_cls, ret);
1836   GNUNET_free (ret);
1837 }
1838
1839
1840 /**
1841  * Convert the transports address to a nice, human-readable
1842  * format.
1843  *
1844  * @param cls closure
1845  * @param type name of the transport that generated the address
1846  * @param addr one of the addresses of the host, NULL for the last address
1847  *        the specific address format depends on the transport
1848  * @param addrlen length of the address
1849  * @param numeric should (IP) addresses be displayed in numeric form?
1850  * @param timeout after how long should we give up?
1851  * @param asc function to call on each string
1852  * @param asc_cls closure for asc
1853  */
1854 static void
1855 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1856                                    const void *addr, size_t addrlen,
1857                                    int numeric,
1858                                    struct GNUNET_TIME_Relative timeout,
1859                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1860                                    void *asc_cls)
1861 {
1862   struct PrettyPrinterContext *ppc;
1863   const void *sb;
1864   size_t sbs;
1865   struct sockaddr_in a4;
1866   struct sockaddr_in6 a6;
1867   const struct IPv4TcpAddress *t4;
1868   const struct IPv6TcpAddress *t6;
1869   uint16_t port;
1870   uint32_t options;
1871
1872   if (addrlen == sizeof (struct IPv6TcpAddress))
1873   {
1874     t6 = addr;
1875     memset (&a6, 0, sizeof (a6));
1876     a6.sin6_family = AF_INET6;
1877     a6.sin6_port = t6->t6_port;
1878     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1879     port = ntohs (t6->t6_port);
1880     options = ntohl (t6->options);
1881     sb = &a6;
1882     sbs = sizeof (a6);
1883   }
1884   else if (addrlen == sizeof (struct IPv4TcpAddress))
1885   {
1886     t4 = addr;
1887     memset (&a4, 0, sizeof (a4));
1888     a4.sin_family = AF_INET;
1889     a4.sin_port = t4->t4_port;
1890     a4.sin_addr.s_addr = t4->ipv4_addr;
1891     port = ntohs (t4->t4_port);
1892     options = ntohl (t4->options);
1893     sb = &a4;
1894     sbs = sizeof (a4);
1895   }
1896   else if (0 == addrlen)
1897   {
1898     asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1899     asc (asc_cls, NULL);
1900     return;
1901   }
1902   else
1903   {
1904     /* invalid address */
1905     GNUNET_break_op (0);
1906     asc (asc_cls, NULL);
1907     return;
1908   }
1909   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1910   if (addrlen == sizeof (struct IPv6TcpAddress))
1911     ppc->ipv6 = GNUNET_YES;
1912   else
1913     ppc->ipv6 = GNUNET_NO;
1914   ppc->asc = asc;
1915   ppc->asc_cls = asc_cls;
1916   ppc->port = port;
1917   ppc->options = options;
1918   ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(timeout, 2),
1919                                                     &ppc_cancel_task, ppc);
1920   ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1921                                                        timeout,
1922                                                        &append_port, ppc);
1923   if (NULL != ppc->resolver_handle)
1924   {
1925     //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1926     GNUNET_CONTAINER_DLL_insert (ppc_dll_head, ppc_dll_tail, ppc);
1927   }
1928   else
1929   {
1930     GNUNET_break (0);
1931     GNUNET_free (ppc);
1932   }
1933 }
1934
1935
1936 /**
1937  * Check if the given port is plausible (must be either our listen
1938  * port or our advertised port), or any port if we are behind NAT
1939  * and do not have a port open.  If it is neither, we return
1940  * #GNUNET_SYSERR.
1941  *
1942  * @param plugin global variables
1943  * @param in_port port number to check
1944  * @return #GNUNET_OK if port is either open_port or adv_port
1945  */
1946 static int
1947 check_port (struct Plugin *plugin, uint16_t in_port)
1948 {
1949   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1950     return GNUNET_OK;
1951   return GNUNET_SYSERR;
1952 }
1953
1954
1955 /**
1956  * Function that will be called to check if a binary address for this
1957  * plugin is well-formed and corresponds to an address for THIS peer
1958  * (as per our configuration).  Naturally, if absolutely necessary,
1959  * plugins can be a bit conservative in their answer, but in general
1960  * plugins should make sure that the address does not redirect
1961  * traffic to a 3rd party that might try to man-in-the-middle our
1962  * traffic.
1963  *
1964  * @param cls closure, our 'struct Plugin*'
1965  * @param addr pointer to the address
1966  * @param addrlen length of addr
1967  * @return #GNUNET_OK if this is a plausible address for this peer
1968  *         and transport, #GNUNET_SYSERR if not
1969  */
1970 static int
1971 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1972 {
1973   struct Plugin *plugin = cls;
1974   struct IPv4TcpAddress *v4;
1975   struct IPv6TcpAddress *v6;
1976
1977   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1978       (addrlen != sizeof (struct IPv6TcpAddress)))
1979   {
1980
1981
1982         return GNUNET_SYSERR;
1983   }
1984
1985   if (addrlen == sizeof (struct IPv4TcpAddress))
1986   {
1987     v4 = (struct IPv4TcpAddress *) addr;
1988     if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
1989     {
1990         GNUNET_break (0);
1991         return GNUNET_SYSERR;
1992     }
1993     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1994       return GNUNET_SYSERR;
1995     if (GNUNET_OK !=
1996         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1997                                  sizeof (struct in_addr)))
1998       return GNUNET_SYSERR;
1999   }
2000   else
2001   {
2002     v6 = (struct IPv6TcpAddress *) addr;
2003     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2004     {
2005       GNUNET_break_op (0);
2006       return GNUNET_SYSERR;
2007     }
2008     if (0 != memcmp (&v6->options, &myoptions, sizeof (myoptions)))
2009     {
2010         GNUNET_break (0);
2011         return GNUNET_SYSERR;
2012     }
2013     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
2014       return GNUNET_SYSERR;
2015     if (GNUNET_OK !=
2016         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
2017                                  sizeof (struct in6_addr)))
2018       return GNUNET_SYSERR;
2019   }
2020   return GNUNET_OK;
2021 }
2022
2023
2024 /**
2025  * We've received a nat probe from this peer via TCP.  Finish
2026  * creating the client session and resume sending of queued
2027  * messages.
2028  *
2029  * @param cls closure
2030  * @param client identification of the client
2031  * @param message the actual message
2032  */
2033 static void
2034 handle_tcp_nat_probe (void *cls,
2035                       struct GNUNET_SERVER_Client *client,
2036                       const struct GNUNET_MessageHeader *message)
2037 {
2038   struct Plugin *plugin = cls;
2039   struct Session *session;
2040   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2041   size_t alen;
2042   void *vaddr;
2043   struct IPv4TcpAddress *t4;
2044   struct IPv6TcpAddress *t6;
2045   const struct sockaddr_in *s4;
2046   const struct sockaddr_in6 *s6;
2047
2048   LOG (GNUNET_ERROR_TYPE_DEBUG,
2049        "Received NAT probe\n");
2050   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2051    * a connection to this peer by running gnunet-nat-client.  This peer
2052    * received the punch message and now wants us to use the new connection
2053    * as the default for that peer.  Do so and then send a WELCOME message
2054    * so we can really be connected!
2055    */
2056   if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
2057   {
2058     GNUNET_break_op (0);
2059     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2060     return;
2061   }
2062
2063   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2064   if (0 ==
2065       memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2066               sizeof (struct GNUNET_PeerIdentity)))
2067   {
2068     /* refuse connections from ourselves */
2069     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2070     return;
2071   }
2072
2073   session =
2074     GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2075                                        &tcp_nat_probe->clientIdentity);
2076   if (session == NULL)
2077   {
2078     LOG (GNUNET_ERROR_TYPE_DEBUG,
2079          "Did NOT find session for NAT probe!\n");
2080     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2081     return;
2082   }
2083   LOG (GNUNET_ERROR_TYPE_DEBUG,
2084        "Found session for NAT probe!\n");
2085
2086   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
2087   {
2088     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2089     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2090   }
2091
2092   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2093   {
2094     GNUNET_break (0);
2095     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2096     tcp_disconnect_session (plugin, session);
2097     return;
2098   }
2099   GNUNET_assert (GNUNET_CONTAINER_multipeermap_remove
2100                  (plugin->nat_wait_conns,
2101                   &tcp_nat_probe->clientIdentity,
2102                   session) == GNUNET_YES);
2103   GNUNET_SERVER_client_set_user_context (client, session);
2104   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2105                                      &session->target, session,
2106                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2107   session->last_activity = GNUNET_TIME_absolute_get ();
2108   session->inbound = GNUNET_NO;
2109   LOG (GNUNET_ERROR_TYPE_DEBUG,
2110        "Found address `%s' for incoming connection\n",
2111        GNUNET_a2s (vaddr, alen));
2112   switch (((const struct sockaddr *) vaddr)->sa_family)
2113   {
2114   case AF_INET:
2115     s4 = vaddr;
2116     t4 = GNUNET_new (struct IPv4TcpAddress);
2117     t4->options = 0;
2118     t4->t4_port = s4->sin_port;
2119     t4->ipv4_addr = s4->sin_addr.s_addr;
2120     session->addr = t4;
2121     session->addrlen = sizeof (struct IPv4TcpAddress);
2122     break;
2123   case AF_INET6:
2124     s6 = vaddr;
2125     t6 = GNUNET_new (struct IPv6TcpAddress);
2126     t6->options = 0;
2127     t6->t6_port = s6->sin6_port;
2128     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2129     session->addr = t6;
2130     session->addrlen = sizeof (struct IPv6TcpAddress);
2131     break;
2132   default:
2133     GNUNET_break_op (0);
2134     LOG (GNUNET_ERROR_TYPE_DEBUG,
2135          "Bad address for incoming connection!\n");
2136     GNUNET_free (vaddr);
2137     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2138     tcp_disconnect_session (plugin, session);
2139     return;
2140   }
2141   GNUNET_free (vaddr);
2142   GNUNET_break (NULL == session->client);
2143   GNUNET_SERVER_client_keep (client);
2144   session->client = client;
2145   GNUNET_STATISTICS_update (plugin->env->stats,
2146                             gettext_noop ("# TCP sessions active"), 1,
2147                             GNUNET_NO);
2148   process_pending_messages (session);
2149   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2150 }
2151
2152
2153 /**
2154  * We've received a welcome from this peer via TCP.  Possibly create a
2155  * fresh client record and send back our welcome.
2156  *
2157  * @param cls closure
2158  * @param client identification of the client
2159  * @param message the actual message
2160  */
2161 static void
2162 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2163                     const struct GNUNET_MessageHeader *message)
2164 {
2165   struct Plugin *plugin = cls;
2166   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2167   struct Session *session;
2168   size_t alen;
2169   void *vaddr;
2170   struct IPv4TcpAddress *t4;
2171   struct IPv6TcpAddress *t6;
2172   const struct sockaddr_in *s4;
2173   const struct sockaddr_in6 *s6;
2174   struct GNUNET_ATS_Information ats;
2175
2176   if (0 ==
2177       memcmp (&wm->clientIdentity, plugin->env->my_identity,
2178               sizeof (struct GNUNET_PeerIdentity)))
2179   {
2180     /* refuse connections from ourselves */
2181     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2182     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2183     {
2184         LOG (GNUNET_ERROR_TYPE_WARNING,
2185          "Received %s message from my own identity `%4s' on address `%s'\n",
2186          "WELCOME", GNUNET_i2s (&wm->clientIdentity), GNUNET_a2s (vaddr, alen));
2187         GNUNET_free (vaddr);
2188     }
2189     GNUNET_break_op (0);
2190     return;
2191   }
2192   LOG (GNUNET_ERROR_TYPE_DEBUG,
2193        "Received %s message from `%4s' %p\n", "WELCOME",
2194        GNUNET_i2s (&wm->clientIdentity), client);
2195   GNUNET_STATISTICS_update (plugin->env->stats,
2196                             gettext_noop ("# TCP WELCOME messages received"), 1,
2197                             GNUNET_NO);
2198   session = lookup_session_by_client (plugin, client);
2199   if (session != NULL)
2200   {
2201     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2202     {
2203       LOG (GNUNET_ERROR_TYPE_DEBUG,
2204            "Found existing session %p for peer `%s'\n",
2205            session,
2206            GNUNET_a2s (vaddr, alen));
2207       GNUNET_free (vaddr);
2208     }
2209   }
2210   else
2211   {
2212     GNUNET_SERVER_client_keep (client);
2213     if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
2214         plugin->cur_connections++;
2215     if (plugin->cur_connections == plugin->max_connections)
2216         GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2217
2218     session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
2219     session->inbound = GNUNET_YES;
2220     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2221     {
2222       if (alen == sizeof (struct sockaddr_in))
2223       {
2224         s4 = vaddr;
2225         t4 = GNUNET_new (struct IPv4TcpAddress);
2226         t4->options = htonl (0);
2227         t4->t4_port = s4->sin_port;
2228         t4->ipv4_addr = s4->sin_addr.s_addr;
2229         session->addr = t4;
2230         session->addrlen = sizeof (struct IPv4TcpAddress);
2231       }
2232       else if (alen == sizeof (struct sockaddr_in6))
2233       {
2234         s6 = vaddr;
2235         t6 = GNUNET_new (struct IPv6TcpAddress);
2236         t6->options = htonl (0);
2237         t6->t6_port = s6->sin6_port;
2238         memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2239         session->addr = t6;
2240         session->addrlen = sizeof (struct IPv6TcpAddress);
2241       }
2242
2243       ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
2244       session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
2245       LOG (GNUNET_ERROR_TYPE_DEBUG,
2246            "Creating new session %p for peer `%s'\n",
2247            session,
2248            GNUNET_a2s (vaddr, alen));
2249       GNUNET_free (vaddr);
2250       GNUNET_SERVER_client_set_user_context (session->client, session);
2251       GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2252                                          &session->target,
2253                                          session,
2254                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2255     }
2256     else
2257     {
2258       LOG (GNUNET_ERROR_TYPE_DEBUG,
2259            "Did not obtain TCP socket address for incoming connection\n");
2260       GNUNET_break (0);
2261     }
2262   }
2263
2264   if (session->expecting_welcome != GNUNET_YES)
2265   {
2266     GNUNET_break_op (0);
2267     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2268     GNUNET_break (0);
2269     return;
2270   }
2271   session->last_activity = GNUNET_TIME_absolute_get ();
2272   session->expecting_welcome = GNUNET_NO;
2273
2274   /* Notify transport and ATS about new session */
2275   if (GNUNET_YES == session->inbound)
2276   {
2277         plugin->env->session_start (NULL, &wm->clientIdentity, PLUGIN_NAME,
2278                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2279                   (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2280                   session, &ats, 1);
2281   }
2282
2283   process_pending_messages (session);
2284
2285   GNUNET_SERVER_client_set_timeout (client,
2286                                     GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2287   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2288 }
2289
2290
2291 /**
2292  * Task to signal the server that we can continue
2293  * receiving from the TCP client now.
2294  *
2295  * @param cls the 'struct Session*'
2296  * @param tc task context (unused)
2297  */
2298 static void
2299 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2300 {
2301   struct Session *session = cls;
2302
2303   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2304   reschedule_session_timeout (session);
2305
2306   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2307 }
2308
2309
2310 /**
2311  * We've received data for this peer via TCP.  Unbox,
2312  * compute latency and forward.
2313  *
2314  * @param cls closure
2315  * @param client identification of the client
2316  * @param message the actual message
2317  */
2318 static void
2319 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2320                  const struct GNUNET_MessageHeader *message)
2321 {
2322   struct Plugin *plugin = cls;
2323   struct Session *session;
2324   struct GNUNET_TIME_Relative delay;
2325   uint16_t type;
2326
2327   type = ntohs (message->type);
2328   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
2329       (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2330   {
2331     /* We don't want to propagate WELCOME and NAT Probe messages up! */
2332     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2333     return;
2334   }
2335   session = lookup_session_by_client (plugin, client);
2336   if (NULL == session)
2337   {
2338     /* No inbound session found */
2339     void *vaddr;
2340     size_t alen;
2341
2342     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2343     LOG (GNUNET_ERROR_TYPE_ERROR,
2344          "Received unexpected %u bytes of type %u from `%s'\n",
2345          (unsigned int) ntohs (message->size),
2346          (unsigned int) ntohs (message->type),
2347          GNUNET_a2s(vaddr, alen));
2348     GNUNET_break_op (0);
2349     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2350     GNUNET_free_non_null(vaddr);
2351     return;
2352   }
2353   else if (GNUNET_YES == session->expecting_welcome)
2354   {
2355     /* Session is expecting WELCOME message */
2356     void *vaddr;
2357     size_t alen;
2358
2359     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2360     LOG (GNUNET_ERROR_TYPE_ERROR,
2361          "Received unexpected %u bytes of type %u from `%s'\n",
2362          (unsigned int) ntohs (message->size),
2363          (unsigned int) ntohs (message->type),
2364          GNUNET_a2s(vaddr, alen));
2365     GNUNET_break_op (0);
2366     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2367     GNUNET_free_non_null(vaddr);
2368     return;
2369   }
2370
2371   session->last_activity = GNUNET_TIME_absolute_get ();
2372   LOG (GNUNET_ERROR_TYPE_DEBUG,
2373                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2374                    (unsigned int) ntohs (message->size),
2375                    (unsigned int) ntohs (message->type),
2376                    GNUNET_i2s (&session->target));
2377
2378   GNUNET_STATISTICS_update (plugin->env->stats,
2379                             gettext_noop ("# bytes received via TCP"),
2380                             ntohs (message->size), GNUNET_NO);
2381   struct GNUNET_ATS_Information distance;
2382
2383   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2384   distance.value = htonl ((uint32_t) session->ats_address_network_type);
2385   GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2386
2387   GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2388                                                                &session->target,
2389                                                                session));
2390
2391   delay = plugin->env->receive (plugin->env->cls,
2392                                 &session->target,
2393                                 message,
2394                                 session,
2395                                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2396                                 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
2397   plugin->env->update_address_metrics (plugin->env->cls,
2398                                        &session->target,
2399                                        (GNUNET_YES == session->inbound) ? NULL : session->addr,
2400                                        (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2401                                        session, &distance, 1);
2402   reschedule_session_timeout (session);
2403   if (0 == delay.rel_value_us)
2404   {
2405     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2406   }
2407   else
2408   {
2409     LOG (GNUNET_ERROR_TYPE_DEBUG,
2410          "Throttling receiving from `%s' for %s\n",
2411          GNUNET_i2s (&session->target),
2412          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2413     GNUNET_SERVER_disable_receive_done_warning (client);
2414     session->receive_delay_task =
2415       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2416   }
2417 }
2418
2419
2420 /**
2421  * Functions with this signature are called whenever a peer
2422  * is disconnected on the network level.
2423  *
2424  * @param cls closure
2425  * @param client identification of the client
2426  */
2427 static void
2428 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2429 {
2430   struct Plugin *plugin = cls;
2431   struct Session *session;
2432
2433   if (client == NULL)
2434     return;
2435   session = lookup_session_by_client (plugin, client);
2436   if (session == NULL)
2437     return;                     /* unknown, nothing to do */
2438   LOG (GNUNET_ERROR_TYPE_DEBUG,
2439        "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2440        GNUNET_i2s (&session->target),
2441        (session->addr !=
2442         NULL) ? tcp_address_to_string (session->plugin,
2443                                        session->addr,
2444                                        session->addrlen) :
2445        "*");
2446
2447   if (plugin->cur_connections == plugin->max_connections)
2448     GNUNET_SERVER_resume (plugin->server); /* Resume server  */
2449
2450   if (plugin->cur_connections < 1)
2451     GNUNET_break (0);
2452   else
2453     plugin->cur_connections--;
2454
2455   GNUNET_STATISTICS_update (session->plugin->env->stats,
2456                             gettext_noop
2457                             ("# network-level TCP disconnect events"), 1,
2458                             GNUNET_NO);
2459   tcp_disconnect_session (plugin, session);
2460 }
2461
2462
2463 /**
2464  * We can now send a probe message, copy into buffer to really send.
2465  *
2466  * @param cls closure, a struct TCPProbeContext
2467  * @param size max size to copy
2468  * @param buf buffer to copy message to
2469  * @return number of bytes copied into buf
2470  */
2471 static size_t
2472 notify_send_probe (void *cls, size_t size, void *buf)
2473 {
2474   struct TCPProbeContext *tcp_probe_ctx = cls;
2475   struct Plugin *plugin = tcp_probe_ctx->plugin;
2476   size_t ret;
2477
2478   tcp_probe_ctx->transmit_handle = NULL;
2479   GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2480                                tcp_probe_ctx);
2481   if (buf == NULL)
2482   {
2483     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2484     GNUNET_free (tcp_probe_ctx);
2485     return 0;
2486   }
2487   GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2488   memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2489   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2490                                 tcp_probe_ctx->sock);
2491   ret = sizeof (tcp_probe_ctx->message);
2492   GNUNET_free (tcp_probe_ctx);
2493   return ret;
2494 }
2495
2496
2497 /**
2498  * Function called by the NAT subsystem suggesting another peer wants
2499  * to connect to us via connection reversal.  Try to connect back to the
2500  * given IP.
2501  *
2502  * @param cls closure
2503  * @param addr address to try
2504  * @param addrlen number of bytes in @a addr
2505  */
2506 static void
2507 try_connection_reversal (void *cls, const struct sockaddr *addr,
2508                          socklen_t addrlen)
2509 {
2510   struct Plugin *plugin = cls;
2511   struct GNUNET_CONNECTION_Handle *sock;
2512   struct TCPProbeContext *tcp_probe_ctx;
2513
2514   /**
2515    * We have received an ICMP response, ostensibly from a peer
2516    * that wants to connect to us! Send a message to establish a connection.
2517    */
2518   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2519   if (sock == NULL)
2520   {
2521     /* failed for some odd reason (out of sockets?); ignore attempt */
2522     return;
2523   }
2524
2525   /* FIXME: do we need to track these probe context objects so that
2526    * we can clean them up on plugin unload? */
2527   tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2528   tcp_probe_ctx->message.header.size =
2529       htons (sizeof (struct TCP_NAT_ProbeMessage));
2530   tcp_probe_ctx->message.header.type =
2531       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2532   memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2533           sizeof (struct GNUNET_PeerIdentity));
2534   tcp_probe_ctx->plugin = plugin;
2535   tcp_probe_ctx->sock = sock;
2536   GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2537                                tcp_probe_ctx);
2538   tcp_probe_ctx->transmit_handle =
2539       GNUNET_CONNECTION_notify_transmit_ready (sock,
2540                                                ntohs (tcp_probe_ctx->
2541                                                       message.header.size),
2542                                                GNUNET_TIME_UNIT_FOREVER_REL,
2543                                                &notify_send_probe,
2544                                                tcp_probe_ctx);
2545
2546 }
2547
2548
2549 /**
2550  * Function obtain the network type for a session
2551  *
2552  * @param cls closure ('struct Plugin*')
2553  * @param session the session
2554  * @return the network type in HBO or #GNUNET_SYSERR
2555  */
2556 static enum GNUNET_ATS_Network_Type
2557 tcp_get_network (void *cls,
2558                  struct Session *session)
2559 {
2560   GNUNET_assert (NULL != session);
2561   return session->ats_address_network_type;
2562 }
2563
2564
2565 /**
2566  * Entry point for the plugin.
2567  *
2568  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2569  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2570  */
2571 void *
2572 libgnunet_plugin_transport_tcp_init (void *cls)
2573 {
2574   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2575     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2576      sizeof (struct WelcomeMessage)},
2577     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2578      sizeof (struct TCP_NAT_ProbeMessage)},
2579     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2580     {NULL, NULL, 0, 0}
2581   };
2582   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2583   struct GNUNET_TRANSPORT_PluginFunctions *api;
2584   struct Plugin *plugin;
2585   struct GNUNET_SERVICE_Context *service;
2586   unsigned long long aport;
2587   unsigned long long bport;
2588   unsigned long long max_connections;
2589   unsigned int i;
2590   struct GNUNET_TIME_Relative idle_timeout;
2591   int ret;
2592   int ret_s;
2593   struct sockaddr **addrs;
2594   socklen_t *addrlens;
2595
2596
2597   if (NULL == env->receive)
2598   {
2599     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2600        initialze the plugin or the API */
2601     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2602     api->cls = NULL;
2603     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2604     api->address_to_string = &tcp_address_to_string;
2605     api->string_to_address = &tcp_string_to_address;
2606     return api;
2607   }
2608
2609   GNUNET_assert (NULL != env->cfg);
2610   if (GNUNET_OK !=
2611       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2612                                              "MAX_CONNECTIONS",
2613                                              &max_connections))
2614     max_connections = 128;
2615
2616   aport = 0;
2617   if ((GNUNET_OK !=
2618        GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2619                                               &bport)) || (bport > 65535) ||
2620       ((GNUNET_OK ==
2621         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2622                                                "ADVERTISED-PORT", &aport)) &&
2623        (aport > 65535)))
2624   {
2625     LOG (GNUNET_ERROR_TYPE_ERROR,
2626          _("Require valid port number for service `%s' in configuration!\n"),
2627          "transport-tcp");
2628     return NULL;
2629   }
2630   if (aport == 0)
2631     aport = bport;
2632   if (bport == 0)
2633     aport = 0;
2634   if (bport != 0)
2635   {
2636     service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2637     if (service == NULL)
2638     {
2639       LOG (GNUNET_ERROR_TYPE_WARNING,
2640            _("Failed to start service.\n"));
2641       return NULL;
2642     }
2643   }
2644   else
2645     service = NULL;
2646
2647   /* Initialize my flags */
2648   myoptions = 0;
2649
2650   plugin = GNUNET_new (struct Plugin);
2651   plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections, GNUNET_YES);
2652   plugin->max_connections = max_connections;
2653   plugin->cur_connections = 0;
2654   plugin->open_port = bport;
2655   plugin->adv_port = aport;
2656   plugin->env = env;
2657   plugin->lsock = NULL;
2658   if ((service != NULL) &&
2659       (GNUNET_SYSERR !=
2660        (ret_s =
2661         GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2662                                              &addrlens))))
2663   {
2664     for (ret = ret_s-1; ret >= 0; ret--)
2665       LOG (GNUNET_ERROR_TYPE_INFO,
2666            "Binding to address `%s'\n",
2667            GNUNET_a2s (addrs[ret], addrlens[ret]));
2668     plugin->nat =
2669         GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2670                              (const struct sockaddr **) addrs, addrlens,
2671                              &tcp_nat_port_map_callback,
2672                              &try_connection_reversal, plugin);
2673     for (ret = ret_s -1; ret >= 0; ret--)
2674     {
2675       GNUNET_assert (addrs[ret] != NULL);
2676       GNUNET_free (addrs[ret]);
2677     }
2678     GNUNET_free_non_null (addrs);
2679     GNUNET_free_non_null (addrlens);
2680   }
2681   else
2682   {
2683     plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2684                                        GNUNET_YES, 0, 0, NULL, NULL, NULL,
2685                                        &try_connection_reversal, plugin);
2686   }
2687   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2688   api->cls = plugin;
2689   api->send = &tcp_plugin_send;
2690   api->get_session = &tcp_plugin_get_session;
2691
2692   api->disconnect_session = &tcp_disconnect_session;
2693   api->query_keepalive_factor = &tcp_query_keepalive_factor;
2694   api->disconnect_peer = &tcp_plugin_disconnect;
2695   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2696   api->check_address = &tcp_plugin_check_address;
2697   api->address_to_string = &tcp_address_to_string;
2698   api->string_to_address = &tcp_string_to_address;
2699   api->get_network = &tcp_get_network;
2700   api->update_session_timeout = &tcp_plugin_update_session_timeout;
2701   plugin->service = service;
2702   if (NULL != service)
2703   {
2704     plugin->server = GNUNET_SERVICE_get_server (service);
2705   }
2706   else
2707   {
2708     if (GNUNET_OK !=
2709         GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2710                                              "TIMEOUT", &idle_timeout))
2711     {
2712       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2713                                  "transport-tcp", "TIMEOUT");
2714       if (plugin->nat != NULL)
2715         GNUNET_NAT_unregister (plugin->nat);
2716       GNUNET_free (plugin);
2717       GNUNET_free (api);
2718       return NULL;
2719     }
2720     plugin->server =
2721         GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2722                                            NULL, idle_timeout, GNUNET_YES);
2723   }
2724   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2725   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2726   for (i = 0;
2727        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2728        i++)
2729     plugin->handlers[i].callback_cls = plugin;
2730
2731   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2732   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2733   plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
2734   if (bport != 0)
2735     LOG (GNUNET_ERROR_TYPE_INFO,
2736          _("TCP transport listening on port %llu\n"), bport);
2737   else
2738     LOG (GNUNET_ERROR_TYPE_INFO,
2739          _("TCP transport not listening on any port (client only)\n"));
2740   if (aport != bport)
2741     LOG (GNUNET_ERROR_TYPE_INFO,
2742          _("TCP transport advertises itself as being on port %llu\n"),
2743          aport);
2744   /* Initially set connections to 0 */
2745   GNUNET_assert (NULL != plugin->env->stats);
2746   GNUNET_STATISTICS_set (plugin->env->stats,
2747                          gettext_noop ("# TCP sessions active"), 0,
2748                          GNUNET_NO);
2749   return api;
2750 }
2751
2752
2753 /**
2754  * Exit point from the plugin.
2755  */
2756 void *
2757 libgnunet_plugin_transport_tcp_done (void *cls)
2758 {
2759   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2760   struct Plugin *plugin = api->cls;
2761   struct TCPProbeContext *tcp_probe;
2762   struct PrettyPrinterContext *cur;
2763   struct PrettyPrinterContext *next;
2764
2765   if (NULL == plugin)
2766   {
2767     GNUNET_free (api);
2768     return NULL;
2769   }
2770   LOG (GNUNET_ERROR_TYPE_DEBUG,
2771        "Shutting down TCP plugin\n");
2772
2773   /* Removing leftover sessions */
2774   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2775                                          &session_disconnect_it, plugin);
2776   /* Removing leftover NAT sessions */
2777   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2778                                          &session_disconnect_it, plugin);
2779
2780   next = ppc_dll_head;
2781   for (cur = next; NULL != cur; cur = next)
2782   {
2783     next = cur->next;
2784     GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
2785     if (NULL != cur->resolver_handle)
2786       GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2787     GNUNET_SCHEDULER_cancel (cur->timeout_task);
2788     GNUNET_free (cur);
2789     GNUNET_break (0);
2790   }
2791
2792   if (plugin->service != NULL)
2793     GNUNET_SERVICE_stop (plugin->service);
2794   else
2795     GNUNET_SERVER_destroy (plugin->server);
2796   GNUNET_free (plugin->handlers);
2797   if (plugin->nat != NULL)
2798     GNUNET_NAT_unregister (plugin->nat);
2799   while (NULL != (tcp_probe = plugin->probe_head))
2800   {
2801     GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2802                                  tcp_probe);
2803     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2804     GNUNET_free (tcp_probe);
2805   }
2806   GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2807   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2808   GNUNET_free (plugin);
2809   GNUNET_free (api);
2810   return NULL;
2811 }
2812
2813 /* end of plugin_transport_tcp.c */