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