comment
[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                                      NULL,
520                                      &session->target,
521                                      1,
522                                      session->connect_addr,
523                                      session->connect_alen);
524     }
525   if (session->client != NULL)
526     {
527       GNUNET_SERVER_client_drop (session->client);
528       session->client = NULL;
529     }
530   GNUNET_free_non_null (session->connect_addr);
531   GNUNET_free (session);
532 }
533
534
535 /**
536  * Function that can be used by the transport service to transmit
537  * a message using the plugin.   Note that in the case of a
538  * peer disconnecting, the continuation MUST be called
539  * prior to the disconnect notification itself.  This function
540  * will be called with this peer's HELLO message to initiate
541  * a fresh connection to another peer.
542  *
543  * @param cls closure
544  * @param target who should receive this message
545  * @param msg the message to transmit
546  * @param priority how important is the message (most plugins will
547  *                 ignore message priority and just FIFO)
548  * @param timeout how long to wait at most for the transmission (does not
549  *                require plugins to discard the message after the timeout,
550  *                just advisory for the desired delay; most plugins will ignore
551  *                this as well)
552  * @param addr the address to use (can be NULL if the plugin
553  *                is "on its own" (i.e. re-use existing TCP connection))
554  * @param addrlen length of the address in bytes
555  * @param force_address GNUNET_YES if the plugin MUST use the given address,
556  *                otherwise the plugin may use other addresses or
557  *                existing connections (if available)
558  * @param cont continuation to call once the message has
559  *        been transmitted (or if the transport is ready
560  *        for the next transmission call; or if the
561  *        peer disconnected...); can be NULL
562  * @param cont_cls closure for cont
563  * @return number of bytes used (on the physical network, with overheads);
564  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
565  *         and does NOT mean that the message was not transmitted (DV)
566  */
567 static ssize_t
568 tcp_plugin_send (void *cls,
569                  const struct GNUNET_PeerIdentity *target,
570                  const struct GNUNET_MessageHeader *msg,
571                  uint32_t priority,
572                  struct GNUNET_TIME_Relative timeout,
573                  const void *addr,
574                  size_t addrlen,
575                  int force_address,
576                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
577 {
578   struct Plugin *plugin = cls;
579   struct Session *session;
580   struct PendingMessage *pm;
581   struct PendingMessage *pme;
582   struct GNUNET_CONNECTION_Handle *sa;
583   int af;
584   uint16_t mlen;
585
586   mlen = ntohs (msg->size);
587   session = find_session_by_target (plugin, target);
588   if ( (GNUNET_YES == force_address) &&
589        ( (session->connect_alen != addrlen) ||
590          (0 != memcmp (session->connect_addr,
591                        addr,
592                        addrlen)) ) )    
593     session = NULL; /* ignore existing session */
594   if ( (session == NULL) &&
595        (addr == NULL) )
596     {
597 #if DEBUG_TCP
598       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
599                        "tcp",
600                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
601                        GNUNET_i2s (target));
602 #endif      
603       return -1;
604     }
605   if (session == NULL)
606     {
607       if (sizeof (struct sockaddr_in) == addrlen)
608         af = AF_INET;
609       else if (sizeof (struct sockaddr_in6) == addrlen)
610         af = AF_INET6;
611       else
612         {
613           GNUNET_break_op (0);
614           return -1;
615         }
616       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
617                                                    af, addr, addrlen,
618                                                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
619       if (sa == NULL)
620         {
621 #if DEBUG_TCP
622           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
623                            "tcp",
624                            "Failed to create connection to `%4s' at `%s'\n",
625                            GNUNET_i2s (target),
626                            GNUNET_a2s (addr, addrlen));
627 #endif      
628           return -1;
629         }
630
631 #if DEBUG_TCP
632       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
633                        "tcp",
634                        "Asked to transmit to `%4s', creating fresh session.\n",
635                        GNUNET_i2s (target));
636 #endif
637       session = create_session (plugin,
638                                 target,
639                                 GNUNET_SERVER_connect_socket (session->plugin->server,
640                                                               sa));
641       session->connect_addr = GNUNET_malloc (addrlen);
642       memcpy (session->connect_addr,
643               addr,
644               addrlen);
645       session->connect_alen = addrlen;
646     }
647   GNUNET_assert (session != NULL);
648   GNUNET_assert (session->client != NULL);
649
650   /* create new message entry */
651   pm = GNUNET_malloc (mlen + sizeof (struct PendingMessage));
652   memcpy (&pm[1], msg, mlen);
653   pm->msg = (const struct GNUNET_MessageHeader*) &pm[1];
654   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
655   pm->transmit_cont = cont;
656   pm->transmit_cont_cls = cont_cls;
657
658   /* append pm to pending_messages list */
659   pme = session->pending_messages;
660   if (pme == NULL)
661     {
662       session->pending_messages = pm;
663     }
664   else
665     {
666       /* FIXME: this could be done faster by keeping 
667          track of the tail of the list... */
668       while (NULL != pme->next)
669         pme = pme->next;
670       pme->next = pm;
671     }
672 #if DEBUG_TCP
673   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
674                    "tcp",
675                    "Asked to transmit %u bytes to `%s', added message to list.\n",
676                    mlen,
677                    GNUNET_i2s (target));
678 #endif
679   process_pending_messages (session);
680   return mlen;
681 }
682
683
684 /**
685  * Function that can be called to force a disconnect from the
686  * specified neighbour.  This should also cancel all previously
687  * scheduled transmissions.  Obviously the transmission may have been
688  * partially completed already, which is OK.  The plugin is supposed
689  * to close the connection (if applicable) and no longer call the
690  * transmit continuation(s).
691  *
692  * Finally, plugin MUST NOT call the services's receive function to
693  * notify the service that the connection to the specified target was
694  * closed after a getting this call.
695  *
696  * @param cls closure
697  * @param target peer for which the last transmission is
698  *        to be cancelled
699  */
700 static void
701 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
702 {
703   struct Plugin *plugin = cls;
704   struct Session *session;
705   struct PendingMessage *pm;
706
707 #if DEBUG_TCP
708   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
709                    "tcp",
710                    "Asked to cancel session with `%4s'\n",
711                    GNUNET_i2s (target));
712 #endif
713   while (NULL != (session = find_session_by_target (plugin, target)))
714     {
715       pm = session->pending_messages;
716       while (pm != NULL)
717         {
718           pm->transmit_cont = NULL;
719           pm->transmit_cont_cls = NULL;
720           pm = pm->next;
721         }
722       if (session->client != NULL)
723         {
724           GNUNET_SERVER_client_drop (session->client);
725           session->client = NULL;
726         }
727       /* rest of the clean-up of the session will be done as part of
728          disconnect_notify which should be triggered any time now 
729          (or which may be triggering this call in the first place) */
730     }
731 }
732
733
734 struct PrettyPrinterContext
735 {
736   GNUNET_TRANSPORT_AddressStringCallback asc;
737   void *asc_cls;
738   uint16_t port;
739 };
740
741
742 /**
743  * Append our port and forward the result.
744  */
745 static void
746 append_port (void *cls, const char *hostname)
747 {
748   struct PrettyPrinterContext *ppc = cls;
749   char *ret;
750
751   if (hostname == NULL)
752     {
753       ppc->asc (ppc->asc_cls, NULL);
754       GNUNET_free (ppc);
755       return;
756     }
757   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
758   ppc->asc (ppc->asc_cls, ret);
759   GNUNET_free (ret);
760 }
761
762
763 /**
764  * Convert the transports address to a nice, human-readable
765  * format.
766  *
767  * @param cls closure
768  * @param type name of the transport that generated the address
769  * @param addr one of the addresses of the host, NULL for the last address
770  *        the specific address format depends on the transport
771  * @param addrlen length of the address
772  * @param numeric should (IP) addresses be displayed in numeric form?
773  * @param timeout after how long should we give up?
774  * @param asc function to call on each string
775  * @param asc_cls closure for asc
776  */
777 static void
778 tcp_plugin_address_pretty_printer (void *cls,
779                                    const char *type,
780                                    const void *addr,
781                                    size_t addrlen,
782                                    int numeric,
783                                    struct GNUNET_TIME_Relative timeout,
784                                    GNUNET_TRANSPORT_AddressStringCallback asc,
785                                    void *asc_cls)
786 {
787   struct Plugin *plugin = cls;
788   const struct sockaddr_in *v4;
789   const struct sockaddr_in6 *v6;
790   struct PrettyPrinterContext *ppc;
791
792   if ((addrlen != sizeof (struct sockaddr_in)) &&
793       (addrlen != sizeof (struct sockaddr_in6)))
794     {
795       /* invalid address */
796       GNUNET_break_op (0);
797       asc (asc_cls, NULL);
798       return;
799     }
800   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
801   ppc->asc = asc;
802   ppc->asc_cls = asc_cls;
803   if (addrlen == sizeof (struct sockaddr_in))
804     {
805       v4 = (const struct sockaddr_in *) addr;
806       ppc->port = ntohs (v4->sin_port);
807     }
808   else
809     {
810       v6 = (const struct sockaddr_in6 *) addr;
811       ppc->port = ntohs (v6->sin6_port);
812
813     }
814   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
815                                 plugin->env->cfg,
816                                 addr,
817                                 addrlen,
818                                 !numeric, timeout, &append_port, ppc);
819 }
820
821
822 /**
823  * Update the last-received and bandwidth quota values
824  * for this session.
825  *
826  * @param session session to update
827  * @param force set to GNUNET_YES if we should update even
828  *        though the minimum refresh time has not yet expired
829  */
830 static void
831 update_quota (struct Session *session, int force)
832 {
833   struct GNUNET_TIME_Absolute now;
834   unsigned long long delta;
835   unsigned long long total_allowed;
836   unsigned long long total_remaining;
837
838   now = GNUNET_TIME_absolute_get ();
839   delta = now.value - session->last_quota_update.value;
840   if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
841     return;                     /* too early, not enough data */
842
843   total_allowed = session->quota_in * delta;
844   if (total_allowed > session->last_received)
845     {
846       /* got less than acceptable */
847       total_remaining = total_allowed - session->last_received;
848       session->last_received = 0;
849       delta = total_remaining / session->quota_in;      /* bonus seconds */
850       if (delta > MAX_BANDWIDTH_CARRY)
851         delta = MAX_BANDWIDTH_CARRY;    /* limit amount of carry-over */
852     }
853   else
854     {
855       /* got more than acceptable */
856       session->last_received -= total_allowed;
857       delta = 0;
858     }
859   session->last_quota_update.value = now.value - delta;
860 }
861
862
863 /**
864  * Set a quota for receiving data from the given peer; this is a
865  * per-transport limit.  The transport should limit its read/select
866  * calls to stay below the quota (in terms of incoming data).
867  *
868  * @param cls closure
869  * @param target the peer for whom the quota is given
870  * @param quota_in quota for receiving/sending data in bytes per ms
871  */
872 static void
873 tcp_plugin_set_receive_quota (void *cls,
874                               const struct GNUNET_PeerIdentity *target,
875                               uint32_t quota_in)
876 {
877   struct Plugin *plugin = cls;
878   struct Session *session;
879
880   session = find_session_by_target (plugin, target);
881   if (session == NULL)
882     return;                     /* peer must have disconnected, ignore */
883   if (session->quota_in != quota_in)
884     {
885       update_quota (session, GNUNET_YES);
886       if (session->quota_in > quota_in)
887         session->last_quota_update = GNUNET_TIME_absolute_get ();
888       session->quota_in = quota_in;
889     }
890 }
891
892
893 /**
894  * Check if the given port is plausible (must be either
895  * our listen port or our advertised port).  If it is
896  * neither, we return one of these two ports at random.
897  *
898  * @return either in_port or a more plausible port
899  */
900 static uint16_t
901 check_port (struct Plugin *plugin, uint16_t in_port)
902 {
903   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
904     return in_port;
905   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
906                                     2) == 0)
907     ? plugin->open_port : plugin->adv_port;
908 }
909
910
911 /**
912  * Another peer has suggested an address for this peer and transport
913  * plugin.  Check that this could be a valid address.
914  *
915  * @param cls closure
916  * @param addr pointer to the address
917  * @param addrlen length of addr
918  * @return GNUNET_OK if this is a plausible address for this peer
919  *         and transport
920  */
921 static int
922 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
923 {
924   struct Plugin *plugin = cls;
925   char buf[sizeof (struct sockaddr_in6)];
926   struct sockaddr_in *v4;
927   struct sockaddr_in6 *v6;
928
929   if ((addrlen != sizeof (struct sockaddr_in)) &&
930       (addrlen != sizeof (struct sockaddr_in6)))
931     {
932       GNUNET_break_op (0);
933       return GNUNET_SYSERR;
934     }
935   memcpy (buf, addr, sizeof (struct sockaddr_in6));
936   if (addrlen == sizeof (struct sockaddr_in))
937     {
938       v4 = (struct sockaddr_in *) buf;
939       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
940     }
941   else
942     {
943       v6 = (struct sockaddr_in6 *) buf;
944       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
945     }
946 #if DEBUG_TCP
947   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
948                    "tcp",
949                    "Informing transport service about my address `%s'.\n",
950                    GNUNET_a2s (addr, addrlen));
951 #endif
952   return GNUNET_OK;
953 }
954
955
956 /**
957  * We've received a welcome from this peer via TCP.  Possibly create a
958  * fresh client record and send back our welcome.
959  *
960  * @param cls closure
961  * @param client identification of the client
962  * @param message the actual message
963  */
964 static void
965 handle_tcp_welcome (void *cls,
966                     struct GNUNET_SERVER_Client *client,
967                     const struct GNUNET_MessageHeader *message)
968 {
969   struct Plugin *plugin = cls;
970   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
971   struct Session *session;
972   size_t alen;
973   void *vaddr;
974
975 #if DEBUG_TCP
976   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
977                    "tcp",
978                    "Received `%s' message from `%4s/%p'.\n", "WELCOME",
979                    GNUNET_i2s (&wm->clientIdentity), client);
980 #endif
981   session = find_session_by_client (plugin, client);
982   if (session == NULL)
983     {
984       GNUNET_SERVER_client_keep (client);
985       session = create_session (plugin,
986                                 &wm->clientIdentity, client);
987       if (GNUNET_OK == 
988           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
989         {
990           session->connect_addr = vaddr;
991           session->connect_alen = alen;
992         }
993 #if DEBUG_TCP
994       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
995                        "tcp",
996                        "Creating new session %p for incoming `%s' message.\n",
997                        session_c, "WELCOME");
998 #endif
999       process_pending_messages (session);
1000     }
1001   if (session->expecting_welcome != GNUNET_YES)
1002     {
1003       GNUNET_break_op (0);
1004       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1005       return;
1006     }
1007   session->expecting_welcome = GNUNET_NO;
1008   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1009 }
1010
1011
1012 /**
1013  * Calculate how long we should delay reading from the TCP socket to
1014  * ensure that we stay within our bandwidth limits (push back).
1015  *
1016  * @param session for which client should this be calculated
1017  */
1018 static struct GNUNET_TIME_Relative
1019 calculate_throttle_delay (struct Session *session)
1020 {
1021   struct GNUNET_TIME_Relative ret;
1022   struct GNUNET_TIME_Absolute now;
1023   uint64_t del;
1024   uint64_t avail;
1025   uint64_t excess;
1026
1027   now = GNUNET_TIME_absolute_get ();
1028   del = now.value - session->last_quota_update.value;
1029   if (del > MAX_BANDWIDTH_CARRY)
1030     {
1031       update_quota (session, GNUNET_YES);
1032       del = now.value - session->last_quota_update.value;
1033       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1034     }
1035   if (session->quota_in == 0)
1036     session->quota_in = 1;      /* avoid divison by zero */
1037   avail = del * session->quota_in;
1038   if (avail > session->last_received)
1039     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1040   excess = session->last_received - avail;
1041   ret.value = excess / session->quota_in;
1042   return ret;
1043 }
1044
1045
1046 /**
1047  * Task to signal the server that we can continue
1048  * receiving from the TCP client now.
1049  */
1050 static void
1051 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1052 {
1053   struct Session *session = cls;
1054   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1055 }
1056
1057
1058 /**
1059  * We've received data for this peer via TCP.  Unbox,
1060  * compute latency and forward.
1061  *
1062  * @param cls closure
1063  * @param client identification of the client
1064  * @param message the actual message
1065  */
1066 static void
1067 handle_tcp_data (void *cls,
1068                  struct GNUNET_SERVER_Client *client,
1069                  const struct GNUNET_MessageHeader *message)
1070 {
1071   struct Plugin *plugin = cls;
1072   struct Session *session;
1073   uint16_t msize;
1074   struct GNUNET_TIME_Relative delay;
1075
1076   msize = ntohs (message->size);
1077   session = find_session_by_client (plugin, client);
1078   if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1079     {
1080       GNUNET_break_op (0);
1081       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1082       return;
1083     }
1084 #if DEBUG_TCP
1085   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1086                    "tcp", "Receiving %u bytes from `%4s'.\n",
1087                    msize, GNUNET_i2s (&session->target));
1088 #endif
1089 #if DEBUG_TCP
1090   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1091                    "tcp",
1092                    "Forwarding %u bytes of data of type %u to transport service.\n",
1093                    (unsigned int) msize,
1094                    (unsigned int) ntohs (msg->type));
1095 #endif
1096   plugin->env->receive (plugin->env->cls, message, &session->target, 1,
1097                         session->connect_addr,
1098                         session->connect_alen);
1099   /* update bandwidth used */
1100   session->last_received += msize;
1101   update_quota (session, GNUNET_NO);
1102   delay = calculate_throttle_delay (session);
1103   if (delay.value == 0)
1104     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1105   else
1106     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1107                                   delay, &delayed_done, session);
1108 }
1109
1110
1111 /**
1112  * Handlers for the various TCP messages.
1113  */
1114 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1115   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 
1116    sizeof (struct WelcomeMessage)},
1117   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1118   {NULL, NULL, 0, 0}
1119 };
1120
1121
1122 static void
1123 create_tcp_handlers (struct Plugin *plugin)
1124 {
1125   unsigned int i;
1126   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1127   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1128   for (i = 0;
1129        i <
1130        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1131        i++)
1132     plugin->handlers[i].callback_cls = plugin;
1133   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1134 }
1135
1136
1137 /**
1138  * Functions with this signature are called whenever a peer
1139  * is disconnected on the network level.
1140  *
1141  * @param cls closure
1142  * @param client identification of the client
1143  */
1144 static void
1145 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1146 {
1147   struct Plugin *plugin = cls;
1148   struct Session *session;
1149
1150   session = find_session_by_client (plugin, client);
1151   if (session == NULL)
1152     return;                     /* unknown, nothing to do */
1153 #if DEBUG_TCP
1154   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1155                    "tcp",
1156                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1157                    GNUNET_i2s (&session->target),
1158                    (session->connect_addr != NULL) ?
1159                    GNUNET_a2s (session->connect_addr,
1160                                session->connect_alen) : "*", client);
1161 #endif
1162   disconnect_session (session);
1163 }
1164
1165
1166 /**
1167  * Add the IP of our network interface to the list of
1168  * our external IP addresses.
1169  */
1170 static int
1171 process_interfaces (void *cls,
1172                     const char *name,
1173                     int isDefault,
1174                     const struct sockaddr *addr, socklen_t addrlen)
1175 {
1176   struct Plugin *plugin = cls;
1177   int af;
1178   struct sockaddr_in *v4;
1179   struct sockaddr_in6 *v6;
1180
1181   af = addr->sa_family;
1182   if (af == AF_INET)
1183     {
1184       v4 = (struct sockaddr_in *) addr;
1185       v4->sin_port = htons (plugin->adv_port);
1186     }
1187   else
1188     {
1189       GNUNET_assert (af == AF_INET6);
1190       v6 = (struct sockaddr_in6 *) addr;
1191       v6->sin6_port = htons (plugin->adv_port);
1192     }
1193   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1194                    GNUNET_ERROR_TYPE_BULK,
1195                    "tcp", _("Found address `%s' (%s)\n"),
1196                    GNUNET_a2s (addr, addrlen), name);
1197   plugin->env->notify_address (plugin->env->cls,
1198                                "tcp",
1199                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1200   return GNUNET_OK;
1201 }
1202
1203
1204 /**
1205  * Function called by the resolver for each address obtained from DNS
1206  * for our own hostname.  Add the addresses to the list of our
1207  * external IP addresses.
1208  *
1209  * @param cls closure
1210  * @param addr one of the addresses of the host, NULL for the last address
1211  * @param addrlen length of the address
1212  */
1213 static void
1214 process_hostname_ips (void *cls,
1215                       const struct sockaddr *addr, socklen_t addrlen)
1216 {
1217   struct Plugin *plugin = cls;
1218
1219   if (addr == NULL)
1220     {
1221       plugin->hostname_dns = NULL;
1222       return;
1223     }
1224   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1225 }
1226
1227
1228 /**
1229  * Entry point for the plugin.
1230  */
1231 void *
1232 libgnunet_plugin_transport_tcp_init (void *cls)
1233 {
1234   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1235   struct GNUNET_TRANSPORT_PluginFunctions *api;
1236   struct Plugin *plugin;
1237   struct GNUNET_SERVICE_Context *service;
1238   unsigned long long aport;
1239   unsigned long long bport;
1240
1241   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1242   if (service == NULL)
1243     {
1244       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1245                        "tcp",
1246                        _
1247                        ("Failed to start service for `%s' transport plugin.\n"),
1248                        "tcp");
1249       return NULL;
1250     }
1251   aport = 0;
1252   if ((GNUNET_OK !=
1253        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1254                                               "transport-tcp",
1255                                               "PORT",
1256                                               &bport)) ||
1257       (bport > 65535) ||
1258       ((GNUNET_OK ==
1259         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1260                                                "transport-tcp",
1261                                                "ADVERTISED-PORT",
1262                                                &aport)) && (aport > 65535)))
1263     {
1264       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1265                        "tcp",
1266                        _
1267                        ("Require valid port number for service `%s' in configuration!\n"),
1268                        "transport-tcp");
1269       GNUNET_SERVICE_stop (service);
1270       return NULL;
1271     }
1272   if (aport == 0)
1273     aport = bport;
1274   plugin = GNUNET_malloc (sizeof (struct Plugin));
1275   plugin->open_port = bport;
1276   plugin->adv_port = aport;
1277   plugin->env = env;
1278   plugin->lsock = NULL;
1279   plugin->statistics = NULL;
1280   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1281   api->cls = plugin;
1282   api->send = &tcp_plugin_send;
1283   api->disconnect = &tcp_plugin_disconnect;
1284   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1285   api->set_receive_quota = &tcp_plugin_set_receive_quota;
1286   api->check_address = &tcp_plugin_check_address;
1287   plugin->service = service;
1288   plugin->server = GNUNET_SERVICE_get_server (service);
1289   create_tcp_handlers (plugin);
1290   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1291                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1292   if (aport != bport)
1293     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1294                      "tcp",
1295                      _
1296                      ("TCP transport advertises itself as being on port %llu\n"),
1297                      aport);
1298   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1299                                    plugin);
1300   /* FIXME: do the two calls below periodically again and 
1301      not just once (since the info we get might change...) */
1302   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1303   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1304                                                            env->cfg,
1305                                                            AF_UNSPEC,
1306                                                            HOSTNAME_RESOLVE_TIMEOUT,
1307                                                            &process_hostname_ips,
1308                                                            plugin);
1309   return api;
1310 }
1311
1312
1313 /**
1314  * Exit point from the plugin.
1315  */
1316 void *
1317 libgnunet_plugin_transport_tcp_done (void *cls)
1318 {
1319   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1320   struct Plugin *plugin = api->cls;
1321   struct Session *session;
1322
1323   while (NULL != (session = plugin->sessions))
1324     disconnect_session (session);
1325   if (NULL != plugin->hostname_dns)
1326     {
1327       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1328       plugin->hostname_dns = NULL;
1329     }
1330   GNUNET_SERVICE_stop (plugin->service);
1331   GNUNET_free (plugin->handlers);
1332   GNUNET_free (plugin);
1333   GNUNET_free (api);
1334   return NULL;
1335 }
1336
1337 /* end of plugin_transport_tcp.c */