plugin changed to be loadable multiple times
[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  * Functions with this signature are called whenever a peer
1716  * is disconnected on the network level.
1717  *
1718  * @param cls closure
1719  * @param client identification of the client
1720  */
1721 static void
1722 disconnect_notify (void *cls, 
1723                    struct GNUNET_SERVER_Client *client)
1724 {
1725   struct Plugin *plugin = cls;
1726   struct Session *session;
1727
1728   if (client == NULL)
1729     return;
1730   session = find_session_by_client (plugin, client);
1731   if (session == NULL)
1732     return;                     /* unknown, nothing to do */
1733 #if DEBUG_TCP
1734   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1735                    "tcp",
1736                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1737                    GNUNET_i2s (&session->target),
1738                    (session->connect_addr != NULL) ?
1739                    tcp_address_to_string (session->plugin,
1740                                           session->connect_addr,
1741                                           session->connect_alen) : "*",
1742                    client);
1743 #endif
1744   disconnect_session (session);
1745 }
1746
1747
1748 /**
1749  * Add the IP of our network interface to the list of
1750  * our external IP addresses.
1751  *
1752  * @param cls the 'struct Plugin*'
1753  * @param name name of the interface
1754  * @param isDefault do we think this may be our default interface
1755  * @param addr address of the interface
1756  * @param addrlen number of bytes in addr
1757  * @return GNUNET_OK to continue iterating
1758  */
1759 static int
1760 process_interfaces (void *cls,
1761                     const char *name,
1762                     int isDefault,
1763                     const struct sockaddr *addr, socklen_t addrlen)
1764 {
1765   struct Plugin *plugin = cls;
1766   int af;
1767   struct IPv4TcpAddress t4;
1768   struct IPv6TcpAddress t6;
1769   struct IPv4TcpAddress t4_nat;
1770   struct IPv6TcpAddress t6_nat;
1771   void *arg;
1772   uint16_t args;
1773   void *arg_nat;
1774
1775   af = addr->sa_family;
1776   arg_nat = NULL;
1777   if (af == AF_INET)
1778     {
1779       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1780       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1781         t4.t_port = htons(0);
1782       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1783         {
1784           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1785           t4_nat.t_port = htons(plugin->adv_port);
1786           arg_nat = &t4_nat;
1787         }
1788       else
1789         t4.t_port = htons (plugin->adv_port);
1790       arg = &t4;
1791       args = sizeof (t4);
1792     }
1793   else if (af == AF_INET6)
1794     {
1795       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1796         {
1797           /* skip link local addresses */
1798           return GNUNET_OK;
1799         }
1800       memcpy (&t6.ipv6_addr,
1801               &((struct sockaddr_in6 *) addr)->sin6_addr,
1802               sizeof (struct in6_addr));
1803       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1804         t6.t6_port = htons(0);
1805       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1806         {
1807           memcpy (&t6_nat.ipv6_addr,
1808                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1809                   sizeof (struct in6_addr));
1810           t6_nat.t6_port = htons(plugin->adv_port);
1811           arg_nat = &t6;
1812         }
1813       else
1814         t6.t6_port = htons (plugin->adv_port);
1815       arg = &t6;
1816       args = sizeof (t6);
1817     }
1818   else
1819     {
1820       GNUNET_break (0);
1821       return GNUNET_OK;
1822     }
1823   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1824                    GNUNET_ERROR_TYPE_BULK,
1825                    "tcp", 
1826                    _("Found address `%s' (%s)\n"),
1827                    GNUNET_a2s (addr, addrlen), name);
1828
1829   plugin->env->notify_address (plugin->env->cls,
1830                                "tcp",
1831                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1832
1833   if (arg_nat != NULL)
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       plugin->env->notify_address (plugin->env->cls,
1841                                    "tcp",
1842                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1843     }
1844
1845   return GNUNET_OK;
1846 }
1847
1848
1849 /**
1850  * Function called by the resolver for each address obtained from DNS
1851  * for our own hostname.  Add the addresses to the list of our
1852  * external IP addresses.
1853  *
1854  * @param cls closure
1855  * @param addr one of the addresses of the host, NULL for the last address
1856  * @param addrlen length of the address
1857  */
1858 static void
1859 process_hostname_ips (void *cls,
1860                       const struct sockaddr *addr, socklen_t addrlen)
1861 {
1862   struct Plugin *plugin = cls;
1863
1864   if (addr == NULL)
1865     {
1866       plugin->hostname_dns = NULL;
1867       return;
1868     }
1869   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1870   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1871 }
1872
1873 /**
1874  * We can now send a probe message, copy into buffer to really send.
1875  *
1876  * @param cls closure, a struct TCPProbeContext
1877  * @param size max size to copy
1878  * @param buf buffer to copy message to
1879  */
1880 static size_t notify_send_probe (void *cls,
1881                                  size_t size, void *buf)
1882 {
1883   struct TCPProbeContext *tcp_probe_ctx = cls;
1884
1885   if (buf == NULL)
1886     {
1887       return 0;
1888     }
1889
1890   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1891   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1892   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1893                                 tcp_probe_ctx->sock);
1894
1895   GNUNET_free(tcp_probe_ctx);
1896   return sizeof(tcp_probe_ctx->message);
1897 }
1898
1899 /*
1900  * @param cls the plugin handle
1901  * @param tc the scheduling context (for rescheduling this function again)
1902  *
1903  * We have been notified that gnunet-nat-server has written something to stdout.
1904  * Handle the output, then reschedule this function to be called again once
1905  * more is available.
1906  *
1907  */
1908 static void
1909 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 {
1911   struct Plugin *plugin = cls;
1912   char mybuf[40];
1913   ssize_t bytes;
1914   memset(&mybuf, 0, sizeof(mybuf));
1915   int i;
1916   int port;
1917   char *port_start;
1918   struct sockaddr_in in_addr;
1919   struct TCPProbeContext *tcp_probe_ctx;
1920   struct GNUNET_CONNECTION_Handle *sock;
1921
1922   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1923     return;
1924
1925   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
1926
1927   if (bytes < 1)
1928     {
1929 #if DEBUG_TCP_NAT
1930       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1931                       _("Finished reading from server stdout with code: %d\n"), bytes);
1932 #endif
1933       return;
1934     }
1935
1936   port = 0;
1937   port_start = NULL;
1938   for (i = 0; i < sizeof(mybuf); i++)
1939     {
1940       if (mybuf[i] == '\n')
1941         mybuf[i] = '\0';
1942
1943       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
1944         {
1945           mybuf[i] = '\0';
1946           port_start = &mybuf[i + 1];
1947         }
1948     }
1949
1950   if (port_start != NULL)
1951     port = atoi(port_start);
1952   else
1953     {
1954       plugin->server_read_task =
1955            GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1956                                            GNUNET_TIME_UNIT_FOREVER_REL,
1957                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1958       return;
1959     }
1960
1961 #if DEBUG_UDP_NAT
1962   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1963                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
1964 #endif
1965
1966
1967   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
1968     {
1969
1970       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1971                   _("nat-server-read malformed address\n"), &mybuf, port);
1972
1973       plugin->server_read_task =
1974           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1975                                           GNUNET_TIME_UNIT_FOREVER_REL,
1976                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1977       return;
1978     }
1979
1980   in_addr.sin_family = AF_INET;
1981   in_addr.sin_port = htons(port);
1982   /**
1983    * We have received an ICMP response, ostensibly from a non-NAT'd peer
1984    *  that wants to connect to us! Send a message to establish a connection.
1985    */
1986   sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
1987                                                  sizeof(in_addr), GNUNET_SERVER_MAX_MESSAGE_SIZE);
1988   if (sock == NULL)
1989     {
1990       plugin->server_read_task =
1991           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1992                                           GNUNET_TIME_UNIT_FOREVER_REL,
1993                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1994       return;
1995     }
1996   else
1997     {
1998       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
1999
2000       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2001       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2002       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2003       tcp_probe_ctx->plugin = plugin;
2004       tcp_probe_ctx->sock = sock;
2005       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2006                                                                  ntohs(tcp_probe_ctx->message.header.size),
2007                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2008                                                                  &notify_send_probe, tcp_probe_ctx);
2009
2010     }
2011
2012   plugin->server_read_task =
2013       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2014                                       GNUNET_TIME_UNIT_FOREVER_REL,
2015                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2016 }
2017
2018 /**
2019  * Start the gnunet-nat-server process for users behind NAT.
2020  *
2021  * @param plugin the transport plugin
2022  *
2023  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2024  */
2025 static int
2026 tcp_transport_start_nat_server(struct Plugin *plugin)
2027 {
2028
2029   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2030   if (plugin->server_stdout == NULL)
2031     return GNUNET_SYSERR;
2032
2033 #if DEBUG_TCP_NAT
2034   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2035                    "tcp",
2036                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2037 #endif
2038   /* Start the server process */
2039   plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2040   if (plugin->server_pid == GNUNET_SYSERR)
2041     {
2042 #if DEBUG_TCP_NAT
2043     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2044                      "tcp",
2045                      "Failed to start gnunet-nat-server process\n");
2046 #endif
2047       return GNUNET_SYSERR;
2048     }
2049   /* Close the write end of the read pipe */
2050   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2051
2052   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2053   plugin->server_read_task =
2054       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2055                                       GNUNET_TIME_UNIT_FOREVER_REL,
2056                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2057   return GNUNET_YES;
2058 }
2059
2060 /**
2061  * Return the actual path to a file found in the current
2062  * PATH environment variable.
2063  *
2064  * @param binary the name of the file to find
2065  */
2066 static char *
2067 get_path_from_PATH (char *binary)
2068 {
2069   char *path;
2070   char *pos;
2071   char *end;
2072   char *buf;
2073   const char *p;
2074
2075   p = getenv ("PATH");
2076   if (p == NULL)
2077     return NULL;
2078   path = GNUNET_strdup (p);     /* because we write on it */
2079   buf = GNUNET_malloc (strlen (path) + 20);
2080   pos = path;
2081
2082   while (NULL != (end = strchr (pos, ':')))
2083     {
2084       *end = '\0';
2085       sprintf (buf, "%s/%s", pos, binary);
2086       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2087         {
2088           GNUNET_free (path);
2089           return buf;
2090         }
2091       pos = end + 1;
2092     }
2093   sprintf (buf, "%s/%s", pos, binary);
2094   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2095     {
2096       GNUNET_free (path);
2097       return buf;
2098     }
2099   GNUNET_free (buf);
2100   GNUNET_free (path);
2101   return NULL;
2102 }
2103
2104 /**
2105  * Check whether the suid bit is set on a file.
2106  * Attempts to find the file using the current
2107  * PATH environment variable as a search path.
2108  *
2109  * @param binary the name of the file to check
2110  */
2111 static int
2112 check_gnunet_nat_binary(char *binary)
2113 {
2114   struct stat statbuf;
2115   char *p;
2116
2117   p = get_path_from_PATH (binary);
2118   if (p == NULL)
2119     return GNUNET_NO;
2120   if (0 != STAT (p, &statbuf))
2121     {
2122       GNUNET_free (p);
2123       return GNUNET_SYSERR;
2124     }
2125   GNUNET_free (p);
2126   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2127        (statbuf.st_uid == 0) )
2128     return GNUNET_YES;
2129   return GNUNET_NO;
2130 }
2131
2132 /**
2133  * Entry point for the plugin.
2134  *
2135  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2136  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2137  */
2138 void *
2139 libgnunet_plugin_transport_tcp_init (void *cls)
2140 {
2141   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2142     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2143      sizeof (struct WelcomeMessage)},
2144     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2145     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2146     {NULL, NULL, 0, 0}
2147   };
2148   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2149   struct GNUNET_TRANSPORT_PluginFunctions *api;
2150   struct Plugin *plugin;
2151   struct GNUNET_SERVICE_Context *service;
2152   unsigned long long aport;
2153   unsigned long long bport;
2154   unsigned int i;
2155   int behind_nat;
2156   int allow_nat;
2157   int only_nat_addresses;
2158   char *internal_address;
2159   char *external_address;
2160   struct sockaddr_in in_addr;
2161   struct IPv4TcpAddress t4;
2162
2163   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2164   if (service == NULL)
2165     {
2166       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2167                        "tcp",
2168                        _
2169                        ("Failed to start service for `%s' transport plugin.\n"),
2170                        "tcp");
2171       return NULL;
2172     }
2173
2174   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2175                                                            "transport-tcp",
2176                                                            "BEHIND_NAT"))
2177     {
2178       /* We are behind nat (according to the user) */
2179       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2180         {
2181           behind_nat = GNUNET_YES;
2182         }
2183       else
2184         {
2185           behind_nat = GNUNET_NO;
2186           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");
2187         }
2188     }
2189   else
2190     behind_nat = GNUNET_NO; /* We are not behind nat! */
2191
2192   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2193                                                            "transport-tcp",
2194                                                            "ALLOW_NAT"))
2195     {
2196       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2197         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2198       else
2199       {
2200         allow_nat = GNUNET_NO;
2201         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");
2202       }
2203     }
2204   else
2205     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2206
2207
2208   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2209                                                            "transport-tcp",
2210                                                            "ONLY_NAT_ADDRESSES"))
2211     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2212   else
2213     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2214
2215   external_address = NULL;
2216   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2217          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2218                                                 "transport-tcp",
2219                                                 "EXTERNAL_ADDRESS",
2220                                                 &external_address)))
2221     {
2222       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2223                        "tcp",
2224                        _
2225                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2226                        "transport-tcp");
2227       GNUNET_SERVICE_stop (service);
2228       return NULL;
2229     }
2230
2231   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2232     {
2233       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2234     }
2235
2236   internal_address = NULL;
2237   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2238          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2239                                                 "transport-tcp",
2240                                                 "INTERNAL_ADDRESS",
2241                                                 &internal_address)))
2242     {
2243       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2244                        "tcp",
2245                        _
2246                        ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2247                        "transport-tcp");
2248       GNUNET_SERVICE_stop (service);
2249       GNUNET_free_non_null(external_address);
2250       return NULL;
2251     }
2252
2253   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2254     {
2255       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2256     }
2257
2258   aport = 0;
2259   if ((GNUNET_OK !=
2260        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2261                                               "transport-tcp",
2262                                               "PORT",
2263                                               &bport)) ||
2264       (bport > 65535) ||
2265       ((GNUNET_OK ==
2266         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2267                                                "transport-tcp",
2268                                                "ADVERTISED-PORT",
2269                                                &aport)) && (aport > 65535)))
2270     {
2271       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2272                        "tcp",
2273                        _
2274                        ("Require valid port number for service `%s' in configuration!\n"),
2275                        "transport-tcp");
2276       GNUNET_free_non_null(external_address);
2277       GNUNET_free_non_null(internal_address);
2278       GNUNET_SERVICE_stop (service);
2279       return NULL;
2280     }
2281
2282   if (aport == 0)
2283     aport = bport;
2284   plugin = GNUNET_malloc (sizeof (struct Plugin));
2285   plugin->open_port = bport;
2286   plugin->adv_port = aport;
2287   plugin->external_address = external_address;
2288   plugin->internal_address = internal_address;
2289   plugin->behind_nat = behind_nat;
2290   plugin->allow_nat = allow_nat;
2291   plugin->only_nat_addresses = only_nat_addresses;
2292   plugin->env = env;
2293   plugin->lsock = NULL;
2294   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2295   api->cls = plugin;
2296   api->send = &tcp_plugin_send;
2297   api->disconnect = &tcp_plugin_disconnect;
2298   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2299   api->check_address = &tcp_plugin_check_address;
2300   api->address_to_string = &tcp_address_to_string;
2301   plugin->service = service;
2302   plugin->server = GNUNET_SERVICE_get_server (service);
2303   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2304   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2305   for (i = 0;
2306        i <
2307        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2308        i++)
2309     plugin->handlers[i].callback_cls = plugin;
2310   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2311
2312   if (behind_nat == GNUNET_YES)
2313     {
2314       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2315         {
2316           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2317                            "tcp",
2318                            _
2319                            ("Failed to start %s required for NAT in %s!\n"),
2320                            "gnunet-nat-server"
2321                            "transport-tcp");
2322           GNUNET_free_non_null(external_address);
2323           GNUNET_free_non_null(internal_address);
2324           GNUNET_SERVICE_stop (service);
2325           return NULL;
2326         }
2327     }
2328
2329   if (allow_nat == GNUNET_YES)
2330     {
2331       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2332       GNUNET_assert(plugin->nat_wait_conns != NULL);
2333     }
2334
2335   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2336                    "tcp", _("TCP transport listening on port %llu\n"), bport);
2337   if (aport != bport)
2338     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2339                      "tcp",
2340                      _("TCP transport advertises itself as being on port %llu\n"),
2341                      aport);
2342   GNUNET_SERVER_disconnect_notify (plugin->server, 
2343                                    &disconnect_notify,
2344                                    plugin);
2345   if (plugin->behind_nat == GNUNET_NO)
2346     {
2347       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2348     }
2349
2350   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2351                                                            env->cfg,
2352                                                            AF_UNSPEC,
2353                                                            HOSTNAME_RESOLVE_TIMEOUT,
2354                                                            &process_hostname_ips,
2355                                                            plugin);
2356
2357   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2358     {
2359       t4.t_port = htons(0);
2360       plugin->env->notify_address (plugin->env->cls,
2361                                   "tcp",
2362                                   &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2363     }
2364   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2365     {
2366       t4.t_port = htons(plugin->adv_port);
2367       plugin->env->notify_address (plugin->env->cls,
2368                                    "tcp",
2369                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2370     }
2371
2372   return api;
2373 }
2374
2375
2376 /**
2377  * Exit point from the plugin.
2378  */
2379 void *
2380 libgnunet_plugin_transport_tcp_done (void *cls)
2381 {
2382   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2383   struct Plugin *plugin = api->cls;
2384   struct Session *session;
2385
2386   while (NULL != (session = plugin->sessions))
2387     disconnect_session (session);
2388   if (NULL != plugin->hostname_dns)
2389     {
2390       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2391       plugin->hostname_dns = NULL;
2392     }
2393   GNUNET_SERVICE_stop (plugin->service);
2394   GNUNET_free (plugin->handlers);
2395   GNUNET_free (plugin);
2396   GNUNET_free (api);
2397   return NULL;
2398 }
2399
2400 /* end of plugin_transport_tcp.c */