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