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