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