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