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