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