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