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