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