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