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