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