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