pre-commit
[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 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_peerinfo_service.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  * After how long do we expire an address that we
46  * learned from another peer if it is not reconfirmed
47  * by anyone?
48  */
49 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
50
51 /**
52  * How long until we give up on transmitting the welcome message?
53  */
54 #define WELCOME_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
55
56 /**
57  * How long until we give up on transmitting the welcome message?
58  */
59 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
60
61 /**
62  * For how many messages back to we keep transmission times?
63  */
64 #define ACK_LOG_SIZE 32
65
66
67
68 /**
69  * Message used to ask a peer to validate receipt (to check an address
70  * from a HELLO).  Followed by the address used.  Note that the
71  * recipients response does not affirm that he has this address,
72  * only that he got the challenge message.
73  */
74 struct ValidationChallengeMessage
75 {
76
77   /**
78    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING
79    */
80   struct GNUNET_MessageHeader header;
81
82   /**
83    * Random challenge number (in network byte order).
84    */
85   uint32_t challenge GNUNET_PACKED;
86
87   /**
88    * Who is the intended recipient?
89    */
90   struct GNUNET_PeerIdentity target;
91
92 };
93
94
95 /**
96  * Message used to validate a HELLO.  The challenge is included in the
97  * confirmation to make matching of replies to requests possible.  The
98  * signature signs the original challenge number, our public key, the
99  * sender's address (so that the sender can check that the address we
100  * saw is plausible for him and possibly detect a MiM attack) and a
101  * timestamp (to limit replay).<p>
102  *
103  * This message is followed by the address of the
104  * client that we are observing (which is part of what
105  * is being signed).
106  */
107 struct ValidationChallengeResponse
108 {
109
110   /**
111    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG
112    */
113   struct GNUNET_MessageHeader header;
114
115   /**
116    * For padding, always zero.
117    */
118   uint32_t reserved GNUNET_PACKED;
119
120   /**
121    * Signature.
122    */
123   struct GNUNET_CRYPTO_RsaSignature signature;
124
125   /**
126    * What are we signing and why?
127    */
128   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
129
130   /**
131    * Random challenge number (in network byte order).
132    */
133   uint32_t challenge GNUNET_PACKED;
134
135   /**
136    * Who signed this message?
137    */
138   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
139
140 };
141
142
143
144 /**
145  * Initial handshake message for a session.  This header
146  * is followed by the address that the other peer used to
147  * connect to us (so that we may learn it) or the address
148  * that the other peer got from the accept call.
149  */
150 struct WelcomeMessage
151 {
152   struct GNUNET_MessageHeader header;
153
154   /**
155    * Identity of the node connecting (TCP client)
156    */
157   struct GNUNET_PeerIdentity clientIdentity;
158
159 };
160
161
162 /**
163  * Encapsulation for normal TCP traffic.
164  */
165 struct DataMessage
166 {
167   struct GNUNET_MessageHeader header;
168
169   /**
170    * For alignment.
171    */
172   uint32_t reserved GNUNET_PACKED;
173
174   /**
175    * Number of the last message that was received from the other peer.
176    */
177   uint64_t ack_in GNUNET_PACKED;
178
179   /**
180    * Number of this outgoing message.
181    */
182   uint64_t ack_out GNUNET_PACKED;
183
184   /**
185    * How long was sending this ack delayed by the other peer
186    * (estimate).  The receiver of this message can use the delay
187    * between sending his message number 'ack' and receiving this ack
188    * minus the delay as an estimate of the round-trip time.
189    */
190   struct GNUNET_TIME_RelativeNBO delay;
191
192 };
193
194
195 /**
196  * Encapsulation of all of the state of the plugin.
197  */
198 struct Plugin;
199
200
201 /**
202  * Information kept for each message that is yet to
203  * be transmitted.
204  */
205 struct PendingMessage
206 {
207
208   /**
209    * This is a linked list.
210    */
211   struct PendingMessage *next;
212
213   /**
214    * The pending message, pointer to the end
215    * of this struct, do not free!
216    */
217   struct GNUNET_MessageHeader *msg;
218
219   /**
220    * Continuation function to call once the message
221    * has been sent.  Can be NULL if there is no
222    * continuation to call.
223    */
224   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
225
226   /**
227    * Closure for transmit_cont.
228    */
229   void *transmit_cont_cls;
230
231   /**
232    * Timeout value for the pending message.
233    */
234   struct GNUNET_TIME_Absolute timeout;
235
236   /**
237    * GNUNET_YES if this is a welcome message;
238    * otherwise this should be a DATA message.
239    */
240   int is_welcome;
241
242 };
243
244
245 /**
246  * Session handle for TCP connections.
247  */
248 struct Session
249 {
250
251   /**
252    * Stored in a linked list.
253    */
254   struct Session *next;
255
256   /**
257    * Pointer to the global plugin struct.
258    */
259   struct Plugin *plugin;
260
261   /**
262    * The client (used to identify this connection)
263    */
264   struct GNUNET_SERVER_Client *client;
265
266   /**
267    * Messages currently pending for transmission
268    * to this peer, if any.
269    */
270   struct PendingMessage *pending_messages;
271
272   /**
273    * Handle for pending transmission request.
274    */
275   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
276
277   /**
278    * To whom are we talking to (set to our identity
279    * if we are still waiting for the welcome message)
280    */
281   struct GNUNET_PeerIdentity target;
282
283   /**
284    * At what time did we reset last_received last?
285    */
286   struct GNUNET_TIME_Absolute last_quota_update;
287
288   /**
289    * Context for our iteration to find HELLOs for this peer.  NULL
290    * after iteration has completed.
291    */
292   struct GNUNET_PEERINFO_IteratorContext *ic;
293
294   /**
295    * Address of the other peer if WE initiated the connection
296    * (and hence can be sure what it is), otherwise NULL.
297    */
298   void *connect_addr;
299
300   /**
301    * How many bytes have we received since the "last_quota_update"
302    * timestamp?
303    */
304   uint64_t last_received;
305
306   /**
307    * Our current latency estimate (in ms).
308    */
309   double latency_estimate;
310
311   /**
312    * Time when we generated the last ACK_LOG_SIZE acks.
313    * (the "last" refers to the "out_msg_counter" here)
314    */
315   struct GNUNET_TIME_Absolute gen_time[ACK_LOG_SIZE];
316
317   /**
318    * Our current sequence number.
319    */
320   uint64_t out_msg_counter;
321
322   /**
323    * Highest received incoming sequence number.
324    */
325   uint64_t max_in_msg_counter;
326
327   /**
328    * Number of bytes per ms that this peer is allowed
329    * to send to us.
330    */
331   uint32_t quota_in;
332
333   /**
334    * Length of connect_addr, can be 0.
335    */
336   size_t connect_alen;
337
338   /**
339    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
340    * GNUNET_SYSERR is used to mark non-welcoming connections (HELLO
341    * validation only).
342    */
343   int expecting_welcome;
344
345 };
346
347
348 /**
349  * Encapsulation of all of the state of the plugin.
350  */
351 struct Plugin
352 {
353   /**
354    * Our environment.
355    */
356   struct GNUNET_TRANSPORT_PluginEnvironment *env;
357
358   /**
359    * The listen socket.
360    */
361   struct GNUNET_CONNECTION_Handle *lsock;
362
363   /**
364    * List of open TCP sessions.
365    */
366   struct Session *sessions;
367
368   /**
369    * Handle for the statistics service.
370    */
371   struct GNUNET_STATISTICS_Handle *statistics;
372
373   /**
374    * Handle to the network service.
375    */
376   struct GNUNET_SERVICE_Context *service;
377
378   /**
379    * Handle to the server for this service.
380    */
381   struct GNUNET_SERVER_Handle *server;
382
383   /**
384    * Copy of the handler array where the closures are
385    * set to this struct's instance.
386    */
387   struct GNUNET_SERVER_MessageHandler *handlers;
388
389   /**
390    * Handle for request of hostname resolution, non-NULL if pending.
391    */
392   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
393
394   /**
395    * ID of task used to update our addresses when one expires.
396    */
397   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
398
399   /**
400    * Port that we are actually listening on.
401    */
402   uint16_t open_port;
403
404   /**
405    * Port that the user said we would have visible to the
406    * rest of the world.
407    */
408   uint16_t adv_port;
409
410 };
411
412
413 /**
414  * Find the session handle for the given peer.
415  */
416 static struct Session *
417 find_session_by_target (struct Plugin *plugin,
418                         const struct GNUNET_PeerIdentity *target)
419 {
420   struct Session *ret;
421
422   ret = plugin->sessions;
423   while ((ret != NULL) &&
424          ((GNUNET_SYSERR == ret->expecting_welcome) ||
425           (0 != memcmp (target,
426                         &ret->target, sizeof (struct GNUNET_PeerIdentity)))))
427     ret = ret->next;
428   return ret;
429 }
430
431
432 /**
433  * Find the session handle for the given peer.
434  */
435 static struct Session *
436 find_session_by_client (struct Plugin *plugin,
437                         const struct GNUNET_SERVER_Client *client)
438 {
439   struct Session *ret;
440
441   ret = plugin->sessions;
442   while ((ret != NULL) && (client != ret->client))
443     ret = ret->next;
444   return ret;
445 }
446
447
448 /**
449  * Create a welcome message.
450  */
451 static struct PendingMessage *
452 create_welcome (size_t addrlen, const void *addr, struct Plugin *plugin)
453 {
454   struct PendingMessage *pm;
455   struct WelcomeMessage *welcome;
456
457   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
458                       sizeof (struct WelcomeMessage) + addrlen);
459   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
460   welcome = (struct WelcomeMessage *) &pm[1];
461   welcome->header.size = htons (sizeof (struct WelcomeMessage) + addrlen);
462   welcome->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
463   GNUNET_CRYPTO_hash (plugin->env->my_public_key,
464                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
465                       &welcome->clientIdentity.hashPubKey);
466   memcpy (&welcome[1], addr, addrlen);
467   pm->timeout = GNUNET_TIME_relative_to_absolute (WELCOME_TIMEOUT);
468   pm->is_welcome = GNUNET_YES;
469   return pm;
470 }
471
472
473 /**
474  * Create a new session using the specified address
475  * for the welcome message.
476  *
477  * @param plugin us
478  * @param target peer to connect to
479  * @param client client to use
480  * @param addrlen IPv4 or IPv6
481  * @param addr either struct sockaddr_in or struct sockaddr_in6
482  * @return NULL connection failed / invalid address
483  */
484 static struct Session *
485 create_session (struct Plugin *plugin,
486                 const struct GNUNET_PeerIdentity *target,
487                 struct GNUNET_SERVER_Client *client,
488                 const void *addr, size_t addrlen)
489 {
490   struct Session *ret;
491
492   ret = GNUNET_malloc (sizeof (struct Session));
493   ret->plugin = plugin;
494   ret->next = plugin->sessions;
495   plugin->sessions = ret;
496   ret->client = client;
497   ret->target = *target;
498   ret->last_quota_update = GNUNET_TIME_absolute_get ();
499   ret->quota_in = plugin->env->default_quota_in;
500   ret->expecting_welcome = GNUNET_YES;
501   ret->pending_messages = create_welcome (addrlen, addr, plugin);
502   return ret;
503 }
504
505
506 /**
507  * If we have pending messages, ask the server to
508  * transmit them (schedule the respective tasks, etc.)
509  *
510  * @param session for which session should we do this
511  */
512 static void process_pending_messages (struct Session *session);
513
514
515 /**
516  * Function called to notify a client about the socket
517  * being ready to queue more data.  "buf" will be
518  * NULL and "size" zero if the socket was closed for
519  * writing in the meantime.
520  *
521  * @param cls closure
522  * @param size number of bytes available in buf
523  * @param buf where the callee should write the message
524  * @return number of bytes written to buf
525  */
526 static size_t
527 do_transmit (void *cls, size_t size, void *buf)
528 {
529   struct Session *session = cls;
530   struct PendingMessage *pm;
531   char *cbuf;
532   uint16_t msize;
533   size_t ret;
534   struct DataMessage *dm;
535
536   session->transmit_handle = NULL;
537   if (buf == NULL)
538     {
539 #if DEBUG_TCP
540       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
541                        "tcp",
542                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
543                        GNUNET_i2s (&session->target));
544 #endif
545       /* timeout */
546       while (NULL != (pm = session->pending_messages))
547         {
548           session->pending_messages = pm->next;
549 #if DEBUG_TCP
550           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
551                            "tcp",
552                            "Failed to transmit message of type %u to `%4s'.\n",
553                            ntohs (pm->msg->type),
554                            GNUNET_i2s (&session->target));
555 #endif
556           if (pm->transmit_cont != NULL)
557             pm->transmit_cont (pm->transmit_cont_cls,
558                                &session->target, GNUNET_SYSERR);
559           GNUNET_free (pm);
560         }
561       return 0;
562     }
563   ret = 0;
564   cbuf = buf;
565   while (NULL != (pm = session->pending_messages))
566     {
567       if (pm->is_welcome)
568         {
569           if (size < (msize = ntohs (pm->msg->size)))
570             break;
571           memcpy (cbuf, pm->msg, msize);
572           cbuf += msize;
573           ret += msize;
574           size -= msize;
575         }
576       else
577         {
578           if (size <
579               sizeof (struct DataMessage) + (msize = ntohs (pm->msg->size)))
580             break;
581           dm = (struct DataMessage *) cbuf;
582           dm->header.size = htons (sizeof (struct DataMessage) + msize);
583           dm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA);
584           dm->ack_out = GNUNET_htonll (++session->out_msg_counter);
585           dm->ack_in = GNUNET_htonll (session->max_in_msg_counter);
586           cbuf += sizeof (struct DataMessage);
587           ret += sizeof (struct DataMessage);
588           size -= sizeof (struct DataMessage);
589           memcpy (cbuf, pm->msg, msize);
590           cbuf += msize;
591           ret += msize;
592           size -= msize;
593         }
594       session->pending_messages = pm->next;
595       if (pm->transmit_cont != NULL)
596         pm->transmit_cont (pm->transmit_cont_cls,
597                            &session->target, GNUNET_OK);
598       GNUNET_free (pm);
599       session->gen_time[session->out_msg_counter % ACK_LOG_SIZE]
600         = GNUNET_TIME_absolute_get ();
601     }
602   process_pending_messages (session);
603 #if DEBUG_TCP
604   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
605                    "tcp", "Transmitting %u bytes\n", ret);
606 #endif
607   return ret;
608 }
609
610
611 /**
612  * If we have pending messages, ask the server to
613  * transmit them (schedule the respective tasks, etc.)
614  *
615  * @param session for which session should we do this
616  */
617 static void
618 process_pending_messages (struct Session *session)
619 {
620   GNUNET_assert (session->client != NULL);
621   if (session->pending_messages == NULL)
622     return;
623   if (session->transmit_handle != NULL)
624     return;
625   session->transmit_handle
626     = GNUNET_SERVER_notify_transmit_ready (session->client,
627                                            ntohs (session->pending_messages->
628                                                   msg->size) +
629                                            (session->pending_messages->
630                                             is_welcome ? 0 : sizeof (struct
631                                                                      DataMessage)),
632                                            GNUNET_TIME_absolute_get_remaining
633                                            (session->pending_messages[0].
634                                             timeout), &do_transmit, session);
635 }
636
637
638
639 /**
640  * Create a new session connecting to the specified
641  * target at the specified address.  The session will
642  * be used to verify an address in a HELLO and should
643  * not expect to receive a WELCOME.
644  *
645  * @param plugin us
646  * @param target peer to connect to
647  * @param addrlen IPv4 or IPv6
648  * @param addr either struct sockaddr_in or struct sockaddr_in6
649  * @return NULL connection failed / invalid address
650  */
651 static struct Session *
652 connect_and_create_validation_session (struct Plugin *plugin,
653                                        const struct GNUNET_PeerIdentity
654                                        *target, const void *addr,
655                                        size_t addrlen)
656 {
657   struct GNUNET_SERVER_Client *client;
658   struct GNUNET_CONNECTION_Handle *conn;
659   struct Session *session;
660   int af;
661
662   if (addrlen == sizeof (struct sockaddr_in))
663     af = AF_INET;
664   else if (addrlen == sizeof (struct sockaddr_in6))
665     af = AF_INET6;
666   else
667     {
668       GNUNET_break_op (0);
669       return NULL;              /* invalid address */
670     }
671   conn = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
672                                                  af,
673                                                  addr,
674                                                  addrlen,
675                                                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
676   if (conn == NULL)
677     {
678 #if DEBUG_TCP
679       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
680                        "tcp",
681                        "Failed to create connection to peer at `%s'.\n",
682                        GNUNET_a2s (addr, addrlen));
683 #endif
684       return NULL;
685     }
686   client = GNUNET_SERVER_connect_socket (plugin->server, conn);
687   GNUNET_assert (client != NULL);
688   session = create_session (plugin, target, client, addr, addrlen);
689   /* kill welcome */
690   GNUNET_free (session->pending_messages);
691   session->pending_messages = NULL;
692   session->connect_alen = addrlen;
693   session->connect_addr = GNUNET_malloc (addrlen);
694   session->expecting_welcome = GNUNET_SYSERR;
695   memcpy (session->connect_addr, addr, addrlen);
696 #if DEBUG_TCP
697   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
698                    "tcp",
699                    "Creating new session %p with `%s' for `%4s' based on `%s' request.\n",
700                    session,
701                    GNUNET_a2s (addr, addrlen),
702                    GNUNET_i2s (&session->target), "VALIDATE");
703 #endif
704   return session;
705 }
706
707
708 /**
709  * Function that can be used by the transport service to validate that
710  * another peer is reachable at a particular address (even if we
711  * already have a connection to this peer, this function is required
712  * to establish a new one).
713  *
714  * @param cls closure
715  * @param target who should receive this message
716  * @param challenge challenge code to use
717  * @param addrlen length of the address
718  * @param addr the address
719  * @param timeout how long should we try to transmit these?
720  * @return GNUNET_OK if the transmission has been scheduled
721  */
722 static int
723 tcp_plugin_validate (void *cls,
724                      const struct GNUNET_PeerIdentity *target,
725                      uint32_t challenge,
726                      struct GNUNET_TIME_Relative timeout,
727                      const void *addr, size_t addrlen)
728 {
729   struct Plugin *plugin = cls;
730   struct Session *session;
731   struct PendingMessage *pm;
732   struct ValidationChallengeMessage *vcm;
733
734   session =
735     connect_and_create_validation_session (plugin, target, addr, addrlen);
736   if (session == NULL)
737     {
738 #if DEBUG_TCP
739       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
740                        "tcp", "Failed to create fresh session.\n");
741 #endif
742       return GNUNET_SYSERR;
743     }
744   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
745                       sizeof (struct ValidationChallengeMessage) + addrlen);
746   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
747   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
748   pm->is_welcome = GNUNET_YES;
749   vcm = (struct ValidationChallengeMessage *) &pm[1];
750   vcm->header.size =
751     htons (sizeof (struct ValidationChallengeMessage) + addrlen);
752   vcm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING);
753   vcm->challenge = htonl (challenge);
754   vcm->target = *target;
755   memcpy (&vcm[1], addr, addrlen);
756   GNUNET_assert (session->pending_messages == NULL);
757   session->pending_messages = pm;
758   process_pending_messages (session);
759   return GNUNET_OK;
760 }
761
762
763 /**
764  * Functions with this signature are called whenever we need
765  * to close a session due to a disconnect or failure to
766  * establish a connection.
767  *
768  * @param session session to close down
769  */
770 static void
771 disconnect_session (struct Session *session)
772 {
773   struct Session *prev;
774   struct Session *pos;
775   struct PendingMessage *pm;
776
777 #if DEBUG_TCP
778   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
779                    "tcp",
780                    "Disconnecting from `%4s' at %s (session %p).\n",
781                    GNUNET_i2s (&session->target),
782                    (session->connect_addr != NULL) ?
783                    GNUNET_a2s (session->connect_addr,
784                                session->connect_alen) : "*", session);
785 #endif
786   /* remove from session list */
787   prev = NULL;
788   pos = session->plugin->sessions;
789   while (pos != session)
790     {
791       prev = pos;
792       pos = pos->next;
793     }
794   if (prev == NULL)
795     session->plugin->sessions = session->next;
796   else
797     prev->next = session->next;
798   /* clean up state */
799   if (session->ic != NULL)
800     {
801       GNUNET_PEERINFO_iterate_cancel (session->ic);
802       session->ic = NULL;
803     }
804   if (session->transmit_handle != NULL)
805     {
806       GNUNET_CONNECTION_notify_transmit_ready_cancel (session->
807                                                       transmit_handle);
808       session->transmit_handle = NULL;
809     }
810   while (NULL != (pm = session->pending_messages))
811     {
812 #if DEBUG_TCP
813       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
814                        "tcp",
815                        pm->transmit_cont != NULL
816                        ? "Could not deliver message of type %u to `%4s'.\n"
817                        :
818                        "Could not deliver message of type %u to `%4s', notifying.\n",
819                        ntohs (pm->msg->type), GNUNET_i2s (&session->target));
820 #endif
821       session->pending_messages = pm->next;
822       if (NULL != pm->transmit_cont)
823         pm->transmit_cont (pm->transmit_cont_cls,
824                            &session->target, GNUNET_SYSERR);
825       GNUNET_free (pm);
826     }
827   if (GNUNET_NO == session->expecting_welcome)
828     {
829 #if DEBUG_TCP
830       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
831                        "tcp",
832                        "Notifying transport service about loss of data connection with `%4s'.\n",
833                        GNUNET_i2s (&session->target));
834 #endif
835       /* Data session that actually went past the 
836          initial handshake; transport service may
837          know about this one, so we need to 
838          notify transport service about disconnect */
839       session->plugin->env->receive (session->plugin->env->cls,
840                                      GNUNET_TIME_UNIT_ZERO,
841                                      &session->target, NULL);
842     }
843   if (session->client != NULL)
844     {
845       GNUNET_SERVER_client_drop (session->client);
846       session->client = NULL;
847     }
848   GNUNET_free_non_null (session->connect_addr);
849   GNUNET_free (session);
850 }
851
852
853 /**
854  * Iterator callback to go over all addresses.  If we get
855  * a TCP address, increment the counter
856  *
857  * @param cls closure, points to the counter
858  * @param tname name of the transport
859  * @param expiration expiration time
860  * @param addr the address
861  * @param addrlen length of the address
862  * @return GNUNET_OK to keep the address,
863  *         GNUNET_NO to delete it from the HELLO
864  *         GNUNET_SYSERR to stop iterating (but keep current address)
865  */
866 static int
867 count_tcp_addresses (void *cls,
868                      const char *tname,
869                      struct GNUNET_TIME_Absolute expiration,
870                      const void *addr, size_t addrlen)
871 {
872   unsigned int *counter = cls;
873
874   if (0 != strcmp (tname, "tcp"))
875     return GNUNET_OK;           /* not one of ours */
876   (*counter)++;
877   return GNUNET_OK;             /* failed to connect */
878 }
879
880
881 struct ConnectContext
882 {
883   struct Plugin *plugin;
884
885   struct GNUNET_CONNECTION_Handle *sa;
886
887   struct PendingMessage *welcome;
888
889   unsigned int pos;
890 };
891
892
893 /**
894  * Iterator callback to go over all addresses.  If we get
895  * the "pos" TCP address, try to connect to it.
896  *
897  * @param cls closure
898  * @param tname name of the transport
899  * @param expiration expiration time
900  * @param addrlen length of the address
901  * @param addr the address
902  * @return GNUNET_OK to keep the address,
903  *         GNUNET_NO to delete it from the HELLO
904  *         GNUNET_SYSERR to stop iterating (but keep current address)
905  */
906 static int
907 try_connect_to_address (void *cls,
908                         const char *tname,
909                         struct GNUNET_TIME_Absolute expiration,
910                         const void *addr, size_t addrlen)
911 {
912   struct ConnectContext *cc = cls;
913   int af;
914
915   if (0 != strcmp (tname, "tcp"))
916     return GNUNET_OK;           /* not one of ours */
917   if (sizeof (struct sockaddr_in) == addrlen)
918     af = AF_INET;
919   else if (sizeof (struct sockaddr_in6) == addrlen)
920     af = AF_INET6;
921   else
922     {
923       /* not a valid address */
924       GNUNET_break (0);
925       return GNUNET_NO;
926     }
927   if (0 == cc->pos--)
928     {
929       cc->welcome = create_welcome (addrlen, addr, cc->plugin);
930       cc->sa =
931         GNUNET_CONNECTION_create_from_sockaddr (cc->plugin->env->sched,
932                                                 af, addr, addrlen,
933                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
934 #if DEBUG_TCP
935       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
936                        "tcp",
937                        "Connecting using address %s.\n",
938                        GNUNET_a2s (addr, addrlen));
939 #endif
940       return GNUNET_SYSERR;
941     }
942   return GNUNET_OK;             /* failed to connect */
943 }
944
945
946 /**
947  * Type of an iterator over the hosts.  Note that each
948  * host will be called with each available protocol.
949  *
950  * @param cls closure
951  * @param peer id of the peer, NULL for last call
952  * @param hello hello message for the peer (can be NULL)
953  * @param trust amount of trust we have in the peer
954  */
955 static void
956 session_try_connect (void *cls,
957                      const struct GNUNET_PeerIdentity *peer,
958                      const struct GNUNET_HELLO_Message *hello, uint32_t trust)
959 {
960   struct Session *session = cls;
961   unsigned int count;
962   struct ConnectContext cctx;
963   struct PendingMessage *pm;
964
965   if (peer == NULL)
966     {
967       session->ic = NULL;
968       /* last call, destroy session if we are still not
969          connected */
970       if (session->client != NULL)
971         {
972 #if DEBUG_TCP
973           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
974                            "tcp",
975                            "Now connected to `%4s', now processing messages.\n",
976                            GNUNET_i2s (&session->target));
977 #endif
978           process_pending_messages (session);
979         }
980       else
981         {
982 #if DEBUG_TCP
983           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
984                            "tcp",
985                            "Failed to connect to `%4s' (no working `%s'), closing session.\n",
986                            GNUNET_i2s (&session->target), "HELLO");
987 #endif
988           disconnect_session (session);
989         }
990       return;
991     }
992   if ((hello == NULL) || (session->client != NULL))
993     {
994       GNUNET_break (0);         /* should this ever happen!? */
995       return;
996     }
997   count = 0;
998   GNUNET_HELLO_iterate_addresses (hello,
999                                   GNUNET_NO, &count_tcp_addresses, &count);
1000   if (count == 0)
1001     {
1002 #if DEBUG_TCP
1003       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1004                        "tcp",
1005                        "Asked to connect to `%4s', but have no addresses to try.\n",
1006                        GNUNET_i2s (&session->target));
1007 #endif
1008       return;
1009     }
1010   cctx.plugin = session->plugin;
1011   cctx.sa = NULL;
1012   cctx.welcome = NULL;
1013   cctx.pos = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1014   GNUNET_HELLO_iterate_addresses (hello,
1015                                   GNUNET_NO, &try_connect_to_address, &cctx);
1016   if (cctx.sa == NULL)
1017     {
1018 #if DEBUG_TCP
1019       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1020                        "tcp",
1021                        "Asked to connect, but all addresses failed.\n");
1022 #endif
1023       GNUNET_free_non_null (cctx.welcome);
1024       return;
1025     }
1026   session->client = GNUNET_SERVER_connect_socket (session->plugin->server,
1027                                                   cctx.sa);
1028 #if DEBUG_TCP
1029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030               "Connected to `%4s' for session %p\n",
1031               GNUNET_i2s (&session->target), session->client);
1032 #endif
1033   if (session->client == NULL)
1034     {
1035       GNUNET_break (0);         /* how could this happen? */
1036       GNUNET_free_non_null (cctx.welcome);
1037       return;
1038     }
1039   pm = cctx.welcome;
1040   /* prepend (!) */
1041   pm->next = session->pending_messages;
1042   session->pending_messages = pm;
1043 #if DEBUG_TCP
1044   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1045                    "tcp",
1046                    "Connected to `%4s', now sending `%s' message.\n",
1047                    GNUNET_i2s (&session->target), "WELCOME");
1048 #endif
1049 }
1050
1051
1052 /**
1053  * Function that can be used by the transport service to transmit
1054  * a message using the plugin.
1055  *
1056  * @param cls closure
1057  * @param service_context value passed to the transport-service
1058  *        to identify the neighbour
1059  * @param target who should receive this message
1060  * @param priority how important is the message
1061  * @param msg the message to transmit
1062  * @param timeout when should we time out (give up) if we can not transmit?
1063  * @param cont continuation to call once the message has
1064  *        been transmitted (or if the transport is ready
1065  *        for the next transmission call; or if the
1066  *        peer disconnected...)
1067  * @param cont_cls closure for cont
1068  */
1069 static void
1070 tcp_plugin_send (void *cls,
1071                  const struct GNUNET_PeerIdentity *target,
1072                  unsigned int priority,
1073                  const struct GNUNET_MessageHeader *msg,
1074                  struct GNUNET_TIME_Relative timeout,
1075                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1076 {
1077   struct Plugin *plugin = cls;
1078   struct Session *session;
1079   struct PendingMessage *pm;
1080   struct PendingMessage *pme;
1081
1082   session = find_session_by_target (plugin, target);
1083   pm = GNUNET_malloc (sizeof (struct PendingMessage) + ntohs (msg->size));
1084   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1085   memcpy (pm->msg, msg, ntohs (msg->size));
1086   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1087   pm->transmit_cont = cont;
1088   pm->transmit_cont_cls = cont_cls;
1089   if (session == NULL)
1090     {
1091       session = GNUNET_malloc (sizeof (struct Session));
1092 #if DEBUG_TCP
1093       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1094                        "tcp",
1095                        "Asked to transmit, creating fresh session %p.\n",
1096                        session);
1097 #endif
1098       session->next = plugin->sessions;
1099       plugin->sessions = session;
1100       session->plugin = plugin;
1101       session->target = *target;
1102       session->last_quota_update = GNUNET_TIME_absolute_get ();
1103       session->quota_in = plugin->env->default_quota_in;
1104       session->expecting_welcome = GNUNET_YES;
1105       session->pending_messages = pm;
1106       session->ic = GNUNET_PEERINFO_iterate (plugin->env->cfg,
1107                                              plugin->env->sched,
1108                                              target,
1109                                              0, timeout, &session_try_connect,
1110                                              session);
1111       return;
1112     }
1113   GNUNET_assert (session != NULL);
1114   GNUNET_assert (session->client != NULL);
1115   /* append pm to pending_messages list */
1116   pme = session->pending_messages;
1117   if (pme == NULL)
1118     {
1119       session->pending_messages = pm;
1120     }
1121   else
1122     {
1123       while (NULL != pme->next)
1124         pme = pme->next;
1125       pme->next = pm;
1126     }
1127 #if DEBUG_TCP
1128   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1129                    "tcp", "Asked to transmit, added message to list.\n");
1130 #endif
1131   process_pending_messages (session);
1132 }
1133
1134
1135
1136 /**
1137  * Function that can be called to force a disconnect from the
1138  * specified neighbour.  This should also cancel all previously
1139  * scheduled transmissions.  Obviously the transmission may have been
1140  * partially completed already, which is OK.  The plugin is supposed
1141  * to close the connection (if applicable) and no longer call the
1142  * transmit continuation(s).
1143  *
1144  * Finally, plugin MUST NOT call the services's receive function to
1145  * notify the service that the connection to the specified target was
1146  * closed after a getting this call.
1147  *
1148  * @param cls closure
1149  * @param target peer for which the last transmission is
1150  *        to be cancelled
1151  */
1152 static void
1153 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1154 {
1155   struct Plugin *plugin = cls;
1156   struct Session *session;
1157   struct PendingMessage *pm;
1158
1159   session = find_session_by_target (plugin, target);
1160   if (session == NULL)
1161     {
1162       GNUNET_break (0);
1163       return;
1164     }
1165 #if DEBUG_TCP
1166   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1167                    "tcp",
1168                    "Asked to cancel session with `%4s'\n",
1169                    GNUNET_i2s (target));
1170 #endif
1171   pm = session->pending_messages;
1172   while (pm != NULL)
1173     {
1174       pm->transmit_cont = NULL;
1175       pm->transmit_cont_cls = NULL;
1176       pm = pm->next;
1177     }
1178   if (session->client != NULL)
1179     {
1180       GNUNET_SERVER_client_drop (session->client);
1181       session->client = NULL;
1182     }
1183   /* rest of the clean-up of the session will be done as part of
1184      disconnect_notify which should be triggered any time now 
1185      (or which may be triggering this call in the first place) */
1186 }
1187
1188
1189 struct PrettyPrinterContext
1190 {
1191   GNUNET_TRANSPORT_AddressStringCallback asc;
1192   void *asc_cls;
1193   uint16_t port;
1194 };
1195
1196
1197 /**
1198  * Append our port and forward the result.
1199  */
1200 static void
1201 append_port (void *cls, const char *hostname)
1202 {
1203   struct PrettyPrinterContext *ppc = cls;
1204   char *ret;
1205
1206   if (hostname == NULL)
1207     {
1208       ppc->asc (ppc->asc_cls, NULL);
1209       GNUNET_free (ppc);
1210       return;
1211     }
1212   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1213   ppc->asc (ppc->asc_cls, ret);
1214   GNUNET_free (ret);
1215 }
1216
1217
1218 /**
1219  * Convert the transports address to a nice, human-readable
1220  * format.
1221  *
1222  * @param cls closure
1223  * @param type name of the transport that generated the address
1224  * @param addr one of the addresses of the host, NULL for the last address
1225  *        the specific address format depends on the transport
1226  * @param addrlen length of the address
1227  * @param numeric should (IP) addresses be displayed in numeric form?
1228  * @param timeout after how long should we give up?
1229  * @param asc function to call on each string
1230  * @param asc_cls closure for asc
1231  */
1232 static void
1233 tcp_plugin_address_pretty_printer (void *cls,
1234                                    const char *type,
1235                                    const void *addr,
1236                                    size_t addrlen,
1237                                    int numeric,
1238                                    struct GNUNET_TIME_Relative timeout,
1239                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1240                                    void *asc_cls)
1241 {
1242   struct Plugin *plugin = cls;
1243   const struct sockaddr_in *v4;
1244   const struct sockaddr_in6 *v6;
1245   struct PrettyPrinterContext *ppc;
1246
1247   if ((addrlen != sizeof (struct sockaddr_in)) &&
1248       (addrlen != sizeof (struct sockaddr_in6)))
1249     {
1250       /* invalid address */
1251       GNUNET_break_op (0);
1252       asc (asc_cls, NULL);
1253       return;
1254     }
1255   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1256   ppc->asc = asc;
1257   ppc->asc_cls = asc_cls;
1258   if (addrlen == sizeof (struct sockaddr_in))
1259     {
1260       v4 = (const struct sockaddr_in *) addr;
1261       ppc->port = ntohs (v4->sin_port);
1262     }
1263   else
1264     {
1265       v6 = (const struct sockaddr_in6 *) addr;
1266       ppc->port = ntohs (v6->sin6_port);
1267
1268     }
1269   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1270                                 plugin->env->cfg,
1271                                 addr,
1272                                 addrlen,
1273                                 !numeric, timeout, &append_port, ppc);
1274 }
1275
1276
1277 /**
1278  * Update the last-received and bandwidth quota values
1279  * for this session.
1280  *
1281  * @param session session to update
1282  * @param force set to GNUNET_YES if we should update even
1283  *        though the minimum refresh time has not yet expired
1284  */
1285 static void
1286 update_quota (struct Session *session, int force)
1287 {
1288   struct GNUNET_TIME_Absolute now;
1289   unsigned long long delta;
1290   unsigned long long total_allowed;
1291   unsigned long long total_remaining;
1292
1293   now = GNUNET_TIME_absolute_get ();
1294   delta = now.value - session->last_quota_update.value;
1295   if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
1296     return;                     /* too early, not enough data */
1297
1298   total_allowed = session->quota_in * delta;
1299   if (total_allowed > session->last_received)
1300     {
1301       /* got less than acceptable */
1302       total_remaining = total_allowed - session->last_received;
1303       session->last_received = 0;
1304       delta = total_remaining / session->quota_in;      /* bonus seconds */
1305       if (delta > MAX_BANDWIDTH_CARRY)
1306         delta = MAX_BANDWIDTH_CARRY;    /* limit amount of carry-over */
1307     }
1308   else
1309     {
1310       /* got more than acceptable */
1311       session->last_received -= total_allowed;
1312       delta = 0;
1313     }
1314   session->last_quota_update.value = now.value - delta;
1315 }
1316
1317
1318 /**
1319  * Set a quota for receiving data from the given peer; this is a
1320  * per-transport limit.  The transport should limit its read/select
1321  * calls to stay below the quota (in terms of incoming data).
1322  *
1323  * @param cls closure
1324  * @param target the peer for whom the quota is given
1325  * @param quota_in quota for receiving/sending data in bytes per ms
1326  */
1327 static void
1328 tcp_plugin_set_receive_quota (void *cls,
1329                               const struct GNUNET_PeerIdentity *target,
1330                               uint32_t quota_in)
1331 {
1332   struct Plugin *plugin = cls;
1333   struct Session *session;
1334
1335   session = find_session_by_target (plugin, target);
1336   if (session == NULL)
1337     return;                     /* peer must have disconnected, ignore */
1338   if (session->quota_in != quota_in)
1339     {
1340       update_quota (session, GNUNET_YES);
1341       if (session->quota_in > quota_in)
1342         session->last_quota_update = GNUNET_TIME_absolute_get ();
1343       session->quota_in = quota_in;
1344     }
1345 }
1346
1347
1348 /**
1349  * Check if the given port is plausible (must be either
1350  * our listen port or our advertised port).  If it is
1351  * neither, we return one of these two ports at random.
1352  *
1353  * @return either in_port or a more plausible port
1354  */
1355 static uint16_t
1356 check_port (struct Plugin *plugin, uint16_t in_port)
1357 {
1358   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1359     return in_port;
1360   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1361                                     2) == 0)
1362     ? plugin->open_port : plugin->adv_port;
1363 }
1364
1365
1366 /**
1367  * Another peer has suggested an address for this
1368  * peer and transport plugin.  Check that this could be a valid
1369  * address.  If so, consider adding it to the list
1370  * of addresses.
1371  *
1372  * @param cls closure
1373  * @param addr pointer to the address
1374  * @param addrlen length of addr
1375  * @return GNUNET_OK if this is a plausible address for this peer
1376  *         and transport
1377  */
1378 static int
1379 tcp_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1380 {
1381   struct Plugin *plugin = cls;
1382   char buf[sizeof (struct sockaddr_in6)];
1383   struct sockaddr_in *v4;
1384   struct sockaddr_in6 *v6;
1385
1386   if ((addrlen != sizeof (struct sockaddr_in)) &&
1387       (addrlen != sizeof (struct sockaddr_in6)))
1388     {
1389       GNUNET_break_op (0);
1390       return GNUNET_SYSERR;
1391     }
1392   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1393   if (addrlen == sizeof (struct sockaddr_in))
1394     {
1395       v4 = (struct sockaddr_in *) buf;
1396       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1397     }
1398   else
1399     {
1400       v6 = (struct sockaddr_in6 *) buf;
1401       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1402     }
1403 #if DEBUG_TCP
1404   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1405                    "tcp",
1406                    "Informing transport service about my address `%s'.\n",
1407                    GNUNET_a2s (addr, addrlen));
1408 #endif
1409   plugin->env->notify_address (plugin->env->cls,
1410                                "tcp",
1411                                buf, addrlen, LEARNED_ADDRESS_EXPIRATION);
1412   return GNUNET_OK;
1413 }
1414
1415
1416 /**
1417  * Send a validation challenge response.
1418  */
1419 static size_t
1420 send_vcr (void *cls, size_t size, void *buf)
1421 {
1422   struct ValidationChallengeResponse *vcr = cls;
1423   uint16_t msize;
1424
1425   if (NULL == buf)
1426     {
1427       GNUNET_free (vcr);
1428       return 0;
1429     }
1430   msize = ntohs (vcr->header.size);
1431   GNUNET_assert (size >= msize);
1432   memcpy (buf, vcr, msize);
1433   GNUNET_free (vcr);
1434   return msize;
1435 }
1436
1437
1438 /**
1439  * We've received a PING from this peer via TCP.
1440  * Send back our PONG.
1441  *
1442  * @param cls closure
1443  * @param client identification of the client
1444  * @param message the actual message
1445  */
1446 static void
1447 handle_tcp_ping (void *cls,
1448                  struct GNUNET_SERVER_Client *client,
1449                  const struct GNUNET_MessageHeader *message)
1450 {
1451   struct Plugin *plugin = cls;
1452   const struct ValidationChallengeMessage *vcm;
1453   struct ValidationChallengeResponse *vcr;
1454   uint16_t msize;
1455   size_t addrlen;
1456   void *addr;
1457
1458 #if DEBUG_TRANSPORT
1459   if (GNUNET_OK ==
1460       GNUNET_SERVER_client_get_address (client, (void **) &addr, &addrlen))
1461     {
1462       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1463                   "Processing `%s' from `%s'\n",
1464                   "PING", GNUNET_a2s (addr, addrlen));
1465       GNUNET_free (addr);
1466     }
1467 #endif
1468   msize = ntohs (message->size);
1469   if (msize < sizeof (struct ValidationChallengeMessage))
1470     {
1471       GNUNET_break_op (0);
1472       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1473       return;
1474     }
1475   vcm = (const struct ValidationChallengeMessage *) message;
1476   if (0 != memcmp (&vcm->target,
1477                    plugin->env->my_identity,
1478                    sizeof (struct GNUNET_PeerIdentity)))
1479     {
1480       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1481                   _("Received `%s' message not destined for me!\n"), "PING");
1482       /* TODO: call statistics */
1483       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1484       return;
1485     }
1486   msize -= sizeof (struct ValidationChallengeMessage);
1487   if (GNUNET_OK != tcp_plugin_address_suggested (plugin, &vcm[1], msize))
1488     {
1489       GNUNET_break_op (0);
1490       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1491       return;
1492     }
1493   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &addr, &addrlen))
1494     {
1495       GNUNET_break (0);
1496       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1497       return;
1498     }
1499   vcr = GNUNET_malloc (sizeof (struct ValidationChallengeResponse) + addrlen);
1500   vcr->header.size =
1501     htons (sizeof (struct ValidationChallengeResponse) + addrlen);
1502   vcr->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG);
1503   vcr->purpose.size =
1504     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1505            sizeof (uint32_t) +
1506            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + addrlen);
1507   vcr->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
1508   vcr->challenge = vcm->challenge;
1509   vcr->signer = *plugin->env->my_public_key;
1510   memcpy (&vcr[1], addr, addrlen);
1511   GNUNET_assert (GNUNET_OK ==
1512                  GNUNET_CRYPTO_rsa_sign (plugin->env->my_private_key,
1513                                          &vcr->purpose, &vcr->signature));
1514 #if EXTRA_CHECKS
1515   GNUNET_assert (GNUNET_OK ==
1516                  GNUNET_CRYPTO_rsa_verify
1517                  (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING,
1518                   &vcr->purpose,
1519                   &vcr->signature, plugin->env->my_public_key));
1520 #endif
1521   GNUNET_free (addr);
1522   if (NULL ==
1523       GNUNET_SERVER_notify_transmit_ready (client,
1524                                            sizeof (struct
1525                                                    ValidationChallengeResponse)
1526                                            + addrlen,
1527                                            GNUNET_TIME_UNIT_SECONDS,
1528                                            &send_vcr, vcr))
1529     {
1530       GNUNET_break (0);
1531       GNUNET_free (vcr);
1532     }
1533   /* after a PING, we always close the connection */
1534   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1535 }
1536
1537
1538 /**
1539  * Handle PONG-message.
1540  *
1541  * @param cls handle for this plugin
1542  * @param client from where did we receive the PONG
1543  * @param message the actual message
1544  */
1545 static void
1546 handle_tcp_pong (void *cls,
1547                  struct GNUNET_SERVER_Client *client,
1548                  const struct GNUNET_MessageHeader *message)
1549 {
1550   struct Plugin *plugin = cls;
1551   const struct ValidationChallengeResponse *vcr;
1552   struct GNUNET_PeerIdentity peer;
1553   char *sender_addr;
1554   size_t addrlen;
1555   const struct sockaddr *addr;
1556   struct sockaddr_in v4;
1557   struct sockaddr_in6 v6;
1558
1559 #if DEBUG_TRANSPORT
1560   struct sockaddr *claddr;
1561
1562   if (GNUNET_OK ==
1563       GNUNET_SERVER_client_get_address (client, (void **) &claddr, &addrlen))
1564     {
1565       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1566                   "Processing `%s' from `%s'\n",
1567                   "PONG", GNUNET_a2s (claddr, addrlen));
1568       GNUNET_free (claddr);
1569     }
1570 #endif
1571   if (ntohs (message->size) < sizeof (struct ValidationChallengeResponse))
1572     {
1573       GNUNET_break_op (0);
1574       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1575       return;
1576     }
1577   addrlen =
1578     ntohs (message->size) - sizeof (struct ValidationChallengeResponse);
1579   vcr = (const struct ValidationChallengeResponse *) message;
1580   if ((ntohl (vcr->purpose.size) !=
1581        sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1582        sizeof (uint32_t) +
1583        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + addrlen))
1584     {
1585       GNUNET_break_op (0);
1586       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1587       return;
1588     }
1589   if (GNUNET_OK !=
1590       GNUNET_CRYPTO_rsa_verify
1591       (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING,
1592        &vcr->purpose, &vcr->signature, &vcr->signer))
1593     {
1594       GNUNET_break_op (0);
1595       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1596       return;
1597     }
1598   GNUNET_CRYPTO_hash (&vcr->signer,
1599                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1600                       &peer.hashPubKey);
1601   addr = (const struct sockaddr *) &vcr[1];
1602   if (addrlen == sizeof (struct sockaddr_in))
1603     {
1604       memcpy (&v4, addr, sizeof (struct sockaddr_in));
1605       v4.sin_port = htons (check_port (plugin, ntohs (v4.sin_port)));
1606       sender_addr = GNUNET_strdup (GNUNET_a2s ((const struct sockaddr *) &v4,
1607                                                addrlen));
1608     }
1609   else if (addrlen == sizeof (struct sockaddr_in6))
1610     {
1611       memcpy (&v6, addr, sizeof (struct sockaddr_in6));
1612       v6.sin6_port = htons (check_port (plugin, ntohs (v6.sin6_port)));
1613       sender_addr = GNUNET_strdup (GNUNET_a2s ((const struct sockaddr *) &v6,
1614                                                addrlen));
1615     }
1616   else
1617     {
1618       GNUNET_break_op (0);
1619       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1620       return;
1621     }
1622   plugin->env->notify_validation (plugin->env->cls,
1623                                   "tcp",
1624                                   &peer, ntohl (vcr->challenge), sender_addr);
1625   GNUNET_free (sender_addr);
1626   /* after a PONG, we always close the connection */
1627   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1628 }
1629
1630
1631 /**
1632  * We've received a welcome from this peer via TCP.
1633  * Possibly create a fresh client record and send back
1634  * our welcome.
1635  *
1636  * @param cls closure
1637  * @param client identification of the client
1638  * @param message the actual message
1639  */
1640 static void
1641 handle_tcp_welcome (void *cls,
1642                     struct GNUNET_SERVER_Client *client,
1643                     const struct GNUNET_MessageHeader *message)
1644 {
1645   struct Plugin *plugin = cls;
1646   struct Session *session_c;
1647   const struct WelcomeMessage *wm;
1648   uint16_t msize;
1649   uint32_t addrlen;
1650   size_t alen;
1651   void *vaddr;
1652   const struct sockaddr *addr;
1653
1654   msize = ntohs (message->size);
1655   if (msize < sizeof (struct WelcomeMessage))
1656     {
1657       GNUNET_break_op (0);
1658       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1659       return;
1660     }
1661   wm = (const struct WelcomeMessage *) message;
1662 #if DEBUG_TCP
1663   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1664                    "tcp",
1665                    "Received `%s' message from `%4s/%p'.\n", "WELCOME",
1666                    GNUNET_i2s (&wm->clientIdentity), client);
1667 #endif
1668   session_c = find_session_by_client (plugin, client);
1669   if (session_c == NULL)
1670     {
1671       vaddr = NULL;
1672       GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1673       GNUNET_SERVER_client_keep (client);
1674       session_c = create_session (plugin,
1675                                   &wm->clientIdentity, client, vaddr, alen);
1676 #if DEBUG_TCP
1677       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1678                        "tcp",
1679                        "Creating new session %p for incoming `%s' message.\n",
1680                        session_c, "WELCOME");
1681 #endif
1682       GNUNET_free_non_null (vaddr);
1683       process_pending_messages (session_c);
1684     }
1685   if (session_c->expecting_welcome != GNUNET_YES)
1686     {
1687       GNUNET_break_op (0);
1688       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1689       return;
1690     }
1691   session_c->expecting_welcome = GNUNET_NO;
1692   if (0 < (addrlen = msize - sizeof (struct WelcomeMessage)))
1693     {
1694       addr = (const struct sockaddr *) &wm[1];
1695       tcp_plugin_address_suggested (plugin, addr, addrlen);
1696     }
1697   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1698 }
1699
1700
1701 /**
1702  * Calculate how long we should delay reading from the TCP socket to
1703  * ensure that we stay within our bandwidth limits (push back).
1704  *
1705  * @param session for which client should this be calculated
1706  */
1707 static struct GNUNET_TIME_Relative
1708 calculate_throttle_delay (struct Session *session)
1709 {
1710   struct GNUNET_TIME_Relative ret;
1711   struct GNUNET_TIME_Absolute now;
1712   uint64_t del;
1713   uint64_t avail;
1714   uint64_t excess;
1715
1716   now = GNUNET_TIME_absolute_get ();
1717   del = now.value - session->last_quota_update.value;
1718   if (del > MAX_BANDWIDTH_CARRY)
1719     {
1720       update_quota (session, GNUNET_YES);
1721       del = now.value - session->last_quota_update.value;
1722       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1723     }
1724   if (session->quota_in == 0)
1725     session->quota_in = 1;      /* avoid divison by zero */
1726   avail = del * session->quota_in;
1727   if (avail > session->last_received)
1728     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1729   excess = session->last_received - avail;
1730   ret.value = excess / session->quota_in;
1731   return ret;
1732 }
1733
1734
1735 /**
1736  * Task to signal the server that we can continue
1737  * receiving from the TCP client now.
1738  */
1739 static void
1740 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1741 {
1742   struct Session *session = cls;
1743   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1744 }
1745
1746
1747 /**
1748  * We've received data for this peer via TCP.  Unbox,
1749  * compute latency and forward.
1750  *
1751  * @param cls closure
1752  * @param client identification of the client
1753  * @param message the actual message
1754  */
1755 static void
1756 handle_tcp_data (void *cls,
1757                  struct GNUNET_SERVER_Client *client,
1758                  const struct GNUNET_MessageHeader *message)
1759 {
1760   struct Plugin *plugin = cls;
1761   struct Session *session;
1762   const struct DataMessage *dm;
1763   uint16_t msize;
1764   const struct GNUNET_MessageHeader *msg;
1765   struct GNUNET_TIME_Relative latency;
1766   struct GNUNET_TIME_Absolute ttime;
1767   struct GNUNET_TIME_Absolute now;
1768   struct GNUNET_TIME_Relative delay;
1769   uint64_t ack_in;
1770
1771   msize = ntohs (message->size);
1772   if ((msize <
1773        sizeof (struct DataMessage) + sizeof (struct GNUNET_MessageHeader)))
1774     {
1775       GNUNET_break_op (0);
1776       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1777       return;
1778     }
1779   session = find_session_by_client (plugin, client);
1780   if ((NULL == session) || (GNUNET_NO != session->expecting_welcome))
1781     {
1782       GNUNET_break_op (0);
1783       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1784       return;
1785     }
1786 #if DEBUG_TCP
1787   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1788                    "tcp", "Receiving %u bytes from `%4s'.\n",
1789                    msize, GNUNET_i2s (&session->target));
1790 #endif
1791   dm = (const struct DataMessage *) message;
1792   session->max_in_msg_counter = GNUNET_MAX (session->max_in_msg_counter,
1793                                             GNUNET_ntohll (dm->ack_out));
1794   msg = (const struct GNUNET_MessageHeader *) &dm[1];
1795   if (msize != sizeof (struct DataMessage) + ntohs (msg->size))
1796     {
1797       GNUNET_break_op (0);
1798       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1799       return;
1800     }
1801   /* estimate latency */
1802   ack_in = GNUNET_ntohll (dm->ack_in);
1803   if ((ack_in <= session->out_msg_counter) &&
1804       (session->out_msg_counter - ack_in < ACK_LOG_SIZE))
1805     {
1806       delay = GNUNET_TIME_relative_ntoh (dm->delay);
1807       ttime = session->gen_time[ack_in % ACK_LOG_SIZE];
1808       now = GNUNET_TIME_absolute_get ();
1809       if (delay.value > now.value - ttime.value)
1810         delay.value = 0;        /* not plausible */
1811       /* update (round-trip) latency using ageing; we
1812          use 7:1 so that we can reasonably quickly react
1813          to changes, but not so fast that latency is largely
1814          jitter... */
1815       session->latency_estimate
1816         = ((7 * session->latency_estimate) +
1817            (now.value - ttime.value - delay.value)) / 8;
1818     }
1819   latency.value = (uint64_t) session->latency_estimate;
1820   /* deliver on */
1821 #if DEBUG_TCP
1822   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1823                    "tcp",
1824                    "Forwarding data of type %u to transport service.\n",
1825                    ntohs (msg->type));
1826 #endif
1827   plugin->env->receive (plugin->env->cls, latency, &session->target, msg);
1828   /* update bandwidth used */
1829   session->last_received += msize;
1830   update_quota (session, GNUNET_NO);
1831
1832   delay = calculate_throttle_delay (session);
1833   if (delay.value == 0)
1834     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1835   else
1836     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1837                                   delay, &delayed_done, session);
1838 }
1839
1840
1841 /**
1842  * Handlers for the various TCP messages.
1843  */
1844 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1845   {&handle_tcp_ping, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING, 0},
1846   {&handle_tcp_pong, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG, 0},
1847   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 0},
1848   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1849   {NULL, NULL, 0, 0}
1850 };
1851
1852
1853 static void
1854 create_tcp_handlers (struct Plugin *plugin)
1855 {
1856   unsigned int i;
1857   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1858   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1859   for (i = 0;
1860        i <
1861        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1862        i++)
1863     plugin->handlers[i].callback_cls = plugin;
1864   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1865 }
1866
1867
1868 /**
1869  * Functions with this signature are called whenever a peer
1870  * is disconnected on the network level.
1871  *
1872  * @param cls closure
1873  * @param client identification of the client
1874  */
1875 static void
1876 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1877 {
1878   struct Plugin *plugin = cls;
1879   struct Session *session;
1880
1881   session = find_session_by_client (plugin, client);
1882   if (session == NULL)
1883     return;                     /* unknown, nothing to do */
1884 #if DEBUG_TCP
1885   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1886                    "tcp",
1887                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1888                    GNUNET_i2s (&session->target),
1889                    (session->connect_addr != NULL) ?
1890                    GNUNET_a2s (session->connect_addr,
1891                                session->connect_alen) : "*", client);
1892 #endif
1893   disconnect_session (session);
1894 }
1895
1896
1897 /**
1898  * Add the IP of our network interface to the list of
1899  * our external IP addresses.
1900  */
1901 static int
1902 process_interfaces (void *cls,
1903                     const char *name,
1904                     int isDefault,
1905                     const struct sockaddr *addr, socklen_t addrlen)
1906 {
1907   struct Plugin *plugin = cls;
1908   int af;
1909   struct sockaddr_in *v4;
1910   struct sockaddr_in6 *v6;
1911
1912   af = addr->sa_family;
1913   if (af == AF_INET)
1914     {
1915       v4 = (struct sockaddr_in *) addr;
1916       v4->sin_port = htons (plugin->adv_port);
1917     }
1918   else
1919     {
1920       GNUNET_assert (af == AF_INET6);
1921       v6 = (struct sockaddr_in6 *) addr;
1922       v6->sin6_port = htons (plugin->adv_port);
1923     }
1924   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1925                    GNUNET_ERROR_TYPE_BULK,
1926                    "tcp", _("Found address `%s' (%s)\n"),
1927                    GNUNET_a2s (addr, addrlen), name);
1928   plugin->env->notify_address (plugin->env->cls,
1929                                "tcp",
1930                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1931   return GNUNET_OK;
1932 }
1933
1934
1935 /**
1936  * Function called by the resolver for each address obtained from DNS
1937  * for our own hostname.  Add the addresses to the list of our
1938  * external IP addresses.
1939  *
1940  * @param cls closure
1941  * @param addr one of the addresses of the host, NULL for the last address
1942  * @param addrlen length of the address
1943  */
1944 static void
1945 process_hostname_ips (void *cls,
1946                       const struct sockaddr *addr, socklen_t addrlen)
1947 {
1948   struct Plugin *plugin = cls;
1949
1950   if (addr == NULL)
1951     {
1952       plugin->hostname_dns = NULL;
1953       return;
1954     }
1955   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1956 }
1957
1958
1959 /**
1960  * Entry point for the plugin.
1961  */
1962 void *
1963 libgnunet_plugin_transport_tcp_init (void *cls)
1964 {
1965   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1966   struct GNUNET_TRANSPORT_PluginFunctions *api;
1967   struct Plugin *plugin;
1968   struct GNUNET_SERVICE_Context *service;
1969   unsigned long long aport;
1970   unsigned long long bport;
1971
1972   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1973   if (service == NULL)
1974     {
1975       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1976                        "tcp",
1977                        _
1978                        ("Failed to start service for `%s' transport plugin.\n"),
1979                        "tcp");
1980       return NULL;
1981     }
1982   aport = 0;
1983   if ((GNUNET_OK !=
1984        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1985                                               "transport-tcp",
1986                                               "PORT",
1987                                               &bport)) ||
1988       (bport > 65535) ||
1989       ((GNUNET_OK ==
1990         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1991                                                "transport-tcp",
1992                                                "ADVERTISED-PORT",
1993                                                &aport)) && (aport > 65535)))
1994     {
1995       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1996                        "tcp",
1997                        _
1998                        ("Require valid port number for service `%s' in configuration!\n"),
1999                        "transport-tcp");
2000       GNUNET_SERVICE_stop (service);
2001       return NULL;
2002     }
2003   if (aport == 0)
2004     aport = bport;
2005   plugin = GNUNET_malloc (sizeof (struct Plugin));
2006   plugin->open_port = bport;
2007   plugin->adv_port = aport;
2008   plugin->env = env;
2009   plugin->lsock = NULL;
2010   plugin->statistics = NULL;
2011   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2012   api->cls = plugin;
2013   api->validate = &tcp_plugin_validate;
2014   api->send = &tcp_plugin_send;
2015   api->disconnect = &tcp_plugin_disconnect;
2016   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2017   api->set_receive_quota = &tcp_plugin_set_receive_quota;
2018   api->address_suggested = &tcp_plugin_address_suggested;
2019   api->cost_estimate = 42;      /* TODO: ATS */
2020   plugin->service = service;
2021   plugin->server = GNUNET_SERVICE_get_server (service);
2022   create_tcp_handlers (plugin);
2023   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2024                    "tcp", _("TCP transport listening on port %llu\n"), bport);
2025   if (aport != bport)
2026     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2027                      "tcp",
2028                      _
2029                      ("TCP transport advertises itself as being on port %llu\n"),
2030                      aport);
2031   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
2032                                    plugin);
2033   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2034   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2035                                                            env->cfg,
2036                                                            AF_UNSPEC,
2037                                                            HOSTNAME_RESOLVE_TIMEOUT,
2038                                                            &process_hostname_ips,
2039                                                            plugin);
2040   return api;
2041 }
2042
2043
2044 /**
2045  * Exit point from the plugin.
2046  */
2047 void *
2048 libgnunet_plugin_transport_tcp_done (void *cls)
2049 {
2050   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2051   struct Plugin *plugin = api->cls;
2052   struct Session *session;
2053
2054   while (NULL != (session = plugin->sessions))
2055     disconnect_session (session);
2056   if (NULL != plugin->hostname_dns)
2057     {
2058       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2059       plugin->hostname_dns = NULL;
2060     }
2061   GNUNET_SERVICE_stop (plugin->service);
2062   GNUNET_free (plugin->handlers);
2063   GNUNET_free (plugin);
2064   GNUNET_free (api);
2065   return NULL;
2066 }
2067
2068 /* end of plugin_transport_tcp.c */