resolver for udp plugin, don't propagate welcomes in tcp
[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_YES
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 ( (session != NULL) && ((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
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 (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 a `%4s/%p'.\n", "WELCOME",
979                    GNUNET_i2s (&wm->clientIdentity), client);
980 #endif
981
982   session = find_session_by_client (plugin, client);
983   if (session == NULL)
984     {
985       GNUNET_SERVER_client_keep (client);
986       session = create_session (plugin,
987                                 &wm->clientIdentity, client);
988       if (GNUNET_OK ==
989           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
990         {
991 #if DEBUG_TCP
992       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
993                        "tcp",
994                        "Found address for incoming `%s' message\n",
995                        "WELCOME");
996 #endif
997           session->connect_addr = vaddr;
998           session->connect_alen = alen;
999         }
1000       else
1001         {
1002 #if DEBUG_TCP
1003       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1004                        "tcp",
1005                        "Didn't find address for incoming `%s' message\n",
1006                        "WELCOME");
1007 #endif
1008         }
1009 #if DEBUG_TCP
1010       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1011                        "tcp",
1012                        "Creating new session %p for incoming `%s' message.\n",
1013                        session, "WELCOME");
1014 #endif
1015       process_pending_messages (session);
1016     }
1017   if (session->expecting_welcome != GNUNET_YES)
1018     {
1019       GNUNET_break_op (0);
1020       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1021       return;
1022     }
1023   session->expecting_welcome = GNUNET_NO;
1024   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1025 }
1026
1027
1028 /**
1029  * Calculate how long we should delay reading from the TCP socket to
1030  * ensure that we stay within our bandwidth limits (push back).
1031  *
1032  * @param session for which client should this be calculated
1033  */
1034 static struct GNUNET_TIME_Relative
1035 calculate_throttle_delay (struct Session *session)
1036 {
1037   struct GNUNET_TIME_Relative ret;
1038   struct GNUNET_TIME_Absolute now;
1039   uint64_t del;
1040   uint64_t avail;
1041   uint64_t excess;
1042
1043   now = GNUNET_TIME_absolute_get ();
1044   del = now.value - session->last_quota_update.value;
1045   if (del > MAX_BANDWIDTH_CARRY)
1046     {
1047       update_quota (session, GNUNET_YES);
1048       del = now.value - session->last_quota_update.value;
1049       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1050     }
1051   if (session->quota_in == 0)
1052     session->quota_in = 1;      /* avoid divison by zero */
1053   avail = del * session->quota_in;
1054   if (avail > session->last_received)
1055     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1056   excess = session->last_received - avail;
1057   ret.value = excess / session->quota_in;
1058   return ret;
1059 }
1060
1061
1062 /**
1063  * Task to signal the server that we can continue
1064  * receiving from the TCP client now.
1065  */
1066 static void
1067 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1068 {
1069   struct Session *session = cls;
1070   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1071 }
1072
1073
1074 /**
1075  * We've received data for this peer via TCP.  Unbox,
1076  * compute latency and forward.
1077  *
1078  * @param cls closure
1079  * @param client identification of the client
1080  * @param message the actual message
1081  */
1082 static void
1083 handle_tcp_data (void *cls,
1084                  struct GNUNET_SERVER_Client *client,
1085                  const struct GNUNET_MessageHeader *message)
1086 {
1087   struct Plugin *plugin = cls;
1088   struct Session *session;
1089   uint16_t msize;
1090   struct GNUNET_TIME_Relative delay;
1091
1092   msize = ntohs (message->size);
1093   session = find_session_by_client (plugin, client);
1094
1095   if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1096   {
1097 #if DEBUG_TCP
1098   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1099                    "tcp", "Received a welcome, NOT sending to clients!\n");
1100 #endif
1101     return; /* We don't want to propogate WELCOME messages up! */
1102   }
1103
1104   if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1105     {
1106       GNUNET_break_op (0);
1107       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1108       return;
1109     }
1110 #if DEBUG_TCP
1111   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1112                    "tcp", "Receiving %u bytes from `%4s'.\n",
1113                    msize, GNUNET_i2s (&session->target));
1114 #endif
1115 #if DEBUG_TCP
1116   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1117                    "tcp",
1118                    "Forwarding %u bytes of data of type %u to transport service.\n",
1119                    (unsigned int) msize,
1120                    (unsigned int) ntohs (message->type));
1121 #endif
1122   plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1123                         session->connect_addr,
1124                         session->connect_alen);
1125   /* update bandwidth used */
1126   session->last_received += msize;
1127   update_quota (session, GNUNET_NO);
1128   delay = calculate_throttle_delay (session);
1129   if (delay.value == 0)
1130     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1131   else
1132     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1133                                   delay, &delayed_done, session);
1134 }
1135
1136
1137 /**
1138  * Handlers for the various TCP messages.
1139  */
1140 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1141   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1142    sizeof (struct WelcomeMessage)},
1143   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1144   {NULL, NULL, 0, 0}
1145 };
1146
1147
1148 static void
1149 create_tcp_handlers (struct Plugin *plugin)
1150 {
1151   unsigned int i;
1152   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1153   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1154   for (i = 0;
1155        i <
1156        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1157        i++)
1158     plugin->handlers[i].callback_cls = plugin;
1159   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1160 }
1161
1162
1163 /**
1164  * Functions with this signature are called whenever a peer
1165  * is disconnected on the network level.
1166  *
1167  * @param cls closure
1168  * @param client identification of the client
1169  */
1170 static void
1171 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1172 {
1173   struct Plugin *plugin = cls;
1174   struct Session *session;
1175
1176   if (client == NULL)
1177     return;
1178   session = find_session_by_client (plugin, client);
1179   if (session == NULL)
1180     return;                     /* unknown, nothing to do */
1181 #if DEBUG_TCP
1182   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1183                    "tcp",
1184                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1185                    GNUNET_i2s (&session->target),
1186                    (session->connect_addr != NULL) ?
1187                    GNUNET_a2s (session->connect_addr,
1188                                session->connect_alen) : "*", client);
1189 #endif
1190   disconnect_session (session);
1191 }
1192
1193
1194 /**
1195  * Add the IP of our network interface to the list of
1196  * our external IP addresses.
1197  */
1198 static int
1199 process_interfaces (void *cls,
1200                     const char *name,
1201                     int isDefault,
1202                     const struct sockaddr *addr, socklen_t addrlen)
1203 {
1204   struct Plugin *plugin = cls;
1205   int af;
1206   struct sockaddr_in *v4;
1207   struct sockaddr_in6 *v6;
1208
1209   af = addr->sa_family;
1210   if (af == AF_INET)
1211     {
1212       v4 = (struct sockaddr_in *) addr;
1213       v4->sin_port = htons (plugin->adv_port);
1214     }
1215   else
1216     {
1217       GNUNET_assert (af == AF_INET6);
1218       v6 = (struct sockaddr_in6 *) addr;
1219       v6->sin6_port = htons (plugin->adv_port);
1220     }
1221   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1222                    GNUNET_ERROR_TYPE_BULK,
1223                    "tcp", _("Found address `%s' (%s)\n"),
1224                    GNUNET_a2s (addr, addrlen), name);
1225   plugin->env->notify_address (plugin->env->cls,
1226                                "tcp",
1227                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1228   return GNUNET_OK;
1229 }
1230
1231
1232 /**
1233  * Function called by the resolver for each address obtained from DNS
1234  * for our own hostname.  Add the addresses to the list of our
1235  * external IP addresses.
1236  *
1237  * @param cls closure
1238  * @param addr one of the addresses of the host, NULL for the last address
1239  * @param addrlen length of the address
1240  */
1241 static void
1242 process_hostname_ips (void *cls,
1243                       const struct sockaddr *addr, socklen_t addrlen)
1244 {
1245   struct Plugin *plugin = cls;
1246
1247   if (addr == NULL)
1248     {
1249       plugin->hostname_dns = NULL;
1250       return;
1251     }
1252   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1253 }
1254
1255
1256 /**
1257  * Entry point for the plugin.
1258  */
1259 void *
1260 libgnunet_plugin_transport_tcp_init (void *cls)
1261 {
1262   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1263   struct GNUNET_TRANSPORT_PluginFunctions *api;
1264   struct Plugin *plugin;
1265   struct GNUNET_SERVICE_Context *service;
1266   unsigned long long aport;
1267   unsigned long long bport;
1268
1269   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1270   if (service == NULL)
1271     {
1272       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1273                        "tcp",
1274                        _
1275                        ("Failed to start service for `%s' transport plugin.\n"),
1276                        "tcp");
1277       return NULL;
1278     }
1279   aport = 0;
1280   if ((GNUNET_OK !=
1281        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1282                                               "transport-tcp",
1283                                               "PORT",
1284                                               &bport)) ||
1285       (bport > 65535) ||
1286       ((GNUNET_OK ==
1287         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1288                                                "transport-tcp",
1289                                                "ADVERTISED-PORT",
1290                                                &aport)) && (aport > 65535)))
1291     {
1292       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1293                        "tcp",
1294                        _
1295                        ("Require valid port number for service `%s' in configuration!\n"),
1296                        "transport-tcp");
1297       GNUNET_SERVICE_stop (service);
1298       return NULL;
1299     }
1300   if (aport == 0)
1301     aport = bport;
1302   plugin = GNUNET_malloc (sizeof (struct Plugin));
1303   plugin->open_port = bport;
1304   plugin->adv_port = aport;
1305   plugin->env = env;
1306   plugin->lsock = NULL;
1307   plugin->statistics = NULL;
1308   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1309   api->cls = plugin;
1310   api->send = &tcp_plugin_send;
1311   api->disconnect = &tcp_plugin_disconnect;
1312   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1313   api->set_receive_quota = &tcp_plugin_set_receive_quota;
1314   api->check_address = &tcp_plugin_check_address;
1315   plugin->service = service;
1316   plugin->server = GNUNET_SERVICE_get_server (service);
1317   create_tcp_handlers (plugin);
1318   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1319                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1320   if (aport != bport)
1321     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1322                      "tcp",
1323                      _
1324                      ("TCP transport advertises itself as being on port %llu\n"),
1325                      aport);
1326   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1327                                    plugin);
1328   /* FIXME: do the two calls below periodically again and
1329      not just once (since the info we get might change...) */
1330   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1331   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1332                                                            env->cfg,
1333                                                            AF_UNSPEC,
1334                                                            HOSTNAME_RESOLVE_TIMEOUT,
1335                                                            &process_hostname_ips,
1336                                                            plugin);
1337   return api;
1338 }
1339
1340
1341 /**
1342  * Exit point from the plugin.
1343  */
1344 void *
1345 libgnunet_plugin_transport_tcp_done (void *cls)
1346 {
1347   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1348   struct Plugin *plugin = api->cls;
1349   struct Session *session;
1350
1351   while (NULL != (session = plugin->sessions))
1352     disconnect_session (session);
1353   if (NULL != plugin->hostname_dns)
1354     {
1355       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1356       plugin->hostname_dns = NULL;
1357     }
1358   GNUNET_SERVICE_stop (plugin->service);
1359   GNUNET_free (plugin->handlers);
1360   GNUNET_free (plugin);
1361   GNUNET_free (api);
1362   return NULL;
1363 }
1364
1365 /* end of plugin_transport_tcp.c */