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