done
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, 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_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
39
40 #define DEBUG_TCP GNUNET_YES
41
42 /**
43  * How long until we give up on transmitting the welcome message?
44  */
45 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
46
47
48 /**
49  * Initial handshake message for a session.
50  */
51 struct WelcomeMessage
52 {
53   /**
54    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
55    */
56   struct GNUNET_MessageHeader header;
57
58   /**
59    * Identity of the node connecting (TCP client)
60    */
61   struct GNUNET_PeerIdentity clientIdentity;
62
63 };
64
65
66 /**
67  * Encapsulation of all of the state of the plugin.
68  */
69 struct Plugin;
70
71
72 /**
73  * Information kept for each message that is yet to
74  * be transmitted.
75  */
76 struct PendingMessage
77 {
78
79   /**
80    * This is a doubly-linked list.
81    */
82   struct PendingMessage *next;
83
84   /**
85    * This is a doubly-linked list.
86    */
87   struct PendingMessage *prev;
88
89   /**
90    * The pending message
91    */
92   const char *msg;
93
94   /**
95    * Continuation function to call once the message
96    * has been sent.  Can be NULL if there is no
97    * continuation to call.
98    */
99   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
100
101   /**
102    * Closure for transmit_cont.
103    */
104   void *transmit_cont_cls;
105
106   /**
107    * Timeout value for the pending message.
108    */
109   struct GNUNET_TIME_Absolute timeout;
110
111   /**
112    * So that the gnunet-service-transport can group messages together,
113    * these pending messages need to accept a message buffer and size
114    * instead of just a GNUNET_MessageHeader.
115    */
116   size_t message_size;
117
118 };
119
120
121 /**
122  * Session handle for TCP connections.
123  */
124 struct Session
125 {
126
127   /**
128    * Stored in a linked list.
129    */
130   struct Session *next;
131
132   /**
133    * Pointer to the global plugin struct.
134    */
135   struct Plugin *plugin;
136
137   /**
138    * The client (used to identify this connection)
139    */
140   struct GNUNET_SERVER_Client *client;
141
142   /**
143    * Messages currently pending for transmission
144    * to this peer, if any.
145    */
146   struct PendingMessage *pending_messages_head;
147
148   /**
149    * Messages currently pending for transmission
150    * to this peer, if any.
151    */
152   struct PendingMessage *pending_messages_tail;
153
154   /**
155    * Handle for pending transmission request.
156    */
157   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
158
159   /**
160    * To whom are we talking to (set to our identity
161    * if we are still waiting for the welcome message)
162    */
163   struct GNUNET_PeerIdentity target;
164
165   /**
166    * ID of task used to delay receiving more to throttle sender.
167    */
168   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
169
170   /**
171    * Address of the other peer (either based on our 'connect'
172    * call or on our 'accept' call).
173    */
174   void *connect_addr;
175
176   /**
177    * Last activity on this connection.  Used to select preferred
178    * connection.
179    */
180   struct GNUNET_TIME_Absolute last_activity;
181
182   /**
183    * Length of connect_addr.
184    */
185   size_t connect_alen;
186
187   /**
188    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
189    */
190   int expecting_welcome;
191
192   /**
193    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
194    */
195   int inbound;
196
197 };
198
199
200 /**
201  * Encapsulation of all of the state of the plugin.
202  */
203 struct Plugin
204 {
205   /**
206    * Our environment.
207    */
208   struct GNUNET_TRANSPORT_PluginEnvironment *env;
209
210   /**
211    * The listen socket.
212    */
213   struct GNUNET_CONNECTION_Handle *lsock;
214
215   /**
216    * List of open TCP sessions.
217    */
218   struct Session *sessions;
219
220   /**
221    * Handle for the statistics service.
222    */
223   struct GNUNET_STATISTICS_Handle *statistics;
224
225   /**
226    * Handle to the network service.
227    */
228   struct GNUNET_SERVICE_Context *service;
229
230   /**
231    * Handle to the server for this service.
232    */
233   struct GNUNET_SERVER_Handle *server;
234
235   /**
236    * Copy of the handler array where the closures are
237    * set to this struct's instance.
238    */
239   struct GNUNET_SERVER_MessageHandler *handlers;
240
241   /**
242    * Handle for request of hostname resolution, non-NULL if pending.
243    */
244   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
245
246   /**
247    * ID of task used to update our addresses when one expires.
248    */
249   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
250
251   /**
252    * Port that we are actually listening on.
253    */
254   uint16_t open_port;
255
256   /**
257    * Port that the user said we would have visible to the
258    * rest of the world.
259    */
260   uint16_t adv_port;
261
262 };
263
264
265 /**
266  * Find the session handle for the given client.
267  *
268  * @return NULL if no matching session exists
269  */
270 static struct Session *
271 find_session_by_client (struct Plugin *plugin,
272                         const struct GNUNET_SERVER_Client *client)
273 {
274   struct Session *ret;
275
276   ret = plugin->sessions;
277   while ((ret != NULL) && (client != ret->client))
278     ret = ret->next;
279   return ret;
280 }
281
282
283 /**
284  * Create a new session.  Also queues a welcome message.
285  *
286  * @param plugin us
287  * @param target peer to connect to
288  * @param client client to use
289  * @return new session object
290  */
291 static struct Session *
292 create_session (struct Plugin *plugin,
293                 const struct GNUNET_PeerIdentity *target,
294                 struct GNUNET_SERVER_Client *client)
295 {
296   struct Session *ret;
297   struct PendingMessage *pm;
298   struct WelcomeMessage welcome;
299
300   GNUNET_assert (client != NULL);
301   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
302                    "tcp",
303                    "Creating new session for peer `%4s'\n",
304                    GNUNET_i2s (target));
305   ret = GNUNET_malloc (sizeof (struct Session));
306   ret->last_activity = GNUNET_TIME_absolute_get ();
307   ret->plugin = plugin;
308   ret->next = plugin->sessions;
309   plugin->sessions = ret;
310   ret->client = client;
311   ret->target = *target;
312   ret->expecting_welcome = GNUNET_YES;
313   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
314   pm->msg = (const char*) &pm[1];
315   pm->message_size = sizeof (struct WelcomeMessage);
316   welcome.header.size = htons (sizeof (struct WelcomeMessage));
317   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
318   welcome.clientIdentity = *plugin->env->my_identity;
319   memcpy (&pm[1], &welcome, sizeof (welcome));
320   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
321   GNUNET_STATISTICS_update (plugin->env->stats,
322                             gettext_noop ("# bytes currently in TCP buffers"),
323                             pm->message_size,
324                             GNUNET_NO);      
325   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
326                                ret->pending_messages_tail,
327                                pm);
328   GNUNET_STATISTICS_update (plugin->env->stats,
329                             gettext_noop ("# TCP sessions active"),
330                             1,
331                             GNUNET_NO);      
332   return ret;
333 }
334
335
336 /**
337  * If we have pending messages, ask the server to
338  * transmit them (schedule the respective tasks, etc.)
339  *
340  * @param session for which session should we do this
341  */
342 static void process_pending_messages (struct Session *session);
343
344
345 /**
346  * Function called to notify a client about the socket
347  * being ready to queue more data.  "buf" will be
348  * NULL and "size" zero if the socket was closed for
349  * writing in the meantime.
350  *
351  * @param cls closure
352  * @param size number of bytes available in buf
353  * @param buf where the callee should write the message
354  * @return number of bytes written to buf
355  */
356 static size_t
357 do_transmit (void *cls, size_t size, void *buf)
358 {
359   struct Session *session = cls;
360   struct GNUNET_PeerIdentity pid;
361   struct Plugin *plugin;
362   struct PendingMessage *pos;
363   struct PendingMessage *hd;
364   struct PendingMessage *tl;
365   struct GNUNET_TIME_Absolute now;
366   char *cbuf;
367   size_t ret;
368
369   session->transmit_handle = NULL;
370   plugin = session->plugin;
371   if (buf == NULL)
372     {
373 #if DEBUG_TCP
374       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
375                        "tcp",
376                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
377                        GNUNET_i2s (&session->target));
378 #endif
379       /* timeout; cancel all messages that have already expired */
380       hd = NULL;
381       tl = NULL;
382       ret = 0;
383       now = GNUNET_TIME_absolute_get ();
384       while ( (NULL != (pos = session->pending_messages_head)) &&
385               (pos->timeout.value <= now.value) )
386         {
387           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
388                                        session->pending_messages_tail,
389                                        pos);
390 #if DEBUG_TCP
391           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
392                            "tcp",
393                            "Failed to transmit %u byte message to `%4s'.\n",
394                            pos->message_size,
395                            GNUNET_i2s (&session->target));
396 #endif
397           ret += pos->message_size;
398           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
399         }
400       /* do this call before callbacks (so that if callbacks destroy
401          session, they have a chance to cancel actions done by this
402          call) */
403       process_pending_messages (session);  
404       pid = session->target;
405       /* no do callbacks and do not use session again since
406          the callbacks may abort the session */
407       while (NULL != (pos = hd))
408         {
409           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
410           if (pos->transmit_cont != NULL)
411             pos->transmit_cont (pos->transmit_cont_cls,
412                                 &pid, GNUNET_SYSERR);
413           GNUNET_free (pos);
414         }
415       GNUNET_STATISTICS_update (plugin->env->stats,
416                                 gettext_noop ("# bytes currently in TCP buffers"),
417                                 - (int64_t) ret,
418                                 GNUNET_NO); 
419       GNUNET_STATISTICS_update (plugin->env->stats,
420                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
421                                 ret,
422                                 GNUNET_NO);      
423       return 0;
424     }
425   /* copy all pending messages that would fit */
426   ret = 0;
427   cbuf = buf;
428   hd = NULL;
429   tl = NULL;
430   while (NULL != (pos = session->pending_messages_head)) 
431     {
432       if (ret + pos->message_size > size) 
433         break;
434       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
435                                    session->pending_messages_tail,
436                                    pos);
437       GNUNET_assert (size >= pos->message_size);
438       memcpy (cbuf, pos->msg, pos->message_size);
439       cbuf += pos->message_size;
440       ret += pos->message_size;
441       size -= pos->message_size;
442       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
443     }
444   /* schedule 'continuation' before callbacks so that callbacks that
445      cancel everything don't cause us to use a session that no longer
446      exists... */
447   process_pending_messages (session);  
448   session->last_activity = GNUNET_TIME_absolute_get ();
449   pid = session->target;
450   /* we'll now call callbacks that may cancel the session; hence
451      we should not use 'session' after this point */
452   while (NULL != (pos = hd))
453     {
454       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
455       if (pos->transmit_cont != NULL)
456         pos->transmit_cont (pos->transmit_cont_cls,
457                             &pid, GNUNET_OK);
458       GNUNET_free (pos);
459     }
460   GNUNET_assert (hd == NULL);
461   GNUNET_assert (tl == NULL);
462 #if DEBUG_TCP > 1
463   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
464                    "tcp", "Transmitting %u bytes\n", ret);
465 #endif
466   GNUNET_STATISTICS_update (plugin->env->stats,
467                             gettext_noop ("# bytes currently in TCP buffers"),
468                             - (int64_t) ret,
469                             GNUNET_NO);       
470   GNUNET_STATISTICS_update (plugin->env->stats,
471                             gettext_noop ("# bytes transmitted via TCP"),
472                             ret,
473                             GNUNET_NO);      
474   return ret;
475 }
476
477
478 /**
479  * If we have pending messages, ask the server to
480  * transmit them (schedule the respective tasks, etc.)
481  *
482  * @param session for which session should we do this
483  */
484 static void
485 process_pending_messages (struct Session *session)
486 {
487   struct PendingMessage *pm;
488
489   GNUNET_assert (session->client != NULL);
490   if (session->transmit_handle != NULL)
491     return;
492   if (NULL == (pm = session->pending_messages_head))
493     return;
494   session->transmit_handle
495     = GNUNET_SERVER_notify_transmit_ready (session->client,
496                                            pm->message_size,
497                                            GNUNET_TIME_absolute_get_remaining
498                                            (pm->timeout),
499                                            &do_transmit, session);
500 }
501
502
503 /**
504  * Functions with this signature are called whenever we need
505  * to close a session due to a disconnect or failure to
506  * establish a connection.
507  *
508  * @param session session to close down
509  */
510 static void
511 disconnect_session (struct Session *session)
512 {
513   struct Session *prev;
514   struct Session *pos;
515   struct PendingMessage *pm;
516
517 #if DEBUG_TCP
518   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
519                    "tcp",
520                    "Disconnecting from `%4s' at %s (session %p).\n",
521                    GNUNET_i2s (&session->target),
522                    (session->connect_addr != NULL) ?
523                    GNUNET_a2s (session->connect_addr,
524                                session->connect_alen) : "*", session);
525 #endif
526   /* remove from session list */
527   prev = NULL;
528   pos = session->plugin->sessions;
529   while (pos != session)
530     {
531       prev = pos;
532       pos = pos->next;
533     }
534   if (prev == NULL)
535     session->plugin->sessions = session->next;
536   else
537     prev->next = session->next;
538   /* clean up state */
539   if (session->transmit_handle != NULL)
540     {
541       GNUNET_CONNECTION_notify_transmit_ready_cancel
542         (session->transmit_handle);
543       session->transmit_handle = NULL;
544     }
545   while (NULL != (pm = session->pending_messages_head))
546     {
547 #if DEBUG_TCP
548       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
549                        "tcp",
550                        pm->transmit_cont != NULL
551                        ? "Could not deliver message to `%4s'.\n"
552                        :
553                        "Could not deliver message to `%4s', notifying.\n",
554                        GNUNET_i2s (&session->target));
555 #endif
556       GNUNET_STATISTICS_update (session->plugin->env->stats,
557                                 gettext_noop ("# bytes currently in TCP buffers"),
558                                 - (int64_t) pm->message_size,
559                                 GNUNET_NO);      
560       GNUNET_STATISTICS_update (session->plugin->env->stats,
561                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
562                                 pm->message_size,
563                                 GNUNET_NO);      
564       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
565                                    session->pending_messages_tail,
566                                    pm);
567       if (NULL != pm->transmit_cont)
568         pm->transmit_cont (pm->transmit_cont_cls,
569                            &session->target, GNUNET_SYSERR);
570       GNUNET_free (pm);
571     }
572   GNUNET_break (session->client != NULL);
573   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
574     {
575       GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
576                                session->receive_delay_task);
577       GNUNET_SERVER_receive_done (session->client, 
578                                   GNUNET_SYSERR);       
579     }
580   GNUNET_SERVER_client_drop (session->client);
581   GNUNET_STATISTICS_update (session->plugin->env->stats,
582                             gettext_noop ("# TCP sessions active"),
583                             -1,
584                             GNUNET_NO);      
585   GNUNET_free_non_null (session->connect_addr);
586   GNUNET_free (session);
587 }
588
589
590 /**
591  * Given two otherwise equivalent sessions, pick the better one.
592  * 
593  * @param s1 one session (also default)
594  * @param s2 other session
595  * @return "better" session (more active)
596  */
597 static struct Session *
598 select_better_session (struct Session *s1,
599                        struct Session *s2)
600 {
601   if (s1 == NULL)
602     return s2;
603   if (s2 == NULL)
604     return s1;
605   if ( (s1->expecting_welcome == GNUNET_NO) &&
606        (s2->expecting_welcome == GNUNET_YES) )
607     return s1;
608   if ( (s1->expecting_welcome == GNUNET_YES) &&
609        (s2->expecting_welcome == GNUNET_NO) )
610     return s2;
611   if (s1->last_activity.value < s2->last_activity.value)
612     return s2;
613   if (s1->last_activity.value > s2->last_activity.value)
614     return s1;
615   if ( (GNUNET_YES == s1->inbound) &&
616        (GNUNET_NO  == s2->inbound) )
617     return s1;
618   if ( (GNUNET_NO  == s1->inbound) &&
619        (GNUNET_YES == s2->inbound) )
620     return s2;
621   return s1;
622 }
623
624
625 /**
626  * Function that can be used by the transport service to transmit
627  * a message using the plugin.   Note that in the case of a
628  * peer disconnecting, the continuation MUST be called
629  * prior to the disconnect notification itself.  This function
630  * will be called with this peer's HELLO message to initiate
631  * a fresh connection to another peer.
632  *
633  * @param cls closure
634  * @param target who should receive this message
635  * @param msg the message to transmit
636  * @param msgbuf_size number of bytes in 'msg'
637  * @param priority how important is the message (most plugins will
638  *                 ignore message priority and just FIFO)
639  * @param timeout how long to wait at most for the transmission (does not
640  *                require plugins to discard the message after the timeout,
641  *                just advisory for the desired delay; most plugins will ignore
642  *                this as well)
643  * @param addr the address to use (can be NULL if the plugin
644  *                is "on its own" (i.e. re-use existing TCP connection))
645  * @param addrlen length of the address in bytes
646  * @param force_address GNUNET_YES if the plugin MUST use the given address,
647  *                GNUNET_NO means the plugin may use any other address and
648  *                GNUNET_SYSERR means that only reliable existing
649  *                bi-directional connections should be used (regardless
650  *                of address)
651  * @param cont continuation to call once the message has
652  *        been transmitted (or if the transport is ready
653  *        for the next transmission call; or if the
654  *        peer disconnected...); can be NULL
655  * @param cont_cls closure for cont
656  * @return number of bytes used (on the physical network, with overheads);
657  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
658  *         and does NOT mean that the message was not transmitted (DV)
659  */
660 static ssize_t
661 tcp_plugin_send (void *cls,
662                  const struct GNUNET_PeerIdentity *target,
663                  const char *msg,
664                  size_t msgbuf_size,
665                  uint32_t priority,
666                  struct GNUNET_TIME_Relative timeout,
667                  const void *addr,
668                  size_t addrlen,
669                  int force_address,
670                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
671 {
672   struct Plugin *plugin = cls;
673   struct Session *session;
674   struct Session *cand_session;
675   struct Session *next;
676   struct PendingMessage *pm;
677   struct GNUNET_CONNECTION_Handle *sa;
678   int af;
679
680   GNUNET_STATISTICS_update (plugin->env->stats,
681                             gettext_noop ("# bytes TCP was asked to transmit"),
682                             msgbuf_size,
683                             GNUNET_NO);      
684   /* FIXME: we could do this a cheaper with a hash table
685      where we could restrict the iteration to entries that match
686      the target peer... */
687   cand_session = NULL;
688   next = plugin->sessions;
689   while (NULL != (session = next)) 
690     {
691       next = session->next;
692       GNUNET_assert (session->client != NULL);
693       if (0 != memcmp (target,
694                        &session->target, 
695                        sizeof (struct GNUNET_PeerIdentity)))
696         continue;
697       if ( ( (GNUNET_SYSERR == force_address) &&
698              (session->expecting_welcome == GNUNET_NO) ) ||
699            (GNUNET_NO == force_address) )   
700         {
701           cand_session = select_better_session (cand_session,
702                                                 session);
703           continue;
704         }
705       if (GNUNET_SYSERR == force_address)
706         continue;
707       GNUNET_break (GNUNET_YES == force_address);
708       if (addr == NULL)
709         {
710           GNUNET_break (0);
711           break;
712         }
713       if (session->inbound == GNUNET_YES) 
714         continue;
715       if (addrlen != session->connect_alen)
716         continue;
717       if (0 != memcmp (session->connect_addr,
718                        addr,
719                        addrlen))
720         continue;
721       cand_session = select_better_session (cand_session,
722                                             session);         
723     }
724   session = cand_session;
725   if ( (session == NULL) &&
726        (addr == NULL) )
727     {
728 #if DEBUG_TCP
729       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
730                        "tcp",
731                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
732                        GNUNET_i2s (target));
733 #endif
734       GNUNET_STATISTICS_update (plugin->env->stats,
735                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
736                                 msgbuf_size,
737                                 GNUNET_NO);      
738       return -1;
739     }
740   if (session == NULL)
741     {
742       if (sizeof (struct sockaddr_in) == addrlen)
743         {
744           af = AF_INET;
745         }
746       else if (sizeof (struct sockaddr_in6) == addrlen)
747         {
748           af = AF_INET6;
749         }
750       else
751         {
752           GNUNET_break_op (0);
753           return -1;
754         }
755       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
756                                                    af, addr, addrlen,
757                                                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
758       if (sa == NULL)
759         {
760 #if DEBUG_TCP
761           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
762                            "tcp",
763                            "Failed to create connection to `%4s' at `%s'\n",
764                            GNUNET_i2s (target),
765                            GNUNET_a2s (addr, addrlen));
766 #endif
767           GNUNET_STATISTICS_update (plugin->env->stats,
768                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
769                                     msgbuf_size,
770                                     GNUNET_NO);      
771           return -1;
772         }
773 #if DEBUG_TCP
774       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
775                        "tcp",
776                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
777                        GNUNET_i2s (target),
778                        GNUNET_a2s (addr, addrlen));
779 #endif
780       session = create_session (plugin,
781                                 target,
782                                 GNUNET_SERVER_connect_socket (plugin->server,
783                                                               sa));
784       session->connect_addr = GNUNET_malloc (addrlen);
785       memcpy (session->connect_addr,
786               addr,
787               addrlen);
788       session->connect_alen = addrlen;
789     }
790   GNUNET_assert (session != NULL);
791   GNUNET_assert (session->client != NULL);
792   GNUNET_STATISTICS_update (plugin->env->stats,
793                             gettext_noop ("# bytes currently in TCP buffers"),
794                             msgbuf_size,
795                             GNUNET_NO);      
796   /* create new message entry */
797   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
798   pm->msg = (const char*) &pm[1];
799   memcpy (&pm[1], msg, msgbuf_size);
800   pm->message_size = msgbuf_size;
801   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
802   pm->transmit_cont = cont;
803   pm->transmit_cont_cls = cont_cls;
804
805   /* append pm to pending_messages list */
806   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
807                                      session->pending_messages_tail,
808                                      session->pending_messages_tail,
809                                      pm);
810 #if DEBUG_TCP
811   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
812                    "tcp",
813                    "Asked to transmit %u bytes to `%s', added message to list.\n",
814                    msgbuf_size,
815                    GNUNET_i2s (target));
816 #endif
817   process_pending_messages (session);
818   return msgbuf_size;
819 }
820
821
822 /**
823  * Function that can be called to force a disconnect from the
824  * specified neighbour.  This should also cancel all previously
825  * scheduled transmissions.  Obviously the transmission may have been
826  * partially completed already, which is OK.  The plugin is supposed
827  * to close the connection (if applicable) and no longer call the
828  * transmit continuation(s).
829  *
830  * Finally, plugin MUST NOT call the services's receive function to
831  * notify the service that the connection to the specified target was
832  * closed after a getting this call.
833  *
834  * @param cls closure
835  * @param target peer for which the last transmission is
836  *        to be cancelled
837  */
838 static void
839 tcp_plugin_disconnect (void *cls,
840                        const struct GNUNET_PeerIdentity *target)
841 {
842   struct Plugin *plugin = cls;
843   struct Session *session;
844   struct Session *next;
845   struct PendingMessage *pm;
846
847 #if DEBUG_TCP
848   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
849                    "tcp",
850                    "Asked to cancel session with `%4s'\n",
851                    GNUNET_i2s (target));
852 #endif
853   next = plugin->sessions;
854   while (NULL != (session = next))
855     {
856       next = session->next;
857       if (0 != memcmp (target,
858                        &session->target,
859                        sizeof (struct GNUNET_PeerIdentity)))
860         continue;
861       pm = session->pending_messages_head;
862       while (pm != NULL)
863         {
864           pm->transmit_cont = NULL;
865           pm->transmit_cont_cls = NULL;
866           pm = pm->next;
867         }
868       disconnect_session (session);
869     }
870 }
871
872
873 /**
874  * Context for address to string conversion.
875  */
876 struct PrettyPrinterContext
877 {
878   /**
879    * Function to call with the result.
880    */
881   GNUNET_TRANSPORT_AddressStringCallback asc;
882
883   /**
884    * Clsoure for 'asc'.
885    */
886   void *asc_cls;
887
888   /**
889    * Port to add after the IP address.
890    */
891   uint16_t port;
892 };
893
894
895 /**
896  * Append our port and forward the result.
897  *
898  * @param cls the 'struct PrettyPrinterContext*'
899  * @param hostname hostname part of the address
900  */
901 static void
902 append_port (void *cls, const char *hostname)
903 {
904   struct PrettyPrinterContext *ppc = cls;
905   char *ret;
906
907   if (hostname == NULL)
908     {
909       ppc->asc (ppc->asc_cls, NULL);
910       GNUNET_free (ppc);
911       return;
912     }
913   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
914   ppc->asc (ppc->asc_cls, ret);
915   GNUNET_free (ret);
916 }
917
918
919 /**
920  * Convert the transports address to a nice, human-readable
921  * format.
922  *
923  * @param cls closure
924  * @param type name of the transport that generated the address
925  * @param addr one of the addresses of the host, NULL for the last address
926  *        the specific address format depends on the transport
927  * @param addrlen length of the address
928  * @param numeric should (IP) addresses be displayed in numeric form?
929  * @param timeout after how long should we give up?
930  * @param asc function to call on each string
931  * @param asc_cls closure for asc
932  */
933 static void
934 tcp_plugin_address_pretty_printer (void *cls,
935                                    const char *type,
936                                    const void *addr,
937                                    size_t addrlen,
938                                    int numeric,
939                                    struct GNUNET_TIME_Relative timeout,
940                                    GNUNET_TRANSPORT_AddressStringCallback asc,
941                                    void *asc_cls)
942 {
943   struct Plugin *plugin = cls;
944   const struct sockaddr_in *v4;
945   const struct sockaddr_in6 *v6;
946   struct PrettyPrinterContext *ppc;
947
948   if ((addrlen != sizeof (struct sockaddr_in)) &&
949       (addrlen != sizeof (struct sockaddr_in6)))
950     {
951       /* invalid address */
952       GNUNET_break_op (0);
953       asc (asc_cls, NULL);
954       return;
955     }
956   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
957   ppc->asc = asc;
958   ppc->asc_cls = asc_cls;
959   if (addrlen == sizeof (struct sockaddr_in))
960     {
961       v4 = (const struct sockaddr_in *) addr;
962       ppc->port = ntohs (v4->sin_port);
963     }
964   else
965     {
966       v6 = (const struct sockaddr_in6 *) addr;
967       ppc->port = ntohs (v6->sin6_port);
968
969     }
970   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
971                                 plugin->env->cfg,
972                                 addr,
973                                 addrlen,
974                                 !numeric, timeout, &append_port, ppc);
975 }
976
977
978 /**
979  * Check if the given port is plausible (must be either
980  * our listen port or our advertised port).  If it is
981  * neither, we return one of these two ports at random.
982  *
983  * @param plugin global variables
984  * @param in_port port number to check
985  * @return either in_port or a more plausible port
986  */
987 static uint16_t
988 check_port (struct Plugin *plugin, uint16_t in_port)
989 {
990   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
991     return in_port;
992   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
993                                     2) == 0)
994     ? plugin->open_port : plugin->adv_port;
995 }
996
997
998 /**
999  * Another peer has suggested an address for this peer and transport
1000  * plugin.  Check that this could be a valid address.
1001  *
1002  * @param cls closure, our 'struct Plugin*'
1003  * @param addr pointer to the address
1004  * @param addrlen length of addr
1005  * @return GNUNET_OK if this is a plausible address for this peer
1006  *         and transport
1007  */
1008 static int
1009 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1010 {
1011   struct Plugin *plugin = cls;
1012   char buf[sizeof (struct sockaddr_in6)];
1013   struct sockaddr_in *v4;
1014   struct sockaddr_in6 *v6;
1015
1016   if ((addrlen != sizeof (struct sockaddr_in)) &&
1017       (addrlen != sizeof (struct sockaddr_in6)))
1018     {
1019       GNUNET_break_op (0);
1020       return GNUNET_SYSERR;
1021     }
1022   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1023   if (addrlen == sizeof (struct sockaddr_in))
1024     {
1025       v4 = (struct sockaddr_in *) buf;
1026       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1027     }
1028   else
1029     {
1030       v6 = (struct sockaddr_in6 *) buf;
1031       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1032     }
1033 #if DEBUG_TCP
1034   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1035                    "tcp",
1036                    "Informing transport service about my address `%s'.\n",
1037                    GNUNET_a2s (addr, addrlen));
1038 #endif
1039   return GNUNET_OK;
1040 }
1041
1042
1043 /**
1044  * We've received a welcome from this peer via TCP.  Possibly create a
1045  * fresh client record and send back our welcome.
1046  *
1047  * @param cls closure
1048  * @param client identification of the client
1049  * @param message the actual message
1050  */
1051 static void
1052 handle_tcp_welcome (void *cls,
1053                     struct GNUNET_SERVER_Client *client,
1054                     const struct GNUNET_MessageHeader *message)
1055 {
1056   struct Plugin *plugin = cls;
1057   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1058   struct Session *session;
1059   size_t alen;
1060   void *vaddr;
1061
1062 #if DEBUG_TCP
1063   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1064                    "tcp",
1065                    "Received %s message from a `%4s/%p'.\n", 
1066                    "WELCOME",
1067                    GNUNET_i2s (&wm->clientIdentity), client);
1068 #endif
1069   GNUNET_STATISTICS_update (plugin->env->stats,
1070                             gettext_noop ("# TCP WELCOME messages received"),
1071                             1,
1072                             GNUNET_NO);      
1073   session = find_session_by_client (plugin, client);
1074   if (session == NULL)
1075     {
1076       GNUNET_SERVER_client_keep (client);
1077       session = create_session (plugin,
1078                                 &wm->clientIdentity, client);
1079       session->inbound = GNUNET_YES;
1080       if (GNUNET_OK ==
1081           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1082         {
1083 #if DEBUG_TCP
1084           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1085                            "tcp",
1086                            "Found address `%s' for incoming connection %p\n",
1087                            GNUNET_a2s (vaddr, alen),
1088                            client);
1089 #endif
1090           session->connect_addr = vaddr;
1091           session->connect_alen = alen;
1092         }
1093       else
1094         {
1095 #if DEBUG_TCP
1096           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1097                            "tcp",
1098                            "Did not obtain TCP socket address for incoming connection\n");
1099 #endif
1100         }
1101 #if DEBUG_TCP
1102       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1103                        "tcp",
1104                        "Creating new session %p for connection %p\n",
1105                        session, client);
1106 #endif
1107       process_pending_messages (session);
1108     }
1109   if (session->expecting_welcome != GNUNET_YES)
1110     {
1111       GNUNET_break_op (0);
1112       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1113       return;
1114     }
1115   session->last_activity = GNUNET_TIME_absolute_get ();
1116   session->expecting_welcome = GNUNET_NO;
1117   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1118 }
1119
1120
1121 /**
1122  * Task to signal the server that we can continue
1123  * receiving from the TCP client now.
1124  *
1125  * @param cls the 'struct Session*'
1126  * @param tc task context (unused)
1127  */
1128 static void
1129 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1130 {
1131   struct Session *session = cls;
1132   struct GNUNET_TIME_Relative delay;
1133
1134   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1135   delay = session->plugin->env->receive (session->plugin->env->cls,
1136                                          &session->target,
1137                                          NULL, 0, NULL, 0);
1138   if (delay.value == 0)
1139     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1140   else
1141     session->receive_delay_task = 
1142       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1143                                     delay, &delayed_done, session);
1144 }
1145
1146
1147 /**
1148  * We've received data for this peer via TCP.  Unbox,
1149  * compute latency and forward.
1150  *
1151  * @param cls closure
1152  * @param client identification of the client
1153  * @param message the actual message
1154  */
1155 static void
1156 handle_tcp_data (void *cls,
1157                  struct GNUNET_SERVER_Client *client,
1158                  const struct GNUNET_MessageHeader *message)
1159 {
1160   struct Plugin *plugin = cls;
1161   struct Session *session;
1162   struct GNUNET_TIME_Relative delay;
1163
1164   if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1165     {
1166       /* We don't want to propagate WELCOME messages up! */
1167       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1168       return; 
1169     }    
1170   session = find_session_by_client (plugin, client);
1171   if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1172     {
1173       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1174       return;
1175     }
1176   session->last_activity = GNUNET_TIME_absolute_get ();
1177 #if DEBUG_TCP
1178   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1179                    "tcp", 
1180                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1181                    (unsigned int) ntohs (message->size), 
1182                    (unsigned int) ntohs (message->type),
1183                    GNUNET_i2s (&session->target));
1184 #endif
1185   GNUNET_STATISTICS_update (plugin->env->stats,
1186                             gettext_noop ("# bytes received via TCP"),
1187                             ntohs (message->size),
1188                             GNUNET_NO); 
1189   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1190                                 session->connect_addr,
1191                                 session->connect_alen);
1192
1193   if (delay.value == 0)
1194     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1195   else
1196     session->receive_delay_task = 
1197       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1198                                     delay, &delayed_done, session);
1199 }
1200
1201
1202 /**
1203  * Handlers for the various TCP messages.
1204  */
1205 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1206   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1207    sizeof (struct WelcomeMessage)},
1208   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1209   {NULL, NULL, 0, 0}
1210 };
1211
1212
1213 /**
1214  * Functions with this signature are called whenever a peer
1215  * is disconnected on the network level.
1216  *
1217  * @param cls closure
1218  * @param client identification of the client
1219  */
1220 static void
1221 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1222 {
1223   struct Plugin *plugin = cls;
1224   struct Session *session;
1225
1226   if (client == NULL)
1227     return;
1228   session = find_session_by_client (plugin, client);
1229   if (session == NULL)
1230     return;                     /* unknown, nothing to do */
1231 #if DEBUG_TCP
1232   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1233                    "tcp",
1234                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1235                    GNUNET_i2s (&session->target),
1236                    (session->connect_addr != NULL) ?
1237                    GNUNET_a2s (session->connect_addr,
1238                                session->connect_alen) : "*", client);
1239 #endif
1240   disconnect_session (session);
1241 }
1242
1243
1244 /**
1245  * Add the IP of our network interface to the list of
1246  * our external IP addresses.
1247  */
1248 static int
1249 process_interfaces (void *cls,
1250                     const char *name,
1251                     int isDefault,
1252                     const struct sockaddr *addr, socklen_t addrlen)
1253 {
1254   struct Plugin *plugin = cls;
1255   int af;
1256   struct sockaddr_in *v4;
1257   struct sockaddr_in6 *v6;
1258
1259   af = addr->sa_family;
1260   if (af == AF_INET)
1261     {
1262       v4 = (struct sockaddr_in *) addr;
1263       v4->sin_port = htons (plugin->adv_port);
1264     }
1265   else
1266     {
1267       GNUNET_assert (af == AF_INET6);
1268       v6 = (struct sockaddr_in6 *) addr;
1269       v6->sin6_port = htons (plugin->adv_port);
1270     }
1271   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1272                    GNUNET_ERROR_TYPE_BULK,
1273                    "tcp", _("Found address `%s' (%s)\n"),
1274                    GNUNET_a2s (addr, addrlen), name);
1275   plugin->env->notify_address (plugin->env->cls,
1276                                "tcp",
1277                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1278   return GNUNET_OK;
1279 }
1280
1281
1282 /**
1283  * Function called by the resolver for each address obtained from DNS
1284  * for our own hostname.  Add the addresses to the list of our
1285  * external IP addresses.
1286  *
1287  * @param cls closure
1288  * @param addr one of the addresses of the host, NULL for the last address
1289  * @param addrlen length of the address
1290  */
1291 static void
1292 process_hostname_ips (void *cls,
1293                       const struct sockaddr *addr, socklen_t addrlen)
1294 {
1295   struct Plugin *plugin = cls;
1296
1297   if (addr == NULL)
1298     {
1299       plugin->hostname_dns = NULL;
1300       return;
1301     }
1302   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1303 }
1304
1305
1306 /**
1307  * Entry point for the plugin.
1308  */
1309 void *
1310 libgnunet_plugin_transport_tcp_init (void *cls)
1311 {
1312   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1313   struct GNUNET_TRANSPORT_PluginFunctions *api;
1314   struct Plugin *plugin;
1315   struct GNUNET_SERVICE_Context *service;
1316   unsigned long long aport;
1317   unsigned long long bport;
1318   unsigned int i;
1319
1320   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1321   if (service == NULL)
1322     {
1323       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1324                        "tcp",
1325                        _
1326                        ("Failed to start service for `%s' transport plugin.\n"),
1327                        "tcp");
1328       return NULL;
1329     }
1330   aport = 0;
1331   if ((GNUNET_OK !=
1332        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1333                                               "transport-tcp",
1334                                               "PORT",
1335                                               &bport)) ||
1336       (bport > 65535) ||
1337       ((GNUNET_OK ==
1338         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1339                                                "transport-tcp",
1340                                                "ADVERTISED-PORT",
1341                                                &aport)) && (aport > 65535)))
1342     {
1343       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1344                        "tcp",
1345                        _
1346                        ("Require valid port number for service `%s' in configuration!\n"),
1347                        "transport-tcp");
1348       GNUNET_SERVICE_stop (service);
1349       return NULL;
1350     }
1351   if (aport == 0)
1352     aport = bport;
1353   plugin = GNUNET_malloc (sizeof (struct Plugin));
1354   plugin->open_port = bport;
1355   plugin->adv_port = aport;
1356   plugin->env = env;
1357   plugin->lsock = NULL;
1358   plugin->statistics = NULL;
1359   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1360   api->cls = plugin;
1361   api->send = &tcp_plugin_send;
1362   api->disconnect = &tcp_plugin_disconnect;
1363   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1364   api->check_address = &tcp_plugin_check_address;
1365   plugin->service = service;
1366   plugin->server = GNUNET_SERVICE_get_server (service);
1367   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1368   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1369   for (i = 0;
1370        i <
1371        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1372        i++)
1373     plugin->handlers[i].callback_cls = plugin;
1374   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1375
1376   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1377                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1378   if (aport != bport)
1379     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1380                      "tcp",
1381                      _("TCP transport advertises itself as being on port %llu\n"),
1382                      aport);
1383   GNUNET_SERVER_disconnect_notify (plugin->server, 
1384                                    &disconnect_notify,
1385                                    plugin);
1386   /* FIXME: do the two calls below periodically again and
1387      not just once (since the info we get might change...) */
1388   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1389   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1390                                                            env->cfg,
1391                                                            AF_UNSPEC,
1392                                                            HOSTNAME_RESOLVE_TIMEOUT,
1393                                                            &process_hostname_ips,
1394                                                            plugin);
1395   return api;
1396 }
1397
1398
1399 /**
1400  * Exit point from the plugin.
1401  */
1402 void *
1403 libgnunet_plugin_transport_tcp_done (void *cls)
1404 {
1405   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1406   struct Plugin *plugin = api->cls;
1407   struct Session *session;
1408
1409   while (NULL != (session = plugin->sessions))
1410     disconnect_session (session);
1411   if (NULL != plugin->hostname_dns)
1412     {
1413       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1414       plugin->hostname_dns = NULL;
1415     }
1416   GNUNET_SERVICE_stop (plugin->service);
1417   GNUNET_free (plugin->handlers);
1418   GNUNET_free (plugin);
1419   GNUNET_free (api);
1420   return NULL;
1421 }
1422
1423 /* end of plugin_transport_tcp.c */