add connection limit to TCP
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_nat_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_resolver_service.h"
33 #include "gnunet_server_lib.h"
34 #include "gnunet_service_lib.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_transport_plugin.h"
39 #include "transport.h"
40
41 #define DEBUG_TCP GNUNET_NO
42
43 #define DEBUG_TCP_NAT GNUNET_YES
44
45 /**
46  * How long until we give up on transmitting the welcome message?
47  */
48 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
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 /**
70  * Basically a WELCOME message, but with the purpose
71  * of giving the waiting peer a client handle to use
72  */
73 struct TCP_NAT_ProbeMessage
74 {
75   /**
76    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
77    */
78   struct GNUNET_MessageHeader header;
79
80   /**
81    * Identity of the sender of the message.
82    */
83   struct GNUNET_PeerIdentity clientIdentity;
84
85 };
86
87
88 /**
89  * Context for sending a NAT probe via TCP.
90  */
91 struct TCPProbeContext
92 {
93
94   /**
95    * Active probes are kept in a DLL.
96    */
97   struct TCPProbeContext *next;
98
99   /**
100    * Active probes are kept in a DLL.
101    */
102   struct TCPProbeContext *prev;
103
104   /**
105    * Probe connection.
106    */
107   struct GNUNET_CONNECTION_Handle *sock;
108
109   /**
110    * Message to be sent.
111    */
112   struct TCP_NAT_ProbeMessage message;
113
114   /**
115    * Handle to the transmission.
116    */
117   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
118
119   /**
120    * Transport plugin handle.
121    */
122   struct Plugin *plugin;
123 };
124
125
126 /**
127  * Network format for IPv4 addresses.
128  */
129 struct IPv4TcpAddress
130 {
131   /**
132    * IPv4 address, in network byte order.
133    */
134   uint32_t ipv4_addr GNUNET_PACKED;
135
136   /**
137    * Port number, in network byte order.
138    */
139   uint16_t t_port GNUNET_PACKED;
140
141 };
142
143
144 /**
145  * Network format for IPv6 addresses.
146  */
147 struct IPv6TcpAddress
148 {
149   /**
150    * IPv6 address.
151    */
152   struct in6_addr ipv6_addr GNUNET_PACKED;
153
154   /**
155    * Port number, in network byte order.
156    */
157   uint16_t t6_port GNUNET_PACKED;
158
159 };
160
161
162 /**
163  * Encapsulation of all of the state of the plugin.
164  */
165 struct Plugin;
166
167
168 /**
169  * Local network addresses (actual IP address follows this struct).
170  * PORT is NOT included!
171  */
172 struct LocalAddrList
173 {
174
175   /**
176    * This is a doubly linked list.
177    */
178   struct LocalAddrList *next;
179
180   /**
181    * This is a doubly linked list.
182    */
183   struct LocalAddrList *prev;
184
185   /**
186    * Link to plugin.
187    */
188   struct Plugin *plugin;
189
190   /**
191    * Handle to NAT holes we've tried to punch for this address.
192    */
193   struct GNUNET_NAT_Handle *nat;
194
195   /**
196    * Pointer to a 'struct IPv4/V6TcpAddress' describing our external IP and port
197    * as obtained from the NAT by automatic port mapping.
198    */
199   void *external_nat_address;
200
201   /**
202    * Number of bytes in 'external_nat_address'
203    */
204   size_t ena_size;
205
206   /**
207    * Number of bytes of the address that follow
208    */
209   size_t size;
210
211 };
212
213
214 /**
215  * Information kept for each message that is yet to
216  * be transmitted.
217  */
218 struct PendingMessage
219 {
220
221   /**
222    * This is a doubly-linked list.
223    */
224   struct PendingMessage *next;
225
226   /**
227    * This is a doubly-linked list.
228    */
229   struct PendingMessage *prev;
230
231   /**
232    * The pending message
233    */
234   const char *msg;
235
236   /**
237    * Continuation function to call once the message
238    * has been sent.  Can be NULL if there is no
239    * continuation to call.
240    */
241   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
242
243   /**
244    * Closure for transmit_cont.
245    */
246   void *transmit_cont_cls;
247
248   /**
249    * Timeout value for the pending message.
250    */
251   struct GNUNET_TIME_Absolute timeout;
252
253   /**
254    * So that the gnunet-service-transport can group messages together,
255    * these pending messages need to accept a message buffer and size
256    * instead of just a GNUNET_MessageHeader.
257    */
258   size_t message_size;
259
260 };
261
262
263 /**
264  * Session handle for TCP connections.
265  */
266 struct Session
267 {
268
269   /**
270    * API requirement.
271    */
272   struct SessionHeader header;
273
274   /**
275    * Stored in a linked list.
276    */
277   struct Session *next;
278
279   /**
280    * Pointer to the global plugin struct.
281    */
282   struct Plugin *plugin;
283
284   /**
285    * The client (used to identify this connection)
286    */
287   struct GNUNET_SERVER_Client *client;
288
289   /**
290    * Messages currently pending for transmission
291    * to this peer, if any.
292    */
293   struct PendingMessage *pending_messages_head;
294
295   /**
296    * Messages currently pending for transmission
297    * to this peer, if any.
298    */
299   struct PendingMessage *pending_messages_tail;
300
301   /**
302    * Handle for pending transmission request.
303    */
304   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
305
306   /**
307    * To whom are we talking to (set to our identity
308    * if we are still waiting for the welcome message)
309    */
310   struct GNUNET_PeerIdentity target;
311
312   /**
313    * ID of task used to delay receiving more to throttle sender.
314    */
315   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
316
317   /**
318    * Address of the other peer (either based on our 'connect'
319    * call or on our 'accept' call).
320    */
321   void *connect_addr;
322
323   /**
324    * Last activity on this connection.  Used to select preferred
325    * connection.
326    */
327   struct GNUNET_TIME_Absolute last_activity;
328
329   /**
330    * Length of connect_addr.
331    */
332   size_t connect_alen;
333
334   /**
335    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
336    */
337   int expecting_welcome;
338
339   /**
340    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
341    */
342   int inbound;
343
344   /**
345    * Was this session created using NAT traversal?
346    */
347   int is_nat;
348
349 };
350
351
352 /**
353  * Encapsulation of all of the state of the plugin.
354  */
355 struct Plugin
356 {
357   /**
358    * Our environment.
359    */
360   struct GNUNET_TRANSPORT_PluginEnvironment *env;
361
362   /**
363    * The listen socket.
364    */
365   struct GNUNET_CONNECTION_Handle *lsock;
366
367   /**
368    * stdout pipe handle for the gnunet-nat-server process
369    */
370   struct GNUNET_DISK_PipeHandle *server_stdout;
371
372   /**
373    * stdout file handle (for reading) for the gnunet-nat-server process
374    */
375   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
376
377   /**
378    * ID of select gnunet-nat-server stdout read task
379    */
380   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
381
382   /**
383    * The process id of the server process (if behind NAT)
384    */
385   struct GNUNET_OS_Process *server_proc;
386
387   /**
388    * List of open TCP sessions.
389    */
390   struct Session *sessions;
391
392   /**
393    * Handle to the network service.
394    */
395   struct GNUNET_SERVICE_Context *service;
396
397   /**
398    * Handle to the server for this service.
399    */
400   struct GNUNET_SERVER_Handle *server;
401
402   /**
403    * Copy of the handler array where the closures are
404    * set to this struct's instance.
405    */
406   struct GNUNET_SERVER_MessageHandler *handlers;
407
408   /**
409    * Handle for request of hostname resolution, non-NULL if pending.
410    */
411   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
412
413   /**
414    * Map of peers we have tried to contact behind a NAT
415    */
416   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
417
418   /**
419    * The external address given to us by the user.  Used for HELLOs
420    * and address validation.
421    */
422   char *external_address;
423
424   /**
425    * The internal address given to us by the user (or discovered).
426    * Used for NAT traversal (ICMP method), but not as a 'validateable'
427    * address in HELLOs.
428    */
429   char *internal_address;
430
431   /**
432    * Address given for us to bind to (ONLY).
433    */
434   char *bind_address;
435
436   /**
437    * use local addresses?
438    */
439   int use_localaddresses;
440
441   /**
442    * List of our IP addresses.
443    */
444   struct LocalAddrList *lal_head;
445
446   /**
447    * Tail of our IP address list.
448    */
449   struct LocalAddrList *lal_tail;
450
451   /**
452    * List of active TCP probes.
453    */
454   struct TCPProbeContext *probe_head;
455
456   /**
457    * List of active TCP probes.
458    */
459   struct TCPProbeContext *probe_tail;
460
461   /**
462    * Handle for (DYN)DNS lookup of our external IP.
463    */
464   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
465   
466   /**
467    * How many more TCP sessions are we allowed to open right now?
468    */
469   unsigned long long max_connections;
470
471   /**
472    * ID of task used to update our addresses when one expires.
473    */
474   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
475
476   /**
477    * Port that we are actually listening on.
478    */
479   uint16_t open_port;
480
481   /**
482    * Port that the user said we would have visible to the
483    * rest of the world.
484    */
485   uint16_t adv_port;
486
487   /**
488    * Is this transport configured to be behind a NAT?
489    */
490   int behind_nat;
491
492   /**
493    * Has the NAT been punched?
494    */
495   int nat_punched;
496
497   /**
498    * Is this transport configured to allow connections to NAT'd peers?
499    */
500   int enable_nat_client;
501
502   /**
503    * Should we run the gnunet-nat-server?
504    */
505   int enable_nat_server;
506
507   /**
508    * Are we allowed to try UPnP/PMP for NAT traversal?
509    */
510   int enable_upnp;
511
512 };
513
514
515 /**
516  * Function to check if an inbound connection is acceptable.
517  * Mostly used to limit the total number of open connections 
518  * we can have.
519  *
520  * @param cls the 'struct Plugin'
521  * @param ucred credentials, if available, otherwise NULL
522  * @param addr address
523  * @param addrlen length of address
524  * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
525  *   for unknown address family (will be denied).
526  */
527 static int
528 plugin_tcp_access_check (void *cls,
529                          const struct GNUNET_CONNECTION_Credentials *ucred,
530                          const struct sockaddr *addr,
531                          socklen_t addrlen)
532 {
533   struct Plugin *plugin = cls;
534
535   if (0 == plugin->max_connections)
536     return GNUNET_NO;
537   plugin->max_connections--;
538   return GNUNET_YES;
539 }
540
541
542 /**
543  * Our external IP address/port mapping has changed.
544  *
545  * @param cls closure, the 'struct LocalAddrList'
546  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
547  *     the previous (now invalid) one
548  * @param addr either the previous or the new public IP address
549  * @param addrlen actual lenght of the address
550  */
551 static void
552 nat_port_map_callback (void *cls,
553                        int add_remove,
554                        const struct sockaddr *addr,
555                        socklen_t addrlen)
556 {
557   struct LocalAddrList *lal = cls;
558   struct Plugin *plugin = lal->plugin;
559   int af;
560   struct IPv4TcpAddress t4;
561   struct IPv6TcpAddress t6;
562   void *arg;
563   uint16_t args;
564
565   /* convert 'addr' to our internal format */
566   af = addr->sa_family;
567   switch (af)
568     {
569     case AF_INET:
570       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
571       t4.t_port = ((struct sockaddr_in *) addr)->sin_port;
572       arg = &t4;
573       args = sizeof (t4);
574       break;
575     case AF_INET6:
576       memcpy (&t6.ipv6_addr,
577               &((struct sockaddr_in6 *) addr)->sin6_addr,
578               sizeof (struct in6_addr));
579       t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
580       arg = &t6;
581       args = sizeof (t6);    
582       break;
583     default:
584       GNUNET_break (0);
585       return;
586     } 
587
588   /* modify our published address list */
589   if (GNUNET_YES == add_remove)
590     {
591       plugin->env->notify_address (plugin->env->cls,
592                                    "tcp",
593                                    arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
594       GNUNET_free_non_null (lal->external_nat_address);
595       lal->external_nat_address = GNUNET_memdup (arg, args);
596       lal->ena_size = args;
597     }
598   else
599     {
600       plugin->env->notify_address (plugin->env->cls,
601                                    "tcp",
602                                    arg, args, GNUNET_TIME_UNIT_ZERO);
603       GNUNET_free_non_null (lal->external_nat_address);
604       lal->ena_size = 0;
605     }
606 }
607
608
609 /**
610  * Add the given address to the list of 'local' addresses, thereby
611  * making it a 'legal' address for this peer to have.  
612  * 
613  * @param plugin the plugin
614  * @param arg the address, either an IPv4 or an IPv6 IP address
615  * @param arg_size number of bytes in arg
616  */
617 static void
618 add_to_address_list (struct Plugin *plugin,
619                      const void *arg,
620                      size_t arg_size)
621 {
622   struct LocalAddrList *lal;
623   struct sockaddr_in v4;
624   struct sockaddr_in6 v6;
625   const struct sockaddr *sa;
626   socklen_t salen;
627
628   lal = plugin->lal_head;
629   while (NULL != lal)
630     {
631       if ( (lal->size == arg_size) &&
632            (0 == memcmp (&lal[1], arg, arg_size)) )
633         return;
634       lal = lal->next;
635     }
636   lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
637   lal->plugin = plugin;
638   lal->size = arg_size;
639   memcpy (&lal[1], arg, arg_size);
640   GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
641                                plugin->lal_tail,
642                                lal);
643   if (plugin->open_port == 0)
644     return; /* we're not listening at all... */
645   if (arg_size == sizeof (struct in_addr))
646     {
647       memset (&v4, 0, sizeof (v4));
648       v4.sin_family = AF_INET;
649       v4.sin_port = htons (plugin->open_port);
650       memcpy (&v4.sin_addr, arg, arg_size);
651 #if HAVE_SOCKADDR_IN_SIN_LEN
652       v4.sin_len = sizeof (struct sockaddr_in);
653 #endif
654       sa = (const struct sockaddr*) &v4;
655       salen = sizeof (v4);
656     }
657   else if (arg_size == sizeof (struct in6_addr))
658     {     
659       memset (&v6, 0, sizeof (v6));
660       v6.sin6_family = AF_INET6;
661       v6.sin6_port = htons (plugin->open_port);
662       memcpy (&v6.sin6_addr, arg, arg_size);
663 #if HAVE_SOCKADDR_IN_SIN_LEN
664       v6.sin6_len = sizeof (struct sockaddr_in6);
665 #endif
666       sa = (const struct sockaddr*) &v6;
667       salen = sizeof (v6);
668     }
669   else
670     {
671       GNUNET_break (0);
672       return;
673     }
674   if ( (plugin->behind_nat == GNUNET_YES) &&
675        (plugin->enable_upnp == GNUNET_YES) )
676     lal->nat = GNUNET_NAT_register (plugin->env->cfg,
677                                     sa, salen,
678                                     &nat_port_map_callback,
679                                     lal);
680 }
681
682
683 /**
684  * Check if the given address is in the list of 'local' addresses.
685  * 
686  * @param plugin the plugin
687  * @param arg the address, either an IPv4 or an IPv6 IP address
688  * @param arg_size number of bytes in arg
689  * @return GNUNET_OK if this is one of our IPs, GNUNET_SYSERR if not
690  */
691 static int
692 check_local_addr (struct Plugin *plugin,
693                   const void *arg,
694                   size_t arg_size)
695 {
696   struct LocalAddrList *lal;
697
698   lal = plugin->lal_head;
699   while (NULL != lal)
700     {
701       if ( (lal->size == arg_size) &&
702            (0 == memcmp (&lal[1], arg, arg_size)) )
703         return GNUNET_OK;
704       lal = lal->next;
705     }
706   return GNUNET_SYSERR;
707 }
708
709
710 /**
711  * Check if the given address is in the list of 'mapped' addresses.
712  * 
713  * @param plugin the plugin
714  * @param arg the address, either a 'struct IPv4TcpAddress' or a 'struct IPv6TcpAddress'
715  * @param arg_size number of bytes in arg
716  * @return GNUNET_OK if this is one of our IPs, GNUNET_SYSERR if not
717  */
718 static int
719 check_mapped_addr (struct Plugin *plugin,
720                    const void *arg,
721                    size_t arg_size)
722 {
723   struct LocalAddrList *lal;
724
725   lal = plugin->lal_head;
726   while (NULL != lal)
727     {
728       if ( (lal->ena_size == arg_size) &&
729            (0 == memcmp (lal->external_nat_address, arg, arg_size)) )
730         return GNUNET_OK;
731       lal = lal->next;
732     }
733   return GNUNET_SYSERR;
734 }
735
736
737 /**
738  * Function called for a quick conversion of the binary address to
739  * a numeric address.  Note that the caller must not free the
740  * address and that the next call to this function is allowed
741  * to override the address again.
742  *
743  * @param cls closure ('struct Plugin*')
744  * @param addr binary address
745  * @param addrlen length of the address
746  * @return string representing the same address
747  */
748 static const char*
749 tcp_address_to_string (void *cls,
750                        const void *addr,
751                        size_t addrlen)
752 {
753   static char rbuf[INET6_ADDRSTRLEN + 12];
754   char buf[INET6_ADDRSTRLEN];
755   const void *sb;
756   struct in_addr a4;
757   struct in6_addr a6;
758   const struct IPv4TcpAddress *t4;
759   const struct IPv6TcpAddress *t6;
760   int af;
761   uint16_t port;
762
763   if (addrlen == sizeof (struct IPv6TcpAddress))
764     {
765       t6 = addr;
766       af = AF_INET6;
767       port = ntohs (t6->t6_port);
768       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
769       sb = &a6;
770     }
771   else if (addrlen == sizeof (struct IPv4TcpAddress))
772     {
773       t4 = addr;
774       af = AF_INET;
775       port = ntohs (t4->t_port);
776       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
777       sb = &a4;
778     }
779   else
780     {
781       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
782                        "tcp",
783                        _("Unexpected address length: %u bytes\n"),
784                        (unsigned int) addrlen);
785       GNUNET_break (0);
786       return NULL;
787     }
788   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
789     {
790       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
791       return NULL;
792     }
793   GNUNET_snprintf (rbuf,
794                    sizeof (rbuf),
795                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
796                    buf,
797                    port);
798   return rbuf;
799 }
800
801
802 /**
803  * Find the session handle for the given client.
804  *
805  * @param plugin the plugin
806  * @param client which client to find the session handle for
807  * @return NULL if no matching session exists
808  */
809 static struct Session *
810 find_session_by_client (struct Plugin *plugin,
811                         const struct GNUNET_SERVER_Client *client)
812 {
813   struct Session *ret;
814
815   ret = plugin->sessions;
816   while ((ret != NULL) && (client != ret->client))
817     ret = ret->next;
818   return ret;
819 }
820
821
822 /**
823  * Create a new session.  Also queues a welcome message.
824  *
825  * @param plugin the plugin
826  * @param target peer to connect to
827  * @param client client to use
828  * @param is_nat this a NAT session, we should wait for a client to
829  *               connect to us from an address, then assign that to
830  *               the session
831  * @return new session object
832  */
833 static struct Session *
834 create_session (struct Plugin *plugin,
835                 const struct GNUNET_PeerIdentity *target,
836                 struct GNUNET_SERVER_Client *client, 
837                 int is_nat)
838 {
839   struct Session *ret;
840   struct PendingMessage *pm;
841   struct WelcomeMessage welcome;
842
843   if (is_nat != GNUNET_YES)
844     GNUNET_assert (client != NULL);
845   else
846     GNUNET_assert (client == NULL);
847 #if DEBUG_TCP
848   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
849                    "tcp",
850                    "Creating new session for peer `%4s'\n",
851                    GNUNET_i2s (target));
852 #endif
853   ret = GNUNET_malloc (sizeof (struct Session));
854   ret->last_activity = GNUNET_TIME_absolute_get ();
855   ret->plugin = plugin;
856   ret->is_nat = is_nat;
857   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
858     {
859       ret->next = plugin->sessions;
860       plugin->sessions = ret;
861     }
862   ret->client = client;
863   ret->target = *target;
864   ret->expecting_welcome = GNUNET_YES;
865   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
866   pm->msg = (const char*) &pm[1];
867   pm->message_size = sizeof (struct WelcomeMessage);
868   welcome.header.size = htons (sizeof (struct WelcomeMessage));
869   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
870   welcome.clientIdentity = *plugin->env->my_identity;
871   memcpy (&pm[1], &welcome, sizeof (welcome));
872   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
873   GNUNET_STATISTICS_update (plugin->env->stats,
874                             gettext_noop ("# bytes currently in TCP buffers"),
875                             pm->message_size,
876                             GNUNET_NO);
877   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
878                                ret->pending_messages_tail,
879                                pm);
880   if (is_nat != GNUNET_YES)
881     GNUNET_STATISTICS_update (plugin->env->stats,
882                               gettext_noop ("# TCP sessions active"),
883                               1,
884                               GNUNET_NO);
885   return ret;
886 }
887
888
889 /**
890  * If we have pending messages, ask the server to
891  * transmit them (schedule the respective tasks, etc.)
892  *
893  * @param session for which session should we do this
894  */
895 static void process_pending_messages (struct Session *session);
896
897
898 /**
899  * Function called to notify a client about the socket
900  * being ready to queue more data.  "buf" will be
901  * NULL and "size" zero if the socket was closed for
902  * writing in the meantime.
903  *
904  * @param cls closure
905  * @param size number of bytes available in buf
906  * @param buf where the callee should write the message
907  * @return number of bytes written to buf
908  */
909 static size_t
910 do_transmit (void *cls, size_t size, void *buf)
911 {
912   struct Session *session = cls;
913   struct GNUNET_PeerIdentity pid;
914   struct Plugin *plugin;
915   struct PendingMessage *pos;
916   struct PendingMessage *hd;
917   struct PendingMessage *tl;
918   struct GNUNET_TIME_Absolute now;
919   char *cbuf;
920   size_t ret;
921
922   session->transmit_handle = NULL;
923   plugin = session->plugin;
924   if (buf == NULL)
925     {
926 #if DEBUG_TCP
927       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
928                        "tcp",
929                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
930                        GNUNET_i2s (&session->target));
931 #endif
932       /* timeout; cancel all messages that have already expired */
933       hd = NULL;
934       tl = NULL;
935       ret = 0;
936       now = GNUNET_TIME_absolute_get ();
937       while ( (NULL != (pos = session->pending_messages_head)) &&
938               (pos->timeout.abs_value <= now.abs_value) )
939         {
940           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
941                                        session->pending_messages_tail,
942                                        pos);
943 #if DEBUG_TCP
944           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
945                            "tcp",
946                            "Failed to transmit %u byte message to `%4s'.\n",
947                            pos->message_size,
948                            GNUNET_i2s (&session->target));
949 #endif
950           ret += pos->message_size;
951           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
952         }
953       /* do this call before callbacks (so that if callbacks destroy
954          session, they have a chance to cancel actions done by this
955          call) */
956       process_pending_messages (session);
957       pid = session->target;
958       /* no do callbacks and do not use session again since
959          the callbacks may abort the session */
960       while (NULL != (pos = hd))
961         {
962           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
963           if (pos->transmit_cont != NULL)
964             pos->transmit_cont (pos->transmit_cont_cls,
965                                 &pid, GNUNET_SYSERR);
966           GNUNET_free (pos);
967         }
968       GNUNET_STATISTICS_update (plugin->env->stats,
969                                 gettext_noop ("# bytes currently in TCP buffers"),
970                                 - (int64_t) ret,
971                                 GNUNET_NO);
972       GNUNET_STATISTICS_update (plugin->env->stats,
973                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
974                                 ret,
975                                 GNUNET_NO);
976       return 0;
977     }
978   /* copy all pending messages that would fit */
979   ret = 0;
980   cbuf = buf;
981   hd = NULL;
982   tl = NULL;
983   while (NULL != (pos = session->pending_messages_head))
984     {
985       if (ret + pos->message_size > size)
986         break;
987       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
988                                    session->pending_messages_tail,
989                                    pos);
990       GNUNET_assert (size >= pos->message_size);
991       /* FIXME: this memcpy can be up to 7% of our total runtime */
992       memcpy (cbuf, pos->msg, pos->message_size);
993       cbuf += pos->message_size;
994       ret += pos->message_size;
995       size -= pos->message_size;
996       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
997     }
998   /* schedule 'continuation' before callbacks so that callbacks that
999      cancel everything don't cause us to use a session that no longer
1000      exists... */
1001   process_pending_messages (session);
1002   session->last_activity = GNUNET_TIME_absolute_get ();
1003   pid = session->target;
1004   /* we'll now call callbacks that may cancel the session; hence
1005      we should not use 'session' after this point */
1006   while (NULL != (pos = hd))
1007     {
1008       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1009       if (pos->transmit_cont != NULL)
1010         pos->transmit_cont (pos->transmit_cont_cls,
1011                             &pid, GNUNET_OK);
1012       GNUNET_free (pos);
1013     }
1014   GNUNET_assert (hd == NULL);
1015   GNUNET_assert (tl == NULL);
1016 #if DEBUG_TCP > 1
1017   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1018                    "tcp",
1019                    "Transmitting %u bytes\n", 
1020                    ret);
1021 #endif
1022   GNUNET_STATISTICS_update (plugin->env->stats,
1023                             gettext_noop ("# bytes currently in TCP buffers"),
1024                             - (int64_t) ret,
1025                             GNUNET_NO);
1026   GNUNET_STATISTICS_update (plugin->env->stats,
1027                             gettext_noop ("# bytes transmitted via TCP"),
1028                             ret,
1029                             GNUNET_NO);
1030   return ret;
1031 }
1032
1033
1034 /**
1035  * If we have pending messages, ask the server to
1036  * transmit them (schedule the respective tasks, etc.)
1037  *
1038  * @param session for which session should we do this
1039  */
1040 static void
1041 process_pending_messages (struct Session *session)
1042 {
1043   struct PendingMessage *pm;
1044
1045   GNUNET_assert (session->client != NULL);
1046   if (session->transmit_handle != NULL)
1047     return;
1048   if (NULL == (pm = session->pending_messages_head))
1049     return;
1050
1051   session->transmit_handle
1052     = GNUNET_SERVER_notify_transmit_ready (session->client,
1053                                            pm->message_size,
1054                                            GNUNET_TIME_absolute_get_remaining
1055                                            (pm->timeout),
1056                                            &do_transmit, session);
1057 }
1058
1059
1060 /**
1061  * Functions with this signature are called whenever we need
1062  * to close a session due to a disconnect or failure to
1063  * establish a connection.
1064  *
1065  * @param session session to close down
1066  */
1067 static void
1068 disconnect_session (struct Session *session)
1069 {
1070   struct Session *prev;
1071   struct Session *pos;
1072   struct PendingMessage *pm;
1073
1074 #if DEBUG_TCP
1075   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1076                    "tcp",
1077                    "Disconnecting from `%4s' at %s.\n",
1078                    GNUNET_i2s (&session->target),
1079                    (session->connect_addr != NULL) ?
1080                    tcp_address_to_string (session->plugin,
1081                                           session->connect_addr,
1082                                           session->connect_alen) : "*");
1083 #endif
1084   /* remove from session list */
1085   prev = NULL;
1086   pos = session->plugin->sessions;
1087   while (pos != session)
1088     {
1089       prev = pos;
1090       pos = pos->next;
1091     }
1092   if (prev == NULL)
1093     session->plugin->sessions = session->next;
1094   else
1095     prev->next = session->next;
1096
1097   /* clean up state */
1098   if (session->transmit_handle != NULL)
1099     {
1100       GNUNET_CONNECTION_notify_transmit_ready_cancel
1101         (session->transmit_handle);
1102       session->transmit_handle = NULL;
1103     }
1104   while (NULL != (pm = session->pending_messages_head))
1105     {
1106 #if DEBUG_TCP
1107       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1108                        "tcp",
1109                        pm->transmit_cont != NULL
1110                        ? "Could not deliver message to `%4s'.\n"
1111                        : "Could not deliver message to `%4s', notifying.\n",
1112                        GNUNET_i2s (&session->target));
1113 #endif
1114       GNUNET_STATISTICS_update (session->plugin->env->stats,
1115                                 gettext_noop ("# bytes currently in TCP buffers"),
1116                                 - (int64_t) pm->message_size,
1117                                 GNUNET_NO);
1118       GNUNET_STATISTICS_update (session->plugin->env->stats,
1119                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
1120                                 pm->message_size,
1121                                 GNUNET_NO);
1122       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1123                                    session->pending_messages_tail,
1124                                    pm);
1125       if (NULL != pm->transmit_cont)
1126         pm->transmit_cont (pm->transmit_cont_cls,
1127                            &session->target, GNUNET_SYSERR);
1128       GNUNET_free (pm);
1129     }
1130   GNUNET_break (session->client != NULL);
1131   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
1132     {
1133       GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1134       if (session->client != NULL)
1135         GNUNET_SERVER_receive_done (session->client,
1136                                     GNUNET_SYSERR);     
1137     }
1138   else if (session->client != NULL)
1139     GNUNET_SERVER_client_drop (session->client);
1140   GNUNET_STATISTICS_update (session->plugin->env->stats,
1141                             gettext_noop ("# TCP sessions active"),
1142                             -1,
1143                             GNUNET_NO);
1144   GNUNET_free_non_null (session->connect_addr);
1145
1146   session->plugin->env->session_end (session->plugin->env->cls,
1147                                      &session->target,
1148                                      session);
1149
1150   GNUNET_free (session);
1151 }
1152
1153
1154 /**
1155  * Given two otherwise equivalent sessions, pick the better one.
1156  *
1157  * @param s1 one session (also default)
1158  * @param s2 other session
1159  * @return "better" session (more active)
1160  */
1161 static struct Session *
1162 select_better_session (struct Session *s1,
1163                        struct Session *s2)
1164 {
1165   if (s1 == NULL)
1166     return s2;
1167   if (s2 == NULL)
1168     return s1;
1169   if ( (s1->expecting_welcome == GNUNET_NO) &&
1170        (s2->expecting_welcome == GNUNET_YES) )
1171     return s1;
1172   if ( (s1->expecting_welcome == GNUNET_YES) &&
1173        (s2->expecting_welcome == GNUNET_NO) )
1174     return s2;
1175   if (s1->last_activity.abs_value < s2->last_activity.abs_value)
1176     return s2;
1177   if (s1->last_activity.abs_value > s2->last_activity.abs_value)
1178     return s1;
1179   if ( (GNUNET_YES == s1->inbound) &&
1180        (GNUNET_NO  == s2->inbound) )
1181     return s1;
1182   if ( (GNUNET_NO  == s1->inbound) &&
1183        (GNUNET_YES == s2->inbound) )
1184     return s2;
1185   return s1;
1186 }
1187
1188
1189 /**
1190  * We learned about a peer (possibly behind NAT) so run the
1191  * gnunet-nat-client to send dummy ICMP responses.
1192  *
1193  * @param plugin the plugin for this transport
1194  * @param sa the address of the peer (IPv4-only)
1195  */
1196 static void
1197 run_gnunet_nat_client (struct Plugin *plugin, 
1198                        const struct sockaddr_in *sa)
1199 {
1200   char inet4[INET_ADDRSTRLEN];
1201   char port_as_string[6];
1202   struct GNUNET_OS_Process *proc;
1203
1204   if (plugin->internal_address == NULL)
1205     {
1206       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1207                        "tcp",
1208                        _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1209       return;
1210     }
1211   GNUNET_assert (sa->sin_family == AF_INET);
1212   if (NULL == inet_ntop (AF_INET,
1213                          &sa->sin_addr,
1214                          inet4, INET_ADDRSTRLEN))
1215     {
1216       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
1217       return;
1218     }
1219   GNUNET_snprintf(port_as_string, 
1220                   sizeof (port_as_string),
1221                   "%d", 
1222                   plugin->adv_port);
1223 #if DEBUG_TCP_NAT
1224   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1225                    "tcp",
1226                    _("Running gnunet-nat-client %s %s %u\n"), 
1227                    plugin->internal_address,
1228                    inet4,
1229                    (unsigned int) plugin->adv_port);
1230 #endif
1231   proc = GNUNET_OS_start_process (NULL, 
1232                                   NULL, 
1233                                   "gnunet-nat-client",
1234                                   "gnunet-nat-client",
1235                                   plugin->internal_address, 
1236                                   inet4,
1237                                   port_as_string, 
1238                                   NULL);
1239   if (NULL == proc)
1240     return;
1241   /* we know that the gnunet-nat-client will terminate virtually
1242      instantly */
1243   GNUNET_OS_process_wait (proc);
1244   GNUNET_OS_process_close (proc);
1245 }
1246
1247
1248 /**
1249  * Function that can be used by the transport service to transmit
1250  * a message using the plugin.   Note that in the case of a
1251  * peer disconnecting, the continuation MUST be called
1252  * prior to the disconnect notification itself.  This function
1253  * will be called with this peer's HELLO message to initiate
1254  * a fresh connection to another peer.
1255  *
1256  * @param cls closure
1257  * @param target who should receive this message
1258  * @param msg the message to transmit
1259  * @param msgbuf_size number of bytes in 'msg'
1260  * @param priority how important is the message (most plugins will
1261  *                 ignore message priority and just FIFO)
1262  * @param timeout how long to wait at most for the transmission (does not
1263  *                require plugins to discard the message after the timeout,
1264  *                just advisory for the desired delay; most plugins will ignore
1265  *                this as well)
1266  * @param session which session must be used (or NULL for "any")
1267  * @param addr the address to use (can be NULL if the plugin
1268  *                is "on its own" (i.e. re-use existing TCP connection))
1269  * @param addrlen length of the address in bytes
1270  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1271  *                GNUNET_NO means the plugin may use any other address and
1272  *                GNUNET_SYSERR means that only reliable existing
1273  *                bi-directional connections should be used (regardless
1274  *                of address)
1275  * @param cont continuation to call once the message has
1276  *        been transmitted (or if the transport is ready
1277  *        for the next transmission call; or if the
1278  *        peer disconnected...); can be NULL
1279  * @param cont_cls closure for cont
1280  * @return number of bytes used (on the physical network, with overheads);
1281  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1282  *         and does NOT mean that the message was not transmitted (DV and NAT)
1283  */
1284 static ssize_t
1285 tcp_plugin_send (void *cls,
1286                  const struct GNUNET_PeerIdentity *target,
1287                  const char *msg,
1288                  size_t msgbuf_size,
1289                  uint32_t priority,
1290                  struct GNUNET_TIME_Relative timeout,
1291                  struct Session *session,
1292                  const void *addr,
1293                  size_t addrlen,
1294                  int force_address,
1295                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1296 {
1297   struct Plugin *plugin = cls;
1298   struct Session *cand_session;
1299   struct Session *next;
1300   struct PendingMessage *pm;
1301   struct GNUNET_CONNECTION_Handle *sa;
1302   int af;
1303   const void *sb;
1304   size_t sbs;
1305   struct sockaddr_in a4;
1306   struct sockaddr_in6 a6;
1307   const struct IPv4TcpAddress *t4;
1308   const struct IPv6TcpAddress *t6;
1309   unsigned int is_natd;
1310
1311   GNUNET_STATISTICS_update (plugin->env->stats,
1312                             gettext_noop ("# bytes TCP was asked to transmit"),
1313                             msgbuf_size,
1314                             GNUNET_NO);
1315   /* FIXME: we could do this cheaper with a hash table
1316      where we could restrict the iteration to entries that match
1317      the target peer... */
1318   is_natd = GNUNET_NO;
1319   if (session == NULL)
1320     {
1321       cand_session = NULL;
1322       next = plugin->sessions;
1323       while (NULL != (session = next))
1324         {
1325           next = session->next;
1326           GNUNET_assert (session->client != NULL);
1327           if (0 != memcmp (target,
1328                            &session->target,
1329                            sizeof (struct GNUNET_PeerIdentity)))
1330             continue;
1331           if ( ( (GNUNET_SYSERR == force_address) &&
1332                  (session->expecting_welcome == GNUNET_NO) ) ||
1333                (GNUNET_NO == force_address) )
1334             {
1335               cand_session = select_better_session (cand_session,
1336                                                     session);
1337               continue;
1338             }
1339           if (GNUNET_SYSERR == force_address)
1340             continue;
1341           GNUNET_break (GNUNET_YES == force_address);
1342           if (addr == NULL)
1343             {
1344               GNUNET_break (0);
1345               break;
1346             }
1347           if ( (addrlen != session->connect_alen) && 
1348                (session->is_nat == GNUNET_NO) )
1349             continue;
1350           if ((0 != memcmp (session->connect_addr,
1351                            addr,
1352                            addrlen)) && (session->is_nat == GNUNET_NO))
1353             continue;
1354           cand_session = select_better_session (cand_session,
1355                                                 session);       
1356         }
1357       session = cand_session;
1358     }
1359   if ( (session == NULL) &&
1360        (addr == NULL) )
1361     {
1362 #if DEBUG_TCP
1363       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1364                        "tcp",
1365                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1366                        GNUNET_i2s (target));
1367 #endif
1368       GNUNET_STATISTICS_update (plugin->env->stats,
1369                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1370                                 msgbuf_size,
1371                                 GNUNET_NO);
1372       return -1;
1373     }
1374   if (session == NULL)
1375     {
1376       if (addrlen == sizeof (struct IPv6TcpAddress))
1377         {
1378           t6 = addr;
1379           af = AF_INET6;
1380           memset (&a6, 0, sizeof (a6));
1381 #if HAVE_SOCKADDR_IN_SIN_LEN
1382           a6.sin6_len = sizeof (a6);
1383 #endif
1384           a6.sin6_family = AF_INET6;
1385           a6.sin6_port = t6->t6_port;
1386           if (t6->t6_port == 0)
1387             is_natd = GNUNET_YES;
1388           memcpy (&a6.sin6_addr,
1389                   &t6->ipv6_addr,
1390                   sizeof (struct in6_addr));
1391           sb = &a6;
1392           sbs = sizeof (a6);
1393         }
1394       else if (addrlen == sizeof (struct IPv4TcpAddress))
1395         {
1396           t4 = addr;
1397           af = AF_INET;
1398           memset (&a4, 0, sizeof (a4));
1399 #if HAVE_SOCKADDR_IN_SIN_LEN
1400           a4.sin_len = sizeof (a4);
1401 #endif
1402           a4.sin_family = AF_INET;
1403           a4.sin_port = t4->t_port;
1404           if (t4->t_port == 0)
1405             is_natd = GNUNET_YES;
1406           a4.sin_addr.s_addr = t4->ipv4_addr;
1407           sb = &a4;
1408           sbs = sizeof (a4);
1409         }
1410       else
1411         {
1412           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1413                            "tcp",
1414                            _("Address of unexpected length: %u\n"),
1415                            addrlen);
1416           GNUNET_break (0);
1417           return -1;
1418         }
1419
1420       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1421         return -1; /* NAT client only works with IPv4 addresses */
1422       if (0 == plugin->max_connections)
1423         return -1; /* saturated */
1424
1425       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1426            (is_natd == GNUNET_YES) &&
1427            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns,
1428                                                                 &target->hashPubKey)) )
1429         {
1430 #if DEBUG_TCP_NAT
1431           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1432                            "tcp",
1433                            _("Found valid IPv4 NAT address (creating session)!\n"));
1434 #endif
1435           session = create_session (plugin,
1436                                     target,
1437                                     NULL, 
1438                                     GNUNET_YES);
1439
1440           /* create new message entry */
1441           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1442           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1443           pm->msg = (const char*) &pm[1];
1444           memcpy (&pm[1], msg, msgbuf_size);
1445           /* FIXME: this memcpy can be up to 7% of our total run-time
1446              (for transport service) */
1447           pm->message_size = msgbuf_size;
1448           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1449           pm->transmit_cont = cont;
1450           pm->transmit_cont_cls = cont_cls;
1451
1452           /* append pm to pending_messages list */
1453           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1454                                              session->pending_messages_tail,
1455                                              session->pending_messages_tail,
1456                                              pm);
1457
1458           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns,
1459                                                           &target->hashPubKey,
1460                                                           session, 
1461                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1462 #if DEBUG_TCP_NAT
1463           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1464                            "tcp",
1465                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1466                            GNUNET_i2s (target),
1467                            GNUNET_a2s (sb, sbs));
1468 #endif
1469           run_gnunet_nat_client (plugin, &a4);
1470           return 0;
1471         }
1472       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1473            (is_natd == GNUNET_YES) && 
1474            (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, 
1475                                                                  &target->hashPubKey)) )
1476         {
1477           /* Only do one NAT punch attempt per peer identity */
1478           return -1;
1479         }
1480       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1481       if (sa == NULL)
1482         {
1483 #if DEBUG_TCP
1484           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1485                            "tcp",
1486                            "Failed to create connection to `%4s' at `%s'\n",
1487                            GNUNET_i2s (target),
1488                            GNUNET_a2s (sb, sbs));
1489 #endif
1490           GNUNET_STATISTICS_update (plugin->env->stats,
1491                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1492                                     msgbuf_size,
1493                                     GNUNET_NO);
1494           return -1;
1495         }
1496       GNUNET_assert (0 != plugin->max_connections);
1497       plugin->max_connections--;
1498 #if DEBUG_TCP_NAT
1499       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1500                        "tcp",
1501                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1502                        GNUNET_i2s (target),
1503                        GNUNET_a2s (sb, sbs));
1504 #endif
1505       session = create_session (plugin,
1506                                 target,
1507                                 GNUNET_SERVER_connect_socket (plugin->server,
1508                                                               sa), 
1509                                 GNUNET_NO);
1510       session->connect_addr = GNUNET_malloc (addrlen);
1511       memcpy (session->connect_addr,
1512               addr,
1513               addrlen);
1514       session->connect_alen = addrlen;
1515     }
1516   GNUNET_assert (session != NULL);
1517   GNUNET_assert (session->client != NULL);
1518   GNUNET_STATISTICS_update (plugin->env->stats,
1519                             gettext_noop ("# bytes currently in TCP buffers"),
1520                             msgbuf_size,
1521                             GNUNET_NO);
1522   /* create new message entry */
1523   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1524   pm->msg = (const char*) &pm[1];
1525   memcpy (&pm[1], msg, msgbuf_size);
1526   pm->message_size = msgbuf_size;
1527   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1528   pm->transmit_cont = cont;
1529   pm->transmit_cont_cls = cont_cls;
1530
1531   /* append pm to pending_messages list */
1532   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1533                                      session->pending_messages_tail,
1534                                      session->pending_messages_tail,
1535                                      pm);
1536 #if DEBUG_TCP
1537   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1538                    "tcp",
1539                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1540                    msgbuf_size,
1541                    GNUNET_i2s (target));
1542 #endif
1543   process_pending_messages (session);
1544   return msgbuf_size;
1545 }
1546
1547
1548 /**
1549  * Function that can be called to force a disconnect from the
1550  * specified neighbour.  This should also cancel all previously
1551  * scheduled transmissions.  Obviously the transmission may have been
1552  * partially completed already, which is OK.  The plugin is supposed
1553  * to close the connection (if applicable) and no longer call the
1554  * transmit continuation(s).
1555  *
1556  * Finally, plugin MUST NOT call the services's receive function to
1557  * notify the service that the connection to the specified target was
1558  * closed after a getting this call.
1559  *
1560  * @param cls closure
1561  * @param target peer for which the last transmission is
1562  *        to be cancelled
1563  */
1564 static void
1565 tcp_plugin_disconnect (void *cls,
1566                        const struct GNUNET_PeerIdentity *target)
1567 {
1568   struct Plugin *plugin = cls;
1569   struct Session *session;
1570   struct Session *next;
1571   struct PendingMessage *pm;
1572
1573 #if DEBUG_TCP
1574   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1575                    "tcp",
1576                    "Asked to cancel session with `%4s'\n",
1577                    GNUNET_i2s (target));
1578 #endif
1579   next = plugin->sessions;
1580   while (NULL != (session = next))
1581     {
1582       next = session->next;
1583       if (0 != memcmp (target,
1584                        &session->target,
1585                        sizeof (struct GNUNET_PeerIdentity)))
1586         continue;
1587       pm = session->pending_messages_head;
1588       while (pm != NULL)
1589         {
1590           pm->transmit_cont = NULL;
1591           pm->transmit_cont_cls = NULL;
1592           pm = pm->next;
1593         }
1594       GNUNET_STATISTICS_update (session->plugin->env->stats,
1595                                 gettext_noop ("# transport-service disconnect requests for TCP"),
1596                                 1,
1597                                 GNUNET_NO);
1598       disconnect_session (session);
1599     }
1600 }
1601
1602
1603 /**
1604  * Context for address to string conversion.
1605  */
1606 struct PrettyPrinterContext
1607 {
1608   /**
1609    * Function to call with the result.
1610    */
1611   GNUNET_TRANSPORT_AddressStringCallback asc;
1612
1613   /**
1614    * Clsoure for 'asc'.
1615    */
1616   void *asc_cls;
1617
1618   /**
1619    * Port to add after the IP address.
1620    */
1621   uint16_t port;
1622 };
1623
1624
1625 /**
1626  * Append our port and forward the result.
1627  *
1628  * @param cls the 'struct PrettyPrinterContext*'
1629  * @param hostname hostname part of the address
1630  */
1631 static void
1632 append_port (void *cls, const char *hostname)
1633 {
1634   struct PrettyPrinterContext *ppc = cls;
1635   char *ret;
1636
1637   if (hostname == NULL)
1638     {
1639       ppc->asc (ppc->asc_cls, NULL);
1640       GNUNET_free (ppc);
1641       return;
1642     }
1643   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1644   ppc->asc (ppc->asc_cls, ret);
1645   GNUNET_free (ret);
1646 }
1647
1648
1649 /**
1650  * Convert the transports address to a nice, human-readable
1651  * format.
1652  *
1653  * @param cls closure
1654  * @param type name of the transport that generated the address
1655  * @param addr one of the addresses of the host, NULL for the last address
1656  *        the specific address format depends on the transport
1657  * @param addrlen length of the address
1658  * @param numeric should (IP) addresses be displayed in numeric form?
1659  * @param timeout after how long should we give up?
1660  * @param asc function to call on each string
1661  * @param asc_cls closure for asc
1662  */
1663 static void
1664 tcp_plugin_address_pretty_printer (void *cls,
1665                                    const char *type,
1666                                    const void *addr,
1667                                    size_t addrlen,
1668                                    int numeric,
1669                                    struct GNUNET_TIME_Relative timeout,
1670                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1671                                    void *asc_cls)
1672 {
1673   struct Plugin *plugin = cls;
1674   struct PrettyPrinterContext *ppc;
1675   const void *sb;
1676   size_t sbs;
1677   struct sockaddr_in a4;
1678   struct sockaddr_in6 a6;
1679   const struct IPv4TcpAddress *t4;
1680   const struct IPv6TcpAddress *t6;
1681   uint16_t port;
1682
1683   if (addrlen == sizeof (struct IPv6TcpAddress))
1684     {
1685       t6 = addr;
1686       memset (&a6, 0, sizeof (a6));
1687       a6.sin6_family = AF_INET6;
1688       a6.sin6_port = t6->t6_port;
1689       memcpy (&a6.sin6_addr,
1690               &t6->ipv6_addr,
1691               sizeof (struct in6_addr));
1692       port = ntohs (t6->t6_port);
1693       sb = &a6;
1694       sbs = sizeof (a6);
1695     }
1696   else if (addrlen == sizeof (struct IPv4TcpAddress))
1697     {
1698       t4 = addr;
1699       memset (&a4, 0, sizeof (a4));
1700       a4.sin_family = AF_INET;
1701       a4.sin_port = t4->t_port;
1702       a4.sin_addr.s_addr = t4->ipv4_addr;
1703       port = ntohs (t4->t_port);
1704       sb = &a4;
1705       sbs = sizeof (a4);
1706     }
1707   else
1708     {
1709       /* invalid address */
1710       GNUNET_break_op (0);
1711       asc (asc_cls, NULL);
1712       return;
1713     }
1714   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1715   ppc->asc = asc;
1716   ppc->asc_cls = asc_cls;
1717   ppc->port = port;
1718   GNUNET_RESOLVER_hostname_get (plugin->env->cfg,
1719                                 sb,
1720                                 sbs,
1721                                 !numeric, timeout, &append_port, ppc);
1722 }
1723
1724
1725 /**
1726  * Check if the given port is plausible (must be either our listen
1727  * port or our advertised port), or any port if we are behind NAT
1728  * and do not have a port open.  If it is neither, we return
1729  * GNUNET_SYSERR.
1730  *
1731  * @param plugin global variables
1732  * @param in_port port number to check
1733  * @return GNUNET_OK if port is either open_port or adv_port
1734  */
1735 static int
1736 check_port (struct Plugin *plugin, 
1737             uint16_t in_port)
1738 {
1739   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1740     return GNUNET_OK;
1741   return GNUNET_SYSERR;
1742 }
1743
1744
1745 /**
1746  * Function that will be called to check if a binary address for this
1747  * plugin is well-formed and corresponds to an address for THIS peer
1748  * (as per our configuration).  Naturally, if absolutely necessary,
1749  * plugins can be a bit conservative in their answer, but in general
1750  * plugins should make sure that the address does not redirect
1751  * traffic to a 3rd party that might try to man-in-the-middle our
1752  * traffic.
1753  *
1754  * @param cls closure, our 'struct Plugin*'
1755  * @param addr pointer to the address
1756  * @param addrlen length of addr
1757  * @return GNUNET_OK if this is a plausible address for this peer
1758  *         and transport, GNUNET_SYSERR if not
1759  */
1760 static int
1761 tcp_plugin_check_address (void *cls,
1762                           const void *addr,
1763                           size_t addrlen)
1764 {
1765   struct Plugin *plugin = cls;
1766   struct IPv4TcpAddress *v4;
1767   struct IPv6TcpAddress *v6;
1768
1769   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1770       (addrlen != sizeof (struct IPv6TcpAddress)))
1771     {
1772       GNUNET_break_op (0);
1773       return GNUNET_SYSERR;
1774     }
1775   if (addrlen == sizeof (struct IPv4TcpAddress))
1776     {
1777       v4 = (struct IPv4TcpAddress *) addr;
1778       if (GNUNET_OK ==
1779           check_mapped_addr (plugin, v4, sizeof (struct IPv4TcpAddress)))
1780         return GNUNET_OK;
1781       if (GNUNET_OK !=
1782           check_port (plugin, ntohs (v4->t_port)))
1783         return GNUNET_SYSERR;
1784       if (GNUNET_OK !=
1785           check_local_addr (plugin, &v4->ipv4_addr, sizeof (struct in_addr)))
1786         return GNUNET_SYSERR;   
1787     }
1788   else
1789     {
1790       v6 = (struct IPv6TcpAddress *) addr;
1791       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1792         {
1793           GNUNET_break_op (0);
1794           return GNUNET_SYSERR;
1795         }
1796       if (GNUNET_OK ==
1797           check_mapped_addr (plugin, v6, sizeof (struct IPv6TcpAddress)))
1798         return GNUNET_OK;
1799       if (GNUNET_OK !=
1800           check_port (plugin, ntohs (v6->t6_port)))
1801         return GNUNET_SYSERR;
1802       if (GNUNET_OK !=
1803           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1804         return GNUNET_SYSERR;
1805     }
1806   return GNUNET_OK;
1807 }
1808
1809
1810 /**
1811  * We've received a nat probe from this peer via TCP.  Finish
1812  * creating the client session and resume sending of queued
1813  * messages.
1814  *
1815  * @param cls closure
1816  * @param client identification of the client
1817  * @param message the actual message
1818  */
1819 static void
1820 handle_tcp_nat_probe (void *cls,
1821                       struct GNUNET_SERVER_Client *client,
1822                       const struct GNUNET_MessageHeader *message)
1823 {
1824   struct Plugin *plugin = cls;
1825   struct Session *session;
1826   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1827   size_t alen;
1828   void *vaddr;
1829   struct IPv4TcpAddress *t4;
1830   struct IPv6TcpAddress *t6;
1831   const struct sockaddr_in *s4;
1832   const struct sockaddr_in6 *s6;
1833
1834 #if DEBUG_TCP_NAT
1835   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1836                    "tcp",
1837                    "received NAT probe\n");
1838 #endif
1839   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1840    * a connection to this peer by running gnunet-nat-client.  This peer
1841    * received the punch message and now wants us to use the new connection
1842    * as the default for that peer.  Do so and then send a WELCOME message
1843    * so we can really be connected!
1844    */
1845   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1846     {
1847       GNUNET_break_op(0);
1848       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1849       return;
1850     }
1851
1852   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *)message;
1853
1854   if (0 == memcmp (&tcp_nat_probe->clientIdentity,
1855                    plugin->env->my_identity,
1856                    sizeof (struct GNUNET_PeerIdentity)))
1857     {
1858       /* refuse connections from ourselves */
1859       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1860       return;
1861     }
1862
1863   session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, 
1864                                               &tcp_nat_probe->clientIdentity.hashPubKey);
1865   if (session == NULL)
1866     {
1867 #if DEBUG_TCP_NAT
1868       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1869                        "tcp",
1870                        "Did NOT find session for NAT probe!\n");
1871 #endif
1872       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1873       return;
1874     }
1875 #if DEBUG_TCP_NAT
1876   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1877                    "tcp",
1878                    "Found session for NAT probe!\n");
1879 #endif
1880   GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, 
1881                                                      &tcp_nat_probe->clientIdentity.hashPubKey,
1882                                                      session) == GNUNET_YES);
1883   if (GNUNET_OK !=
1884       GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1885     {
1886       GNUNET_break (0);
1887       GNUNET_free (session);
1888       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1889       return;
1890     }
1891
1892   GNUNET_SERVER_client_keep (client);
1893   session->client = client;
1894   session->last_activity = GNUNET_TIME_absolute_get ();
1895   session->inbound = GNUNET_NO;
1896
1897 #if DEBUG_TCP_NAT
1898   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1899                    "tcp",
1900                    "Found address `%s' for incoming connection\n",
1901                    GNUNET_a2s (vaddr, alen));
1902 #endif
1903   switch (((const struct sockaddr *)vaddr)->sa_family)
1904     {
1905     case AF_INET:
1906       s4 = vaddr;
1907       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1908       t4->t_port = s4->sin_port;
1909       t4->ipv4_addr = s4->sin_addr.s_addr;
1910       session->connect_addr = t4;
1911       session->connect_alen = sizeof (struct IPv4TcpAddress);
1912       break;
1913     case AF_INET6:    
1914       s6 = vaddr;
1915       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1916       t6->t6_port = s6->sin6_port;
1917       memcpy (&t6->ipv6_addr,
1918               &s6->sin6_addr,
1919               sizeof (struct in6_addr));
1920       session->connect_addr = t6;
1921       session->connect_alen = sizeof (struct IPv6TcpAddress);
1922       break;
1923     default:
1924       GNUNET_break_op (0);
1925 #if DEBUG_TCP_NAT
1926       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1927                        "tcp",
1928                        "Bad address for incoming connection!\n");
1929 #endif
1930       GNUNET_free (vaddr);
1931       GNUNET_SERVER_client_drop (client);
1932       GNUNET_free (session);
1933       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1934       return;
1935     }
1936   GNUNET_free (vaddr);
1937   
1938   session->next = plugin->sessions;
1939   plugin->sessions = session;
1940   GNUNET_STATISTICS_update (plugin->env->stats,
1941                             gettext_noop ("# TCP sessions active"),
1942                             1,
1943                             GNUNET_NO);
1944   process_pending_messages (session);
1945   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1946 }
1947
1948
1949 /**
1950  * We've received a welcome from this peer via TCP.  Possibly create a
1951  * fresh client record and send back our welcome.
1952  *
1953  * @param cls closure
1954  * @param client identification of the client
1955  * @param message the actual message
1956  */
1957 static void
1958 handle_tcp_welcome (void *cls,
1959                     struct GNUNET_SERVER_Client *client,
1960                     const struct GNUNET_MessageHeader *message)
1961 {
1962   struct Plugin *plugin = cls;
1963   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1964   struct Session *session;
1965   size_t alen;
1966   void *vaddr;
1967   struct IPv4TcpAddress *t4;
1968   struct IPv6TcpAddress *t6;
1969   const struct sockaddr_in *s4;
1970   const struct sockaddr_in6 *s6;
1971   
1972   if (0 == memcmp (&wm->clientIdentity,
1973                    plugin->env->my_identity,
1974                    sizeof (struct GNUNET_PeerIdentity)))
1975     {
1976       /* refuse connections from ourselves */
1977       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1978       return;
1979     }
1980 #if DEBUG_TCP
1981   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1982                    "tcp",
1983                    "Received %s message from `%4s'.\n",
1984                    "WELCOME",
1985                    GNUNET_i2s (&wm->clientIdentity));
1986 #endif
1987   GNUNET_STATISTICS_update (plugin->env->stats,
1988                             gettext_noop ("# TCP WELCOME messages received"),
1989                             1,
1990                             GNUNET_NO);
1991   session = find_session_by_client (plugin, client);
1992
1993   if (session == NULL)
1994     {
1995 #if DEBUG_TCP_NAT
1996       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1997                        "tcp",
1998                        "Received %s message from a `%4s', creating new session\n",
1999                        "WELCOME",
2000                        GNUNET_i2s (&wm->clientIdentity));
2001 #endif
2002       GNUNET_SERVER_client_keep (client);
2003       session = create_session (plugin,
2004                                 &wm->clientIdentity,
2005                                 client,
2006                                 GNUNET_NO);
2007       session->inbound = GNUNET_YES;
2008       if (GNUNET_OK ==
2009           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2010         {
2011 #if DEBUG_TCP_NAT
2012           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2013                            "tcp",
2014                            "Found address `%s' for incoming connection\n",
2015                            GNUNET_a2s (vaddr, alen));
2016 #endif
2017           if (alen == sizeof (struct sockaddr_in))
2018             {
2019               s4 = vaddr;
2020               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
2021               t4->t_port = s4->sin_port;
2022               t4->ipv4_addr = s4->sin_addr.s_addr;
2023               session->connect_addr = t4;
2024               session->connect_alen = sizeof (struct IPv4TcpAddress);
2025             }
2026           else if (alen == sizeof (struct sockaddr_in6))
2027             {
2028               s6 = vaddr;
2029               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
2030               t6->t6_port = s6->sin6_port;
2031               memcpy (&t6->ipv6_addr,
2032                       &s6->sin6_addr,
2033                       sizeof (struct in6_addr));
2034               session->connect_addr = t6;
2035               session->connect_alen = sizeof (struct IPv6TcpAddress);
2036             }
2037
2038           GNUNET_free (vaddr);
2039         }
2040       else
2041         {
2042 #if DEBUG_TCP
2043           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2044                            "tcp",
2045                            "Did not obtain TCP socket address for incoming connection\n");
2046 #endif
2047         }
2048       process_pending_messages (session);
2049     }
2050   else
2051     {
2052 #if DEBUG_TCP_NAT
2053     if (GNUNET_OK ==
2054         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2055       {
2056         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2057                          "tcp",
2058                          "Found address `%s' (already have session)\n",
2059                          GNUNET_a2s (vaddr, alen));
2060         GNUNET_free (vaddr);
2061       }
2062 #endif
2063     }
2064
2065   if (session->expecting_welcome != GNUNET_YES)
2066     {
2067       GNUNET_break_op (0);
2068       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2069       return;
2070     }
2071   session->last_activity = GNUNET_TIME_absolute_get ();
2072   session->expecting_welcome = GNUNET_NO;
2073   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2074 }
2075
2076
2077 /**
2078  * Task to signal the server that we can continue
2079  * receiving from the TCP client now.
2080  *
2081  * @param cls the 'struct Session*'
2082  * @param tc task context (unused)
2083  */
2084 static void
2085 delayed_done (void *cls, 
2086               const struct GNUNET_SCHEDULER_TaskContext *tc)
2087 {
2088   struct Session *session = cls;
2089   struct GNUNET_TIME_Relative delay;
2090
2091   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2092   delay = session->plugin->env->receive (session->plugin->env->cls,
2093                                          &session->target,
2094                                          NULL,
2095                                          NULL, 0,
2096                                          session,
2097                                          NULL, 0);
2098   if (delay.rel_value == 0)
2099     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2100   else
2101     session->receive_delay_task =
2102       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2103 }
2104
2105
2106 /**
2107  * We've received data for this peer via TCP.  Unbox,
2108  * compute latency and forward.
2109  *
2110  * @param cls closure
2111  * @param client identification of the client
2112  * @param message the actual message
2113  */
2114 static void
2115 handle_tcp_data (void *cls,
2116                  struct GNUNET_SERVER_Client *client,
2117                  const struct GNUNET_MessageHeader *message)
2118 {
2119   struct Plugin *plugin = cls;
2120   struct Session *session;
2121   struct GNUNET_TIME_Relative delay;
2122   uint16_t type;
2123
2124   type = ntohs (message->type);
2125   if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) || 
2126        (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
2127     {
2128       /* We don't want to propagate WELCOME and NAT Probe messages up! */
2129       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2130       return;
2131     }
2132   session = find_session_by_client (plugin, client);
2133   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome) )
2134     {
2135       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2136       return;
2137     }
2138   session->last_activity = GNUNET_TIME_absolute_get ();
2139 #if DEBUG_TCP > 1
2140   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2141                    "tcp",
2142                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2143                    (unsigned int) ntohs (message->size),
2144                    (unsigned int) ntohs (message->type),
2145                    GNUNET_i2s (&session->target));
2146 #endif
2147   GNUNET_STATISTICS_update (plugin->env->stats,
2148                             gettext_noop ("# bytes received via TCP"),
2149                             ntohs (message->size),
2150                             GNUNET_NO);
2151   struct GNUNET_TRANSPORT_ATS_Information distance[2];
2152   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2153   distance[0].value = htonl (1);
2154   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2155   distance[1].value = htonl (0);
2156   delay = plugin->env->receive (plugin->env->cls, &session->target, message,
2157                                 (const struct GNUNET_TRANSPORT_ATS_Information *) &distance,
2158                                 2,
2159                                 session,
2160                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
2161                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
2162   if (delay.rel_value == 0)
2163     {
2164       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2165     }
2166   else
2167     {
2168 #if DEBUG_TCP 
2169       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2170                        "tcp",
2171                        "Throttling receiving from `%s' for %llu ms\n",
2172                        GNUNET_i2s (&session->target),
2173                        (unsigned long long) delay.rel_value);
2174 #endif
2175       GNUNET_SERVER_disable_receive_done_warning (client);
2176       session->receive_delay_task =
2177         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2178     }
2179 }
2180
2181
2182 /**
2183  * Functions with this signature are called whenever a peer
2184  * is disconnected on the network level.
2185  *
2186  * @param cls closure
2187  * @param client identification of the client
2188  */
2189 static void
2190 disconnect_notify (void *cls,
2191                    struct GNUNET_SERVER_Client *client)
2192 {
2193   struct Plugin *plugin = cls;
2194   struct Session *session;
2195
2196   if (client == NULL)
2197     return;
2198   plugin->max_connections++;
2199   session = find_session_by_client (plugin, client);
2200   if (session == NULL)
2201     return;                     /* unknown, nothing to do */
2202 #if DEBUG_TCP
2203   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2204                    "tcp",
2205                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2206                    GNUNET_i2s (&session->target),
2207                    (session->connect_addr != NULL) ?
2208                    tcp_address_to_string (session->plugin,
2209                                           session->connect_addr,
2210                                           session->connect_alen) : "*");
2211 #endif
2212   GNUNET_STATISTICS_update (session->plugin->env->stats,
2213                             gettext_noop ("# network-level TCP disconnect events"),
2214                             1,
2215                             GNUNET_NO);
2216   disconnect_session (session);
2217 }
2218
2219
2220 static int check_localaddress (const struct sockaddr *addr, socklen_t addrlen)
2221 {
2222         uint32_t res = 0;
2223         int local = GNUNET_NO;
2224         int af = addr->sa_family;
2225     switch (af)
2226     {
2227       case AF_INET:
2228       {
2229           uint32_t netmask = 0x7F000000;
2230           uint32_t address = ntohl (((struct sockaddr_in *) addr)->sin_addr.s_addr);
2231           res = (address >> 24) ^ (netmask >> 24);
2232           if (res != 0)
2233                   local = GNUNET_NO;
2234           else
2235                   local = GNUNET_YES;
2236 #if DEBUG_TCP
2237             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238                           "Checking IPv4 address `%s': %s\n", GNUNET_a2s (addr, addrlen), (local==GNUNET_YES) ? "local" : "global");
2239 #endif
2240             break;
2241       }
2242       case AF_INET6:
2243       {
2244            if (IN6_IS_ADDR_LOOPBACK  (&((struct sockaddr_in6 *) addr)->sin6_addr) ||
2245                    IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
2246                    local = GNUNET_YES;
2247            else
2248                    local = GNUNET_NO;
2249 #if DEBUG_TCP
2250            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2251                           "Checking IPv6 address `%s' : %s\n", GNUNET_a2s (addr, addrlen), (local==GNUNET_YES) ? "local" : "global");
2252 #endif
2253            break;
2254       }
2255     }
2256         return local;
2257 }
2258
2259 /**
2260  * Add the IP of our network interface to the list of
2261  * our internal IP addresses.
2262  *
2263  * @param cls the 'struct Plugin*'
2264  * @param name name of the interface
2265  * @param isDefault do we think this may be our default interface
2266  * @param addr address of the interface
2267  * @param addrlen number of bytes in addr
2268  * @return GNUNET_OK to continue iterating
2269  */
2270 static int
2271 process_interfaces (void *cls,
2272                     const char *name,
2273                     int isDefault,
2274                     const struct sockaddr *addr, socklen_t addrlen)
2275 {
2276   struct Plugin *plugin = cls;
2277   int af;
2278   struct IPv4TcpAddress t4;
2279   struct IPv6TcpAddress t6;
2280   struct IPv4TcpAddress t4_nat;
2281   struct IPv6TcpAddress t6_nat;
2282   void *arg;
2283   uint16_t args;
2284   void *arg_nat;
2285   char buf[INET6_ADDRSTRLEN];
2286
2287   af = addr->sa_family;
2288   arg_nat = NULL;
2289
2290   if (plugin->use_localaddresses == GNUNET_NO)
2291   {
2292           if (GNUNET_YES == check_localaddress (addr, addrlen))
2293           {
2294 #if DEBUG_TCP
2295           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2296                            "tcp",
2297                            "Not notifying transport of address `%s' (local address)\n",
2298                            GNUNET_a2s (addr, addrlen));
2299 #endif
2300                   return GNUNET_OK;
2301           }
2302   }
2303
2304   switch (af)
2305     {
2306     case AF_INET:
2307       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2308       GNUNET_assert (NULL != inet_ntop(AF_INET, 
2309                                        &t4.ipv4_addr, 
2310                                        buf, 
2311                                        sizeof (buf)));
2312       if ( (plugin->bind_address != NULL) && 
2313            (0 != strcmp(buf, plugin->bind_address)) )
2314         {
2315 #if DEBUG_TCP
2316           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2317                            "tcp",
2318                            "Not notifying transport of address `%s' (does not match bind address)\n",
2319                            GNUNET_a2s (addr, addrlen));
2320 #endif
2321           return GNUNET_OK;
2322         }
2323       if ( (plugin->internal_address == NULL) &&
2324            (isDefault) )        
2325         plugin->internal_address = GNUNET_strdup (buf); 
2326       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (struct in_addr));
2327       if (plugin->behind_nat == GNUNET_YES) 
2328         {
2329           /* Also advertise as NAT (with port 0) */
2330           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2331           t4_nat.t_port = htons(0);
2332           arg_nat = &t4_nat;
2333         }       
2334       t4.t_port = htons (plugin->adv_port);     
2335       arg = &t4;
2336       args = sizeof (t4);
2337       break;
2338     case AF_INET6:      
2339       if ( (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || 
2340            (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, 
2341                                                                "nat", 
2342                                                                "DISABLEV6")) )
2343         {
2344           /* skip link local addresses */
2345           return GNUNET_OK;
2346         }
2347       memcpy (&t6.ipv6_addr,
2348               &((struct sockaddr_in6 *) addr)->sin6_addr,
2349               sizeof (struct in6_addr));
2350
2351       /* check bind address */
2352       GNUNET_assert (NULL != inet_ntop(AF_INET6,
2353                                        &t6.ipv6_addr,
2354                                        buf,
2355                                        sizeof (buf)));
2356
2357       if ( (plugin->bind_address != NULL) &&
2358            (0 != strcmp(buf, plugin->bind_address)) )
2359         {
2360 #if DEBUG_TCP
2361           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2362                            "tcp",
2363                            "Not notifying transport of address `%s' (does not match bind address)\n",
2364                            GNUNET_a2s (addr, addrlen));
2365 #endif
2366           return GNUNET_OK;
2367         }
2368
2369       add_to_address_list (plugin, 
2370                            &t6.ipv6_addr, 
2371                            sizeof (struct in6_addr));
2372       if (plugin->behind_nat == GNUNET_YES)
2373         {
2374           /* Also advertise as NAT (with port 0) */
2375           memcpy (&t6_nat.ipv6_addr,
2376                   &((struct sockaddr_in6 *) addr)->sin6_addr,
2377                   sizeof (struct in6_addr));
2378           t6_nat.t6_port = htons(0);
2379           arg_nat = &t6;
2380         }
2381       t6.t6_port = htons (plugin->adv_port);
2382       arg = &t6;
2383       args = sizeof (t6);
2384       break;
2385     default:
2386       GNUNET_break (0);
2387       return GNUNET_OK;
2388     }
2389   if (plugin->adv_port != 0)
2390   {
2391 #if DEBUG_TCP
2392   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2393                    "tcp",
2394                    "Found address `%s' (%s) len %d\n",
2395                    GNUNET_a2s (addr, addrlen), name, args);
2396 #endif
2397   plugin->env->notify_address (plugin->env->cls,
2398                                "tcp",
2399                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
2400   }
2401
2402   if (arg_nat != NULL)
2403     {
2404       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2405                        "tcp",
2406                        _("Found address `%s' (%s) len %d\n"),
2407                        GNUNET_a2s (addr, addrlen), name, args);
2408       plugin->env->notify_address (plugin->env->cls,
2409                                    "tcp",
2410                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
2411     }
2412
2413   return GNUNET_OK;
2414 }
2415
2416
2417 /**
2418  * Function called by the resolver for each address obtained from DNS
2419  * for our own hostname.  Add the addresses to the list of our
2420  * external IP addresses.
2421  *
2422  * @param cls closure
2423  * @param addr one of the addresses of the host, NULL for the last address
2424  * @param addrlen length of the address
2425  */
2426 static void
2427 process_hostname_ips (void *cls,
2428                       const struct sockaddr *addr, socklen_t addrlen)
2429 {
2430   struct Plugin *plugin = cls;
2431
2432   if (addr == NULL)
2433     {
2434       plugin->hostname_dns = NULL;
2435       return;
2436     }
2437   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
2438   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
2439 }
2440
2441
2442 /**
2443  * We can now send a probe message, copy into buffer to really send.
2444  *
2445  * @param cls closure, a struct TCPProbeContext
2446  * @param size max size to copy
2447  * @param buf buffer to copy message to
2448  * @return number of bytes copied into buf
2449  */
2450 static size_t
2451 notify_send_probe (void *cls,
2452                    size_t size,
2453                    void *buf)
2454 {
2455   struct TCPProbeContext *tcp_probe_ctx = cls;
2456   struct Plugin *plugin = tcp_probe_ctx->plugin;
2457   size_t ret;
2458
2459   tcp_probe_ctx->transmit_handle = NULL;
2460   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2461                                plugin->probe_tail,
2462                                tcp_probe_ctx);
2463   if (buf == NULL)
2464     {
2465       GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2466       GNUNET_free(tcp_probe_ctx);
2467       return 0;    
2468     }
2469   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2470   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2471   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2472                                 tcp_probe_ctx->sock);
2473   ret = sizeof(tcp_probe_ctx->message);
2474   GNUNET_free(tcp_probe_ctx);
2475   return ret;
2476 }
2477
2478
2479 /**
2480  * We have been notified that gnunet-nat-server has written something to stdout.
2481  * Handle the output, then reschedule this function to be called again once
2482  * more is available.
2483  *
2484  * @param cls the plugin handle
2485  * @param tc the scheduling context
2486  */
2487 static void
2488 tcp_plugin_server_read (void *cls, 
2489                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2490 {
2491   struct Plugin *plugin = cls;
2492   char mybuf[40];
2493   ssize_t bytes;
2494   size_t i;
2495   int port;
2496   const char *port_start;
2497   struct sockaddr_in sin_addr;
2498   struct TCPProbeContext *tcp_probe_ctx;
2499   struct GNUNET_CONNECTION_Handle *sock;
2500
2501   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
2502     return;
2503   memset (mybuf, 0, sizeof(mybuf));
2504   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, 
2505                                 mybuf,
2506                                 sizeof(mybuf));
2507   if (bytes < 1)
2508     {
2509 #if DEBUG_TCP_NAT
2510       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2511                        "tcp",
2512                        "Finished reading from server stdout with code: %d\n", 
2513                        bytes);
2514 #endif
2515       /* FIXME: consider process_wait here? */
2516       return;
2517     }
2518
2519   port_start = NULL;
2520   for (i = 0; i < sizeof(mybuf); i++)
2521     {
2522       if (mybuf[i] == '\n')
2523         {
2524           mybuf[i] = '\0';
2525           break;
2526         }
2527       if ( (mybuf[i] == ':') && (i + 1 < sizeof(mybuf)) )
2528         {
2529           mybuf[i] = '\0';
2530           port_start = &mybuf[i + 1];
2531         }
2532     }
2533
2534   /* construct socket address of sender */
2535   memset (&sin_addr, 0, sizeof (sin_addr));
2536   sin_addr.sin_family = AF_INET;
2537 #if HAVE_SOCKADDR_IN_SIN_LEN
2538   sin_addr.sin_len = sizeof (sin_addr);
2539 #endif
2540   if ( (NULL == port_start) ||
2541        (1 != sscanf (port_start, "%d", &port)) ||
2542        (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr)) )
2543     {
2544       /* should we restart gnunet-nat-server? */
2545       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2546                        "tcp",
2547                        _("gnunet-nat-server generated malformed address `%s'\n"),
2548                        mybuf);
2549       plugin->server_read_task 
2550         = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2551                                           plugin->server_stdout_handle,
2552                                           &tcp_plugin_server_read, 
2553                                           plugin);
2554       return;
2555     }
2556   sin_addr.sin_port = htons((uint16_t) port);
2557 #if DEBUG_TCP_NAT
2558   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2559                    "tcp",
2560                    "gnunet-nat-server read: %s:%d\n", 
2561                    mybuf, port);
2562 #endif
2563
2564   /**
2565    * We have received an ICMP response, ostensibly from a peer
2566    * that wants to connect to us! Send a message to establish a connection.
2567    */
2568   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, 
2569                                                  (const struct sockaddr *)&sin_addr,
2570                                                  sizeof (sin_addr));
2571   if (sock == NULL)
2572     {
2573       /* failed for some odd reason (out of sockets?); ignore attempt */
2574       plugin->server_read_task =
2575           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2576                                           plugin->server_stdout_handle, 
2577                                           &tcp_plugin_server_read, 
2578                                           plugin);
2579       return;
2580     }
2581
2582   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2583                    "Sending TCP probe message to `%s:%u'!\n", 
2584                    mybuf,
2585                    (unsigned int) port);  
2586   /* FIXME: do we need to track these probe context objects so that
2587      we can clean them up on plugin unload? */
2588   tcp_probe_ctx
2589     = GNUNET_malloc(sizeof(struct TCPProbeContext));
2590   tcp_probe_ctx->message.header.size
2591     = htons(sizeof(struct TCP_NAT_ProbeMessage));
2592   tcp_probe_ctx->message.header.type
2593     = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2594   memcpy (&tcp_probe_ctx->message.clientIdentity,
2595           plugin->env->my_identity,
2596           sizeof(struct GNUNET_PeerIdentity));
2597   tcp_probe_ctx->plugin = plugin;
2598   tcp_probe_ctx->sock = sock;
2599   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2600                                plugin->probe_tail,
2601                                tcp_probe_ctx);
2602   tcp_probe_ctx->transmit_handle 
2603     = GNUNET_CONNECTION_notify_transmit_ready (sock,
2604                                                ntohs (tcp_probe_ctx->message.header.size),
2605                                                GNUNET_TIME_UNIT_FOREVER_REL,
2606                                                &notify_send_probe, tcp_probe_ctx);
2607   
2608   plugin->server_read_task =
2609       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2610                                       plugin->server_stdout_handle,
2611                                       &tcp_plugin_server_read,
2612                                       plugin);
2613 }
2614
2615
2616 /**
2617  * Start the gnunet-nat-server process for users behind NAT.
2618  *
2619  * @param plugin the transport plugin
2620  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2621  */
2622 static int
2623 tcp_transport_start_nat_server (struct Plugin *plugin)
2624 {
2625   if (plugin->internal_address == NULL)
2626     return GNUNET_SYSERR;
2627   plugin->server_stdout = GNUNET_DISK_pipe (GNUNET_YES,
2628                                             GNUNET_NO,
2629                                             GNUNET_YES);
2630   if (plugin->server_stdout == NULL)
2631     return GNUNET_SYSERR;
2632 #if DEBUG_TCP_NAT
2633   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2634                    "tcp"
2635                    "Starting %s %s\n", "gnunet-nat-server", plugin->internal_address);
2636 #endif
2637   /* Start the server process */
2638   plugin->server_proc = GNUNET_OS_start_process (NULL,
2639                                                  plugin->server_stdout,
2640                                                  "gnunet-nat-server", 
2641                                                  "gnunet-nat-server", 
2642                                                  plugin->internal_address, 
2643                                                  NULL);
2644   if (plugin->server_proc == NULL)
2645     {
2646       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2647                        "tcp",
2648                        _("Failed to start %s\n"),
2649                        "gnunet-nat-server");
2650       GNUNET_DISK_pipe_close (plugin->server_stdout);
2651       plugin->server_stdout = NULL;    
2652       return GNUNET_SYSERR;
2653     }
2654   /* Close the write end of the read pipe */
2655   GNUNET_DISK_pipe_close_end(plugin->server_stdout, 
2656                              GNUNET_DISK_PIPE_END_WRITE);
2657   plugin->server_stdout_handle 
2658     = GNUNET_DISK_pipe_handle (plugin->server_stdout, 
2659                                GNUNET_DISK_PIPE_END_READ);
2660   plugin->server_read_task 
2661     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2662                                       plugin->server_stdout_handle,
2663                                       &tcp_plugin_server_read, 
2664                                       plugin);
2665   return GNUNET_YES;
2666 }
2667
2668
2669 /**
2670  * Return the actual path to a file found in the current
2671  * PATH environment variable.
2672  *
2673  * @param binary the name of the file to find
2674  * @return path to binary, NULL if not found
2675  */
2676 static char *
2677 get_path_from_PATH (const char *binary)
2678 {
2679   char *path;
2680   char *pos;
2681   char *end;
2682   char *buf;
2683   const char *p;
2684
2685   p = getenv ("PATH");
2686   if (p == NULL)
2687     {
2688       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2689                        "tcp",
2690                        _("PATH environment variable is unset.\n"));
2691       return NULL;
2692     }
2693   path = GNUNET_strdup (p);     /* because we write on it */
2694   buf = GNUNET_malloc (strlen (path) + 20);
2695   pos = path;
2696
2697   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
2698     {
2699       *end = '\0';
2700       sprintf (buf, "%s/%s", pos, binary);
2701       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2702         {
2703           GNUNET_free (path);
2704           return buf;
2705         }
2706       pos = end + 1;
2707     }
2708   sprintf (buf, "%s/%s", pos, binary);
2709   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2710     {
2711       GNUNET_free (path);
2712       return buf;
2713     }
2714   GNUNET_free (buf);
2715   GNUNET_free (path);
2716   return NULL;
2717 }
2718
2719
2720 /**
2721  * Check whether the suid bit is set on a file.
2722  * Attempts to find the file using the current
2723  * PATH environment variable as a search path.
2724  *
2725  * @param binary the name of the file to check
2726  * @return GNUNET_YES if the file is SUID, 
2727  *         GNUNET_NO if not, 
2728  *         GNUNET_SYSERR on error
2729  */
2730 static int
2731 check_gnunet_nat_binary (const char *binary)
2732 {
2733   struct stat statbuf;
2734   char *p;
2735 #ifdef MINGW
2736   SOCKET rawsock;
2737   char *binaryexe;
2738
2739   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
2740   p = get_path_from_PATH (binaryexe);
2741   free (binaryexe);
2742 #else
2743   p = get_path_from_PATH (binary);
2744 #endif
2745   if (p == NULL)
2746     {
2747       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2748                        "tcp",
2749                        _("Could not find binary `%s' in PATH!\n"),
2750                        binary);
2751       return GNUNET_NO;
2752     }
2753   if (0 != STAT (p, &statbuf))
2754     {
2755       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
2756                   _("stat (%s) failed: %s\n"), 
2757                   p,
2758                   STRERROR (errno));
2759       GNUNET_free (p);
2760       return GNUNET_SYSERR;
2761     }
2762   GNUNET_free (p);
2763 #ifndef MINGW
2764   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2765        (statbuf.st_uid == 0) )
2766     return GNUNET_YES;
2767   return GNUNET_NO;
2768 #else
2769   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
2770   if (INVALID_SOCKET == rawsock)
2771     {
2772       DWORD err = GetLastError ();
2773       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
2774                        "tcp",
2775                        "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
2776       return GNUNET_NO; /* not running as administrator */
2777     }
2778   closesocket (rawsock);
2779   return GNUNET_YES;
2780 #endif
2781 }
2782
2783
2784 /**
2785  * Our (external) hostname was resolved.
2786  *
2787  * @param cls the 'struct Plugin'
2788  * @param addr NULL on error, otherwise result of DNS lookup
2789  * @param addrlen number of bytes in addr
2790  */
2791 static void
2792 process_external_ip (void *cls,
2793                      const struct sockaddr *addr,
2794                      socklen_t addrlen)
2795 {
2796   struct Plugin *plugin = cls;
2797   const struct sockaddr_in *s;
2798   struct IPv4TcpAddress t4;
2799   char buf[INET_ADDRSTRLEN];
2800
2801   plugin->ext_dns = NULL;
2802   if (addr == NULL)
2803     return;
2804   GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2805   s = (const struct sockaddr_in *) addr;
2806   t4.ipv4_addr = s->sin_addr.s_addr;
2807   if ( (plugin->behind_nat == GNUNET_YES) &&
2808        (plugin->enable_nat_server == GNUNET_YES) )
2809     {
2810       t4.t_port = htons(0);
2811       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2812                        "tcp",
2813                        "Notifying transport of address %s:%d\n",
2814                        plugin->external_address,
2815                        0);
2816     }
2817   else
2818     {
2819       t4.t_port = htons(plugin->adv_port);
2820       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2821                        "tcp",
2822                        "Notifying transport of address %s:%d\n",
2823                        plugin->external_address, 
2824                        (int) plugin->adv_port);
2825     }
2826
2827   if ((plugin->bind_address != NULL) && (plugin->behind_nat == GNUNET_NO))
2828   {
2829       GNUNET_assert (NULL != inet_ntop(AF_INET,
2830                                        &t4.ipv4_addr,
2831                                        buf,
2832                                        sizeof (buf)));
2833       if (0 != strcmp (plugin->bind_address, buf))
2834       {
2835       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2836                        "tcp",
2837                        "NAT is not enabled and specific bind address `%s' differs from external address `%s'! Not notifying about external address `%s'\n",
2838                        plugin->bind_address,
2839                        plugin->external_address,
2840                        plugin->external_address);
2841       return;
2842       }
2843   }
2844
2845   add_to_address_list (plugin, 
2846                        &t4.ipv4_addr, 
2847                        sizeof (struct in_addr));
2848
2849   plugin->env->notify_address (plugin->env->cls,
2850                                "tcp",
2851                                &t4, sizeof(t4),
2852                                GNUNET_TIME_UNIT_FOREVER_REL);
2853 }
2854
2855
2856 /**
2857  * Entry point for the plugin.
2858  *
2859  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2860  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2861  */
2862 void *
2863 libgnunet_plugin_transport_tcp_init (void *cls)
2864 {
2865   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2866     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2867      sizeof (struct WelcomeMessage)},
2868     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2869     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2870     {NULL, NULL, 0, 0}
2871   };
2872   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2873   struct GNUNET_TRANSPORT_PluginFunctions *api;
2874   struct Plugin *plugin;
2875   struct GNUNET_SERVICE_Context *service;
2876   unsigned long long aport;
2877   unsigned long long bport;
2878   unsigned long long max_connections;
2879   unsigned int i;
2880   int behind_nat;
2881   int nat_punched;
2882   int enable_nat_client;
2883   int enable_nat_server;
2884   int enable_upnp;
2885   int use_localaddresses;
2886   char *internal_address;
2887   char *external_address;
2888   char *bind_address;
2889   struct sockaddr_in in_addr;
2890   struct GNUNET_TIME_Relative idle_timeout;
2891
2892   behind_nat = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2893                                                      "nat",
2894                                                      "BEHIND_NAT");
2895   nat_punched = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2896                                                       "nat",
2897                                                       "NAT_PUNCHED");
2898   enable_nat_client = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2899                                                             "nat",
2900                                                             "ENABLE_NAT_CLIENT");
2901   enable_nat_server = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2902                                                             "nat",
2903                                                             "ENABLE_NAT_SERVER");
2904   enable_upnp = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2905                                                       "nat",
2906                                                       "ENABLE_UPNP");
2907   
2908   if ( (GNUNET_YES == enable_nat_server) &&
2909        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-server")) )
2910     {
2911       enable_nat_server = GNUNET_NO;
2912       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2913                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2914                   "gnunet-nat-server");        
2915     }
2916
2917   if ( (GNUNET_YES == enable_nat_client) &&
2918        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-client")) )
2919     {
2920       enable_nat_client = GNUNET_NO;
2921       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2922                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2923                   "gnunet-nat-client"); 
2924     }
2925   
2926   external_address = NULL;
2927   if (GNUNET_OK ==
2928       GNUNET_CONFIGURATION_have_value (env->cfg,
2929                                        "nat",
2930                                        "EXTERNAL_ADDRESS"))
2931     {
2932       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2933                                                     "nat",
2934                                                     "EXTERNAL_ADDRESS",
2935                                                     &external_address);
2936     }
2937
2938   if ( (external_address != NULL) && 
2939        (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1) ) 
2940     {
2941       
2942       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2943                        "tcp",
2944                        _("Malformed %s `%s' given in configuration!\n"), 
2945                        "EXTERNAL_ADDRESS",
2946                        external_address);
2947       return NULL;   
2948     }
2949   if ( (external_address == NULL) &&
2950        (nat_punched == GNUNET_YES) )
2951     {
2952       nat_punched = GNUNET_NO;
2953       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2954                   _("Configuration says NAT was punched, but `%s' is not given.  Option ignored.\n"),
2955                   "EXTERNAL_ADDRESS");  
2956     }
2957
2958   if (GNUNET_YES == nat_punched)
2959     {
2960       enable_nat_server = GNUNET_NO;
2961       enable_upnp = GNUNET_NO;
2962     }
2963
2964   bind_address = NULL;
2965   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2966                                                            "nat",
2967                                                            "BINDTO",
2968                                                            &bind_address))
2969         {
2970           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2971                            "tcp",
2972                            _("Binding TCP plugin to specific address: `%s'\n"),
2973                            bind_address);
2974         }
2975
2976   internal_address = NULL;
2977   if (GNUNET_OK ==
2978       GNUNET_CONFIGURATION_have_value (env->cfg,
2979                                        "nat",
2980                                        "INTERNAL_ADDRESS"))
2981     {
2982       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2983                                                     "nat",
2984                                                     "INTERNAL_ADDRESS",
2985                                                     &internal_address);
2986     }
2987
2988   if ( (internal_address != NULL) && 
2989        (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1) )
2990     {
2991       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2992                        "tcp",
2993                        _("Malformed %s `%s' given in configuration!\n"), 
2994                        "INTERNAL_ADDRESS",
2995                        internal_address);      
2996       GNUNET_free_non_null(internal_address);
2997       GNUNET_free_non_null(external_address);
2998       return NULL;
2999     }
3000
3001   if ((bind_address != NULL) && (internal_address != NULL))
3002     {
3003       if (0 != strcmp(internal_address, bind_address ))
3004         {
3005           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3006                            "tcp",
3007                            "Specific bind address `%s' and internal address `%s' must not differ, forcing internal address to bind address!\n", 
3008                            bind_address, internal_address);
3009           GNUNET_free (internal_address);
3010           internal_address = bind_address;
3011           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3012                            "tcp","New internal address `%s'\n", internal_address);
3013         }
3014     }
3015   if (GNUNET_OK !=
3016       GNUNET_CONFIGURATION_get_value_number (env->cfg,
3017                                              "transport-tcp",
3018                                              "MAX_CONNECTIONS",
3019                                              &max_connections))
3020     max_connections = 128;
3021   
3022   aport = 0;
3023   if ( (GNUNET_OK !=
3024         GNUNET_CONFIGURATION_get_value_number (env->cfg,
3025                                                "transport-tcp",
3026                                                "PORT",
3027                                                &bport)) ||
3028        (bport > 65535) ||
3029        ((GNUNET_OK ==
3030          GNUNET_CONFIGURATION_get_value_number (env->cfg,
3031                                                 "transport-tcp",
3032                                                 "ADVERTISED-PORT",
3033                                                 &aport)) && 
3034         (aport > 65535)) )
3035     {
3036       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3037                        "tcp",
3038                        _("Require valid port number for service `%s' in configuration!\n"),
3039                        "transport-tcp");
3040       GNUNET_free_non_null(external_address);
3041       GNUNET_free_non_null(internal_address);
3042       return NULL;
3043     }
3044
3045   use_localaddresses = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3046                                                              "transport-tcp",
3047                                                              "USE_LOCALADDR");
3048   if (use_localaddresses == GNUNET_SYSERR)
3049     use_localaddresses = GNUNET_NO;
3050   
3051   if (aport == 0)
3052     aport = bport;
3053   if (bport == 0)
3054     aport = 0;
3055
3056   if (bport != 0)
3057     {
3058       service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
3059       if (service == NULL)
3060         {
3061           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
3062                            "tcp",
3063                            _("Failed to start service.\n"));
3064           return NULL;
3065         }
3066     }
3067   else
3068     service = NULL;
3069
3070   plugin = GNUNET_malloc (sizeof (struct Plugin));
3071   plugin->max_connections = max_connections;
3072   plugin->open_port = bport;
3073   plugin->adv_port = aport;
3074   plugin->bind_address = bind_address;
3075   plugin->external_address = external_address;
3076   plugin->internal_address = internal_address;
3077   plugin->behind_nat = behind_nat;
3078   plugin->nat_punched = nat_punched;
3079   plugin->enable_nat_client = enable_nat_client;
3080   plugin->enable_nat_server = enable_nat_server;
3081   plugin->enable_upnp = enable_upnp;
3082   plugin->use_localaddresses = use_localaddresses;
3083   plugin->env = env;
3084   plugin->lsock = NULL;
3085   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3086   api->cls = plugin;
3087   api->send = &tcp_plugin_send;
3088   api->disconnect = &tcp_plugin_disconnect;
3089   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
3090   api->check_address = &tcp_plugin_check_address;
3091   api->address_to_string = &tcp_address_to_string;
3092   plugin->service = service;
3093   if (service != NULL)   
3094     {
3095       plugin->server = GNUNET_SERVICE_get_server (service);
3096     }
3097   else
3098     {
3099       if (GNUNET_OK !=
3100           GNUNET_CONFIGURATION_get_value_time (env->cfg,
3101                                                "transport-tcp",
3102                                                "TIMEOUT",
3103                                                &idle_timeout))
3104         {
3105           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3106                            "tcp",
3107                            _("Failed to find option %s in section %s!\n"),
3108                            "TIMEOUT",
3109                            "transport-tcp");
3110           GNUNET_free_non_null(external_address);
3111           GNUNET_free_non_null(internal_address);
3112           GNUNET_free (api);
3113           return NULL;
3114         }
3115       plugin->server = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin, NULL,
3116                                                           idle_timeout, GNUNET_YES);
3117     }
3118   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
3119   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
3120   for (i = 0;
3121        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
3122        i++)
3123     plugin->handlers[i].callback_cls = plugin;
3124   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
3125   GNUNET_SERVER_disconnect_notify (plugin->server,
3126                                    &disconnect_notify,
3127                                    plugin);    
3128   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
3129
3130   if ( (plugin->behind_nat == GNUNET_YES) &&
3131        (plugin->enable_nat_server == GNUNET_YES) &&
3132        (GNUNET_YES != tcp_transport_start_nat_server(plugin)) )
3133     {
3134       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3135                        "tcp",
3136                        _("Failed to start %s required for NAT in %s!\n"),
3137                        "gnunet-nat-server"
3138                        "transport-tcp");
3139       GNUNET_free_non_null(external_address);
3140       GNUNET_free_non_null(internal_address);
3141       if (service != NULL)
3142         GNUNET_SERVICE_stop (service);
3143       else
3144         GNUNET_SERVER_destroy (plugin->server);
3145       GNUNET_free (api);
3146       return NULL;
3147     }
3148
3149   if (enable_nat_client == GNUNET_YES)
3150     {
3151       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(16);
3152       GNUNET_assert (plugin->nat_wait_conns != NULL);
3153     }
3154
3155   if (bport != 0)
3156     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3157                      "tcp",
3158                      _("TCP transport listening on port %llu\n"), 
3159                      bport);
3160   else
3161     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3162                      "tcp",
3163                      _("TCP transport not listening on any port (client only)\n"));
3164   if (aport != bport)
3165     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
3166                      "tcp",
3167                      _("TCP transport advertises itself as being on port %llu\n"),
3168                      aport);
3169
3170   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->cfg,
3171                                                            AF_UNSPEC,
3172                                                            HOSTNAME_RESOLVE_TIMEOUT,
3173                                                            &process_hostname_ips,
3174                                                            plugin);
3175
3176   if (plugin->external_address != NULL) 
3177     {
3178       plugin->ext_dns = GNUNET_RESOLVER_ip_get (env->cfg,
3179                                                 plugin->external_address,
3180                                                 AF_INET,
3181                                                 GNUNET_TIME_UNIT_MINUTES,
3182                                                 &process_external_ip,
3183                                                 plugin);
3184     }
3185   return api;
3186 }
3187
3188
3189 /**
3190  * Exit point from the plugin.
3191  */
3192 void *
3193 libgnunet_plugin_transport_tcp_done (void *cls)
3194 {
3195   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3196   struct Plugin *plugin = api->cls;
3197   struct Session *session;
3198   struct LocalAddrList *lal;
3199   struct TCPProbeContext *tcp_probe;
3200
3201   if (plugin->ext_dns != NULL)
3202     {
3203       GNUNET_RESOLVER_request_cancel (plugin->ext_dns);
3204       plugin->ext_dns = NULL;
3205     }
3206   while (NULL != (session = plugin->sessions))
3207     disconnect_session (session);
3208   if (NULL != plugin->hostname_dns)
3209     {
3210       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
3211       plugin->hostname_dns = NULL;
3212     }
3213   if (plugin->service != NULL)
3214     GNUNET_SERVICE_stop (plugin->service);
3215   else
3216     GNUNET_SERVER_destroy (plugin->server);
3217   GNUNET_free (plugin->handlers);
3218   while (NULL != (lal = plugin->lal_head))
3219     {
3220       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
3221                                    plugin->lal_tail,
3222                                    lal);
3223       if (lal->nat != NULL)
3224         GNUNET_NAT_unregister (lal->nat);
3225       GNUNET_free_non_null (lal->external_nat_address);
3226       GNUNET_free (lal);
3227     }
3228   while (NULL != (tcp_probe = plugin->probe_head))
3229     {
3230       GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
3231                                    plugin->probe_tail,
3232                                    tcp_probe);
3233       GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
3234       GNUNET_free (tcp_probe);
3235     }
3236
3237   if ((plugin->behind_nat == GNUNET_YES) &&
3238       (plugin->enable_nat_server == GNUNET_YES))
3239     {
3240       if (0 != GNUNET_OS_process_kill (plugin->server_proc, SIGTERM))
3241         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
3242       GNUNET_OS_process_wait (plugin->server_proc);
3243       GNUNET_OS_process_close (plugin->server_proc);
3244       plugin->server_proc = NULL;
3245     }
3246   GNUNET_free_non_null(plugin->bind_address);
3247   GNUNET_free (plugin);
3248   GNUNET_free (api);
3249   return NULL;
3250 }
3251
3252 /* end of plugin_transport_tcp.c */