-const
[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, address->address, address->address_length),
1531         GNUNET_i2s (&address->peer));
1532   }
1533
1534   if (addrlen == sizeof(struct IPv6TcpAddress))
1535   {
1536     GNUNET_assert(NULL != address->address); /* make static analysis happy */
1537     t6 = address->address;
1538     af = AF_INET6;
1539     memset (&a6, 0, sizeof(a6));
1540 #if HAVE_SOCKADDR_IN_SIN_LEN
1541     a6.sin6_len = sizeof (a6);
1542 #endif
1543     a6.sin6_family = AF_INET6;
1544     a6.sin6_port = t6->t6_port;
1545     if (t6->t6_port == 0)
1546       is_natd = GNUNET_YES;
1547     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1548     sb = &a6;
1549     sbs = sizeof(a6);
1550   }
1551   else if (addrlen == sizeof(struct IPv4TcpAddress))
1552   {
1553     GNUNET_assert(NULL != address->address); /* make static analysis happy */
1554     t4 = address->address;
1555     af = AF_INET;
1556     memset (&a4, 0, sizeof(a4));
1557 #if HAVE_SOCKADDR_IN_SIN_LEN
1558     a4.sin_len = sizeof (a4);
1559 #endif
1560     a4.sin_family = AF_INET;
1561     a4.sin_port = t4->t4_port;
1562     if (t4->t4_port == 0)
1563       is_natd = GNUNET_YES;
1564     a4.sin_addr.s_addr = t4->ipv4_addr;
1565     sb = &a4;
1566     sbs = sizeof(a4);
1567   }
1568   else
1569   {
1570     GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1571     ("# requests to create session with invalid address"), 1, GNUNET_NO);
1572     return NULL ;
1573   }
1574
1575   ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1576
1577   if ((is_natd == GNUNET_YES) && (addrlen == sizeof(struct IPv6TcpAddress)))
1578   {
1579     /* NAT client only works with IPv4 addresses */
1580     return NULL ;
1581   }
1582
1583   if (plugin->cur_connections >= plugin->max_connections)
1584   {
1585     /* saturated */
1586     return NULL ;
1587   }
1588
1589   if ((is_natd == GNUNET_YES)
1590       && (GNUNET_YES
1591           == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1592               &address->peer)))
1593   {
1594     /* Only do one NAT punch attempt per peer identity */
1595     return NULL ;
1596   }
1597
1598   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1599       (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1600               &address->peer)))
1601   {
1602     LOG (GNUNET_ERROR_TYPE_DEBUG,
1603         "Found valid IPv4 NAT address (creating session)!\n");
1604     session = create_session (plugin, address, NULL, GNUNET_YES);
1605     session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1606         ats.value);
1607     GNUNET_break(
1608         session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1609     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1610         &nat_connect_timeout, session);
1611     GNUNET_assert(session != NULL);
1612     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1613         &session->target, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1614
1615     LOG(GNUNET_ERROR_TYPE_DEBUG,
1616         "Created NAT WAIT connection to `%4s' at `%s'\n",
1617         GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1618
1619     if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1620       return session;
1621     else
1622     {
1623       LOG(GNUNET_ERROR_TYPE_DEBUG,
1624           "Running NAT client for `%4s' at `%s' failed\n",
1625           GNUNET_i2s (&session->target),
1626           GNUNET_a2s (sb, sbs));
1627       tcp_plugin_disconnect_session (plugin,
1628                                      session);
1629       return NULL;
1630     }
1631   }
1632
1633   /* create new outbound session */
1634   GNUNET_assert(plugin->cur_connections <= plugin->max_connections);
1635   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1636   if (NULL == sa)
1637   {
1638     LOG(GNUNET_ERROR_TYPE_DEBUG,
1639         "Failed to create connection to `%4s' at `%s'\n",
1640         GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1641     return NULL ;
1642   }
1643   plugin->cur_connections++;
1644   if (plugin->cur_connections == plugin->max_connections)
1645     GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1646
1647   LOG(GNUNET_ERROR_TYPE_DEBUG,
1648       "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1649       GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1650
1651   session = create_session (plugin, address,
1652       GNUNET_SERVER_connect_socket (plugin->server, sa), GNUNET_NO);
1653   session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1654       ats.value);
1655   GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1656   GNUNET_SERVER_client_set_user_context(session->client, session);
1657   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1658       session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1659   LOG(GNUNET_ERROR_TYPE_DEBUG,
1660       "Creating new session for `%s' address `%s' session %p\n",
1661       GNUNET_i2s (&address->peer),
1662       tcp_plugin_address_to_string(NULL, address->address, address->address_length),
1663       session);
1664   /* Send TCP Welcome */
1665   process_pending_messages (session);
1666
1667   return session;
1668 }
1669
1670
1671 static int
1672 session_disconnect_it (void *cls,
1673                        const struct GNUNET_PeerIdentity *key,
1674                        void *value)
1675 {
1676   struct Plugin *plugin = cls;
1677   struct Session *session = value;
1678
1679   GNUNET_STATISTICS_update (session->plugin->env->stats,
1680                             gettext_noop ("# transport-service disconnect requests for TCP"),
1681                             1,
1682                             GNUNET_NO);
1683   tcp_plugin_disconnect_session (plugin,
1684                                  session);
1685   return GNUNET_YES;
1686 }
1687
1688
1689 /**
1690  * Function that can be called to force a disconnect from the
1691  * specified neighbour.  This should also cancel all previously
1692  * scheduled transmissions.  Obviously the transmission may have been
1693  * partially completed already, which is OK.  The plugin is supposed
1694  * to close the connection (if applicable) and no longer call the
1695  * transmit continuation(s).
1696  *
1697  * Finally, plugin MUST NOT call the services's receive function to
1698  * notify the service that the connection to the specified target was
1699  * closed after a getting this call.
1700  *
1701  * @param cls closure
1702  * @param target peer for which the last transmission is
1703  *        to be cancelled
1704  */
1705 static void
1706 tcp_plugin_disconnect (void *cls,
1707                        const struct GNUNET_PeerIdentity *target)
1708 {
1709   struct Plugin *plugin = cls;
1710
1711   LOG(GNUNET_ERROR_TYPE_DEBUG,
1712       "Disconnecting peer `%4s'\n",
1713       GNUNET_i2s (target));
1714   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1715                                               target,
1716                                               &session_disconnect_it,
1717                                               plugin);
1718   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns,
1719                                               target,
1720                                               &session_disconnect_it,
1721                                               plugin);
1722 }
1723
1724
1725 /**
1726  * Running pretty printers: head
1727  */
1728 static struct PrettyPrinterContext *ppc_dll_head;
1729
1730 /**
1731  * Running pretty printers: tail
1732  */
1733 static struct PrettyPrinterContext *ppc_dll_tail;
1734
1735 /**
1736  * Context for address to string conversion, closure
1737  * for #append_port().
1738  */
1739 struct PrettyPrinterContext
1740 {
1741   /**
1742    * DLL
1743    */
1744   struct PrettyPrinterContext *next;
1745
1746   /**
1747    * DLL
1748    */
1749   struct PrettyPrinterContext *prev;
1750
1751   /**
1752    * Timeout task
1753    */
1754   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1755
1756   /**
1757    * Resolver handle
1758    */
1759   struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1760
1761   /**
1762    * Function to call with the result.
1763    */
1764   GNUNET_TRANSPORT_AddressStringCallback asc;
1765
1766   /**
1767    * Clsoure for @e asc.
1768    */
1769   void *asc_cls;
1770
1771   /**
1772    * Port to add after the IP address.
1773    */
1774   uint16_t port;
1775
1776   /**
1777    * IPv6 address
1778    */
1779   int ipv6;
1780
1781   /**
1782    * Options
1783    */
1784   uint32_t options;
1785 };
1786
1787
1788 /**
1789  * Append our port and forward the result.
1790  *
1791  * @param cls the `struct PrettyPrinterContext *`
1792  * @param hostname hostname part of the address
1793  */
1794 static void
1795 append_port (void *cls,
1796              const char *hostname)
1797 {
1798   struct PrettyPrinterContext *ppc = cls;
1799   char *ret;
1800
1801   if (NULL == hostname)
1802   {
1803     /* Final call, done */
1804     ppc->resolver_handle = NULL;
1805     GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
1806                                  ppc_dll_tail,
1807                                  ppc);
1808     ppc->asc (ppc->asc_cls,
1809               NULL,
1810               GNUNET_OK);
1811     GNUNET_free (ppc);
1812     return;
1813   }
1814   if (GNUNET_YES == ppc->ipv6)
1815     GNUNET_asprintf (&ret,
1816                      "%s.%u.[%s]:%d",
1817                      PLUGIN_NAME,
1818                      ppc->options,
1819                      hostname,
1820                      ppc->port);
1821   else
1822     GNUNET_asprintf (&ret,
1823                      "%s.%u.%s:%d",
1824                      PLUGIN_NAME,
1825                      ppc->options,
1826                      hostname,
1827                      ppc->port);
1828   ppc->asc (ppc->asc_cls,
1829             ret,
1830             GNUNET_OK);
1831   GNUNET_free (ret);
1832 }
1833
1834
1835 /**
1836  * Convert the transports address to a nice, human-readable
1837  * format.
1838  *
1839  * @param cls closure
1840  * @param type name of the transport that generated the address
1841  * @param addr one of the addresses of the host, NULL for the last address
1842  *        the specific address format depends on the transport
1843  * @param addrlen length of the @a addr
1844  * @param numeric should (IP) addresses be displayed in numeric form?
1845  * @param timeout after how long should we give up?
1846  * @param asc function to call on each string
1847  * @param asc_cls closure for @a asc
1848  */
1849 static void
1850 tcp_plugin_address_pretty_printer (void *cls,
1851                                    const char *type,
1852                                    const void *addr,
1853                                    size_t addrlen,
1854                                    int numeric,
1855                                    struct GNUNET_TIME_Relative timeout,
1856                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1857                                    void *asc_cls)
1858 {
1859   struct PrettyPrinterContext *ppc;
1860   const void *sb;
1861   size_t sbs;
1862   struct sockaddr_in a4;
1863   struct sockaddr_in6 a6;
1864   const struct IPv4TcpAddress *t4;
1865   const struct IPv6TcpAddress *t6;
1866   uint16_t port;
1867   uint32_t options;
1868
1869   if (sizeof(struct IPv6TcpAddress) == addrlen)
1870   {
1871     t6 = addr;
1872     memset (&a6, 0, sizeof(a6));
1873     a6.sin6_family = AF_INET6;
1874     a6.sin6_port = t6->t6_port;
1875     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1876     port = ntohs (t6->t6_port);
1877     options = ntohl (t6->options);
1878     sb = &a6;
1879     sbs = sizeof(a6);
1880   }
1881   else if (sizeof(struct IPv4TcpAddress) == addrlen)
1882   {
1883     t4 = addr;
1884     memset (&a4, 0, sizeof(a4));
1885     a4.sin_family = AF_INET;
1886     a4.sin_port = t4->t4_port;
1887     a4.sin_addr.s_addr = t4->ipv4_addr;
1888     port = ntohs (t4->t4_port);
1889     options = ntohl (t4->options);
1890     sb = &a4;
1891     sbs = sizeof(a4);
1892   }
1893   else
1894   {
1895     /* invalid address */
1896     asc (asc_cls, NULL, GNUNET_SYSERR);
1897     asc (asc_cls, NULL, GNUNET_OK);
1898     return;
1899   }
1900   ppc = GNUNET_new (struct PrettyPrinterContext);
1901   if (addrlen == sizeof(struct IPv6TcpAddress))
1902     ppc->ipv6 = GNUNET_YES;
1903   else
1904     ppc->ipv6 = GNUNET_NO;
1905   ppc->asc = asc;
1906   ppc->asc_cls = asc_cls;
1907   ppc->port = port;
1908   ppc->options = options;
1909   ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb,
1910                                                        sbs,
1911                                                        ! numeric,
1912                                                        timeout,
1913                                                        &append_port, ppc);
1914   if (NULL == ppc->resolver_handle)
1915   {
1916     GNUNET_break (0);
1917     GNUNET_free (ppc);
1918     return;
1919   }
1920   GNUNET_CONTAINER_DLL_insert (ppc_dll_head,
1921                                ppc_dll_tail,
1922                                ppc);
1923 }
1924
1925
1926 /**
1927  * Check if the given port is plausible (must be either our listen
1928  * port or our advertised port), or any port if we are behind NAT
1929  * and do not have a port open.  If it is neither, we return
1930  * #GNUNET_SYSERR.
1931  *
1932  * @param plugin global variables
1933  * @param in_port port number to check
1934  * @return #GNUNET_OK if port is either open_port or adv_port
1935  */
1936 static int
1937 check_port (struct Plugin *plugin, uint16_t in_port)
1938 {
1939   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1940     return GNUNET_OK;
1941   return GNUNET_SYSERR;
1942 }
1943
1944 /**
1945  * Function that will be called to check if a binary address for this
1946  * plugin is well-formed and corresponds to an address for THIS peer
1947  * (as per our configuration).  Naturally, if absolutely necessary,
1948  * plugins can be a bit conservative in their answer, but in general
1949  * plugins should make sure that the address does not redirect
1950  * traffic to a 3rd party that might try to man-in-the-middle our
1951  * traffic.
1952  *
1953  * @param cls closure, our `struct Plugin *`
1954  * @param addr pointer to the address
1955  * @param addrlen length of addr
1956  * @return #GNUNET_OK if this is a plausible address for this peer
1957  *         and transport, #GNUNET_SYSERR if not
1958  */
1959 static int
1960 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1961 {
1962   struct Plugin *plugin = cls;
1963   struct IPv4TcpAddress *v4;
1964   struct IPv6TcpAddress *v6;
1965
1966   if ((addrlen != sizeof(struct IPv4TcpAddress))
1967       && (addrlen != sizeof(struct IPv6TcpAddress)))
1968   {
1969     GNUNET_break_op(0);
1970     return GNUNET_SYSERR;
1971   }
1972
1973   if (addrlen == sizeof(struct IPv4TcpAddress))
1974   {
1975     v4 = (struct IPv4TcpAddress *) addr;
1976     if (0 != memcmp (&v4->options,
1977                      &plugin->myoptions,
1978                      sizeof(uint32_t)))
1979     {
1980       GNUNET_break(0);
1981       return GNUNET_SYSERR;
1982     }
1983     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1984       return GNUNET_SYSERR;
1985     if (GNUNET_OK
1986         != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1987             sizeof(struct in_addr)))
1988       return GNUNET_SYSERR;
1989   }
1990   else
1991   {
1992     v6 = (struct IPv6TcpAddress *) addr;
1993     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1994     {
1995       GNUNET_break_op(0);
1996       return GNUNET_SYSERR;
1997     }
1998     if (0 != memcmp (&v6->options,
1999                      &plugin->myoptions,
2000                      sizeof (uint32_t)))
2001     {
2002       GNUNET_break(0);
2003       return GNUNET_SYSERR;
2004     }
2005     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
2006       return GNUNET_SYSERR;
2007     if (GNUNET_OK
2008         != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
2009             sizeof(struct in6_addr)))
2010       return GNUNET_SYSERR;
2011   }
2012   return GNUNET_OK;
2013 }
2014
2015 /**
2016  * We've received a nat probe from this peer via TCP.  Finish
2017  * creating the client session and resume sending of queued
2018  * messages.
2019  *
2020  * @param cls closure
2021  * @param client identification of the client
2022  * @param message the actual message
2023  */
2024 static void
2025 handle_tcp_nat_probe (void *cls,
2026                       struct GNUNET_SERVER_Client *client,
2027                       const struct GNUNET_MessageHeader *message)
2028 {
2029   struct Plugin *plugin = cls;
2030   struct Session *session;
2031   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2032   size_t alen;
2033   void *vaddr;
2034   struct IPv4TcpAddress *t4;
2035   struct IPv6TcpAddress *t6;
2036   const struct sockaddr_in *s4;
2037   const struct sockaddr_in6 *s6;
2038
2039   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
2040   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2041    * a connection to this peer by running gnunet-nat-client.  This peer
2042    * received the punch message and now wants us to use the new connection
2043    * as the default for that peer.  Do so and then send a WELCOME message
2044    * so we can really be connected!
2045    */
2046   if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
2047   {
2048     GNUNET_break_op(0);
2049     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2050     return;
2051   }
2052
2053   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2054   if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2055           sizeof(struct GNUNET_PeerIdentity)))
2056   {
2057     /* refuse connections from ourselves */
2058     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2059     return;
2060   }
2061
2062   session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2063       &tcp_nat_probe->clientIdentity);
2064   if (session == NULL)
2065   {
2066     LOG(GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
2067     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2068     return;
2069   }
2070   LOG(GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
2071
2072   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
2073   {
2074     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2075     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2076   }
2077
2078   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2079   {
2080     GNUNET_break(0);
2081     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2082     tcp_plugin_disconnect_session (plugin,
2083                                    session);
2084     return;
2085   }
2086   GNUNET_assert(
2087       GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity, session) == GNUNET_YES);
2088   GNUNET_SERVER_client_set_user_context(client, session);
2089   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2090       session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2091   session->last_activity = GNUNET_TIME_absolute_get ();
2092   LOG(GNUNET_ERROR_TYPE_DEBUG, "Found address `%s' for incoming connection\n",
2093       GNUNET_a2s (vaddr, alen));
2094   switch (((const struct sockaddr *) vaddr)->sa_family)
2095   {
2096   case AF_INET:
2097     s4 = vaddr;
2098     t4 = GNUNET_new (struct IPv4TcpAddress);
2099     t4->options = htonl(0);
2100     t4->t4_port = s4->sin_port;
2101     t4->ipv4_addr = s4->sin_addr.s_addr;
2102     session->address = GNUNET_HELLO_address_allocate (
2103         &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t4,
2104         sizeof(struct IPv4TcpAddress),
2105         GNUNET_HELLO_ADDRESS_INFO_NONE);
2106     break;
2107   case AF_INET6:
2108     s6 = vaddr;
2109     t6 = GNUNET_new (struct IPv6TcpAddress);
2110     t6->options = htonl(0);
2111     t6->t6_port = s6->sin6_port;
2112     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2113     session->address = GNUNET_HELLO_address_allocate (
2114         &tcp_nat_probe->clientIdentity,
2115         PLUGIN_NAME, &t6, sizeof(struct IPv6TcpAddress),
2116         GNUNET_HELLO_ADDRESS_INFO_NONE);
2117     break;
2118   default:
2119     GNUNET_break_op(0);
2120     LOG(GNUNET_ERROR_TYPE_DEBUG,
2121         "Bad address for incoming connection!\n");
2122     GNUNET_free(vaddr);
2123     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2124     tcp_plugin_disconnect_session (plugin,
2125                                    session);
2126     return;
2127   }
2128   GNUNET_free(vaddr);
2129   GNUNET_break(NULL == session->client);
2130   GNUNET_SERVER_client_keep (client);
2131   session->client = client;
2132   GNUNET_STATISTICS_update (plugin->env->stats,
2133       gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
2134   process_pending_messages (session);
2135   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2136 }
2137
2138 /**
2139  * We've received a welcome from this peer via TCP.  Possibly create a
2140  * fresh client record and send back our welcome.
2141  *
2142  * @param cls closure
2143  * @param client identification of the client
2144  * @param message the actual message
2145  */
2146 static void
2147 handle_tcp_welcome (void *cls,
2148                     struct GNUNET_SERVER_Client *client,
2149                     const struct GNUNET_MessageHeader *message)
2150 {
2151   struct Plugin *plugin = cls;
2152   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2153   struct GNUNET_HELLO_Address *address;
2154   struct Session *session;
2155   size_t alen;
2156   void *vaddr;
2157   struct IPv4TcpAddress t4;
2158   struct IPv6TcpAddress t6;
2159   const struct sockaddr_in *s4;
2160   const struct sockaddr_in6 *s6;
2161   struct GNUNET_ATS_Information ats;
2162
2163
2164   if (0 == memcmp (&wm->clientIdentity, plugin->env->my_identity,
2165           sizeof(struct GNUNET_PeerIdentity)))
2166   {
2167     /* refuse connections from ourselves */
2168     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2169     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2170     {
2171       LOG(GNUNET_ERROR_TYPE_INFO,
2172           "Received %s message from my own identity `%4s' on address `%s'\n",
2173           "WELCOME", GNUNET_i2s (&wm->clientIdentity),
2174           GNUNET_a2s (vaddr, alen));
2175       GNUNET_free(vaddr);
2176     }
2177     return;
2178   }
2179
2180   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received %s message from `%4s' %p\n", "WELCOME",
2181       GNUNET_i2s (&wm->clientIdentity), client);
2182   GNUNET_STATISTICS_update (plugin->env->stats,
2183       gettext_noop ("# TCP WELCOME messages received"), 1, GNUNET_NO);
2184   session = lookup_session_by_client (plugin, client);
2185   if (NULL != session)
2186   {
2187     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2188     {
2189       LOG(GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p for peer `%s'\n",
2190           session, GNUNET_a2s (vaddr, alen));
2191       GNUNET_free(vaddr);
2192     }
2193   }
2194   else
2195   {
2196     GNUNET_SERVER_client_keep (client);
2197     if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
2198       plugin->cur_connections++;
2199     if (plugin->cur_connections == plugin->max_connections)
2200       GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2201
2202     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2203     {
2204       if (alen == sizeof(struct sockaddr_in))
2205       {
2206         s4 = vaddr;
2207         memset (&t4, '\0', sizeof (t4));
2208         t4.options = htonl (0);
2209         t4.t4_port = s4->sin_port;
2210         t4.ipv4_addr = s4->sin_addr.s_addr;
2211         address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2212             PLUGIN_NAME, &t4, sizeof(t4),
2213             GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2214       }
2215       else if (alen == sizeof(struct sockaddr_in6))
2216       {
2217         s6 = vaddr;
2218         memset (&t6, '\0', sizeof (t6));
2219         t6.options = htonl (0);
2220         t6.t6_port = s6->sin6_port;
2221         memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2222         address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2223             PLUGIN_NAME, &t6, sizeof (t6),
2224             GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2225       }
2226       else
2227       {
2228         GNUNET_break (0);
2229         GNUNET_free_non_null (vaddr);
2230         return;
2231       }
2232       session = create_session (plugin, address, client, GNUNET_NO);
2233       GNUNET_HELLO_address_free (address);
2234       ats = plugin->env->get_address_type (plugin->env->cls, vaddr, alen);
2235       session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
2236           ats.value);
2237       LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new%s session %p for peer `%s' client %p \n",
2238           GNUNET_HELLO_address_check_option (session->address,
2239               GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? " inbound" : "", session,
2240           tcp_plugin_address_to_string(NULL, (void *) session->address->address,
2241               session->address->address_length),
2242           client);
2243       GNUNET_free(vaddr);
2244       GNUNET_SERVER_client_set_user_context(session->client, session);
2245       GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2246           session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2247
2248       /* Notify transport and ATS about new session */
2249       plugin->env->session_start (NULL, session->address, session, &ats, 1);
2250     }
2251     else
2252     {
2253       LOG(GNUNET_ERROR_TYPE_DEBUG,
2254           "Did not obtain TCP socket address for incoming connection\n");
2255       GNUNET_break(0);
2256       return;
2257     }
2258   }
2259
2260   if (session->expecting_welcome != GNUNET_YES)
2261   {
2262     GNUNET_break_op(0);
2263     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2264     GNUNET_break(0);
2265     return;
2266   }
2267   session->last_activity = GNUNET_TIME_absolute_get ();
2268   session->expecting_welcome = GNUNET_NO;
2269
2270   process_pending_messages (session);
2271   GNUNET_SERVER_client_set_timeout (client,
2272       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2273   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2274 }
2275
2276
2277 /**
2278  * We've received data for this peer via TCP.  Unbox,
2279  * compute latency and forward.
2280  *
2281  * @param cls closure
2282  * @param client identification of the client
2283  * @param message the actual message
2284  */
2285 static void
2286 handle_tcp_data (void *cls,
2287                  struct GNUNET_SERVER_Client *client,
2288                  const struct GNUNET_MessageHeader *message)
2289 {
2290   struct Plugin *plugin = cls;
2291   struct Session *session;
2292   struct GNUNET_TIME_Relative delay;
2293   uint16_t type;
2294
2295   type = ntohs (message->type);
2296   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type)
2297       || (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2298   {
2299     /* We don't want to propagate WELCOME and NAT Probe messages up! */
2300     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2301     return;
2302   }
2303   session = lookup_session_by_client (plugin, client);
2304   if (NULL == session)
2305   {
2306     /* No inbound session found */
2307     void *vaddr;
2308     size_t alen;
2309
2310     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2311     LOG(GNUNET_ERROR_TYPE_ERROR,
2312         "Received unexpected %u bytes of type %u from `%s'\n",
2313         (unsigned int) ntohs (message->size),
2314         (unsigned int) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2315     GNUNET_break_op(0);
2316     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2317     GNUNET_free_non_null(vaddr);
2318     return;
2319   }
2320   else if (GNUNET_YES == session->expecting_welcome)
2321   {
2322     /* Session is expecting WELCOME message */
2323     void *vaddr;
2324     size_t alen;
2325
2326     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2327     LOG(GNUNET_ERROR_TYPE_ERROR,
2328         "Received unexpected %u bytes of type %u from `%s'\n",
2329         (unsigned int) ntohs (message->size),
2330         (unsigned int) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2331     GNUNET_break_op(0);
2332     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2333     GNUNET_free_non_null(vaddr);
2334     return;
2335   }
2336
2337   session->last_activity = GNUNET_TIME_absolute_get ();
2338   LOG(GNUNET_ERROR_TYPE_DEBUG,
2339       "Passing %u bytes of type %u from `%4s' to transport service.\n",
2340       (unsigned int) ntohs (message->size),
2341       (unsigned int) ntohs (message->type), GNUNET_i2s (&session->target));
2342
2343   GNUNET_STATISTICS_update (plugin->env->stats,
2344       gettext_noop ("# bytes received via TCP"), ntohs (message->size),
2345       GNUNET_NO);
2346   struct GNUNET_ATS_Information distance;
2347
2348   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2349   distance.value = htonl ((uint32_t) session->ats_address_network_type);
2350   GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2351
2352   GNUNET_assert(GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2353                                                               &session->target,
2354                                                               session));
2355
2356   delay = plugin->env->receive (plugin->env->cls,
2357                                 session->address,
2358                                 session,
2359                                 message);
2360   plugin->env->update_address_metrics (plugin->env->cls,
2361                                        session->address,
2362                                        session,
2363                                        &distance, 1);
2364   reschedule_session_timeout (session);
2365   if (0 == delay.rel_value_us)
2366   {
2367     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2368   }
2369   else
2370   {
2371     LOG(GNUNET_ERROR_TYPE_DEBUG,
2372         "Throttling receiving from `%s' for %s\n",
2373         GNUNET_i2s (&session->target),
2374         GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2375     GNUNET_SERVER_disable_receive_done_warning (client);
2376     session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2377         &delayed_done, session);
2378   }
2379 }
2380
2381
2382 /**
2383  * Functions with this signature are called whenever a peer
2384  * is disconnected on the network level.
2385  *
2386  * @param cls closure
2387  * @param client identification of the client
2388  */
2389 static void
2390 disconnect_notify (void *cls,
2391                    struct GNUNET_SERVER_Client *client)
2392 {
2393   struct Plugin *plugin = cls;
2394   struct Session *session;
2395
2396   if (NULL == client)
2397     return;
2398   session = lookup_session_by_client (plugin, client);
2399   if (NULL == session)
2400     return; /* unknown, nothing to do */
2401   LOG (GNUNET_ERROR_TYPE_DEBUG,
2402        "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2403        GNUNET_i2s (&session->target),
2404        tcp_plugin_address_to_string (session->plugin, session->address->address,
2405                               session->address->address_length));
2406
2407   if (plugin->cur_connections == plugin->max_connections)
2408     GNUNET_SERVER_resume (plugin->server); /* Resume server  */
2409
2410   if (plugin->cur_connections < 1)
2411     GNUNET_break(0);
2412   else
2413     plugin->cur_connections--;
2414
2415   GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
2416                             ("# network-level TCP disconnect events"),
2417                             1,
2418                             GNUNET_NO);
2419   tcp_plugin_disconnect_session (plugin, session);
2420 }
2421
2422
2423 /**
2424  * We can now send a probe message, copy into buffer to really send.
2425  *
2426  * @param cls closure, a struct TCPProbeContext
2427  * @param size max size to copy
2428  * @param buf buffer to copy message to
2429  * @return number of bytes copied into @a buf
2430  */
2431 static size_t
2432 notify_send_probe (void *cls,
2433                    size_t size,
2434                    void *buf)
2435 {
2436   struct TCPProbeContext *tcp_probe_ctx = cls;
2437   struct Plugin *plugin = tcp_probe_ctx->plugin;
2438   size_t ret;
2439
2440   tcp_probe_ctx->transmit_handle = NULL;
2441   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2442                                plugin->probe_tail,
2443                                tcp_probe_ctx);
2444   if (buf == NULL)
2445   {
2446     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2447     GNUNET_free(tcp_probe_ctx);
2448     return 0;
2449   }
2450   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2451   memcpy (buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2452   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2453                                 tcp_probe_ctx->sock);
2454   ret = sizeof(tcp_probe_ctx->message);
2455   GNUNET_free(tcp_probe_ctx);
2456   return ret;
2457 }
2458
2459
2460 /**
2461  * Function called by the NAT subsystem suggesting another peer wants
2462  * to connect to us via connection reversal.  Try to connect back to the
2463  * given IP.
2464  *
2465  * @param cls closure
2466  * @param addr address to try
2467  * @param addrlen number of bytes in @a addr
2468  */
2469 static void
2470 try_connection_reversal (void *cls,
2471                          const struct sockaddr *addr,
2472                          socklen_t addrlen)
2473 {
2474   struct Plugin *plugin = cls;
2475   struct GNUNET_CONNECTION_Handle *sock;
2476   struct TCPProbeContext *tcp_probe_ctx;
2477
2478   /**
2479    * We have received an ICMP response, ostensibly from a peer
2480    * that wants to connect to us! Send a message to establish a connection.
2481    */
2482   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2483   if (sock == NULL)
2484   {
2485     /* failed for some odd reason (out of sockets?); ignore attempt */
2486     return;
2487   }
2488
2489   tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
2490   tcp_probe_ctx->message.header.size
2491     = htons (sizeof (struct TCP_NAT_ProbeMessage));
2492   tcp_probe_ctx->message.header.type
2493     = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2494   tcp_probe_ctx->message.clientIdentity
2495     = *plugin->env->my_identity;
2496   tcp_probe_ctx->plugin = plugin;
2497   tcp_probe_ctx->sock = sock;
2498   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2499                                plugin->probe_tail,
2500                                tcp_probe_ctx);
2501   tcp_probe_ctx->transmit_handle
2502     = GNUNET_CONNECTION_notify_transmit_ready (sock,
2503                                                ntohs (tcp_probe_ctx->message.header.size),
2504                                                GNUNET_TIME_UNIT_FOREVER_REL,
2505                                                &notify_send_probe,
2506                                                tcp_probe_ctx);
2507 }
2508
2509
2510 /**
2511  * Function obtain the network type for a session
2512  *
2513  * @param cls closure ('struct Plugin*')
2514  * @param session the session
2515  * @return the network type in HBO or #GNUNET_SYSERR
2516  */
2517 static enum GNUNET_ATS_Network_Type
2518 tcp_plugin_get_network (void *cls,
2519                         struct Session *session)
2520 {
2521   return session->ats_address_network_type;
2522 }
2523
2524
2525 /**
2526  * Return information about the given session to the
2527  * monitor callback.
2528  *
2529  * @param cls the `struct Plugin` with the monitor callback (`sic`)
2530  * @param peer peer we send information about
2531  * @param value our `struct Session` to send information about
2532  * @return #GNUNET_OK (continue to iterate)
2533  */
2534 static int
2535 send_session_info_iter (void *cls,
2536                         const struct GNUNET_PeerIdentity *peer,
2537                         void *value)
2538 {
2539   struct Plugin *plugin = cls;
2540   struct Session *session = value;
2541
2542   notify_session_monitor (plugin,
2543                           session,
2544                           GNUNET_TRANSPORT_SS_UP);
2545   return GNUNET_OK;
2546 }
2547
2548
2549 /**
2550  * Begin monitoring sessions of a plugin.  There can only
2551  * be one active monitor per plugin (i.e. if there are
2552  * multiple monitors, the transport service needs to
2553  * multiplex the generated events over all of them).
2554  *
2555  * @param cls closure of the plugin
2556  * @param sic callback to invoke, NULL to disable monitor;
2557  *            plugin will being by iterating over all active
2558  *            sessions immediately and then enter monitor mode
2559  * @param sic_cls closure for @a sic
2560  */
2561 static void
2562 tcp_plugin_setup_monitor (void *cls,
2563                           GNUNET_TRANSPORT_SessionInfoCallback sic,
2564                           void *sic_cls)
2565 {
2566   struct Plugin *plugin = cls;
2567
2568   plugin->sic = sic;
2569   plugin->sic_cls = sic_cls;
2570   if (NULL != sic)
2571   {
2572     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2573                                            &send_session_info_iter,
2574                                            plugin);
2575     /* signal end of first iteration */
2576     sic (sic_cls, NULL, NULL);
2577   }
2578 }
2579
2580
2581 /**
2582  * Entry point for the plugin.
2583  *
2584  * @param cls closure, the `struct GNUNET_TRANSPORT_PluginEnvironment *`
2585  * @return the `struct GNUNET_TRANSPORT_PluginFunctions *` or NULL on error
2586  */
2587 void *
2588 libgnunet_plugin_transport_tcp_init (void *cls)
2589 {
2590   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2591     { &handle_tcp_welcome, NULL,
2592       GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, sizeof(struct WelcomeMessage) },
2593     { &handle_tcp_nat_probe, NULL,
2594       GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof(struct TCP_NAT_ProbeMessage) },
2595     { &handle_tcp_data, NULL,
2596       GNUNET_MESSAGE_TYPE_ALL, 0 },
2597     { NULL, NULL, 0, 0 }
2598   };
2599   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2600   struct GNUNET_TRANSPORT_PluginFunctions *api;
2601   struct Plugin *plugin;
2602   struct GNUNET_SERVICE_Context *service;
2603   unsigned long long aport;
2604   unsigned long long bport;
2605   unsigned long long max_connections;
2606   unsigned int i;
2607   struct GNUNET_TIME_Relative idle_timeout;
2608   int ret;
2609   int ret_s;
2610   struct sockaddr **addrs;
2611   socklen_t *addrlens;
2612
2613   if (NULL == env->receive)
2614   {
2615     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2616      initialze the plugin or the API */
2617     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2618     api->cls = NULL;
2619     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2620     api->address_to_string = &tcp_plugin_address_to_string;
2621     api->string_to_address = &tcp_plugin_string_to_address;
2622     return api;
2623   }
2624
2625   GNUNET_assert (NULL != env->cfg);
2626   if (GNUNET_OK !=
2627       GNUNET_CONFIGURATION_get_value_number (env->cfg,
2628                                              "transport-tcp",
2629                                              "MAX_CONNECTIONS",
2630                                              &max_connections))
2631     max_connections = 128;
2632
2633   aport = 0;
2634   if ((GNUNET_OK
2635       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2636           "PORT", &bport)) || (bport > 65535)
2637       || ((GNUNET_OK
2638           == GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2639               "ADVERTISED-PORT", &aport)) && (aport > 65535)))
2640   {
2641     LOG(GNUNET_ERROR_TYPE_ERROR,
2642         _("Require valid port number for service `%s' in configuration!\n"),
2643         "transport-tcp");
2644     return NULL ;
2645   }
2646   if (aport == 0)
2647     aport = bport;
2648   if (bport == 0)
2649     aport = 0;
2650   if (bport != 0)
2651   {
2652     service = GNUNET_SERVICE_start ("transport-tcp",
2653                                     env->cfg,
2654                                     GNUNET_SERVICE_OPTION_NONE);
2655     if (service == NULL)
2656     {
2657       LOG (GNUNET_ERROR_TYPE_WARNING,
2658            _("Failed to start service.\n"));
2659       return NULL;
2660     }
2661   }
2662   else
2663     service = NULL;
2664
2665   plugin = GNUNET_new (struct Plugin);
2666   plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
2667       GNUNET_YES);
2668   plugin->max_connections = max_connections;
2669   plugin->open_port = bport;
2670   plugin->adv_port = aport;
2671   plugin->env = env;
2672   if ( (service != NULL) &&
2673        (GNUNET_SYSERR !=
2674         (ret_s =
2675          GNUNET_SERVICE_get_server_addresses ("transport-tcp",
2676                                               env->cfg,
2677                                               &addrs,
2678                                               &addrlens))))
2679   {
2680     for (ret = ret_s-1; ret >= 0; ret--)
2681       LOG (GNUNET_ERROR_TYPE_INFO,
2682            "Binding to address `%s'\n",
2683            GNUNET_a2s (addrs[ret], addrlens[ret]));
2684     plugin->nat
2685       = GNUNET_NAT_register (env->cfg,
2686                              GNUNET_YES,
2687                              aport,
2688                              (unsigned int) ret_s,
2689                              (const struct sockaddr **) addrs, addrlens,
2690                              &tcp_nat_port_map_callback,
2691                              &try_connection_reversal,
2692                              plugin);
2693     for (ret = ret_s -1; ret >= 0; ret--)
2694       GNUNET_free (addrs[ret]);
2695     GNUNET_free_non_null (addrs);
2696     GNUNET_free_non_null (addrlens);
2697   }
2698   else
2699   {
2700     plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2701                                        GNUNET_YES, 0, 0, NULL, NULL, NULL,
2702                                        &try_connection_reversal, plugin);
2703   }
2704   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2705   api->cls = plugin;
2706   api->send = &tcp_plugin_send;
2707   api->get_session = &tcp_plugin_get_session;
2708   api->disconnect_session = &tcp_plugin_disconnect_session;
2709   api->query_keepalive_factor = &tcp_plugin_query_keepalive_factor;
2710   api->disconnect_peer = &tcp_plugin_disconnect;
2711   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2712   api->check_address = &tcp_plugin_check_address;
2713   api->address_to_string = &tcp_plugin_address_to_string;
2714   api->string_to_address = &tcp_plugin_string_to_address;
2715   api->get_network = &tcp_plugin_get_network;
2716   api->update_session_timeout = &tcp_plugin_update_session_timeout;
2717   api->update_inbound_delay = &tcp_plugin_update_inbound_delay;
2718   api->setup_monitor = &tcp_plugin_setup_monitor;
2719   plugin->service = service;
2720   if (NULL != service)
2721   {
2722     plugin->server = GNUNET_SERVICE_get_server (service);
2723   }
2724   else
2725   {
2726     if (GNUNET_OK !=
2727         GNUNET_CONFIGURATION_get_value_time (env->cfg,
2728                                              "transport-tcp",
2729                                              "TIMEOUT",
2730                                              &idle_timeout))
2731     {
2732       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2733                                  "transport-tcp",
2734                                  "TIMEOUT");
2735       if (NULL != plugin->nat)
2736         GNUNET_NAT_unregister (plugin->nat);
2737       GNUNET_free(plugin);
2738       GNUNET_free(api);
2739       return NULL;
2740     }
2741     plugin->server
2742       = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check,
2743                                            plugin, NULL,
2744                                            idle_timeout, GNUNET_YES);
2745   }
2746   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2747   memcpy (plugin->handlers, my_handlers, sizeof(my_handlers));
2748   for (i = 0;i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);i++)
2749     plugin->handlers[i].callback_cls = plugin;
2750
2751   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2752   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2753   plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
2754                                                                  GNUNET_YES);
2755   if (0 != bport)
2756     LOG (GNUNET_ERROR_TYPE_INFO,
2757          _("TCP transport listening on port %llu\n"),
2758          bport);
2759   else
2760     LOG (GNUNET_ERROR_TYPE_INFO,
2761          _("TCP transport not listening on any port (client only)\n"));
2762   if ( (aport != bport) &&
2763        (0 != bport) )
2764     LOG (GNUNET_ERROR_TYPE_INFO,
2765          _("TCP transport advertises itself as being on port %llu\n"),
2766          aport);
2767   /* Initially set connections to 0 */
2768   GNUNET_assert(NULL != plugin->env->stats);
2769   GNUNET_STATISTICS_set (plugin->env->stats,
2770                          gettext_noop ("# TCP sessions active"),
2771                          0,
2772                          GNUNET_NO);
2773   return api;
2774 }
2775
2776
2777 /**
2778  * Exit point from the plugin.
2779  *
2780  * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
2781  * @return NULL
2782  */
2783 void *
2784 libgnunet_plugin_transport_tcp_done (void *cls)
2785 {
2786   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2787   struct Plugin *plugin = api->cls;
2788   struct TCPProbeContext *tcp_probe;
2789   struct PrettyPrinterContext *cur;
2790   struct PrettyPrinterContext *next;
2791
2792   if (NULL == plugin)
2793   {
2794     GNUNET_free(api);
2795     return NULL ;
2796   }
2797   LOG (GNUNET_ERROR_TYPE_DEBUG,
2798        "Shutting down TCP plugin\n");
2799
2800   /* Removing leftover sessions */
2801   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2802                                          &session_disconnect_it,
2803                                          plugin);
2804   /* Removing leftover NAT sessions */
2805   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2806                                          &session_disconnect_it,
2807                                          plugin);
2808
2809   next = ppc_dll_head;
2810   for (cur = next; NULL != cur; cur = next)
2811   {
2812     GNUNET_break (0);
2813     next = cur->next;
2814     GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
2815                                  ppc_dll_tail,
2816                                  cur);
2817     GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2818     GNUNET_free (cur);
2819   }
2820
2821   if (NULL != plugin->service)
2822     GNUNET_SERVICE_stop (plugin->service);
2823   else
2824     GNUNET_SERVER_destroy (plugin->server);
2825   GNUNET_free(plugin->handlers);
2826   if (NULL != plugin->nat)
2827     GNUNET_NAT_unregister (plugin->nat);
2828   while (NULL != (tcp_probe = plugin->probe_head))
2829   {
2830     GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2831                                  plugin->probe_tail,
2832                                  tcp_probe);
2833     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2834     GNUNET_free(tcp_probe);
2835   }
2836   GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2837   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2838   GNUNET_free(plugin);
2839   GNUNET_free(api);
2840   return NULL;
2841 }
2842
2843 /* end of plugin_transport_tcp.c */