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