7fe7481bf53e936b98f56e17b01125b06fafc8f7
[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_YES
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 (GNUNET_ERROR_TYPE_ERROR,
521                   _("Unexpected address length: %u\n"),
522                   addrlen);
523       GNUNET_break (0);
524       return NULL;
525     }
526   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
527     {
528       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
529       return NULL;
530     }
531   GNUNET_snprintf (rbuf,
532                    sizeof (rbuf),
533                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
534                    buf,
535                    port);
536   return rbuf;
537 }
538
539
540 /**
541  * Find the session handle for the given client.
542  *
543  * @return NULL if no matching session exists
544  */
545 static struct Session *
546 find_session_by_client (struct Plugin *plugin,
547                         const struct GNUNET_SERVER_Client *client)
548 {
549   struct Session *ret;
550
551   ret = plugin->sessions;
552   while ((ret != NULL) && (client != ret->client))
553     ret = ret->next;
554   return ret;
555 }
556
557 /**
558  * Create a new session.  Also queues a welcome message.
559  *
560  * @param plugin us
561  * @param target peer to connect to
562  * @param client client to use
563  * @param is_nat this a NAT session, we should wait for a client to
564  *               connect to us from an address, then assign that to
565  *               the session
566  * @return new session object
567  */
568 static struct Session *
569 create_session (struct Plugin *plugin,
570                 const struct GNUNET_PeerIdentity *target,
571                 struct GNUNET_SERVER_Client *client, int is_nat)
572 {
573   struct Session *ret;
574   struct PendingMessage *pm;
575   struct WelcomeMessage welcome;
576
577   if (is_nat != GNUNET_YES)
578     GNUNET_assert (client != NULL);
579   else
580     GNUNET_assert (client == NULL);
581
582 #if DEBUG_TCP
583   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
584                    "tcp",
585                    "Creating new session for peer `%4s'\n",
586                    GNUNET_i2s (target));
587 #endif
588   ret = GNUNET_malloc (sizeof (struct Session));
589   ret->last_activity = GNUNET_TIME_absolute_get ();
590   ret->plugin = plugin;
591   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
592     {
593       ret->next = plugin->sessions;
594       plugin->sessions = ret;
595     }
596   ret->client = client;
597   ret->target = *target;
598   ret->expecting_welcome = GNUNET_YES;
599   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
600   pm->msg = (const char*) &pm[1];
601   pm->message_size = sizeof (struct WelcomeMessage);
602   welcome.header.size = htons (sizeof (struct WelcomeMessage));
603   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
604   welcome.clientIdentity = *plugin->env->my_identity;
605   memcpy (&pm[1], &welcome, sizeof (welcome));
606   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
607   GNUNET_STATISTICS_update (plugin->env->stats,
608                             gettext_noop ("# bytes currently in TCP buffers"),
609                             pm->message_size,
610                             GNUNET_NO);      
611   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
612                                ret->pending_messages_tail,
613                                pm);
614   if (is_nat != GNUNET_YES)
615     GNUNET_STATISTICS_update (plugin->env->stats,
616                               gettext_noop ("# TCP sessions active"),
617                               1,
618                               GNUNET_NO);
619   return ret;
620 }
621
622
623 /**
624  * If we have pending messages, ask the server to
625  * transmit them (schedule the respective tasks, etc.)
626  *
627  * @param session for which session should we do this
628  */
629 static void process_pending_messages (struct Session *session);
630
631
632 /**
633  * Function called to notify a client about the socket
634  * being ready to queue more data.  "buf" will be
635  * NULL and "size" zero if the socket was closed for
636  * writing in the meantime.
637  *
638  * @param cls closure
639  * @param size number of bytes available in buf
640  * @param buf where the callee should write the message
641  * @return number of bytes written to buf
642  */
643 static size_t
644 do_transmit (void *cls, size_t size, void *buf)
645 {
646   struct Session *session = cls;
647   struct GNUNET_PeerIdentity pid;
648   struct Plugin *plugin;
649   struct PendingMessage *pos;
650   struct PendingMessage *hd;
651   struct PendingMessage *tl;
652   struct GNUNET_TIME_Absolute now;
653   char *cbuf;
654   size_t ret;
655
656   session->transmit_handle = NULL;
657   plugin = session->plugin;
658   if (buf == NULL)
659     {
660 #if DEBUG_TCP
661       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
662                        "tcp",
663                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
664                        GNUNET_i2s (&session->target));
665 #endif
666       /* timeout; cancel all messages that have already expired */
667       hd = NULL;
668       tl = NULL;
669       ret = 0;
670       now = GNUNET_TIME_absolute_get ();
671       while ( (NULL != (pos = session->pending_messages_head)) &&
672               (pos->timeout.value <= now.value) )
673         {
674           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
675                                        session->pending_messages_tail,
676                                        pos);
677 #if DEBUG_TCP
678           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
679                            "tcp",
680                            "Failed to transmit %u byte message to `%4s'.\n",
681                            pos->message_size,
682                            GNUNET_i2s (&session->target));
683 #endif
684           ret += pos->message_size;
685           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
686         }
687       /* do this call before callbacks (so that if callbacks destroy
688          session, they have a chance to cancel actions done by this
689          call) */
690       process_pending_messages (session);  
691       pid = session->target;
692       /* no do callbacks and do not use session again since
693          the callbacks may abort the session */
694       while (NULL != (pos = hd))
695         {
696           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
697           if (pos->transmit_cont != NULL)
698             pos->transmit_cont (pos->transmit_cont_cls,
699                                 &pid, GNUNET_SYSERR);
700           GNUNET_free (pos);
701         }
702       GNUNET_STATISTICS_update (plugin->env->stats,
703                                 gettext_noop ("# bytes currently in TCP buffers"),
704                                 - (int64_t) ret,
705                                 GNUNET_NO); 
706       GNUNET_STATISTICS_update (plugin->env->stats,
707                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
708                                 ret,
709                                 GNUNET_NO);      
710       return 0;
711     }
712   /* copy all pending messages that would fit */
713   ret = 0;
714   cbuf = buf;
715   hd = NULL;
716   tl = NULL;
717   while (NULL != (pos = session->pending_messages_head)) 
718     {
719       if (ret + pos->message_size > size) 
720         break;
721       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
722                                    session->pending_messages_tail,
723                                    pos);
724       GNUNET_assert (size >= pos->message_size);
725       /* FIXME: this memcpy can be up to 7% of our total runtime */
726       memcpy (cbuf, pos->msg, pos->message_size);
727       cbuf += pos->message_size;
728       ret += pos->message_size;
729       size -= pos->message_size;
730       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
731     }
732   /* schedule 'continuation' before callbacks so that callbacks that
733      cancel everything don't cause us to use a session that no longer
734      exists... */
735   process_pending_messages (session);  
736   session->last_activity = GNUNET_TIME_absolute_get ();
737   pid = session->target;
738   /* we'll now call callbacks that may cancel the session; hence
739      we should not use 'session' after this point */
740   while (NULL != (pos = hd))
741     {
742       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
743       if (pos->transmit_cont != NULL)
744         pos->transmit_cont (pos->transmit_cont_cls,
745                             &pid, GNUNET_OK);
746       GNUNET_free (pos);
747     }
748   GNUNET_assert (hd == NULL);
749   GNUNET_assert (tl == NULL);
750 #if DEBUG_TCP > 1
751   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
752                    "tcp", "Transmitting %u bytes\n", ret);
753 #endif
754   GNUNET_STATISTICS_update (plugin->env->stats,
755                             gettext_noop ("# bytes currently in TCP buffers"),
756                             - (int64_t) ret,
757                             GNUNET_NO);       
758   GNUNET_STATISTICS_update (plugin->env->stats,
759                             gettext_noop ("# bytes transmitted via TCP"),
760                             ret,
761                             GNUNET_NO);      
762   return ret;
763 }
764
765
766 /**
767  * If we have pending messages, ask the server to
768  * transmit them (schedule the respective tasks, etc.)
769  *
770  * @param session for which session should we do this
771  */
772 static void
773 process_pending_messages (struct Session *session)
774 {
775   struct PendingMessage *pm;
776
777   GNUNET_assert (session->client != NULL);
778   if (session->transmit_handle != NULL)
779     return;
780   if (NULL == (pm = session->pending_messages_head))
781     return;
782   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "processing a pending message\n");
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 (GNUNET_ERROR_TYPE_DEBUG,
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 (GNUNET_ERROR_TYPE_DEBUG,
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 (GNUNET_ERROR_TYPE_ERROR,
1144                            _("Address of unexpected length: %u\n"),
1145                            addrlen);
1146           GNUNET_break (0);
1147           return -1;
1148         }
1149
1150       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1151         return -1; /* NAT client only works with IPv4 addresses */
1152
1153
1154       if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1155            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1156         {
1157 #if DEBUG_TCP_NAT
1158           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159                            _("Found valid IPv4 NAT address!\n"));
1160 #endif
1161           session = create_session (plugin,
1162                                     target,
1163                                     NULL, is_natd);
1164
1165           /* create new message entry */
1166           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1167           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1168           pm->msg = (const char*) &pm[1];
1169           memcpy (&pm[1], msg, msgbuf_size); 
1170           /* FIXME: this memcpy can be up to 7% of our total run-time 
1171              (for transport service) */
1172           pm->message_size = msgbuf_size;
1173           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1174           pm->transmit_cont = cont;
1175           pm->transmit_cont_cls = cont_cls;
1176
1177           /* append pm to pending_messages list */
1178           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1179                                              session->pending_messages_tail,
1180                                              session->pending_messages_tail,
1181                                              pm);
1182
1183           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1184 #if DEBUG_TCP_NAT
1185           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1187                            GNUNET_i2s (target),
1188                            GNUNET_a2s (sb, sbs));
1189 #endif
1190           run_gnunet_nat_client(plugin, sb, sbs);
1191           return 0;
1192         }
1193       else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1194         {
1195           /* Only do one NAT punch attempt per peer identity */
1196           return -1;
1197         }
1198       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1199                                                    af, sb, sbs);
1200       if (sa == NULL)
1201         {
1202 #if DEBUG_TCP
1203           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1204                            "tcp",
1205                            "Failed to create connection to `%4s' at `%s'\n",
1206                            GNUNET_i2s (target),
1207                            GNUNET_a2s (sb, sbs));
1208 #endif
1209           GNUNET_STATISTICS_update (plugin->env->stats,
1210                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1211                                     msgbuf_size,
1212                                     GNUNET_NO);      
1213           return -1;
1214         }
1215 #if DEBUG_TCP
1216       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1217                        "tcp",
1218                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1219                        GNUNET_i2s (target),
1220                        GNUNET_a2s (sb, sbs));
1221 #endif
1222       session = create_session (plugin,
1223                                 target,
1224                                 GNUNET_SERVER_connect_socket (plugin->server,
1225                                                               sa), is_natd);
1226       session->connect_addr = GNUNET_malloc (addrlen);
1227       memcpy (session->connect_addr,
1228               addr,
1229               addrlen);
1230       session->connect_alen = addrlen;
1231     }
1232   GNUNET_assert (session != NULL);
1233   GNUNET_assert (session->client != NULL);
1234   GNUNET_STATISTICS_update (plugin->env->stats,
1235                             gettext_noop ("# bytes currently in TCP buffers"),
1236                             msgbuf_size,
1237                             GNUNET_NO);      
1238   /* create new message entry */
1239   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1240   pm->msg = (const char*) &pm[1];
1241   memcpy (&pm[1], msg, msgbuf_size);
1242   pm->message_size = msgbuf_size;
1243   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1244   pm->transmit_cont = cont;
1245   pm->transmit_cont_cls = cont_cls;
1246
1247   /* append pm to pending_messages list */
1248   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1249                                      session->pending_messages_tail,
1250                                      session->pending_messages_tail,
1251                                      pm);
1252 #if DEBUG_TCP
1253   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1254                    "tcp",
1255                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1256                    msgbuf_size,
1257                    GNUNET_i2s (target));
1258 #endif
1259   process_pending_messages (session);
1260   return msgbuf_size;
1261 }
1262
1263
1264 /**
1265  * Function that can be called to force a disconnect from the
1266  * specified neighbour.  This should also cancel all previously
1267  * scheduled transmissions.  Obviously the transmission may have been
1268  * partially completed already, which is OK.  The plugin is supposed
1269  * to close the connection (if applicable) and no longer call the
1270  * transmit continuation(s).
1271  *
1272  * Finally, plugin MUST NOT call the services's receive function to
1273  * notify the service that the connection to the specified target was
1274  * closed after a getting this call.
1275  *
1276  * @param cls closure
1277  * @param target peer for which the last transmission is
1278  *        to be cancelled
1279  */
1280 static void
1281 tcp_plugin_disconnect (void *cls,
1282                        const struct GNUNET_PeerIdentity *target)
1283 {
1284   struct Plugin *plugin = cls;
1285   struct Session *session;
1286   struct Session *next;
1287   struct PendingMessage *pm;
1288
1289 #if DEBUG_TCP
1290   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1291                    "tcp",
1292                    "Asked to cancel session with `%4s'\n",
1293                    GNUNET_i2s (target));
1294 #endif
1295   next = plugin->sessions;
1296   while (NULL != (session = next))
1297     {
1298       next = session->next;
1299       if (0 != memcmp (target,
1300                        &session->target,
1301                        sizeof (struct GNUNET_PeerIdentity)))
1302         continue;
1303       pm = session->pending_messages_head;
1304       while (pm != NULL)
1305         {
1306           pm->transmit_cont = NULL;
1307           pm->transmit_cont_cls = NULL;
1308           pm = pm->next;
1309         }
1310       disconnect_session (session);
1311     }
1312 }
1313
1314
1315 /**
1316  * Context for address to string conversion.
1317  */
1318 struct PrettyPrinterContext
1319 {
1320   /**
1321    * Function to call with the result.
1322    */
1323   GNUNET_TRANSPORT_AddressStringCallback asc;
1324
1325   /**
1326    * Clsoure for 'asc'.
1327    */
1328   void *asc_cls;
1329
1330   /**
1331    * Port to add after the IP address.
1332    */
1333   uint16_t port;
1334 };
1335
1336
1337 /**
1338  * Append our port and forward the result.
1339  *
1340  * @param cls the 'struct PrettyPrinterContext*'
1341  * @param hostname hostname part of the address
1342  */
1343 static void
1344 append_port (void *cls, const char *hostname)
1345 {
1346   struct PrettyPrinterContext *ppc = cls;
1347   char *ret;
1348
1349   if (hostname == NULL)
1350     {
1351       ppc->asc (ppc->asc_cls, NULL);
1352       GNUNET_free (ppc);
1353       return;
1354     }
1355   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1356   ppc->asc (ppc->asc_cls, ret);
1357   GNUNET_free (ret);
1358 }
1359
1360
1361 /**
1362  * Convert the transports address to a nice, human-readable
1363  * format.
1364  *
1365  * @param cls closure
1366  * @param type name of the transport that generated the address
1367  * @param addr one of the addresses of the host, NULL for the last address
1368  *        the specific address format depends on the transport
1369  * @param addrlen length of the address
1370  * @param numeric should (IP) addresses be displayed in numeric form?
1371  * @param timeout after how long should we give up?
1372  * @param asc function to call on each string
1373  * @param asc_cls closure for asc
1374  */
1375 static void
1376 tcp_plugin_address_pretty_printer (void *cls,
1377                                    const char *type,
1378                                    const void *addr,
1379                                    size_t addrlen,
1380                                    int numeric,
1381                                    struct GNUNET_TIME_Relative timeout,
1382                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1383                                    void *asc_cls)
1384 {
1385   struct Plugin *plugin = cls;
1386   struct PrettyPrinterContext *ppc;
1387   const void *sb;
1388   size_t sbs;
1389   struct sockaddr_in a4;
1390   struct sockaddr_in6 a6;
1391   const struct IPv4TcpAddress *t4;
1392   const struct IPv6TcpAddress *t6;
1393   uint16_t port;
1394
1395   if (addrlen == sizeof (struct IPv6TcpAddress))
1396     {
1397       t6 = addr;
1398       memset (&a6, 0, sizeof (a6));
1399       a6.sin6_family = AF_INET6;
1400       a6.sin6_port = t6->t6_port;
1401       memcpy (&a6.sin6_addr,
1402               &t6->ipv6_addr,
1403               sizeof (struct in6_addr));      
1404       port = ntohs (t6->t6_port);
1405       sb = &a6;
1406       sbs = sizeof (a6);
1407     }
1408   else if (addrlen == sizeof (struct IPv4TcpAddress))
1409     {
1410       t4 = addr;
1411       memset (&a4, 0, sizeof (a4));
1412       a4.sin_family = AF_INET;
1413       a4.sin_port = t4->t_port;
1414       a4.sin_addr.s_addr = t4->ipv4_addr;
1415       port = ntohs (t4->t_port);
1416       sb = &a4;
1417       sbs = sizeof (a4);
1418     }
1419   else
1420     {
1421       /* invalid address */
1422       GNUNET_break_op (0);
1423       asc (asc_cls, NULL);
1424       return;
1425     }
1426   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1427   ppc->asc = asc;
1428   ppc->asc_cls = asc_cls;
1429   ppc->port = port;
1430   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1431                                 plugin->env->cfg,
1432                                 sb,
1433                                 sbs,
1434                                 !numeric, timeout, &append_port, ppc);
1435 }
1436
1437
1438 /**
1439  * Check if the given port is plausible (must be either
1440  * our listen port or our advertised port).  If it is
1441  * neither, we return GNUNET_SYSERR.
1442  *
1443  * @param plugin global variables
1444  * @param in_port port number to check
1445  * @return GNUNET_OK if port is either open_port or adv_port
1446  */
1447 static int
1448 check_port (struct Plugin *plugin, uint16_t in_port)
1449 {
1450   if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1451     return GNUNET_OK;
1452   if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1453        (plugin->behind_nat == GNUNET_YES) )
1454     {
1455       return GNUNET_SYSERR; /* odd case... */
1456     }
1457   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1458     return GNUNET_OK;
1459   return GNUNET_SYSERR;
1460 }
1461
1462
1463 /** 
1464  * Function that will be called to check if a binary address for this
1465  * plugin is well-formed and corresponds to an address for THIS peer
1466  * (as per our configuration).  Naturally, if absolutely necessary,
1467  * plugins can be a bit conservative in their answer, but in general
1468  * plugins should make sure that the address does not redirect
1469  * traffic to a 3rd party that might try to man-in-the-middle our
1470  * traffic.
1471  *
1472  * @param cls closure, our 'struct Plugin*'
1473  * @param addr pointer to the address
1474  * @param addrlen length of addr
1475  * @return GNUNET_OK if this is a plausible address for this peer
1476  *         and transport, GNUNET_SYSERR if not
1477  */
1478 static int
1479 tcp_plugin_check_address (void *cls, 
1480                           const void *addr, 
1481                           size_t addrlen)
1482 {
1483   struct Plugin *plugin = cls;
1484   struct IPv4TcpAddress *v4;
1485   struct IPv6TcpAddress *v6;
1486
1487   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1488       (addrlen != sizeof (struct IPv6TcpAddress)))
1489     {
1490       GNUNET_break_op (0);
1491       return GNUNET_SYSERR;
1492     }
1493   if (addrlen == sizeof (struct IPv4TcpAddress))
1494     {
1495       v4 = (struct IPv4TcpAddress *) addr;
1496       if (GNUNET_OK !=
1497           check_port (plugin, ntohs (v4->t_port)))
1498         return GNUNET_SYSERR;
1499       if (GNUNET_OK !=
1500           check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1501         {
1502           return GNUNET_SYSERR;
1503         }
1504     }
1505   else
1506     {
1507       v6 = (struct IPv6TcpAddress *) addr;
1508       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1509         {
1510           GNUNET_break_op (0);
1511           return GNUNET_SYSERR;
1512         }
1513       if (GNUNET_OK != 
1514           check_port (plugin, ntohs (v6->t6_port)))
1515         return GNUNET_SYSERR;
1516       if (GNUNET_OK !=
1517           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1518         {
1519           return GNUNET_SYSERR;
1520         }
1521     }
1522   return GNUNET_OK;
1523 }
1524
1525 /**
1526  * We've received a nat probe from this peer via TCP.  Finish
1527  * creating the client session and resume sending of queued
1528  * messages.
1529  *
1530  * @param cls closure
1531  * @param client identification of the client
1532  * @param message the actual message
1533  */
1534 static void
1535 handle_tcp_nat_probe (void *cls,
1536                      struct GNUNET_SERVER_Client *client,
1537                      const struct GNUNET_MessageHeader *message)
1538 {
1539   struct Plugin *plugin = cls;
1540   struct Session *session;
1541   struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1542   size_t alen;
1543   void *vaddr;
1544   struct IPv4TcpAddress *t4;
1545   struct IPv6TcpAddress *t6;
1546   const struct sockaddr_in *s4;
1547   const struct sockaddr_in6 *s6;
1548
1549 #if DEBUG_TCP_NAT
1550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received tcp NAT probe\n");
1551 #endif
1552   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1553    * a connection to this peer by running gnunet-nat-client.  This peer
1554    * received the punch message and now wants us to use the new connection
1555    * as the default for that peer.  Do so and then send a WELCOME message
1556    * so we can really be connected!
1557    */
1558   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1559     {
1560 #if DEBUG_TCP_NAT
1561       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));
1562 #endif
1563       GNUNET_break_op(0);
1564       return;
1565     }
1566   tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1567
1568   if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1569     {
1570 #if DEBUG_TCP_NAT
1571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1572 #endif
1573       session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1574       GNUNET_assert(session != NULL);
1575       GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1576       GNUNET_SERVER_client_keep (client);
1577       session->client = client;
1578       session->last_activity = GNUNET_TIME_absolute_get ();
1579
1580       if (GNUNET_OK ==
1581           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1582         {
1583 #if DEBUG_TCP_NAT
1584           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1585                            "Found address `%s' for incoming connection %p\n",
1586                            GNUNET_a2s (vaddr, alen),
1587                            client);
1588 #endif
1589           if (alen == sizeof (struct sockaddr_in))
1590             {
1591               s4 = vaddr;
1592               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1593               t4->t_port = s4->sin_port;
1594               t4->ipv4_addr = s4->sin_addr.s_addr;
1595               session->connect_addr = t4;
1596               session->connect_alen = sizeof (struct IPv4TcpAddress);
1597             }
1598           else if (alen == sizeof (struct sockaddr_in6))
1599             {
1600               s6 = vaddr;
1601               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1602               t6->t6_port = s6->sin6_port;
1603               memcpy (&t6->ipv6_addr,
1604                       &s6->sin6_addr,
1605                       sizeof (struct in6_addr));
1606               session->connect_addr = t6;
1607               session->connect_alen = sizeof (struct IPv6TcpAddress);
1608             }
1609
1610           session->connect_addr = GNUNET_malloc (alen);
1611           memcpy (session->connect_addr,
1612                   vaddr,
1613                   alen);
1614           session->connect_alen = alen;
1615           GNUNET_free (vaddr);
1616         }
1617
1618       session->next = plugin->sessions;
1619       plugin->sessions = session;
1620       GNUNET_STATISTICS_update (plugin->env->stats,
1621                                 gettext_noop ("# TCP sessions active"),
1622                                 1,
1623                                 GNUNET_NO);
1624       process_pending_messages (session);
1625     }
1626   else
1627     {
1628 #if DEBUG_TCP_NAT
1629       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1630 #endif
1631     }
1632 }
1633
1634 /**
1635  * We've received a welcome from this peer via TCP.  Possibly create a
1636  * fresh client record and send back our welcome.
1637  *
1638  * @param cls closure
1639  * @param client identification of the client
1640  * @param message the actual message
1641  */
1642 static void
1643 handle_tcp_welcome (void *cls,
1644                     struct GNUNET_SERVER_Client *client,
1645                     const struct GNUNET_MessageHeader *message)
1646 {
1647   struct Plugin *plugin = cls;
1648   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1649   struct Session *session;
1650   size_t alen;
1651   void *vaddr;
1652   struct IPv4TcpAddress *t4;
1653   struct IPv6TcpAddress *t6;
1654   const struct sockaddr_in *s4;
1655   const struct sockaddr_in6 *s6;
1656
1657
1658 #if DEBUG_TCP
1659   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1660                    "tcp",
1661                    "Received %s message from a `%4s/%p'.\n", 
1662                    "WELCOME",
1663                    GNUNET_i2s (&wm->clientIdentity), client);
1664 #endif
1665   GNUNET_STATISTICS_update (plugin->env->stats,
1666                             gettext_noop ("# TCP WELCOME messages received"),
1667                             1,
1668                             GNUNET_NO);      
1669   session = find_session_by_client (plugin, client);
1670   if (session == NULL)
1671     {
1672       GNUNET_SERVER_client_keep (client);
1673       session = create_session (plugin,
1674                                 &wm->clientIdentity, client, GNUNET_NO);
1675       session->inbound = GNUNET_YES;
1676       if (GNUNET_OK ==
1677           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1678         {
1679 #if DEBUG_TCP
1680           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1681                            "tcp",
1682                            "Found address `%s' for incoming connection %p\n",
1683                            GNUNET_a2s (vaddr, alen),
1684                            client);
1685 #endif
1686           if (alen == sizeof (struct sockaddr_in))
1687             {
1688               s4 = vaddr;
1689               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1690               t4->t_port = s4->sin_port;
1691               t4->ipv4_addr = s4->sin_addr.s_addr;
1692               session->connect_addr = t4;
1693               session->connect_alen = sizeof (struct IPv4TcpAddress);
1694             }
1695           else if (alen == sizeof (struct sockaddr_in6))
1696             {
1697               s6 = vaddr;
1698               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1699               t6->t6_port = s6->sin6_port;
1700               memcpy (&t6->ipv6_addr,
1701                       &s6->sin6_addr,
1702                       sizeof (struct in6_addr));
1703               session->connect_addr = t6;
1704               session->connect_alen = sizeof (struct IPv6TcpAddress);
1705             }
1706           GNUNET_free (vaddr);
1707         }
1708       else
1709         {
1710 #if DEBUG_TCP
1711           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1712                            "tcp",
1713                            "Did not obtain TCP socket address for incoming connection\n");
1714 #endif
1715         }
1716 #if DEBUG_TCP
1717       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1718                        "tcp",
1719                        "Creating new session %p for connection %p\n",
1720                        session, client);
1721 #endif
1722       process_pending_messages (session);
1723     }
1724   if (session->expecting_welcome != GNUNET_YES)
1725     {
1726       GNUNET_break_op (0);
1727       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1728       return;
1729     }
1730   session->last_activity = GNUNET_TIME_absolute_get ();
1731   session->expecting_welcome = GNUNET_NO;
1732   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1733 }
1734
1735
1736 /**
1737  * Task to signal the server that we can continue
1738  * receiving from the TCP client now.
1739  *
1740  * @param cls the 'struct Session*'
1741  * @param tc task context (unused)
1742  */
1743 static void
1744 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1745 {
1746   struct Session *session = cls;
1747   struct GNUNET_TIME_Relative delay;
1748
1749   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1750   delay = session->plugin->env->receive (session->plugin->env->cls,
1751                                          &session->target,
1752                                          NULL, 0, 
1753                                          session,
1754                                          NULL, 0);
1755   if (delay.value == 0)
1756     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1757   else
1758     session->receive_delay_task = 
1759       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1760                                     delay, &delayed_done, session);
1761 }
1762
1763
1764 /**
1765  * We've received data for this peer via TCP.  Unbox,
1766  * compute latency and forward.
1767  *
1768  * @param cls closure
1769  * @param client identification of the client
1770  * @param message the actual message
1771  */
1772 static void
1773 handle_tcp_data (void *cls,
1774                  struct GNUNET_SERVER_Client *client,
1775                  const struct GNUNET_MessageHeader *message)
1776 {
1777   struct Plugin *plugin = cls;
1778   struct Session *session;
1779   struct GNUNET_TIME_Relative delay;
1780
1781   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1782     {
1783       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1784       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1785       return; 
1786     }    
1787   session = find_session_by_client (plugin, client);
1788   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1789     {
1790       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1791       return;
1792     }
1793   session->last_activity = GNUNET_TIME_absolute_get ();
1794 #if DEBUG_TCP
1795   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1796                    "tcp", 
1797                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1798                    (unsigned int) ntohs (message->size), 
1799                    (unsigned int) ntohs (message->type),
1800                    GNUNET_i2s (&session->target));
1801 #endif
1802   GNUNET_STATISTICS_update (plugin->env->stats,
1803                             gettext_noop ("# bytes received via TCP"),
1804                             ntohs (message->size),
1805                             GNUNET_NO); 
1806   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1807                                 session, 
1808                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1809                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1810   if (delay.value == 0)
1811     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1812   else
1813     session->receive_delay_task = 
1814       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1815                                     delay, &delayed_done, session);
1816 }
1817
1818
1819 /**
1820  * Functions with this signature are called whenever a peer
1821  * is disconnected on the network level.
1822  *
1823  * @param cls closure
1824  * @param client identification of the client
1825  */
1826 static void
1827 disconnect_notify (void *cls, 
1828                    struct GNUNET_SERVER_Client *client)
1829 {
1830   struct Plugin *plugin = cls;
1831   struct Session *session;
1832
1833   if (client == NULL)
1834     return;
1835   session = find_session_by_client (plugin, client);
1836   if (session == NULL)
1837     return;                     /* unknown, nothing to do */
1838 #if DEBUG_TCP
1839   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1840                    "tcp",
1841                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1842                    GNUNET_i2s (&session->target),
1843                    (session->connect_addr != NULL) ?
1844                    tcp_address_to_string (session->plugin,
1845                                           session->connect_addr,
1846                                           session->connect_alen) : "*",
1847                    client);
1848 #endif
1849   disconnect_session (session);
1850 }
1851
1852
1853 /**
1854  * Add the IP of our network interface to the list of
1855  * our external IP addresses.
1856  *
1857  * @param cls the 'struct Plugin*'
1858  * @param name name of the interface
1859  * @param isDefault do we think this may be our default interface
1860  * @param addr address of the interface
1861  * @param addrlen number of bytes in addr
1862  * @return GNUNET_OK to continue iterating
1863  */
1864 static int
1865 process_interfaces (void *cls,
1866                     const char *name,
1867                     int isDefault,
1868                     const struct sockaddr *addr, socklen_t addrlen)
1869 {
1870   struct Plugin *plugin = cls;
1871   int af;
1872   struct IPv4TcpAddress t4;
1873   struct IPv6TcpAddress t6;
1874   struct IPv4TcpAddress t4_nat;
1875   struct IPv6TcpAddress t6_nat;
1876   void *arg;
1877   uint16_t args;
1878   void *arg_nat;
1879
1880   af = addr->sa_family;
1881   arg_nat = NULL;
1882   if (af == AF_INET)
1883     {
1884       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1885       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1886       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1887         t4.t_port = htons(0);
1888       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1889         {
1890           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1891           t4_nat.t_port = htons(plugin->adv_port);
1892           arg_nat = &t4_nat;
1893         }
1894       else
1895         t4.t_port = htons (plugin->adv_port);
1896       arg = &t4;
1897       args = sizeof (t4);
1898     }
1899   else if (af == AF_INET6)
1900     {
1901       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1902         {
1903           /* skip link local addresses */
1904           return GNUNET_OK;
1905         }
1906       memcpy (&t6.ipv6_addr,
1907               &((struct sockaddr_in6 *) addr)->sin6_addr,
1908               sizeof (struct in6_addr));
1909       add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1910       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1911         t6.t6_port = htons(0);
1912       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1913         {
1914           memcpy (&t6_nat.ipv6_addr,
1915                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1916                   sizeof (struct in6_addr));
1917           t6_nat.t6_port = htons(plugin->adv_port);
1918           arg_nat = &t6;
1919         }
1920       else
1921         t6.t6_port = htons (plugin->adv_port);
1922       arg = &t6;
1923       args = sizeof (t6);
1924     }
1925   else
1926     {
1927       GNUNET_break (0);
1928       return GNUNET_OK;
1929     }
1930   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1931                    GNUNET_ERROR_TYPE_BULK,
1932                    "tcp", 
1933                    _("Found address `%s' (%s)\n"),
1934                    GNUNET_a2s (addr, addrlen), name);
1935
1936   plugin->env->notify_address (plugin->env->cls,
1937                                "tcp",
1938                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1939
1940   if (arg_nat != NULL)
1941     {
1942       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1943                        GNUNET_ERROR_TYPE_BULK,
1944                       "tcp",
1945                       _("Found address `%s' (%s)\n"),
1946                       GNUNET_a2s (addr, addrlen), name);
1947       plugin->env->notify_address (plugin->env->cls,
1948                                    "tcp",
1949                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1950     }
1951
1952   return GNUNET_OK;
1953 }
1954
1955
1956 /**
1957  * Function called by the resolver for each address obtained from DNS
1958  * for our own hostname.  Add the addresses to the list of our
1959  * external IP addresses.
1960  *
1961  * @param cls closure
1962  * @param addr one of the addresses of the host, NULL for the last address
1963  * @param addrlen length of the address
1964  */
1965 static void
1966 process_hostname_ips (void *cls,
1967                       const struct sockaddr *addr, socklen_t addrlen)
1968 {
1969   struct Plugin *plugin = cls;
1970
1971   if (addr == NULL)
1972     {
1973       plugin->hostname_dns = NULL;
1974       return;
1975     }
1976   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1977   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1978 }
1979
1980 /**
1981  * We can now send a probe message, copy into buffer to really send.
1982  *
1983  * @param cls closure, a struct TCPProbeContext
1984  * @param size max size to copy
1985  * @param buf buffer to copy message to
1986  */
1987 static size_t notify_send_probe (void *cls,
1988                                  size_t size, void *buf)
1989 {
1990   struct TCPProbeContext *tcp_probe_ctx = cls;
1991
1992   if (buf == NULL)
1993     {
1994       return 0;
1995     }
1996
1997   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1998   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1999   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2000                                 tcp_probe_ctx->sock);
2001
2002   GNUNET_free(tcp_probe_ctx);
2003   return sizeof(tcp_probe_ctx->message);
2004 }
2005
2006 /*
2007  * @param cls the plugin handle
2008  * @param tc the scheduling context (for rescheduling this function again)
2009  *
2010  * We have been notified that gnunet-nat-server has written something to stdout.
2011  * Handle the output, then reschedule this function to be called again once
2012  * more is available.
2013  *
2014  */
2015 static void
2016 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2017 {
2018   struct Plugin *plugin = cls;
2019   char mybuf[40];
2020   ssize_t bytes;
2021   memset(&mybuf, 0, sizeof(mybuf));
2022   int i;
2023   int port;
2024   char *port_start;
2025   struct sockaddr_in in_addr;
2026   struct TCPProbeContext *tcp_probe_ctx;
2027   struct GNUNET_CONNECTION_Handle *sock;
2028
2029   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2030     return;
2031
2032   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2033
2034   if (bytes < 1)
2035     {
2036 #if DEBUG_TCP_NAT
2037       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2038                       _("Finished reading from server stdout with code: %d\n"), bytes);
2039 #endif
2040       return;
2041     }
2042
2043   port = 0;
2044   port_start = NULL;
2045   for (i = 0; i < sizeof(mybuf); i++)
2046     {
2047       if (mybuf[i] == '\n')
2048         mybuf[i] = '\0';
2049
2050       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2051         {
2052           mybuf[i] = '\0';
2053           port_start = &mybuf[i + 1];
2054         }
2055     }
2056
2057   if (port_start != NULL)
2058     port = atoi(port_start);
2059   else
2060     {
2061       plugin->server_read_task =
2062            GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2063                                            GNUNET_TIME_UNIT_FOREVER_REL,
2064                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2065       return;
2066     }
2067
2068 #if DEBUG_TCP_NAT
2069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2070                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
2071 #endif
2072
2073
2074   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2075     {
2076
2077       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2078                   _("nat-server-read malformed address\n"), &mybuf, port);
2079
2080       plugin->server_read_task =
2081           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2082                                           GNUNET_TIME_UNIT_FOREVER_REL,
2083                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2084       return;
2085     }
2086
2087   in_addr.sin_family = AF_INET;
2088   in_addr.sin_port = htons(port);
2089   /**
2090    * We have received an ICMP response, ostensibly from a non-NAT'd peer
2091    *  that wants to connect to us! Send a message to establish a connection.
2092    */
2093   sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2094                                                  sizeof(in_addr));
2095   if (sock == NULL)
2096     {
2097       plugin->server_read_task =
2098           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2099                                           GNUNET_TIME_UNIT_FOREVER_REL,
2100                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2101       return;
2102     }
2103   else
2104     {
2105       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2106                 _("Sending TCP probe message!\n"), &mybuf, port);
2107       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2108
2109       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2110       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2111       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2112       tcp_probe_ctx->plugin = plugin;
2113       tcp_probe_ctx->sock = sock;
2114       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2115                                                                  ntohs(tcp_probe_ctx->message.header.size),
2116                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2117                                                                  &notify_send_probe, tcp_probe_ctx);
2118
2119     }
2120
2121   plugin->server_read_task =
2122       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2123                                       GNUNET_TIME_UNIT_FOREVER_REL,
2124                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2125 }
2126
2127 /**
2128  * Start the gnunet-nat-server process for users behind NAT.
2129  *
2130  * @param plugin the transport plugin
2131  *
2132  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2133  */
2134 static int
2135 tcp_transport_start_nat_server(struct Plugin *plugin)
2136 {
2137
2138   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2139   if (plugin->server_stdout == NULL)
2140     return GNUNET_SYSERR;
2141
2142 #if DEBUG_TCP_NAT
2143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2145 #endif
2146   /* Start the server process */
2147   plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2148   if (plugin->server_pid == GNUNET_SYSERR)
2149     {
2150 #if DEBUG_TCP_NAT
2151     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2152                      "Failed to start gnunet-nat-server process\n");
2153 #endif
2154       return GNUNET_SYSERR;
2155     }
2156   /* Close the write end of the read pipe */
2157   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2158
2159   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2160   plugin->server_read_task =
2161       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2162                                       GNUNET_TIME_UNIT_FOREVER_REL,
2163                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2164   return GNUNET_YES;
2165 }
2166
2167 /**
2168  * Return the actual path to a file found in the current
2169  * PATH environment variable.
2170  *
2171  * @param binary the name of the file to find
2172  */
2173 static char *
2174 get_path_from_PATH (char *binary)
2175 {
2176   char *path;
2177   char *pos;
2178   char *end;
2179   char *buf;
2180   const char *p;
2181
2182   p = getenv ("PATH");
2183   if (p == NULL)
2184     return NULL;
2185   path = GNUNET_strdup (p);     /* because we write on it */
2186   buf = GNUNET_malloc (strlen (path) + 20);
2187   pos = path;
2188
2189   while (NULL != (end = strchr (pos, ':')))
2190     {
2191       *end = '\0';
2192       sprintf (buf, "%s/%s", pos, binary);
2193       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2194         {
2195           GNUNET_free (path);
2196           return buf;
2197         }
2198       pos = end + 1;
2199     }
2200   sprintf (buf, "%s/%s", pos, binary);
2201   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2202     {
2203       GNUNET_free (path);
2204       return buf;
2205     }
2206   GNUNET_free (buf);
2207   GNUNET_free (path);
2208   return NULL;
2209 }
2210
2211 /**
2212  * Check whether the suid bit is set on a file.
2213  * Attempts to find the file using the current
2214  * PATH environment variable as a search path.
2215  *
2216  * @param binary the name of the file to check
2217  */
2218 static int
2219 check_gnunet_nat_binary(char *binary)
2220 {
2221   struct stat statbuf;
2222   char *p;
2223
2224   p = get_path_from_PATH (binary);
2225   if (p == NULL)
2226     return GNUNET_NO;
2227   if (0 != STAT (p, &statbuf))
2228     {
2229       GNUNET_free (p);
2230       return GNUNET_SYSERR;
2231     }
2232   GNUNET_free (p);
2233   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2234        (statbuf.st_uid == 0) )
2235     return GNUNET_YES;
2236   return GNUNET_NO;
2237 }
2238
2239 /**
2240  * Entry point for the plugin.
2241  *
2242  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2243  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2244  */
2245 void *
2246 libgnunet_plugin_transport_tcp_init (void *cls)
2247 {
2248   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2249     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2250      sizeof (struct WelcomeMessage)},
2251     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2252     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2253     {NULL, NULL, 0, 0}
2254   };
2255   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2256   struct GNUNET_TRANSPORT_PluginFunctions *api;
2257   struct Plugin *plugin;
2258   struct GNUNET_SERVICE_Context *service;
2259   unsigned long long aport;
2260   unsigned long long bport;
2261   unsigned int i;
2262   int behind_nat;
2263   int allow_nat;
2264   int only_nat_addresses;
2265   char *internal_address;
2266   char *external_address;
2267   struct sockaddr_in in_addr;
2268   struct IPv4TcpAddress t4;
2269
2270   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2271   if (service == NULL)
2272     {
2273       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2274                        "tcp",
2275                        _
2276                        ("Failed to start service for `%s' transport plugin.\n"),
2277                        "tcp");
2278       return NULL;
2279     }
2280
2281   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2282                                                            "transport-tcp",
2283                                                            "BEHIND_NAT"))
2284     {
2285       /* We are behind nat (according to the user) */
2286       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2287         {
2288           behind_nat = GNUNET_YES;
2289         }
2290       else
2291         {
2292           behind_nat = GNUNET_NO;
2293           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");
2294         }
2295     }
2296   else
2297     behind_nat = GNUNET_NO; /* We are not behind nat! */
2298
2299   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2300                                                            "transport-tcp",
2301                                                            "ALLOW_NAT"))
2302     {
2303       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2304         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2305       else
2306       {
2307         allow_nat = GNUNET_NO;
2308         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");
2309       }
2310     }
2311   else
2312     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2313
2314
2315   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2316                                                            "transport-tcp",
2317                                                            "ONLY_NAT_ADDRESSES"))
2318     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2319   else
2320     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2321
2322   external_address = NULL;
2323   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2324          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2325                                                 "transport-tcp",
2326                                                 "EXTERNAL_ADDRESS",
2327                                                 &external_address)))
2328     {
2329       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2330                        "tcp",
2331                        _
2332                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2333                        "transport-tcp");
2334       GNUNET_SERVICE_stop (service);
2335       return NULL;
2336     }
2337
2338   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2339     {
2340       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2341     }
2342
2343   internal_address = NULL;
2344   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2345          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2346                                                 "transport-tcp",
2347                                                 "INTERNAL_ADDRESS",
2348                                                 &internal_address)))
2349     {
2350       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2351                        "tcp",
2352                        _
2353                        ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2354                        "transport-tcp");
2355       GNUNET_SERVICE_stop (service);
2356       GNUNET_free_non_null(external_address);
2357       return NULL;
2358     }
2359
2360   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2361     {
2362       GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2363     }
2364
2365   aport = 0;
2366   if ((GNUNET_OK !=
2367        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2368                                               "transport-tcp",
2369                                               "PORT",
2370                                               &bport)) ||
2371       (bport > 65535) ||
2372       ((GNUNET_OK ==
2373         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2374                                                "transport-tcp",
2375                                                "ADVERTISED-PORT",
2376                                                &aport)) && (aport > 65535)))
2377     {
2378       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2379                        "tcp",
2380                        _
2381                        ("Require valid port number for service `%s' in configuration!\n"),
2382                        "transport-tcp");
2383       GNUNET_free_non_null(external_address);
2384       GNUNET_free_non_null(internal_address);
2385       GNUNET_SERVICE_stop (service);
2386       return NULL;
2387     }
2388
2389   if (aport == 0)
2390     aport = bport;
2391   plugin = GNUNET_malloc (sizeof (struct Plugin));
2392   plugin->open_port = bport;
2393   plugin->adv_port = aport;
2394   plugin->external_address = external_address;
2395   plugin->internal_address = internal_address;
2396   plugin->behind_nat = behind_nat;
2397   plugin->allow_nat = allow_nat;
2398   plugin->only_nat_addresses = only_nat_addresses;
2399   plugin->env = env;
2400   plugin->lsock = NULL;
2401   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2402   api->cls = plugin;
2403   api->send = &tcp_plugin_send;
2404   api->disconnect = &tcp_plugin_disconnect;
2405   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2406   api->check_address = &tcp_plugin_check_address;
2407   api->address_to_string = &tcp_address_to_string;
2408   plugin->service = service;
2409   plugin->server = GNUNET_SERVICE_get_server (service);
2410   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2411   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2412   for (i = 0;
2413        i <
2414        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2415        i++)
2416     plugin->handlers[i].callback_cls = plugin;
2417   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2418
2419   if (behind_nat == GNUNET_YES)
2420     {
2421       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2422         {
2423           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2424                            "tcp",
2425                            _
2426                            ("Failed to start %s required for NAT in %s!\n"),
2427                            "gnunet-nat-server"
2428                            "transport-tcp");
2429           GNUNET_free_non_null(external_address);
2430           GNUNET_free_non_null(internal_address);
2431           GNUNET_SERVICE_stop (service);
2432           GNUNET_free (api);
2433           return NULL;
2434         }
2435     }
2436
2437   if (allow_nat == GNUNET_YES)
2438     {
2439       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2440       GNUNET_assert(plugin->nat_wait_conns != NULL);
2441     }
2442
2443   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2444                    "tcp", _("TCP transport listening on port %llu\n"), bport);
2445   if (aport != bport)
2446     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2447                      "tcp",
2448                      _("TCP transport advertises itself as being on port %llu\n"),
2449                      aport);
2450   GNUNET_SERVER_disconnect_notify (plugin->server, 
2451                                    &disconnect_notify,
2452                                    plugin);
2453   if (plugin->behind_nat == GNUNET_NO)
2454     {
2455       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2456     }
2457
2458   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2459                                                            env->cfg,
2460                                                            AF_UNSPEC,
2461                                                            HOSTNAME_RESOLVE_TIMEOUT,
2462                                                            &process_hostname_ips,
2463                                                            plugin);
2464
2465   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2466     {
2467       t4.t_port = htons(0);
2468       plugin->env->notify_address (plugin->env->cls,
2469                                   "tcp",
2470                                   &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2471     }
2472   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2473     {
2474       t4.t_port = htons(plugin->adv_port);
2475       plugin->env->notify_address (plugin->env->cls,
2476                                    "tcp",
2477                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2478     }
2479
2480   return api;
2481 }
2482
2483
2484 /**
2485  * Exit point from the plugin.
2486  */
2487 void *
2488 libgnunet_plugin_transport_tcp_done (void *cls)
2489 {
2490   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2491   struct Plugin *plugin = api->cls;
2492   struct Session *session;
2493   struct LocalAddrList *lal;
2494
2495   while (NULL != (session = plugin->sessions))
2496     disconnect_session (session);
2497   if (NULL != plugin->hostname_dns)
2498     {
2499       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2500       plugin->hostname_dns = NULL;
2501     }
2502   GNUNET_SERVICE_stop (plugin->service);
2503   GNUNET_free (plugin->handlers);
2504   while (NULL != (lal = plugin->lal_head))
2505     {
2506       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2507                                    plugin->lal_tail,
2508                                    lal);
2509       GNUNET_free (lal);
2510     }
2511
2512   if (plugin->behind_nat == GNUNET_YES)
2513     {
2514       if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2515         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2516       GNUNET_OS_process_wait (plugin->server_pid);
2517     }
2518
2519   GNUNET_free (plugin);
2520   GNUNET_free (api);
2521   return NULL;
2522 }
2523
2524 /* end of plugin_transport_tcp.c */