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