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