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