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