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