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