9b09d894872f63b439016fcdd6bcfcf2a8405dd9
[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 2, 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_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
39
40 #define DEBUG_TCP GNUNET_NO
41 #define DEBUG_TCP_NAT GNUNET_NO
42
43 /**
44  * How long until we give up on transmitting the welcome message?
45  */
46 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
47
48
49 /**
50  * Initial handshake message for a session.
51  */
52 struct WelcomeMessage
53 {
54   /**
55    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
56    */
57   struct GNUNET_MessageHeader header;
58
59   /**
60    * Identity of the node connecting (TCP client)
61    */
62   struct GNUNET_PeerIdentity clientIdentity;
63
64 };
65
66 /**
67  * Basically a WELCOME message, but with the purpose
68  * of giving the waiting peer a client handle to use
69  */
70 struct TCP_NAT_ProbeMessage
71 {
72   /**
73    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
74    */
75   struct GNUNET_MessageHeader header;
76
77   /**
78    * Identity of the sender of the message.
79    */
80   struct GNUNET_PeerIdentity clientIdentity;
81
82 };
83
84 /**
85  * Context for sending a NAT probe via TCP.
86  */
87 struct TCPProbeContext
88 {
89   /**
90    * Probe connection.
91    */
92   struct GNUNET_CONNECTION_Handle *sock;
93
94   /**
95    * Message to be sent.
96    */
97   struct TCP_NAT_ProbeMessage message;
98
99   /**
100    * Handle to the transmission.
101    */
102   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
103
104   /**
105    * Transport plugin handle.
106    */
107   struct Plugin *plugin;
108 };
109
110
111 /**
112  * Network format for IPv4 addresses.
113  */
114 struct IPv4TcpAddress
115 {
116   /**
117    * IPv4 address, in network byte order.
118    */
119   uint32_t ipv4_addr;
120
121   /**
122    * Port number, in network byte order.
123    */
124   uint16_t t_port;
125
126 };
127
128
129 /**
130  * Network format for IPv6 addresses.
131  */
132 struct IPv6TcpAddress
133 {
134   /**
135    * IPv6 address.
136    */
137   struct in6_addr ipv6_addr;
138
139   /**
140    * Port number, in network byte order.
141    */
142   uint16_t t6_port;
143
144 };
145
146 /**
147  * Encapsulation of all of the state of the plugin.
148  */
149 struct Plugin;
150
151
152 /**
153  * Information kept for each message that is yet to
154  * be transmitted.
155  */
156 struct PendingMessage
157 {
158
159   /**
160    * This is a doubly-linked list.
161    */
162   struct PendingMessage *next;
163
164   /**
165    * This is a doubly-linked list.
166    */
167   struct PendingMessage *prev;
168
169   /**
170    * The pending message
171    */
172   const char *msg;
173
174   /**
175    * Continuation function to call once the message
176    * has been sent.  Can be NULL if there is no
177    * continuation to call.
178    */
179   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
180
181   /**
182    * Closure for transmit_cont.
183    */
184   void *transmit_cont_cls;
185
186   /**
187    * Timeout value for the pending message.
188    */
189   struct GNUNET_TIME_Absolute timeout;
190
191   /**
192    * So that the gnunet-service-transport can group messages together,
193    * these pending messages need to accept a message buffer and size
194    * instead of just a GNUNET_MessageHeader.
195    */
196   size_t message_size;
197
198 };
199
200
201 /**
202  * Session handle for TCP connections.
203  */
204 struct Session
205 {
206
207   /**
208    * API requirement.
209    */
210   struct SessionHeader header;
211
212   /**
213    * Stored in a linked list.
214    */
215   struct Session *next;
216
217   /**
218    * Pointer to the global plugin struct.
219    */
220   struct Plugin *plugin;
221
222   /**
223    * The client (used to identify this connection)
224    */
225   struct GNUNET_SERVER_Client *client;
226
227   /**
228    * Messages currently pending for transmission
229    * to this peer, if any.
230    */
231   struct PendingMessage *pending_messages_head;
232
233   /**
234    * Messages currently pending for transmission
235    * to this peer, if any.
236    */
237   struct PendingMessage *pending_messages_tail;
238
239   /**
240    * Handle for pending transmission request.
241    */
242   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
243
244   /**
245    * To whom are we talking to (set to our identity
246    * if we are still waiting for the welcome message)
247    */
248   struct GNUNET_PeerIdentity target;
249
250   /**
251    * ID of task used to delay receiving more to throttle sender.
252    */
253   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
254
255   /**
256    * Address of the other peer (either based on our 'connect'
257    * call or on our 'accept' call).
258    */
259   void *connect_addr;
260
261   /**
262    * Last activity on this connection.  Used to select preferred
263    * connection.
264    */
265   struct GNUNET_TIME_Absolute last_activity;
266
267   /**
268    * Length of connect_addr.
269    */
270   size_t connect_alen;
271
272   /**
273    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
274    */
275   int expecting_welcome;
276
277   /**
278    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
279    */
280   int inbound;
281
282 };
283
284
285 /**
286  * Encapsulation of all of the state of the plugin.
287  */
288 struct Plugin
289 {
290   /**
291    * Our environment.
292    */
293   struct GNUNET_TRANSPORT_PluginEnvironment *env;
294
295   /**
296    * The listen socket.
297    */
298   struct GNUNET_CONNECTION_Handle *lsock;
299
300   /*
301    * stdout pipe handle for the gnunet-nat-server process
302    */
303   struct GNUNET_DISK_PipeHandle *server_stdout;
304
305   /*
306    * stdout file handle (for reading) for the gnunet-nat-server process
307    */
308   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
309
310   /**
311    * ID of select gnunet-nat-server stdout read task
312    */
313   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
314
315   /**
316    * The process id of the server process (if behind NAT)
317    */
318   pid_t server_pid;
319
320   /**
321    * List of open TCP sessions.
322    */
323   struct Session *sessions;
324
325   /**
326    * Handle to the network service.
327    */
328   struct GNUNET_SERVICE_Context *service;
329
330   /**
331    * Handle to the server for this service.
332    */
333   struct GNUNET_SERVER_Handle *server;
334
335   /**
336    * Copy of the handler array where the closures are
337    * set to this struct's instance.
338    */
339   struct GNUNET_SERVER_MessageHandler *handlers;
340
341   /**
342    * Handle for request of hostname resolution, non-NULL if pending.
343    */
344   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
345
346   /**
347    * Map of peers we have tried to contact behind a NAT
348    */
349   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
350
351   /**
352    * The external address given to us by the user.  Must be actual
353    * outside visible address for NAT punching to work.
354    */
355   char *external_address;
356
357   /**
358    * The internal address given to us by the user (or discovered).
359    */
360   char *internal_address;
361
362   /**
363    * ID of task used to update our addresses when one expires.
364    */
365   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
366
367   /**
368    * Port that we are actually listening on.
369    */
370   uint16_t open_port;
371
372   /**
373    * Port that the user said we would have visible to the
374    * rest of the world.
375    */
376   uint16_t adv_port;
377
378   /**
379    * Is this transport configured to be behind a NAT?
380    */
381   int behind_nat;
382
383   /**
384    * Is this transport configured to allow connections to NAT'd peers?
385    */
386   int allow_nat;
387
388   /**
389    * Should this transport advertise only NAT addresses (port set to 0)?
390    * If not, all addresses will be duplicated for NAT punching and regular
391    * ports.
392    */
393   int only_nat_addresses;
394
395 };
396
397
398
399
400 /**
401  * Function called for a quick conversion of the binary address to
402  * a numeric address.  Note that the caller must not free the 
403  * address and that the next call to this function is allowed
404  * to override the address again.
405  *
406  * @param cls closure ('struct Plugin*')
407  * @param addr binary address
408  * @param addrlen length of the address
409  * @return string representing the same address 
410  */
411 static const char* 
412 tcp_address_to_string (void *cls,
413                        const void *addr,
414                        size_t addrlen)
415 {
416   static char rbuf[INET6_ADDRSTRLEN + 12];
417   char buf[INET6_ADDRSTRLEN];
418   const void *sb;
419   struct in_addr a4;
420   struct in6_addr a6;
421   const struct IPv4TcpAddress *t4;
422   const struct IPv6TcpAddress *t6;
423   int af;
424   uint16_t port;
425
426   if (addrlen == sizeof (struct IPv6TcpAddress))
427     {
428       t6 = addr;
429       af = AF_INET6;
430       port = ntohs (t6->t6_port);
431       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
432       sb = &a6;
433     }
434   else if (addrlen == sizeof (struct IPv4TcpAddress))
435     {
436       t4 = addr;
437       af = AF_INET;
438       port = ntohs (t4->t_port);
439       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
440       sb = &a4;
441     }
442   else
443     {
444       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
445                        "tcp",
446                        _("Unexpected address length: %u\n"),
447                        addrlen);
448       GNUNET_break (0);
449       return NULL;
450     }
451   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
452     {
453       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
454       return NULL;
455     }
456   GNUNET_snprintf (rbuf,
457                    sizeof (rbuf),
458                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
459                    buf,
460                    port);
461   return rbuf;
462 }
463
464
465 /**
466  * Find the session handle for the given client.
467  *
468  * @return NULL if no matching session exists
469  */
470 static struct Session *
471 find_session_by_client (struct Plugin *plugin,
472                         const struct GNUNET_SERVER_Client *client)
473 {
474   struct Session *ret;
475
476   ret = plugin->sessions;
477   while ((ret != NULL) && (client != ret->client))
478     ret = ret->next;
479   return ret;
480 }
481
482 /**
483  * Create a new session.  Also queues a welcome message.
484  *
485  * @param plugin us
486  * @param target peer to connect to
487  * @param client client to use
488  * @param is_nat this a NAT session, we should wait for a client to
489  *               connect to us from an address, then assign that to
490  *               the session
491  * @return new session object
492  */
493 static struct Session *
494 create_session (struct Plugin *plugin,
495                 const struct GNUNET_PeerIdentity *target,
496                 struct GNUNET_SERVER_Client *client, int is_nat)
497 {
498   struct Session *ret;
499   struct PendingMessage *pm;
500   struct WelcomeMessage welcome;
501
502   if (is_nat != GNUNET_YES)
503     GNUNET_assert (client != NULL);
504   else
505     GNUNET_assert (client == NULL);
506
507 #if DEBUG_TCP
508   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
509                    "tcp",
510                    "Creating new session for peer `%4s'\n",
511                    GNUNET_i2s (target));
512 #endif
513   ret = GNUNET_malloc (sizeof (struct Session));
514   ret->last_activity = GNUNET_TIME_absolute_get ();
515   ret->plugin = plugin;
516   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
517     {
518       ret->next = plugin->sessions;
519       plugin->sessions = ret;
520     }
521   ret->client = client;
522   ret->target = *target;
523   ret->expecting_welcome = GNUNET_YES;
524   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
525   pm->msg = (const char*) &pm[1];
526   pm->message_size = sizeof (struct WelcomeMessage);
527   welcome.header.size = htons (sizeof (struct WelcomeMessage));
528   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
529   welcome.clientIdentity = *plugin->env->my_identity;
530   memcpy (&pm[1], &welcome, sizeof (welcome));
531   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
532   GNUNET_STATISTICS_update (plugin->env->stats,
533                             gettext_noop ("# bytes currently in TCP buffers"),
534                             pm->message_size,
535                             GNUNET_NO);      
536   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
537                                ret->pending_messages_tail,
538                                pm);
539   if (is_nat != GNUNET_YES)
540     GNUNET_STATISTICS_update (plugin->env->stats,
541                               gettext_noop ("# TCP sessions active"),
542                               1,
543                               GNUNET_NO);
544   return ret;
545 }
546
547
548 /**
549  * If we have pending messages, ask the server to
550  * transmit them (schedule the respective tasks, etc.)
551  *
552  * @param session for which session should we do this
553  */
554 static void process_pending_messages (struct Session *session);
555
556
557 /**
558  * Function called to notify a client about the socket
559  * being ready to queue more data.  "buf" will be
560  * NULL and "size" zero if the socket was closed for
561  * writing in the meantime.
562  *
563  * @param cls closure
564  * @param size number of bytes available in buf
565  * @param buf where the callee should write the message
566  * @return number of bytes written to buf
567  */
568 static size_t
569 do_transmit (void *cls, size_t size, void *buf)
570 {
571   struct Session *session = cls;
572   struct GNUNET_PeerIdentity pid;
573   struct Plugin *plugin;
574   struct PendingMessage *pos;
575   struct PendingMessage *hd;
576   struct PendingMessage *tl;
577   struct GNUNET_TIME_Absolute now;
578   char *cbuf;
579   size_t ret;
580
581   session->transmit_handle = NULL;
582   plugin = session->plugin;
583   if (buf == NULL)
584     {
585 #if DEBUG_TCP
586       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
587                        "tcp",
588                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
589                        GNUNET_i2s (&session->target));
590 #endif
591       /* timeout; cancel all messages that have already expired */
592       hd = NULL;
593       tl = NULL;
594       ret = 0;
595       now = GNUNET_TIME_absolute_get ();
596       while ( (NULL != (pos = session->pending_messages_head)) &&
597               (pos->timeout.value <= now.value) )
598         {
599           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
600                                        session->pending_messages_tail,
601                                        pos);
602 #if DEBUG_TCP
603           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
604                            "tcp",
605                            "Failed to transmit %u byte message to `%4s'.\n",
606                            pos->message_size,
607                            GNUNET_i2s (&session->target));
608 #endif
609           ret += pos->message_size;
610           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
611         }
612       /* do this call before callbacks (so that if callbacks destroy
613          session, they have a chance to cancel actions done by this
614          call) */
615       process_pending_messages (session);  
616       pid = session->target;
617       /* no do callbacks and do not use session again since
618          the callbacks may abort the session */
619       while (NULL != (pos = hd))
620         {
621           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
622           if (pos->transmit_cont != NULL)
623             pos->transmit_cont (pos->transmit_cont_cls,
624                                 &pid, GNUNET_SYSERR);
625           GNUNET_free (pos);
626         }
627       GNUNET_STATISTICS_update (plugin->env->stats,
628                                 gettext_noop ("# bytes currently in TCP buffers"),
629                                 - (int64_t) ret,
630                                 GNUNET_NO); 
631       GNUNET_STATISTICS_update (plugin->env->stats,
632                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
633                                 ret,
634                                 GNUNET_NO);      
635       return 0;
636     }
637   /* copy all pending messages that would fit */
638   ret = 0;
639   cbuf = buf;
640   hd = NULL;
641   tl = NULL;
642   while (NULL != (pos = session->pending_messages_head)) 
643     {
644       if (ret + pos->message_size > size) 
645         break;
646       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
647                                    session->pending_messages_tail,
648                                    pos);
649       GNUNET_assert (size >= pos->message_size);
650       memcpy (cbuf, pos->msg, pos->message_size);
651       cbuf += pos->message_size;
652       ret += pos->message_size;
653       size -= pos->message_size;
654       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
655     }
656   /* schedule 'continuation' before callbacks so that callbacks that
657      cancel everything don't cause us to use a session that no longer
658      exists... */
659   process_pending_messages (session);  
660   session->last_activity = GNUNET_TIME_absolute_get ();
661   pid = session->target;
662   /* we'll now call callbacks that may cancel the session; hence
663      we should not use 'session' after this point */
664   while (NULL != (pos = hd))
665     {
666       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
667       if (pos->transmit_cont != NULL)
668         pos->transmit_cont (pos->transmit_cont_cls,
669                             &pid, GNUNET_OK);
670       GNUNET_free (pos);
671     }
672   GNUNET_assert (hd == NULL);
673   GNUNET_assert (tl == NULL);
674 #if DEBUG_TCP > 1
675   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
676                    "tcp", "Transmitting %u bytes\n", ret);
677 #endif
678   GNUNET_STATISTICS_update (plugin->env->stats,
679                             gettext_noop ("# bytes currently in TCP buffers"),
680                             - (int64_t) ret,
681                             GNUNET_NO);       
682   GNUNET_STATISTICS_update (plugin->env->stats,
683                             gettext_noop ("# bytes transmitted via TCP"),
684                             ret,
685                             GNUNET_NO);      
686   return ret;
687 }
688
689
690 /**
691  * If we have pending messages, ask the server to
692  * transmit them (schedule the respective tasks, etc.)
693  *
694  * @param session for which session should we do this
695  */
696 static void
697 process_pending_messages (struct Session *session)
698 {
699   struct PendingMessage *pm;
700
701   GNUNET_assert (session->client != NULL);
702   if (session->transmit_handle != NULL)
703     return;
704   if (NULL == (pm = session->pending_messages_head))
705     return;
706   session->transmit_handle
707     = GNUNET_SERVER_notify_transmit_ready (session->client,
708                                            pm->message_size,
709                                            GNUNET_TIME_absolute_get_remaining
710                                            (pm->timeout),
711                                            &do_transmit, session);
712 }
713
714
715 /**
716  * Functions with this signature are called whenever we need
717  * to close a session due to a disconnect or failure to
718  * establish a connection.
719  *
720  * @param session session to close down
721  */
722 static void
723 disconnect_session (struct Session *session)
724 {
725   struct Session *prev;
726   struct Session *pos;
727   struct PendingMessage *pm;
728
729 #if DEBUG_TCP
730   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
731                    "tcp",
732                    "Disconnecting from `%4s' at %s (session %p).\n",
733                    GNUNET_i2s (&session->target),
734                    (session->connect_addr != NULL) ?
735                    tcp_address_to_string (session->plugin,
736                                           session->connect_addr,
737                                           session->connect_alen) : "*", 
738                    session);
739 #endif
740   /* remove from session list */
741   prev = NULL;
742   pos = session->plugin->sessions;
743   while (pos != session)
744     {
745       prev = pos;
746       pos = pos->next;
747     }
748   if (prev == NULL)
749     session->plugin->sessions = session->next;
750   else
751     prev->next = session->next;
752   session->plugin->env->session_end (session->plugin->env->cls,
753                             &session->target,
754                             session);
755   /* clean up state */
756   if (session->transmit_handle != NULL)
757     {
758       GNUNET_CONNECTION_notify_transmit_ready_cancel
759         (session->transmit_handle);
760       session->transmit_handle = NULL;
761     }
762   while (NULL != (pm = session->pending_messages_head))
763     {
764 #if DEBUG_TCP
765       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
766                        "tcp",
767                        pm->transmit_cont != NULL
768                        ? "Could not deliver message to `%4s'.\n"
769                        :
770                        "Could not deliver message to `%4s', notifying.\n",
771                        GNUNET_i2s (&session->target));
772 #endif
773       GNUNET_STATISTICS_update (session->plugin->env->stats,
774                                 gettext_noop ("# bytes currently in TCP buffers"),
775                                 - (int64_t) pm->message_size,
776                                 GNUNET_NO);      
777       GNUNET_STATISTICS_update (session->plugin->env->stats,
778                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
779                                 pm->message_size,
780                                 GNUNET_NO);      
781       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
782                                    session->pending_messages_tail,
783                                    pm);
784       if (NULL != pm->transmit_cont)
785         pm->transmit_cont (pm->transmit_cont_cls,
786                            &session->target, GNUNET_SYSERR);
787       GNUNET_free (pm);
788     }
789   GNUNET_break (session->client != NULL);
790   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
791     {
792       GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
793                                session->receive_delay_task);
794       if (session->client != NULL)
795         GNUNET_SERVER_receive_done (session->client, 
796                                     GNUNET_SYSERR);     
797     }
798   if (session->client != NULL)       
799     GNUNET_SERVER_client_drop (session->client);
800   GNUNET_STATISTICS_update (session->plugin->env->stats,
801                             gettext_noop ("# TCP sessions active"),
802                             -1,
803                             GNUNET_NO);      
804   GNUNET_free_non_null (session->connect_addr);
805   GNUNET_free (session);
806 }
807
808
809 /**
810  * Given two otherwise equivalent sessions, pick the better one.
811  * 
812  * @param s1 one session (also default)
813  * @param s2 other session
814  * @return "better" session (more active)
815  */
816 static struct Session *
817 select_better_session (struct Session *s1,
818                        struct Session *s2)
819 {
820   if (s1 == NULL)
821     return s2;
822   if (s2 == NULL)
823     return s1;
824   if ( (s1->expecting_welcome == GNUNET_NO) &&
825        (s2->expecting_welcome == GNUNET_YES) )
826     return s1;
827   if ( (s1->expecting_welcome == GNUNET_YES) &&
828        (s2->expecting_welcome == GNUNET_NO) )
829     return s2;
830   if (s1->last_activity.value < s2->last_activity.value)
831     return s2;
832   if (s1->last_activity.value > s2->last_activity.value)
833     return s1;
834   if ( (GNUNET_YES == s1->inbound) &&
835        (GNUNET_NO  == s2->inbound) )
836     return s1;
837   if ( (GNUNET_NO  == s1->inbound) &&
838        (GNUNET_YES == s2->inbound) )
839     return s2;
840   return s1;
841 }
842
843
844 /**
845  * We learned about a peer (possibly behind NAT) so run the
846  * gnunet-nat-client to send dummy ICMP responses
847  *
848  * @param plugin the plugin for this transport
849  * @param addr the address of the peer
850  * @param addrlen the length of the address
851  */
852 void
853 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
854 {
855   char inet4[INET_ADDRSTRLEN];
856   char *address_as_string;
857   char *port_as_string;
858   pid_t pid;
859   const struct sockaddr *sa = (const struct sockaddr *)addr;
860 #if DEBUG_TCP_NAT
861   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
862                   _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
863 #endif
864
865   if (addrlen < sizeof (struct sockaddr))
866     return;
867
868   switch (sa->sa_family)
869     {
870     case AF_INET:
871       if (addrlen != sizeof (struct sockaddr_in))
872         return;
873       if (NULL == inet_ntop (AF_INET,
874                              &((struct sockaddr_in *) sa)->sin_addr,
875                              inet4, INET_ADDRSTRLEN))
876         {
877           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
878           return;
879         }
880       address_as_string = GNUNET_strdup (inet4);
881       break;
882     case AF_INET6:
883     default:
884       return;
885     }
886
887   GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
888 #if DEBUG_TCP_NAT
889   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
890                   _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
891 #endif
892
893   /* Start the client process */
894   pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
895   GNUNET_free(address_as_string);
896   GNUNET_free(port_as_string);
897   GNUNET_OS_process_wait (pid);
898 }
899
900
901 /**
902  * Function that can be used by the transport service to transmit
903  * a message using the plugin.   Note that in the case of a
904  * peer disconnecting, the continuation MUST be called
905  * prior to the disconnect notification itself.  This function
906  * will be called with this peer's HELLO message to initiate
907  * a fresh connection to another peer.
908  *
909  * @param cls closure
910  * @param target who should receive this message
911  * @param msg the message to transmit
912  * @param msgbuf_size number of bytes in 'msg'
913  * @param priority how important is the message (most plugins will
914  *                 ignore message priority and just FIFO)
915  * @param timeout how long to wait at most for the transmission (does not
916  *                require plugins to discard the message after the timeout,
917  *                just advisory for the desired delay; most plugins will ignore
918  *                this as well)
919  * @param session which session must be used (or NULL for "any")
920  * @param addr the address to use (can be NULL if the plugin
921  *                is "on its own" (i.e. re-use existing TCP connection))
922  * @param addrlen length of the address in bytes
923  * @param force_address GNUNET_YES if the plugin MUST use the given address,
924  *                GNUNET_NO means the plugin may use any other address and
925  *                GNUNET_SYSERR means that only reliable existing
926  *                bi-directional connections should be used (regardless
927  *                of address)
928  * @param cont continuation to call once the message has
929  *        been transmitted (or if the transport is ready
930  *        for the next transmission call; or if the
931  *        peer disconnected...); can be NULL
932  * @param cont_cls closure for cont
933  * @return number of bytes used (on the physical network, with overheads);
934  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
935  *         and does NOT mean that the message was not transmitted (DV and NAT)
936  */
937 static ssize_t
938 tcp_plugin_send (void *cls,
939                  const struct GNUNET_PeerIdentity *target,
940                  const char *msg,
941                  size_t msgbuf_size,
942                  uint32_t priority,
943                  struct GNUNET_TIME_Relative timeout,
944                  struct Session *session,
945                  const void *addr,
946                  size_t addrlen,
947                  int force_address,
948                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
949 {
950   struct Plugin *plugin = cls;
951   struct Session *cand_session;
952   struct Session *next;
953   struct PendingMessage *pm;
954   struct GNUNET_CONNECTION_Handle *sa;
955   int af;
956   const void *sb;
957   size_t sbs;
958   struct sockaddr_in a4;
959   struct sockaddr_in6 a6;
960   const struct IPv4TcpAddress *t4;
961   const struct IPv6TcpAddress *t6;
962   unsigned int is_natd;
963
964   GNUNET_STATISTICS_update (plugin->env->stats,
965                             gettext_noop ("# bytes TCP was asked to transmit"),
966                             msgbuf_size,
967                             GNUNET_NO);      
968   /* FIXME: we could do this cheaper with a hash table
969      where we could restrict the iteration to entries that match
970      the target peer... */
971   is_natd = GNUNET_NO;
972   if (session == NULL)
973     {
974       cand_session = NULL;
975       next = plugin->sessions;
976       while (NULL != (session = next)) 
977         {
978           next = session->next;
979           GNUNET_assert (session->client != NULL);
980           if (0 != memcmp (target,
981                            &session->target, 
982                            sizeof (struct GNUNET_PeerIdentity)))
983             continue;
984           if ( ( (GNUNET_SYSERR == force_address) &&
985                  (session->expecting_welcome == GNUNET_NO) ) ||
986                (GNUNET_NO == force_address) )   
987             {
988               cand_session = select_better_session (cand_session,
989                                                     session);
990               continue;
991             }
992           if (GNUNET_SYSERR == force_address)
993             continue;
994           GNUNET_break (GNUNET_YES == force_address);
995           if (addr == NULL)
996             {
997               GNUNET_break (0);
998               break;
999             }
1000           if (session->inbound == GNUNET_YES) 
1001             continue;
1002           if (addrlen != session->connect_alen)
1003             continue;
1004           if (0 != memcmp (session->connect_addr,
1005                            addr,
1006                            addrlen))
1007             continue;
1008           cand_session = select_better_session (cand_session,
1009                                                 session);             
1010         }
1011       session = cand_session;
1012     }
1013   if ( (session == NULL) &&
1014        (addr == NULL) )
1015     {
1016 #if DEBUG_TCP
1017       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1018                        "tcp",
1019                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1020                        GNUNET_i2s (target));
1021 #endif
1022       GNUNET_STATISTICS_update (plugin->env->stats,
1023                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1024                                 msgbuf_size,
1025                                 GNUNET_NO);      
1026       return -1;
1027     }
1028   if (session == NULL)
1029     {
1030       if (addrlen == sizeof (struct IPv6TcpAddress))
1031         {
1032           t6 = addr;
1033           af = AF_INET6;
1034           memset (&a6, 0, sizeof (a6));
1035 #if HAVE_SOCKADDR_IN_SIN_LEN
1036           a6.sin6_len = sizeof (a6);
1037 #endif
1038           a6.sin6_family = AF_INET6;
1039           a6.sin6_port = t6->t6_port;
1040           if (t6->t6_port == 0)
1041             is_natd = GNUNET_YES;
1042           memcpy (&a6.sin6_addr,
1043                   &t6->ipv6_addr,
1044                   sizeof (struct in6_addr));      
1045           sb = &a6;
1046           sbs = sizeof (a6);
1047         }
1048       else if (addrlen == sizeof (struct IPv4TcpAddress))
1049         {
1050           t4 = addr;
1051           af = AF_INET;
1052           memset (&a4, 0, sizeof (a4));
1053 #if HAVE_SOCKADDR_IN_SIN_LEN
1054           a4.sin_len = sizeof (a4);
1055 #endif
1056           a4.sin_family = AF_INET;
1057           a4.sin_port = t4->t_port;
1058           if (t4->t_port == 0)
1059             is_natd = GNUNET_YES;
1060           a4.sin_addr.s_addr = t4->ipv4_addr;
1061           sb = &a4;
1062           sbs = sizeof (a4);
1063         }
1064       else
1065         {
1066           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1067                            "tcp",
1068                            _("Address of unexpected length: %u\n"),
1069                            addrlen);
1070           GNUNET_break (0);
1071           return -1;
1072         }
1073
1074       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1075         return -1; /* NAT client only works with IPv4 addresses */
1076
1077
1078       if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1079            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1080         {
1081 #if DEBUG_TCP_NAT
1082           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1083                            "tcp",
1084                            _("Found valid IPv4 NAT address!\n"));
1085 #endif
1086           session = create_session (plugin,
1087                                     target,
1088                                     NULL, is_natd);
1089
1090           /* create new message entry */
1091           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1092           pm->msg = (const char*) &pm[1];
1093           memcpy (&pm[1], msg, msgbuf_size);
1094           pm->message_size = msgbuf_size;
1095           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1096           pm->transmit_cont = cont;
1097           pm->transmit_cont_cls = cont_cls;
1098
1099           /* append pm to pending_messages list */
1100           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1101                                              session->pending_messages_tail,
1102                                              session->pending_messages_tail,
1103                                              pm);
1104
1105           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1106 #if DEBUG_TCP_NAT
1107           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1108                            "tcp",
1109                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1110                            GNUNET_i2s (target),
1111                            GNUNET_a2s (sb, sbs));
1112 #endif
1113           run_gnunet_nat_client(plugin, sb, sbs);
1114           return 0;
1115         }
1116       else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1117         {
1118           /* Only do one NAT punch attempt per peer identity */
1119           return -1;
1120         }
1121       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1122                                                    af, sb, sbs,
1123                                                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
1124       if (sa == NULL)
1125         {
1126 #if DEBUG_TCP
1127           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1128                            "tcp",
1129                            "Failed to create connection to `%4s' at `%s'\n",
1130                            GNUNET_i2s (target),
1131                            GNUNET_a2s (sb, sbs));
1132 #endif
1133           GNUNET_STATISTICS_update (plugin->env->stats,
1134                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1135                                     msgbuf_size,
1136                                     GNUNET_NO);      
1137           return -1;
1138         }
1139 #if DEBUG_TCP
1140       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1141                        "tcp",
1142                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1143                        GNUNET_i2s (target),
1144                        GNUNET_a2s (sb, sbs));
1145 #endif
1146       session = create_session (plugin,
1147                                 target,
1148                                 GNUNET_SERVER_connect_socket (plugin->server,
1149                                                               sa), is_natd);
1150       session->connect_addr = GNUNET_malloc (addrlen);
1151       memcpy (session->connect_addr,
1152               addr,
1153               addrlen);
1154       session->connect_alen = addrlen;
1155     }
1156   GNUNET_assert (session != NULL);
1157   GNUNET_assert (session->client != NULL);
1158   GNUNET_STATISTICS_update (plugin->env->stats,
1159                             gettext_noop ("# bytes currently in TCP buffers"),
1160                             msgbuf_size,
1161                             GNUNET_NO);      
1162   /* create new message entry */
1163   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1164   pm->msg = (const char*) &pm[1];
1165   memcpy (&pm[1], msg, msgbuf_size);
1166   pm->message_size = msgbuf_size;
1167   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1168   pm->transmit_cont = cont;
1169   pm->transmit_cont_cls = cont_cls;
1170
1171   /* append pm to pending_messages list */
1172   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1173                                      session->pending_messages_tail,
1174                                      session->pending_messages_tail,
1175                                      pm);
1176 #if DEBUG_TCP
1177   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1178                    "tcp",
1179                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1180                    msgbuf_size,
1181                    GNUNET_i2s (target));
1182 #endif
1183   process_pending_messages (session);
1184   return msgbuf_size;
1185 }
1186
1187
1188 /**
1189  * Function that can be called to force a disconnect from the
1190  * specified neighbour.  This should also cancel all previously
1191  * scheduled transmissions.  Obviously the transmission may have been
1192  * partially completed already, which is OK.  The plugin is supposed
1193  * to close the connection (if applicable) and no longer call the
1194  * transmit continuation(s).
1195  *
1196  * Finally, plugin MUST NOT call the services's receive function to
1197  * notify the service that the connection to the specified target was
1198  * closed after a getting this call.
1199  *
1200  * @param cls closure
1201  * @param target peer for which the last transmission is
1202  *        to be cancelled
1203  */
1204 static void
1205 tcp_plugin_disconnect (void *cls,
1206                        const struct GNUNET_PeerIdentity *target)
1207 {
1208   struct Plugin *plugin = cls;
1209   struct Session *session;
1210   struct Session *next;
1211   struct PendingMessage *pm;
1212
1213 #if DEBUG_TCP
1214   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1215                    "tcp",
1216                    "Asked to cancel session with `%4s'\n",
1217                    GNUNET_i2s (target));
1218 #endif
1219   next = plugin->sessions;
1220   while (NULL != (session = next))
1221     {
1222       next = session->next;
1223       if (0 != memcmp (target,
1224                        &session->target,
1225                        sizeof (struct GNUNET_PeerIdentity)))
1226         continue;
1227       pm = session->pending_messages_head;
1228       while (pm != NULL)
1229         {
1230           pm->transmit_cont = NULL;
1231           pm->transmit_cont_cls = NULL;
1232           pm = pm->next;
1233         }
1234       disconnect_session (session);
1235     }
1236 }
1237
1238
1239 /**
1240  * Context for address to string conversion.
1241  */
1242 struct PrettyPrinterContext
1243 {
1244   /**
1245    * Function to call with the result.
1246    */
1247   GNUNET_TRANSPORT_AddressStringCallback asc;
1248
1249   /**
1250    * Clsoure for 'asc'.
1251    */
1252   void *asc_cls;
1253
1254   /**
1255    * Port to add after the IP address.
1256    */
1257   uint16_t port;
1258 };
1259
1260
1261 /**
1262  * Append our port and forward the result.
1263  *
1264  * @param cls the 'struct PrettyPrinterContext*'
1265  * @param hostname hostname part of the address
1266  */
1267 static void
1268 append_port (void *cls, const char *hostname)
1269 {
1270   struct PrettyPrinterContext *ppc = cls;
1271   char *ret;
1272
1273   if (hostname == NULL)
1274     {
1275       ppc->asc (ppc->asc_cls, NULL);
1276       GNUNET_free (ppc);
1277       return;
1278     }
1279   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1280   ppc->asc (ppc->asc_cls, ret);
1281   GNUNET_free (ret);
1282 }
1283
1284
1285 /**
1286  * Convert the transports address to a nice, human-readable
1287  * format.
1288  *
1289  * @param cls closure
1290  * @param type name of the transport that generated the address
1291  * @param addr one of the addresses of the host, NULL for the last address
1292  *        the specific address format depends on the transport
1293  * @param addrlen length of the address
1294  * @param numeric should (IP) addresses be displayed in numeric form?
1295  * @param timeout after how long should we give up?
1296  * @param asc function to call on each string
1297  * @param asc_cls closure for asc
1298  */
1299 static void
1300 tcp_plugin_address_pretty_printer (void *cls,
1301                                    const char *type,
1302                                    const void *addr,
1303                                    size_t addrlen,
1304                                    int numeric,
1305                                    struct GNUNET_TIME_Relative timeout,
1306                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1307                                    void *asc_cls)
1308 {
1309   struct Plugin *plugin = cls;
1310   struct PrettyPrinterContext *ppc;
1311   const void *sb;
1312   size_t sbs;
1313   struct sockaddr_in a4;
1314   struct sockaddr_in6 a6;
1315   const struct IPv4TcpAddress *t4;
1316   const struct IPv6TcpAddress *t6;
1317   uint16_t port;
1318
1319   if (addrlen == sizeof (struct IPv6TcpAddress))
1320     {
1321       t6 = addr;
1322       memset (&a6, 0, sizeof (a6));
1323       a6.sin6_family = AF_INET6;
1324       a6.sin6_port = t6->t6_port;
1325       memcpy (&a6.sin6_addr,
1326               &t6->ipv6_addr,
1327               sizeof (struct in6_addr));      
1328       port = ntohs (t6->t6_port);
1329       sb = &a6;
1330       sbs = sizeof (a6);
1331     }
1332   else if (addrlen == sizeof (struct IPv4TcpAddress))
1333     {
1334       t4 = addr;
1335       memset (&a4, 0, sizeof (a4));
1336       a4.sin_family = AF_INET;
1337       a4.sin_port = t4->t_port;
1338       a4.sin_addr.s_addr = t4->ipv4_addr;
1339       port = ntohs (t4->t_port);
1340       sb = &a4;
1341       sbs = sizeof (a4);
1342     }
1343   else
1344     {
1345       /* invalid address */
1346       GNUNET_break_op (0);
1347       asc (asc_cls, NULL);
1348       return;
1349     }
1350   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1351   ppc->asc = asc;
1352   ppc->asc_cls = asc_cls;
1353   ppc->port = port;
1354   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1355                                 plugin->env->cfg,
1356                                 sb,
1357                                 sbs,
1358                                 !numeric, timeout, &append_port, ppc);
1359 }
1360
1361
1362 /**
1363  * Check if the given port is plausible (must be either
1364  * our listen port or our advertised port).  If it is
1365  * neither, we return one of these two ports at random.
1366  *
1367  * @param plugin global variables
1368  * @param in_port port number to check
1369  * @return either in_port or a more plausible port
1370  */
1371 static uint16_t
1372 check_port (struct Plugin *plugin, uint16_t in_port)
1373 {
1374   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1375     return in_port;
1376   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1377                                     2) == 0)
1378     ? plugin->open_port : plugin->adv_port;
1379 }
1380
1381
1382 /**
1383  * Another peer has suggested an address for this peer and transport
1384  * plugin.  Check that this could be a valid address. This function
1385  * is not expected to 'validate' the address in the sense of trying to
1386  * connect to it but simply to see if the binary format is technically
1387  * legal for establishing a connection.
1388  *
1389  * @param cls closure, our 'struct Plugin*'
1390  * @param addr pointer to the address
1391  * @param addrlen length of addr
1392  * @return GNUNET_OK if this is a plausible address for this peer
1393  *         and transport, GNUNET_SYSERR if not
1394  */
1395 static int
1396 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1397 {
1398   struct Plugin *plugin = cls;
1399   struct IPv4TcpAddress *v4;
1400   struct IPv6TcpAddress *v6;
1401
1402   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1403       (addrlen != sizeof (struct IPv6TcpAddress)))
1404     {
1405       GNUNET_break_op (0);
1406       return GNUNET_SYSERR;
1407     }
1408   if (addrlen == sizeof (struct IPv4TcpAddress))
1409     {
1410       v4 = (struct IPv4TcpAddress *) addr;
1411       v4->t_port = htons (check_port (plugin, ntohs (v4->t_port)));
1412     }
1413   else
1414     {
1415       v6 = (struct IPv6TcpAddress *) addr;
1416       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1417         {
1418           GNUNET_break_op (0);
1419           return GNUNET_SYSERR;
1420         }
1421       v6->t6_port = htons (check_port (plugin, ntohs (v6->t6_port)));
1422     }
1423   return GNUNET_OK;
1424 }
1425
1426 /**
1427  * We've received a nat probe from this peer via TCP.  Finish
1428  * creating the client session and resume sending of queued
1429  * messages.
1430  *
1431  * @param cls closure
1432  * @param client identification of the client
1433  * @param message the actual message
1434  */
1435 static void
1436 handle_tcp_nat_probe (void *cls,
1437                      struct GNUNET_SERVER_Client *client,
1438                      const struct GNUNET_MessageHeader *message)
1439 {
1440   struct Plugin *plugin = cls;
1441   struct Session *session;
1442   struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1443   size_t alen;
1444   void *vaddr;
1445   struct IPv4TcpAddress *t4;
1446   struct IPv6TcpAddress *t6;
1447   const struct sockaddr_in *s4;
1448   const struct sockaddr_in6 *s6;
1449
1450 #if DEBUG_TCP_NAT
1451   GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "received tcp NAT probe\n");
1452 #endif
1453   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1454    * a connection to this peer by running gnunet-nat-client.  This peer
1455    * received the punch message and now wants us to use the new connection
1456    * as the default for that peer.  Do so and then send a WELCOME message
1457    * so we can really be connected!
1458    */
1459   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1460     {
1461 #if DEBUG_TCP_NAT
1462       GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Bad size fo tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1463 #endif
1464       GNUNET_break_op(0);
1465       return;
1466     }
1467   tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1468
1469   if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1470     {
1471 #if DEBUG_TCP_NAT
1472       GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Found session for NAT probe!\n");
1473 #endif
1474       session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1475       GNUNET_assert(session != NULL);
1476       GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1477       GNUNET_SERVER_client_keep (client);
1478       session->client = client;
1479       session->last_activity = GNUNET_TIME_absolute_get ();
1480
1481       if (GNUNET_OK ==
1482           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1483         {
1484 #if DEBUG_TCP_NAT
1485           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1486                            "tcp",
1487                            "Found address `%s' for incoming connection %p\n",
1488                            GNUNET_a2s (vaddr, alen),
1489                            client);
1490 #endif
1491           if (alen == sizeof (struct sockaddr_in))
1492             {
1493               s4 = vaddr;
1494               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1495               t4->t_port = s4->sin_port;
1496               t4->ipv4_addr = s4->sin_addr.s_addr;
1497               session->connect_addr = t4;
1498               session->connect_alen = sizeof (struct IPv4TcpAddress);
1499             }
1500           else if (alen == sizeof (struct sockaddr_in6))
1501             {
1502               s6 = vaddr;
1503               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1504               t6->t6_port = s6->sin6_port;
1505               memcpy (&t6->ipv6_addr,
1506                       &s6->sin6_addr,
1507                       sizeof (struct in6_addr));
1508               session->connect_addr = t6;
1509               session->connect_alen = sizeof (struct IPv6TcpAddress);
1510             }
1511
1512           session->connect_addr = GNUNET_malloc (alen);
1513           memcpy (session->connect_addr,
1514                   vaddr,
1515                   alen);
1516           session->connect_alen = alen;
1517           GNUNET_free (vaddr);
1518         }
1519
1520       session->next = plugin->sessions;
1521       plugin->sessions = session;
1522       GNUNET_STATISTICS_update (plugin->env->stats,
1523                                 gettext_noop ("# TCP sessions active"),
1524                                 1,
1525                                 GNUNET_NO);
1526       process_pending_messages (session);
1527     }
1528   else
1529     {
1530 #if DEBUG_TCP_NAT
1531       GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Did NOT find session for NAT probe!\n");
1532 #endif
1533     }
1534 }
1535
1536 /**
1537  * We've received a welcome from this peer via TCP.  Possibly create a
1538  * fresh client record and send back our welcome.
1539  *
1540  * @param cls closure
1541  * @param client identification of the client
1542  * @param message the actual message
1543  */
1544 static void
1545 handle_tcp_welcome (void *cls,
1546                     struct GNUNET_SERVER_Client *client,
1547                     const struct GNUNET_MessageHeader *message)
1548 {
1549   struct Plugin *plugin = cls;
1550   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1551   struct Session *session;
1552   size_t alen;
1553   void *vaddr;
1554   struct IPv4TcpAddress *t4;
1555   struct IPv6TcpAddress *t6;
1556   const struct sockaddr_in *s4;
1557   const struct sockaddr_in6 *s6;
1558
1559
1560 #if DEBUG_TCP
1561   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1562                    "tcp",
1563                    "Received %s message from a `%4s/%p'.\n", 
1564                    "WELCOME",
1565                    GNUNET_i2s (&wm->clientIdentity), client);
1566 #endif
1567   GNUNET_STATISTICS_update (plugin->env->stats,
1568                             gettext_noop ("# TCP WELCOME messages received"),
1569                             1,
1570                             GNUNET_NO);      
1571   session = find_session_by_client (plugin, client);
1572   if (session == NULL)
1573     {
1574       GNUNET_SERVER_client_keep (client);
1575       session = create_session (plugin,
1576                                 &wm->clientIdentity, client, GNUNET_NO);
1577       session->inbound = GNUNET_YES;
1578       if (GNUNET_OK ==
1579           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1580         {
1581 #if DEBUG_TCP
1582           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1583                            "tcp",
1584                            "Found address `%s' for incoming connection %p\n",
1585                            GNUNET_a2s (vaddr, alen),
1586                            client);
1587 #endif
1588           if (alen == sizeof (struct sockaddr_in))
1589             {
1590               s4 = vaddr;
1591               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1592               t4->t_port = s4->sin_port;
1593               t4->ipv4_addr = s4->sin_addr.s_addr;
1594               session->connect_addr = t4;
1595               session->connect_alen = sizeof (struct IPv4TcpAddress);
1596             }
1597           else if (alen == sizeof (struct sockaddr_in6))
1598             {
1599               s6 = vaddr;
1600               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1601               t6->t6_port = s6->sin6_port;
1602               memcpy (&t6->ipv6_addr,
1603                       &s6->sin6_addr,
1604                       sizeof (struct in6_addr));
1605               session->connect_addr = t6;
1606               session->connect_alen = sizeof (struct IPv6TcpAddress);
1607             }
1608           GNUNET_free (vaddr);
1609         }
1610       else
1611         {
1612 #if DEBUG_TCP
1613           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1614                            "tcp",
1615                            "Did not obtain TCP socket address for incoming connection\n");
1616 #endif
1617         }
1618 #if DEBUG_TCP
1619       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1620                        "tcp",
1621                        "Creating new session %p for connection %p\n",
1622                        session, client);
1623 #endif
1624       process_pending_messages (session);
1625     }
1626   if (session->expecting_welcome != GNUNET_YES)
1627     {
1628       GNUNET_break_op (0);
1629       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1630       return;
1631     }
1632   session->last_activity = GNUNET_TIME_absolute_get ();
1633   session->expecting_welcome = GNUNET_NO;
1634   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1635 }
1636
1637
1638 /**
1639  * Task to signal the server that we can continue
1640  * receiving from the TCP client now.
1641  *
1642  * @param cls the 'struct Session*'
1643  * @param tc task context (unused)
1644  */
1645 static void
1646 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1647 {
1648   struct Session *session = cls;
1649   struct GNUNET_TIME_Relative delay;
1650
1651   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1652   delay = session->plugin->env->receive (session->plugin->env->cls,
1653                                          &session->target,
1654                                          NULL, 0, 
1655                                          session,
1656                                          NULL, 0);
1657   if (delay.value == 0)
1658     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1659   else
1660     session->receive_delay_task = 
1661       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1662                                     delay, &delayed_done, session);
1663 }
1664
1665
1666 /**
1667  * We've received data for this peer via TCP.  Unbox,
1668  * compute latency and forward.
1669  *
1670  * @param cls closure
1671  * @param client identification of the client
1672  * @param message the actual message
1673  */
1674 static void
1675 handle_tcp_data (void *cls,
1676                  struct GNUNET_SERVER_Client *client,
1677                  const struct GNUNET_MessageHeader *message)
1678 {
1679   struct Plugin *plugin = cls;
1680   struct Session *session;
1681   struct GNUNET_TIME_Relative delay;
1682
1683   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1684     {
1685       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1686       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1687       return; 
1688     }    
1689   session = find_session_by_client (plugin, client);
1690   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1691     {
1692       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1693       return;
1694     }
1695   session->last_activity = GNUNET_TIME_absolute_get ();
1696 #if DEBUG_TCP
1697   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1698                    "tcp", 
1699                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1700                    (unsigned int) ntohs (message->size), 
1701                    (unsigned int) ntohs (message->type),
1702                    GNUNET_i2s (&session->target));
1703 #endif
1704   GNUNET_STATISTICS_update (plugin->env->stats,
1705                             gettext_noop ("# bytes received via TCP"),
1706                             ntohs (message->size),
1707                             GNUNET_NO); 
1708   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1709                                 session, 
1710                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1711                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1712   if (delay.value == 0)
1713     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1714   else
1715     session->receive_delay_task = 
1716       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1717                                     delay, &delayed_done, session);
1718 }
1719
1720
1721 /**
1722  * Functions with this signature are called whenever a peer
1723  * is disconnected on the network level.
1724  *
1725  * @param cls closure
1726  * @param client identification of the client
1727  */
1728 static void
1729 disconnect_notify (void *cls, 
1730                    struct GNUNET_SERVER_Client *client)
1731 {
1732   struct Plugin *plugin = cls;
1733   struct Session *session;
1734
1735   if (client == NULL)
1736     return;
1737   session = find_session_by_client (plugin, client);
1738   if (session == NULL)
1739     return;                     /* unknown, nothing to do */
1740 #if DEBUG_TCP
1741   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1742                    "tcp",
1743                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1744                    GNUNET_i2s (&session->target),
1745                    (session->connect_addr != NULL) ?
1746                    tcp_address_to_string (session->plugin,
1747                                           session->connect_addr,
1748                                           session->connect_alen) : "*",
1749                    client);
1750 #endif
1751   disconnect_session (session);
1752 }
1753
1754
1755 /**
1756  * Add the IP of our network interface to the list of
1757  * our external IP addresses.
1758  *
1759  * @param cls the 'struct Plugin*'
1760  * @param name name of the interface
1761  * @param isDefault do we think this may be our default interface
1762  * @param addr address of the interface
1763  * @param addrlen number of bytes in addr
1764  * @return GNUNET_OK to continue iterating
1765  */
1766 static int
1767 process_interfaces (void *cls,
1768                     const char *name,
1769                     int isDefault,
1770                     const struct sockaddr *addr, socklen_t addrlen)
1771 {
1772   struct Plugin *plugin = cls;
1773   int af;
1774   struct IPv4TcpAddress t4;
1775   struct IPv6TcpAddress t6;
1776   struct IPv4TcpAddress t4_nat;
1777   struct IPv6TcpAddress t6_nat;
1778   void *arg;
1779   uint16_t args;
1780   void *arg_nat;
1781
1782   af = addr->sa_family;
1783   arg_nat = NULL;
1784   if (af == AF_INET)
1785     {
1786       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1787       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1788         t4.t_port = htons(0);
1789       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1790         {
1791           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1792           t4_nat.t_port = htons(plugin->adv_port);
1793           arg_nat = &t4_nat;
1794         }
1795       else
1796         t4.t_port = htons (plugin->adv_port);
1797       arg = &t4;
1798       args = sizeof (t4);
1799     }
1800   else if (af == AF_INET6)
1801     {
1802       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1803         {
1804           /* skip link local addresses */
1805           return GNUNET_OK;
1806         }
1807       memcpy (&t6.ipv6_addr,
1808               &((struct sockaddr_in6 *) addr)->sin6_addr,
1809               sizeof (struct in6_addr));
1810       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1811         t6.t6_port = htons(0);
1812       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1813         {
1814           memcpy (&t6_nat.ipv6_addr,
1815                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1816                   sizeof (struct in6_addr));
1817           t6_nat.t6_port = htons(plugin->adv_port);
1818           arg_nat = &t6;
1819         }
1820       else
1821         t6.t6_port = htons (plugin->adv_port);
1822       arg = &t6;
1823       args = sizeof (t6);
1824     }
1825   else
1826     {
1827       GNUNET_break (0);
1828       return GNUNET_OK;
1829     }
1830   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1831                    GNUNET_ERROR_TYPE_BULK,
1832                    "tcp", 
1833                    _("Found address `%s' (%s)\n"),
1834                    GNUNET_a2s (addr, addrlen), name);
1835
1836   plugin->env->notify_address (plugin->env->cls,
1837                                "tcp",
1838                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1839
1840   if (arg_nat != NULL)
1841     {
1842       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1843                        GNUNET_ERROR_TYPE_BULK,
1844                       "tcp",
1845                       _("Found address `%s' (%s)\n"),
1846                       GNUNET_a2s (addr, addrlen), name);
1847       plugin->env->notify_address (plugin->env->cls,
1848                                    "tcp",
1849                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1850     }
1851
1852   return GNUNET_OK;
1853 }
1854
1855
1856 /**
1857  * Function called by the resolver for each address obtained from DNS
1858  * for our own hostname.  Add the addresses to the list of our
1859  * external IP addresses.
1860  *
1861  * @param cls closure
1862  * @param addr one of the addresses of the host, NULL for the last address
1863  * @param addrlen length of the address
1864  */
1865 static void
1866 process_hostname_ips (void *cls,
1867                       const struct sockaddr *addr, socklen_t addrlen)
1868 {
1869   struct Plugin *plugin = cls;
1870
1871   if (addr == NULL)
1872     {
1873       plugin->hostname_dns = NULL;
1874       return;
1875     }
1876   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1877   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1878 }
1879
1880 /**
1881  * We can now send a probe message, copy into buffer to really send.
1882  *
1883  * @param cls closure, a struct TCPProbeContext
1884  * @param size max size to copy
1885  * @param buf buffer to copy message to
1886  */
1887 static size_t notify_send_probe (void *cls,
1888                                  size_t size, void *buf)
1889 {
1890   struct TCPProbeContext *tcp_probe_ctx = cls;
1891
1892   if (buf == NULL)
1893     {
1894       return 0;
1895     }
1896
1897   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1898   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1899   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1900                                 tcp_probe_ctx->sock);
1901
1902   GNUNET_free(tcp_probe_ctx);
1903   return sizeof(tcp_probe_ctx->message);
1904 }
1905
1906 /*
1907  * @param cls the plugin handle
1908  * @param tc the scheduling context (for rescheduling this function again)
1909  *
1910  * We have been notified that gnunet-nat-server has written something to stdout.
1911  * Handle the output, then reschedule this function to be called again once
1912  * more is available.
1913  *
1914  */
1915 static void
1916 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1917 {
1918   struct Plugin *plugin = cls;
1919   char mybuf[40];
1920   ssize_t bytes;
1921   memset(&mybuf, 0, sizeof(mybuf));
1922   int i;
1923   int port;
1924   char *port_start;
1925   struct sockaddr_in in_addr;
1926   struct TCPProbeContext *tcp_probe_ctx;
1927   struct GNUNET_CONNECTION_Handle *sock;
1928
1929   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1930     return;
1931
1932   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
1933
1934   if (bytes < 1)
1935     {
1936 #if DEBUG_TCP_NAT
1937       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1938                       _("Finished reading from server stdout with code: %d\n"), bytes);
1939 #endif
1940       return;
1941     }
1942
1943   port = 0;
1944   port_start = NULL;
1945   for (i = 0; i < sizeof(mybuf); i++)
1946     {
1947       if (mybuf[i] == '\n')
1948         mybuf[i] = '\0';
1949
1950       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
1951         {
1952           mybuf[i] = '\0';
1953           port_start = &mybuf[i + 1];
1954         }
1955     }
1956
1957   if (port_start != NULL)
1958     port = atoi(port_start);
1959   else
1960     {
1961       plugin->server_read_task =
1962            GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1963                                            GNUNET_TIME_UNIT_FOREVER_REL,
1964                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1965       return;
1966     }
1967
1968 #if DEBUG_UDP_NAT
1969   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1970                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
1971 #endif
1972
1973
1974   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
1975     {
1976
1977       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1978                   _("nat-server-read malformed address\n"), &mybuf, port);
1979
1980       plugin->server_read_task =
1981           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1982                                           GNUNET_TIME_UNIT_FOREVER_REL,
1983                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1984       return;
1985     }
1986
1987   in_addr.sin_family = AF_INET;
1988   in_addr.sin_port = htons(port);
1989   /**
1990    * We have received an ICMP response, ostensibly from a non-NAT'd peer
1991    *  that wants to connect to us! Send a message to establish a connection.
1992    */
1993   sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
1994                                                  sizeof(in_addr), GNUNET_SERVER_MAX_MESSAGE_SIZE);
1995   if (sock == NULL)
1996     {
1997       plugin->server_read_task =
1998           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1999                                           GNUNET_TIME_UNIT_FOREVER_REL,
2000                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2001       return;
2002     }
2003   else
2004     {
2005       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2006
2007       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2008       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2009       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2010       tcp_probe_ctx->plugin = plugin;
2011       tcp_probe_ctx->sock = sock;
2012       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2013                                                                  ntohs(tcp_probe_ctx->message.header.size),
2014                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2015                                                                  &notify_send_probe, tcp_probe_ctx);
2016
2017     }
2018
2019   plugin->server_read_task =
2020       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2021                                       GNUNET_TIME_UNIT_FOREVER_REL,
2022                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2023 }
2024
2025 /**
2026  * Start the gnunet-nat-server process for users behind NAT.
2027  *
2028  * @param plugin the transport plugin
2029  *
2030  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2031  */
2032 static int
2033 tcp_transport_start_nat_server(struct Plugin *plugin)
2034 {
2035
2036   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2037   if (plugin->server_stdout == NULL)
2038     return GNUNET_SYSERR;
2039
2040 #if DEBUG_TCP_NAT
2041   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2042                    "tcp",
2043                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2044 #endif
2045   /* Start the server process */
2046   plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2047   if (plugin->server_pid == GNUNET_SYSERR)
2048     {
2049 #if DEBUG_TCP_NAT
2050     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2051                      "tcp",
2052                      "Failed to start gnunet-nat-server process\n");
2053 #endif
2054       return GNUNET_SYSERR;
2055     }
2056   /* Close the write end of the read pipe */
2057   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2058
2059   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2060   plugin->server_read_task =
2061       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2062                                       GNUNET_TIME_UNIT_FOREVER_REL,
2063                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2064   return GNUNET_YES;
2065 }
2066
2067 /**
2068  * Return the actual path to a file found in the current
2069  * PATH environment variable.
2070  *
2071  * @param binary the name of the file to find
2072  */
2073 static char *
2074 get_path_from_PATH (char *binary)
2075 {
2076   char *path;
2077   char *pos;
2078   char *end;
2079   char *buf;
2080   const char *p;
2081
2082   p = getenv ("PATH");
2083   if (p == NULL)
2084     return NULL;
2085   path = GNUNET_strdup (p);     /* because we write on it */
2086   buf = GNUNET_malloc (strlen (path) + 20);
2087   pos = path;
2088
2089   while (NULL != (end = strchr (pos, ':')))
2090     {
2091       *end = '\0';
2092       sprintf (buf, "%s/%s", pos, binary);
2093       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2094         {
2095           GNUNET_free (path);
2096           return buf;
2097         }
2098       pos = end + 1;
2099     }
2100   sprintf (buf, "%s/%s", pos, binary);
2101   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2102     {
2103       GNUNET_free (path);
2104       return buf;
2105     }
2106   GNUNET_free (buf);
2107   GNUNET_free (path);
2108   return NULL;
2109 }
2110
2111 /**
2112  * Check whether the suid bit is set on a file.
2113  * Attempts to find the file using the current
2114  * PATH environment variable as a search path.
2115  *
2116  * @param binary the name of the file to check
2117  */
2118 static int
2119 check_gnunet_nat_binary(char *binary)
2120 {
2121   struct stat statbuf;
2122   char *p;
2123
2124   p = get_path_from_PATH (binary);
2125   if (p == NULL)
2126     return GNUNET_NO;
2127   if (0 != STAT (p, &statbuf))
2128     {
2129       GNUNET_free (p);
2130       return GNUNET_SYSERR;
2131     }
2132   GNUNET_free (p);
2133   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2134        (statbuf.st_uid == 0) )
2135     return GNUNET_YES;
2136   return GNUNET_NO;
2137 }
2138
2139 /**
2140  * Entry point for the plugin.
2141  *
2142  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2143  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2144  */
2145 void *
2146 libgnunet_plugin_transport_tcp_init (void *cls)
2147 {
2148   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2149     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2150      sizeof (struct WelcomeMessage)},
2151     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2152     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2153     {NULL, NULL, 0, 0}
2154   };
2155   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2156   struct GNUNET_TRANSPORT_PluginFunctions *api;
2157   struct Plugin *plugin;
2158   struct GNUNET_SERVICE_Context *service;
2159   unsigned long long aport;
2160   unsigned long long bport;
2161   unsigned int i;
2162   int behind_nat;
2163   int allow_nat;
2164   int only_nat_addresses;
2165   char *internal_address;
2166   char *external_address;
2167   struct sockaddr_in in_addr;
2168   struct IPv4TcpAddress t4;
2169
2170   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2171   if (service == NULL)
2172     {
2173       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2174                        "tcp",
2175                        _
2176                        ("Failed to start service for `%s' transport plugin.\n"),
2177                        "tcp");
2178       return NULL;
2179     }
2180
2181   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2182                                                            "transport-tcp",
2183                                                            "BEHIND_NAT"))
2184     {
2185       /* We are behind nat (according to the user) */
2186       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2187         {
2188           behind_nat = GNUNET_YES;
2189         }
2190       else
2191         {
2192           behind_nat = GNUNET_NO;
2193           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
2194         }
2195     }
2196   else
2197     behind_nat = GNUNET_NO; /* We are not behind nat! */
2198
2199   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2200                                                            "transport-tcp",
2201                                                            "ALLOW_NAT"))
2202     {
2203       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2204         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2205       else
2206       {
2207         allow_nat = GNUNET_NO;
2208         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
2209       }
2210     }
2211   else
2212     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2213
2214
2215   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2216                                                            "transport-tcp",
2217                                                            "ONLY_NAT_ADDRESSES"))
2218     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2219   else
2220     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2221
2222   external_address = NULL;
2223   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2224          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2225                                                 "transport-tcp",
2226                                                 "EXTERNAL_ADDRESS",
2227                                                 &external_address)))
2228     {
2229       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2230                        "tcp",
2231                        _
2232                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2233                        "transport-tcp");
2234       GNUNET_SERVICE_stop (service);
2235       return NULL;
2236     }
2237
2238   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2239     {
2240       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2241     }
2242
2243   internal_address = NULL;
2244   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2245          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2246                                                 "transport-tcp",
2247                                                 "INTERNAL_ADDRESS",
2248                                                 &internal_address)))
2249     {
2250       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2251                        "tcp",
2252                        _
2253                        ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2254                        "transport-tcp");
2255       GNUNET_SERVICE_stop (service);
2256       GNUNET_free_non_null(external_address);
2257       return NULL;
2258     }
2259
2260   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2261     {
2262       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2263     }
2264
2265   aport = 0;
2266   if ((GNUNET_OK !=
2267        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2268                                               "transport-tcp",
2269                                               "PORT",
2270                                               &bport)) ||
2271       (bport > 65535) ||
2272       ((GNUNET_OK ==
2273         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2274                                                "transport-tcp",
2275                                                "ADVERTISED-PORT",
2276                                                &aport)) && (aport > 65535)))
2277     {
2278       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2279                        "tcp",
2280                        _
2281                        ("Require valid port number for service `%s' in configuration!\n"),
2282                        "transport-tcp");
2283       GNUNET_free_non_null(external_address);
2284       GNUNET_free_non_null(internal_address);
2285       GNUNET_SERVICE_stop (service);
2286       return NULL;
2287     }
2288
2289   if (aport == 0)
2290     aport = bport;
2291   plugin = GNUNET_malloc (sizeof (struct Plugin));
2292   plugin->open_port = bport;
2293   plugin->adv_port = aport;
2294   plugin->external_address = external_address;
2295   plugin->internal_address = internal_address;
2296   plugin->behind_nat = behind_nat;
2297   plugin->allow_nat = allow_nat;
2298   plugin->only_nat_addresses = only_nat_addresses;
2299   plugin->env = env;
2300   plugin->lsock = NULL;
2301   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2302   api->cls = plugin;
2303   api->send = &tcp_plugin_send;
2304   api->disconnect = &tcp_plugin_disconnect;
2305   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2306   api->check_address = &tcp_plugin_check_address;
2307   api->address_to_string = &tcp_address_to_string;
2308   plugin->service = service;
2309   plugin->server = GNUNET_SERVICE_get_server (service);
2310   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2311   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2312   for (i = 0;
2313        i <
2314        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2315        i++)
2316     plugin->handlers[i].callback_cls = plugin;
2317   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2318
2319   if (behind_nat == GNUNET_YES)
2320     {
2321       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2322         {
2323           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2324                            "tcp",
2325                            _
2326                            ("Failed to start %s required for NAT in %s!\n"),
2327                            "gnunet-nat-server"
2328                            "transport-tcp");
2329           GNUNET_free_non_null(external_address);
2330           GNUNET_free_non_null(internal_address);
2331           GNUNET_SERVICE_stop (service);
2332           return NULL;
2333         }
2334     }
2335
2336   if (allow_nat == GNUNET_YES)
2337     {
2338       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2339       GNUNET_assert(plugin->nat_wait_conns != NULL);
2340     }
2341
2342   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2343                    "tcp", _("TCP transport listening on port %llu\n"), bport);
2344   if (aport != bport)
2345     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2346                      "tcp",
2347                      _("TCP transport advertises itself as being on port %llu\n"),
2348                      aport);
2349   GNUNET_SERVER_disconnect_notify (plugin->server, 
2350                                    &disconnect_notify,
2351                                    plugin);
2352   if (plugin->behind_nat == GNUNET_NO)
2353     {
2354       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2355     }
2356
2357   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2358                                                            env->cfg,
2359                                                            AF_UNSPEC,
2360                                                            HOSTNAME_RESOLVE_TIMEOUT,
2361                                                            &process_hostname_ips,
2362                                                            plugin);
2363
2364   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2365     {
2366       t4.t_port = htons(0);
2367       plugin->env->notify_address (plugin->env->cls,
2368                                   "tcp",
2369                                   &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2370     }
2371   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2372     {
2373       t4.t_port = htons(plugin->adv_port);
2374       plugin->env->notify_address (plugin->env->cls,
2375                                    "tcp",
2376                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2377     }
2378
2379   return api;
2380 }
2381
2382
2383 /**
2384  * Exit point from the plugin.
2385  */
2386 void *
2387 libgnunet_plugin_transport_tcp_done (void *cls)
2388 {
2389   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2390   struct Plugin *plugin = api->cls;
2391   struct Session *session;
2392
2393   while (NULL != (session = plugin->sessions))
2394     disconnect_session (session);
2395   if (NULL != plugin->hostname_dns)
2396     {
2397       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2398       plugin->hostname_dns = NULL;
2399     }
2400   GNUNET_SERVICE_stop (plugin->service);
2401   GNUNET_free (plugin->handlers);
2402   GNUNET_free (plugin);
2403   GNUNET_free (api);
2404   return NULL;
2405 }
2406
2407 /* end of plugin_transport_tcp.c */