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