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