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