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