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