making tcp plugin code compile again, but does not work yet
[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 (struct Plugin *plugin)
453 {
454   struct PendingMessage *pm;
455   struct WelcomeMessage *welcome;
456
457   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
458                       sizeof (struct WelcomeMessage));
459   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
460   welcome = (struct WelcomeMessage *) &pm[1];
461   welcome->header.size = htons (sizeof (struct WelcomeMessage));
462   welcome->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
463   welcome->clientIdentity = *plugin->env->my_identity;
464   pm->timeout = GNUNET_TIME_relative_to_absolute (WELCOME_TIMEOUT);
465   pm->is_welcome = GNUNET_YES;
466   return pm;
467 }
468
469
470 /**
471  * Create a new session.
472  *
473  * @param plugin us
474  * @param target peer to connect to
475  * @param client client to use
476  * @return new session object
477  */
478 static struct Session *
479 create_session (struct Plugin *plugin,
480                 const struct GNUNET_PeerIdentity *target,
481                 struct GNUNET_SERVER_Client *client)
482 {
483   struct Session *ret;
484
485   ret = GNUNET_malloc (sizeof (struct Session));
486   ret->plugin = plugin;
487   ret->next = plugin->sessions;
488   plugin->sessions = ret;
489   ret->client = client;
490   ret->target = *target;
491   ret->last_quota_update = GNUNET_TIME_absolute_get ();
492   ret->quota_in = plugin->env->default_quota_in;
493   ret->expecting_welcome = GNUNET_YES;
494   ret->pending_messages = create_welcome (plugin);
495   return ret;
496 }
497
498
499 /**
500  * If we have pending messages, ask the server to
501  * transmit them (schedule the respective tasks, etc.)
502  *
503  * @param session for which session should we do this
504  */
505 static void process_pending_messages (struct Session *session);
506
507
508 /**
509  * Function called to notify a client about the socket
510  * being ready to queue more data.  "buf" will be
511  * NULL and "size" zero if the socket was closed for
512  * writing in the meantime.
513  *
514  * @param cls closure
515  * @param size number of bytes available in buf
516  * @param buf where the callee should write the message
517  * @return number of bytes written to buf
518  */
519 static size_t
520 do_transmit (void *cls, size_t size, void *buf)
521 {
522   struct Session *session = cls;
523   struct PendingMessage *pm;
524   char *cbuf;
525   uint16_t msize;
526   size_t ret;
527   struct DataMessage *dm;
528
529   session->transmit_handle = NULL;
530   if (buf == NULL)
531     {
532 #if DEBUG_TCP
533       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
534                        "tcp",
535                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
536                        GNUNET_i2s (&session->target));
537 #endif
538       /* timeout */
539       while (NULL != (pm = session->pending_messages))
540         {
541           session->pending_messages = pm->next;
542 #if DEBUG_TCP
543           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
544                            "tcp",
545                            "Failed to transmit message of type %u to `%4s'.\n",
546                            ntohs (pm->msg->type),
547                            GNUNET_i2s (&session->target));
548 #endif
549           if (pm->transmit_cont != NULL)
550             pm->transmit_cont (pm->transmit_cont_cls,
551                                &session->target, GNUNET_SYSERR);
552           GNUNET_free (pm);
553         }
554       return 0;
555     }
556   ret = 0;
557   cbuf = buf;
558   while (NULL != (pm = session->pending_messages))
559     {
560       if (pm->is_welcome)
561         {
562           if (size < (msize = ntohs (pm->msg->size)))
563             break;
564           memcpy (cbuf, pm->msg, msize);
565           cbuf += msize;
566           ret += msize;
567           size -= msize;
568         }
569       else
570         {
571           if (size <
572               sizeof (struct DataMessage) + (msize = ntohs (pm->msg->size)))
573             break;
574           dm = (struct DataMessage *) cbuf;
575           dm->header.size = htons (sizeof (struct DataMessage) + msize);
576           dm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA);
577           dm->ack_out = GNUNET_htonll (++session->out_msg_counter);
578           dm->ack_in = GNUNET_htonll (session->max_in_msg_counter);
579           cbuf += sizeof (struct DataMessage);
580           ret += sizeof (struct DataMessage);
581           size -= sizeof (struct DataMessage);
582           memcpy (cbuf, pm->msg, msize);
583           cbuf += msize;
584           ret += msize;
585           size -= msize;
586         }
587       session->pending_messages = pm->next;
588       if (pm->transmit_cont != NULL)
589         pm->transmit_cont (pm->transmit_cont_cls,
590                            &session->target, GNUNET_OK);
591       GNUNET_free (pm);
592       session->gen_time[session->out_msg_counter % ACK_LOG_SIZE]
593         = GNUNET_TIME_absolute_get ();
594     }
595   process_pending_messages (session);
596 #if DEBUG_TCP
597   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
598                    "tcp", "Transmitting %u bytes\n", ret);
599 #endif
600   return ret;
601 }
602
603
604 /**
605  * If we have pending messages, ask the server to
606  * transmit them (schedule the respective tasks, etc.)
607  *
608  * @param session for which session should we do this
609  */
610 static void
611 process_pending_messages (struct Session *session)
612 {
613   GNUNET_assert (session->client != NULL);
614   if (session->pending_messages == NULL)
615     return;
616   if (session->transmit_handle != NULL)
617     return;
618   session->transmit_handle
619     = GNUNET_SERVER_notify_transmit_ready (session->client,
620                                            ntohs (session->
621                                                   pending_messages->msg->
622                                                   size) +
623                                            (session->
624                                             pending_messages->is_welcome ? 0 :
625                                             sizeof (struct DataMessage)),
626                                            GNUNET_TIME_absolute_get_remaining
627                                            (session->
628                                             pending_messages[0].timeout),
629                                            &do_transmit, session);
630 }
631
632
633 /**
634  * Functions with this signature are called whenever we need
635  * to close a session due to a disconnect or failure to
636  * establish a connection.
637  *
638  * @param session session to close down
639  */
640 static void
641 disconnect_session (struct Session *session)
642 {
643   struct Session *prev;
644   struct Session *pos;
645   struct PendingMessage *pm;
646
647 #if DEBUG_TCP
648   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
649                    "tcp",
650                    "Disconnecting from `%4s' at %s (session %p).\n",
651                    GNUNET_i2s (&session->target),
652                    (session->connect_addr != NULL) ?
653                    GNUNET_a2s (session->connect_addr,
654                                session->connect_alen) : "*", session);
655 #endif
656   /* remove from session list */
657   prev = NULL;
658   pos = session->plugin->sessions;
659   while (pos != session)
660     {
661       prev = pos;
662       pos = pos->next;
663     }
664   if (prev == NULL)
665     session->plugin->sessions = session->next;
666   else
667     prev->next = session->next;
668   /* clean up state */
669   if (session->ic != NULL)
670     {
671       GNUNET_PEERINFO_iterate_cancel (session->ic);
672       session->ic = NULL;
673     }
674   if (session->transmit_handle != NULL)
675     {
676       GNUNET_CONNECTION_notify_transmit_ready_cancel
677         (session->transmit_handle);
678       session->transmit_handle = NULL;
679     }
680   while (NULL != (pm = session->pending_messages))
681     {
682 #if DEBUG_TCP
683       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
684                        "tcp",
685                        pm->transmit_cont != NULL
686                        ? "Could not deliver message of type %u to `%4s'.\n"
687                        :
688                        "Could not deliver message of type %u to `%4s', notifying.\n",
689                        ntohs (pm->msg->type), GNUNET_i2s (&session->target));
690 #endif
691       session->pending_messages = pm->next;
692       if (NULL != pm->transmit_cont)
693         pm->transmit_cont (pm->transmit_cont_cls,
694                            &session->target, GNUNET_SYSERR);
695       GNUNET_free (pm);
696     }
697   if (GNUNET_NO == session->expecting_welcome)
698     {
699 #if DEBUG_TCP
700       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
701                        "tcp",
702                        "Notifying transport service about loss of data connection with `%4s'.\n",
703                        GNUNET_i2s (&session->target));
704 #endif
705       /* Data session that actually went past the 
706          initial handshake; transport service may
707          know about this one, so we need to 
708          notify transport service about disconnect */
709       session->plugin->env->receive (session->plugin->env->cls,
710                                      1,
711                                      NULL, 0, /* FIXME: address! */
712                                      &session->target, NULL);
713     }
714   if (session->client != NULL)
715     {
716       GNUNET_SERVER_client_drop (session->client);
717       session->client = NULL;
718     }
719   GNUNET_free_non_null (session->connect_addr);
720   GNUNET_free (session);
721 }
722
723
724 /**
725  * Iterator callback to go over all addresses.  If we get
726  * a TCP address, increment the counter
727  *
728  * @param cls closure, points to the counter
729  * @param tname name of the transport
730  * @param expiration expiration time
731  * @param addr the address
732  * @param addrlen length of the address
733  * @return GNUNET_OK to keep the address,
734  *         GNUNET_NO to delete it from the HELLO
735  *         GNUNET_SYSERR to stop iterating (but keep current address)
736  */
737 static int
738 count_tcp_addresses (void *cls,
739                      const char *tname,
740                      struct GNUNET_TIME_Absolute expiration,
741                      const void *addr, size_t addrlen)
742 {
743   unsigned int *counter = cls;
744
745   if (0 != strcmp (tname, "tcp"))
746     return GNUNET_OK;           /* not one of ours */
747   (*counter)++;
748   return GNUNET_OK;             /* failed to connect */
749 }
750
751
752 struct ConnectContext
753 {
754   struct Plugin *plugin;
755
756   struct GNUNET_CONNECTION_Handle *sa;
757
758   struct PendingMessage *welcome;
759
760   unsigned int pos;
761 };
762
763
764 /**
765  * Iterator callback to go over all addresses.  If we get
766  * the "pos" TCP address, try to connect to it.
767  *
768  * @param cls closure
769  * @param tname name of the transport
770  * @param expiration expiration time
771  * @param addrlen length of the address
772  * @param addr the address
773  * @return GNUNET_OK to keep the address,
774  *         GNUNET_NO to delete it from the HELLO
775  *         GNUNET_SYSERR to stop iterating (but keep current address)
776  */
777 static int
778 try_connect_to_address (void *cls,
779                         const char *tname,
780                         struct GNUNET_TIME_Absolute expiration,
781                         const void *addr, size_t addrlen)
782 {
783   struct ConnectContext *cc = cls;
784   int af;
785
786   if (0 != strcmp (tname, "tcp"))
787     return GNUNET_OK;           /* not one of ours */
788   if (sizeof (struct sockaddr_in) == addrlen)
789     af = AF_INET;
790   else if (sizeof (struct sockaddr_in6) == addrlen)
791     af = AF_INET6;
792   else
793     {
794       /* not a valid address */
795       GNUNET_break (0);
796       return GNUNET_NO;
797     }
798   if (0 == cc->pos--)
799     {
800       cc->welcome = create_welcome (cc->plugin);
801       cc->sa =
802         GNUNET_CONNECTION_create_from_sockaddr (cc->plugin->env->sched,
803                                                 af, addr, addrlen,
804                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
805 #if DEBUG_TCP
806       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
807                        "tcp",
808                        "Connecting using address %s.\n",
809                        GNUNET_a2s (addr, addrlen));
810 #endif
811       return GNUNET_SYSERR;
812     }
813   return GNUNET_OK;             /* failed to connect */
814 }
815
816
817 /**
818  * Type of an iterator over the hosts.  Note that each
819  * host will be called with each available protocol.
820  *
821  * @param cls closure
822  * @param peer id of the peer, NULL for last call
823  * @param hello hello message for the peer (can be NULL)
824  * @param trust amount of trust we have in the peer
825  */
826 static void
827 session_try_connect (void *cls,
828                      const struct GNUNET_PeerIdentity *peer,
829                      const struct GNUNET_HELLO_Message *hello, uint32_t trust)
830 {
831   struct Session *session = cls;
832   unsigned int count;
833   struct ConnectContext cctx;
834   struct PendingMessage *pm;
835
836   if (peer == NULL)
837     {
838       session->ic = NULL;
839       /* last call, destroy session if we are still not
840          connected */
841       if (session->client != NULL)
842         {
843 #if DEBUG_TCP
844           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
845                            "tcp",
846                            "Now connected to `%4s', now processing messages.\n",
847                            GNUNET_i2s (&session->target));
848 #endif
849           process_pending_messages (session);
850         }
851       else
852         {
853 #if DEBUG_TCP
854           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
855                            "tcp",
856                            "Failed to connect to `%4s' (no working `%s'), closing session.\n",
857                            GNUNET_i2s (&session->target), "HELLO");
858 #endif
859           disconnect_session (session);
860         }
861       return;
862     }
863   if ((hello == NULL) || (session->client != NULL))
864     {
865       GNUNET_break (0);         /* should this ever happen!? */
866       return;
867     }
868   count = 0;
869   GNUNET_HELLO_iterate_addresses (hello,
870                                   GNUNET_NO, &count_tcp_addresses, &count);
871   if (count == 0)
872     {
873 #if DEBUG_TCP
874       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
875                        "tcp",
876                        "Asked to connect to `%4s', but have no addresses to try.\n",
877                        GNUNET_i2s (&session->target));
878 #endif
879       return;
880     }
881   cctx.plugin = session->plugin;
882   cctx.sa = NULL;
883   cctx.welcome = NULL;
884   cctx.pos = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
885   GNUNET_HELLO_iterate_addresses (hello,
886                                   GNUNET_NO, &try_connect_to_address, &cctx);
887   if (cctx.sa == NULL)
888     {
889 #if DEBUG_TCP
890       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
891                        "tcp",
892                        "Asked to connect, but all addresses failed.\n");
893 #endif
894       GNUNET_free_non_null (cctx.welcome);
895       return;
896     }
897   session->client = GNUNET_SERVER_connect_socket (session->plugin->server,
898                                                   cctx.sa);
899 #if DEBUG_TCP
900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901               "Connected to `%4s' for session %p\n",
902               GNUNET_i2s (&session->target), session->client);
903 #endif
904   if (session->client == NULL)
905     {
906       GNUNET_break (0);         /* how could this happen? */
907       GNUNET_free_non_null (cctx.welcome);
908       return;
909     }
910   pm = cctx.welcome;
911   /* prepend (!) */
912   pm->next = session->pending_messages;
913   session->pending_messages = pm;
914 #if DEBUG_TCP
915   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
916                    "tcp",
917                    "Connected to `%4s', now sending `%s' message.\n",
918                    GNUNET_i2s (&session->target), "WELCOME");
919 #endif
920 }
921
922
923 /**
924  * Function that can be used by the transport service to transmit
925  * a message using the plugin.   Note that in the case of a
926  * peer disconnecting, the continuation MUST be called
927  * prior to the disconnect notification itself.  This function
928  * will be called with this peer's HELLO message to initiate
929  * a fresh connection to another peer.
930  *
931  * @param cls closure
932  * @param target who should receive this message
933  * @param msg the message to transmit
934  * @param priority how important is the message (most plugins will
935  *                 ignore message priority and just FIFO)
936  * @param timeout how long to wait at most for the transmission (does not
937  *                require plugins to discard the message after the timeout,
938  *                just advisory for the desired delay; most plugins will ignore
939  *                this as well)
940  * @param addr the address to use (can be NULL if the plugin
941  *                is "on its own" (i.e. re-use existing TCP connection))
942  * @param addrlen length of the address in bytes
943  * @param force_address GNUNET_YES if the plugin MUST use the given address,
944  *                otherwise the plugin may use other addresses or
945  *                existing connections (if available)
946  * @param cont continuation to call once the message has
947  *        been transmitted (or if the transport is ready
948  *        for the next transmission call; or if the
949  *        peer disconnected...); can be NULL
950  * @param cont_cls closure for cont
951  * @return number of bytes used (on the physical network, with overheads);
952  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
953  *         and does NOT mean that the message was not transmitted (DV)
954  */
955 static ssize_t
956 tcp_plugin_send (void *cls,
957                  const struct GNUNET_PeerIdentity *target,
958                  const struct GNUNET_MessageHeader *msg,
959                  unsigned int priority,
960                  struct GNUNET_TIME_Relative timeout,
961                  const void *addr,
962                  size_t addrlen,
963                  int force_address,
964                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
965 {
966   struct Plugin *plugin = cls;
967   struct Session *session;
968   struct PendingMessage *pm;
969   struct PendingMessage *pme;
970   uint16_t mlen;
971
972   /* FIXME: support 'force_address' */
973   mlen = ntohs (msg->size);
974   session = find_session_by_target (plugin, target);
975   pm = GNUNET_malloc (sizeof (struct PendingMessage) + ntohs (msg->size));
976   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
977   memcpy (pm->msg, msg, ntohs (msg->size));
978   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
979   pm->transmit_cont = cont;
980   pm->transmit_cont_cls = cont_cls;
981   if (session == NULL)
982     {
983       session = GNUNET_malloc (sizeof (struct Session));
984 #if DEBUG_TCP
985       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
986                        "tcp",
987                        "Asked to transmit, creating fresh session %p.\n",
988                        session);
989 #endif
990       session->next = plugin->sessions;
991       plugin->sessions = session;
992       session->plugin = plugin;
993       session->target = *target;
994       session->last_quota_update = GNUNET_TIME_absolute_get ();
995       session->quota_in = plugin->env->default_quota_in;
996       session->expecting_welcome = GNUNET_YES;
997       session->pending_messages = pm;
998       session->ic = GNUNET_PEERINFO_iterate (plugin->env->cfg,
999                                              plugin->env->sched,
1000                                              target,
1001                                              0, timeout, &session_try_connect,
1002                                              session);
1003       return mlen + sizeof (struct GNUNET_MessageHeader);
1004     }
1005   GNUNET_assert (session != NULL);
1006   GNUNET_assert (session->client != NULL);
1007   /* append pm to pending_messages list */
1008   pme = session->pending_messages;
1009   if (pme == NULL)
1010     {
1011       session->pending_messages = pm;
1012     }
1013   else
1014     {
1015       while (NULL != pme->next)
1016         pme = pme->next;
1017       pme->next = pm;
1018     }
1019 #if DEBUG_TCP
1020   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1021                    "tcp", "Asked to transmit, added message to list.\n");
1022 #endif
1023   process_pending_messages (session);
1024   return mlen + sizeof (struct GNUNET_MessageHeader);
1025 }
1026
1027
1028
1029 /**
1030  * Function that can be called to force a disconnect from the
1031  * specified neighbour.  This should also cancel all previously
1032  * scheduled transmissions.  Obviously the transmission may have been
1033  * partially completed already, which is OK.  The plugin is supposed
1034  * to close the connection (if applicable) and no longer call the
1035  * transmit continuation(s).
1036  *
1037  * Finally, plugin MUST NOT call the services's receive function to
1038  * notify the service that the connection to the specified target was
1039  * closed after a getting this call.
1040  *
1041  * @param cls closure
1042  * @param target peer for which the last transmission is
1043  *        to be cancelled
1044  */
1045 static void
1046 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1047 {
1048   struct Plugin *plugin = cls;
1049   struct Session *session;
1050   struct PendingMessage *pm;
1051
1052   session = find_session_by_target (plugin, target);
1053   if (session == NULL)
1054     {
1055       GNUNET_break (0);
1056       return;
1057     }
1058 #if DEBUG_TCP
1059   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1060                    "tcp",
1061                    "Asked to cancel session with `%4s'\n",
1062                    GNUNET_i2s (target));
1063 #endif
1064   pm = session->pending_messages;
1065   while (pm != NULL)
1066     {
1067       pm->transmit_cont = NULL;
1068       pm->transmit_cont_cls = NULL;
1069       pm = pm->next;
1070     }
1071   if (session->client != NULL)
1072     {
1073       GNUNET_SERVER_client_drop (session->client);
1074       session->client = NULL;
1075     }
1076   /* rest of the clean-up of the session will be done as part of
1077      disconnect_notify which should be triggered any time now 
1078      (or which may be triggering this call in the first place) */
1079 }
1080
1081
1082 struct PrettyPrinterContext
1083 {
1084   GNUNET_TRANSPORT_AddressStringCallback asc;
1085   void *asc_cls;
1086   uint16_t port;
1087 };
1088
1089
1090 /**
1091  * Append our port and forward the result.
1092  */
1093 static void
1094 append_port (void *cls, const char *hostname)
1095 {
1096   struct PrettyPrinterContext *ppc = cls;
1097   char *ret;
1098
1099   if (hostname == NULL)
1100     {
1101       ppc->asc (ppc->asc_cls, NULL);
1102       GNUNET_free (ppc);
1103       return;
1104     }
1105   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1106   ppc->asc (ppc->asc_cls, ret);
1107   GNUNET_free (ret);
1108 }
1109
1110
1111 /**
1112  * Convert the transports address to a nice, human-readable
1113  * format.
1114  *
1115  * @param cls closure
1116  * @param type name of the transport that generated the address
1117  * @param addr one of the addresses of the host, NULL for the last address
1118  *        the specific address format depends on the transport
1119  * @param addrlen length of the address
1120  * @param numeric should (IP) addresses be displayed in numeric form?
1121  * @param timeout after how long should we give up?
1122  * @param asc function to call on each string
1123  * @param asc_cls closure for asc
1124  */
1125 static void
1126 tcp_plugin_address_pretty_printer (void *cls,
1127                                    const char *type,
1128                                    const void *addr,
1129                                    size_t addrlen,
1130                                    int numeric,
1131                                    struct GNUNET_TIME_Relative timeout,
1132                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1133                                    void *asc_cls)
1134 {
1135   struct Plugin *plugin = cls;
1136   const struct sockaddr_in *v4;
1137   const struct sockaddr_in6 *v6;
1138   struct PrettyPrinterContext *ppc;
1139
1140   if ((addrlen != sizeof (struct sockaddr_in)) &&
1141       (addrlen != sizeof (struct sockaddr_in6)))
1142     {
1143       /* invalid address */
1144       GNUNET_break_op (0);
1145       asc (asc_cls, NULL);
1146       return;
1147     }
1148   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1149   ppc->asc = asc;
1150   ppc->asc_cls = asc_cls;
1151   if (addrlen == sizeof (struct sockaddr_in))
1152     {
1153       v4 = (const struct sockaddr_in *) addr;
1154       ppc->port = ntohs (v4->sin_port);
1155     }
1156   else
1157     {
1158       v6 = (const struct sockaddr_in6 *) addr;
1159       ppc->port = ntohs (v6->sin6_port);
1160
1161     }
1162   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1163                                 plugin->env->cfg,
1164                                 addr,
1165                                 addrlen,
1166                                 !numeric, timeout, &append_port, ppc);
1167 }
1168
1169
1170 /**
1171  * Update the last-received and bandwidth quota values
1172  * for this session.
1173  *
1174  * @param session session to update
1175  * @param force set to GNUNET_YES if we should update even
1176  *        though the minimum refresh time has not yet expired
1177  */
1178 static void
1179 update_quota (struct Session *session, int force)
1180 {
1181   struct GNUNET_TIME_Absolute now;
1182   unsigned long long delta;
1183   unsigned long long total_allowed;
1184   unsigned long long total_remaining;
1185
1186   now = GNUNET_TIME_absolute_get ();
1187   delta = now.value - session->last_quota_update.value;
1188   if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
1189     return;                     /* too early, not enough data */
1190
1191   total_allowed = session->quota_in * delta;
1192   if (total_allowed > session->last_received)
1193     {
1194       /* got less than acceptable */
1195       total_remaining = total_allowed - session->last_received;
1196       session->last_received = 0;
1197       delta = total_remaining / session->quota_in;      /* bonus seconds */
1198       if (delta > MAX_BANDWIDTH_CARRY)
1199         delta = MAX_BANDWIDTH_CARRY;    /* limit amount of carry-over */
1200     }
1201   else
1202     {
1203       /* got more than acceptable */
1204       session->last_received -= total_allowed;
1205       delta = 0;
1206     }
1207   session->last_quota_update.value = now.value - delta;
1208 }
1209
1210
1211 /**
1212  * Set a quota for receiving data from the given peer; this is a
1213  * per-transport limit.  The transport should limit its read/select
1214  * calls to stay below the quota (in terms of incoming data).
1215  *
1216  * @param cls closure
1217  * @param target the peer for whom the quota is given
1218  * @param quota_in quota for receiving/sending data in bytes per ms
1219  */
1220 static void
1221 tcp_plugin_set_receive_quota (void *cls,
1222                               const struct GNUNET_PeerIdentity *target,
1223                               uint32_t quota_in)
1224 {
1225   struct Plugin *plugin = cls;
1226   struct Session *session;
1227
1228   session = find_session_by_target (plugin, target);
1229   if (session == NULL)
1230     return;                     /* peer must have disconnected, ignore */
1231   if (session->quota_in != quota_in)
1232     {
1233       update_quota (session, GNUNET_YES);
1234       if (session->quota_in > quota_in)
1235         session->last_quota_update = GNUNET_TIME_absolute_get ();
1236       session->quota_in = quota_in;
1237     }
1238 }
1239
1240
1241 /**
1242  * Check if the given port is plausible (must be either
1243  * our listen port or our advertised port).  If it is
1244  * neither, we return one of these two ports at random.
1245  *
1246  * @return either in_port or a more plausible port
1247  */
1248 static uint16_t
1249 check_port (struct Plugin *plugin, uint16_t in_port)
1250 {
1251   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1252     return in_port;
1253   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1254                                     2) == 0)
1255     ? plugin->open_port : plugin->adv_port;
1256 }
1257
1258
1259 /**
1260  * Another peer has suggested an address for this peer and transport
1261  * plugin.  Check that this could be a valid address.
1262  *
1263  * @param cls closure
1264  * @param addr pointer to the address
1265  * @param addrlen length of addr
1266  * @return GNUNET_OK if this is a plausible address for this peer
1267  *         and transport
1268  */
1269 static int
1270 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1271 {
1272   struct Plugin *plugin = cls;
1273   char buf[sizeof (struct sockaddr_in6)];
1274   struct sockaddr_in *v4;
1275   struct sockaddr_in6 *v6;
1276
1277   if ((addrlen != sizeof (struct sockaddr_in)) &&
1278       (addrlen != sizeof (struct sockaddr_in6)))
1279     {
1280       GNUNET_break_op (0);
1281       return GNUNET_SYSERR;
1282     }
1283   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1284   if (addrlen == sizeof (struct sockaddr_in))
1285     {
1286       v4 = (struct sockaddr_in *) buf;
1287       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1288     }
1289   else
1290     {
1291       v6 = (struct sockaddr_in6 *) buf;
1292       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1293     }
1294 #if DEBUG_TCP
1295   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1296                    "tcp",
1297                    "Informing transport service about my address `%s'.\n",
1298                    GNUNET_a2s (addr, addrlen));
1299 #endif
1300   return GNUNET_OK;
1301 }
1302
1303
1304 /**
1305  * We've received a welcome from this peer via TCP.  Possibly create a
1306  * fresh client record and send back our welcome.
1307  *
1308  * @param cls closure
1309  * @param client identification of the client
1310  * @param message the actual message
1311  */
1312 static void
1313 handle_tcp_welcome (void *cls,
1314                     struct GNUNET_SERVER_Client *client,
1315                     const struct GNUNET_MessageHeader *message)
1316 {
1317   struct Plugin *plugin = cls;
1318   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1319   struct Session *session_c;
1320   size_t alen;
1321   void *vaddr;
1322
1323 #if DEBUG_TCP
1324   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1325                    "tcp",
1326                    "Received `%s' message from `%4s/%p'.\n", "WELCOME",
1327                    GNUNET_i2s (&wm->clientIdentity), client);
1328 #endif
1329   session_c = find_session_by_client (plugin, client);
1330   if (session_c == NULL)
1331     {
1332       vaddr = NULL;
1333       GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1334       /* FIXME: keep vaddr / alen! */
1335       GNUNET_SERVER_client_keep (client);
1336       session_c = create_session (plugin,
1337                                   &wm->clientIdentity, client);
1338 #if DEBUG_TCP
1339       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1340                        "tcp",
1341                        "Creating new session %p for incoming `%s' message.\n",
1342                        session_c, "WELCOME");
1343 #endif
1344       GNUNET_free_non_null (vaddr);
1345       process_pending_messages (session_c);
1346     }
1347   if (session_c->expecting_welcome != GNUNET_YES)
1348     {
1349       GNUNET_break_op (0);
1350       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1351       return;
1352     }
1353   session_c->expecting_welcome = GNUNET_NO;
1354   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1355 }
1356
1357
1358 /**
1359  * Calculate how long we should delay reading from the TCP socket to
1360  * ensure that we stay within our bandwidth limits (push back).
1361  *
1362  * @param session for which client should this be calculated
1363  */
1364 static struct GNUNET_TIME_Relative
1365 calculate_throttle_delay (struct Session *session)
1366 {
1367   struct GNUNET_TIME_Relative ret;
1368   struct GNUNET_TIME_Absolute now;
1369   uint64_t del;
1370   uint64_t avail;
1371   uint64_t excess;
1372
1373   now = GNUNET_TIME_absolute_get ();
1374   del = now.value - session->last_quota_update.value;
1375   if (del > MAX_BANDWIDTH_CARRY)
1376     {
1377       update_quota (session, GNUNET_YES);
1378       del = now.value - session->last_quota_update.value;
1379       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1380     }
1381   if (session->quota_in == 0)
1382     session->quota_in = 1;      /* avoid divison by zero */
1383   avail = del * session->quota_in;
1384   if (avail > session->last_received)
1385     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1386   excess = session->last_received - avail;
1387   ret.value = excess / session->quota_in;
1388   return ret;
1389 }
1390
1391
1392 /**
1393  * Task to signal the server that we can continue
1394  * receiving from the TCP client now.
1395  */
1396 static void
1397 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1398 {
1399   struct Session *session = cls;
1400   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1401 }
1402
1403
1404 /**
1405  * We've received data for this peer via TCP.  Unbox,
1406  * compute latency and forward.
1407  *
1408  * @param cls closure
1409  * @param client identification of the client
1410  * @param message the actual message
1411  */
1412 static void
1413 handle_tcp_data (void *cls,
1414                  struct GNUNET_SERVER_Client *client,
1415                  const struct GNUNET_MessageHeader *message)
1416 {
1417   struct Plugin *plugin = cls;
1418   struct Session *session;
1419   const struct DataMessage *dm;
1420   uint16_t msize;
1421   const struct GNUNET_MessageHeader *msg;
1422   struct GNUNET_TIME_Relative latency;
1423   struct GNUNET_TIME_Absolute ttime;
1424   struct GNUNET_TIME_Absolute now;
1425   struct GNUNET_TIME_Relative delay;
1426   uint64_t ack_in;
1427
1428   msize = ntohs (message->size);
1429   if ((msize <
1430        sizeof (struct DataMessage) + sizeof (struct GNUNET_MessageHeader)))
1431     {
1432       GNUNET_break_op (0);
1433       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1434       return;
1435     }
1436   session = find_session_by_client (plugin, client);
1437   if ((NULL == session) || (GNUNET_NO != session->expecting_welcome))
1438     {
1439       GNUNET_break_op (0);
1440       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1441       return;
1442     }
1443 #if DEBUG_TCP
1444   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1445                    "tcp", "Receiving %u bytes from `%4s'.\n",
1446                    msize, GNUNET_i2s (&session->target));
1447 #endif
1448   dm = (const struct DataMessage *) message;
1449   session->max_in_msg_counter = GNUNET_MAX (session->max_in_msg_counter,
1450                                             GNUNET_ntohll (dm->ack_out));
1451   msg = (const struct GNUNET_MessageHeader *) &dm[1];
1452   if (msize != sizeof (struct DataMessage) + ntohs (msg->size))
1453     {
1454       GNUNET_break_op (0);
1455       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1456       return;
1457     }
1458   /* estimate latency */
1459   ack_in = GNUNET_ntohll (dm->ack_in);
1460   if ((ack_in <= session->out_msg_counter) &&
1461       (session->out_msg_counter - ack_in < ACK_LOG_SIZE))
1462     {
1463       delay = GNUNET_TIME_relative_ntoh (dm->delay);
1464       ttime = session->gen_time[ack_in % ACK_LOG_SIZE];
1465       now = GNUNET_TIME_absolute_get ();
1466       if (delay.value > now.value - ttime.value)
1467         delay.value = 0;        /* not plausible */
1468       /* update (round-trip) latency using ageing; we
1469          use 7:1 so that we can reasonably quickly react
1470          to changes, but not so fast that latency is largely
1471          jitter... */
1472       session->latency_estimate
1473         = ((7 * session->latency_estimate) +
1474            (now.value - ttime.value - delay.value)) / 8;
1475     }
1476   latency.value = (uint64_t) session->latency_estimate;
1477   /* deliver on */
1478 #if DEBUG_TCP
1479   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1480                    "tcp",
1481                    "Forwarding data of type %u to transport service.\n",
1482                    ntohs (msg->type));
1483 #endif
1484   plugin->env->receive (plugin->env->cls, 1,
1485                         NULL, 0, /* FIXME: sender IP! */
1486                         &session->target, msg);
1487   /* update bandwidth used */
1488   session->last_received += msize;
1489   update_quota (session, GNUNET_NO);
1490
1491   delay = calculate_throttle_delay (session);
1492   if (delay.value == 0)
1493     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1494   else
1495     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1496                                   delay, &delayed_done, session);
1497 }
1498
1499
1500 /**
1501  * Handlers for the various TCP messages.
1502  */
1503 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1504   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 
1505    sizeof (struct WelcomeMessage)},
1506   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1507   {NULL, NULL, 0, 0}
1508 };
1509
1510
1511 static void
1512 create_tcp_handlers (struct Plugin *plugin)
1513 {
1514   unsigned int i;
1515   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1516   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1517   for (i = 0;
1518        i <
1519        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1520        i++)
1521     plugin->handlers[i].callback_cls = plugin;
1522   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1523 }
1524
1525
1526 /**
1527  * Functions with this signature are called whenever a peer
1528  * is disconnected on the network level.
1529  *
1530  * @param cls closure
1531  * @param client identification of the client
1532  */
1533 static void
1534 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1535 {
1536   struct Plugin *plugin = cls;
1537   struct Session *session;
1538
1539   session = find_session_by_client (plugin, client);
1540   if (session == NULL)
1541     return;                     /* unknown, nothing to do */
1542 #if DEBUG_TCP
1543   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1544                    "tcp",
1545                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1546                    GNUNET_i2s (&session->target),
1547                    (session->connect_addr != NULL) ?
1548                    GNUNET_a2s (session->connect_addr,
1549                                session->connect_alen) : "*", client);
1550 #endif
1551   disconnect_session (session);
1552 }
1553
1554
1555 /**
1556  * Add the IP of our network interface to the list of
1557  * our external IP addresses.
1558  */
1559 static int
1560 process_interfaces (void *cls,
1561                     const char *name,
1562                     int isDefault,
1563                     const struct sockaddr *addr, socklen_t addrlen)
1564 {
1565   struct Plugin *plugin = cls;
1566   int af;
1567   struct sockaddr_in *v4;
1568   struct sockaddr_in6 *v6;
1569
1570   af = addr->sa_family;
1571   if (af == AF_INET)
1572     {
1573       v4 = (struct sockaddr_in *) addr;
1574       v4->sin_port = htons (plugin->adv_port);
1575     }
1576   else
1577     {
1578       GNUNET_assert (af == AF_INET6);
1579       v6 = (struct sockaddr_in6 *) addr;
1580       v6->sin6_port = htons (plugin->adv_port);
1581     }
1582   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1583                    GNUNET_ERROR_TYPE_BULK,
1584                    "tcp", _("Found address `%s' (%s)\n"),
1585                    GNUNET_a2s (addr, addrlen), name);
1586   plugin->env->notify_address (plugin->env->cls,
1587                                "tcp",
1588                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1589   return GNUNET_OK;
1590 }
1591
1592
1593 /**
1594  * Function called by the resolver for each address obtained from DNS
1595  * for our own hostname.  Add the addresses to the list of our
1596  * external IP addresses.
1597  *
1598  * @param cls closure
1599  * @param addr one of the addresses of the host, NULL for the last address
1600  * @param addrlen length of the address
1601  */
1602 static void
1603 process_hostname_ips (void *cls,
1604                       const struct sockaddr *addr, socklen_t addrlen)
1605 {
1606   struct Plugin *plugin = cls;
1607
1608   if (addr == NULL)
1609     {
1610       plugin->hostname_dns = NULL;
1611       return;
1612     }
1613   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1614 }
1615
1616
1617 /**
1618  * Entry point for the plugin.
1619  */
1620 void *
1621 libgnunet_plugin_transport_tcp_init (void *cls)
1622 {
1623   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1624   struct GNUNET_TRANSPORT_PluginFunctions *api;
1625   struct Plugin *plugin;
1626   struct GNUNET_SERVICE_Context *service;
1627   unsigned long long aport;
1628   unsigned long long bport;
1629
1630   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1631   if (service == NULL)
1632     {
1633       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1634                        "tcp",
1635                        _
1636                        ("Failed to start service for `%s' transport plugin.\n"),
1637                        "tcp");
1638       return NULL;
1639     }
1640   aport = 0;
1641   if ((GNUNET_OK !=
1642        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1643                                               "transport-tcp",
1644                                               "PORT",
1645                                               &bport)) ||
1646       (bport > 65535) ||
1647       ((GNUNET_OK ==
1648         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1649                                                "transport-tcp",
1650                                                "ADVERTISED-PORT",
1651                                                &aport)) && (aport > 65535)))
1652     {
1653       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1654                        "tcp",
1655                        _
1656                        ("Require valid port number for service `%s' in configuration!\n"),
1657                        "transport-tcp");
1658       GNUNET_SERVICE_stop (service);
1659       return NULL;
1660     }
1661   if (aport == 0)
1662     aport = bport;
1663   plugin = GNUNET_malloc (sizeof (struct Plugin));
1664   plugin->open_port = bport;
1665   plugin->adv_port = aport;
1666   plugin->env = env;
1667   plugin->lsock = NULL;
1668   plugin->statistics = NULL;
1669   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1670   api->cls = plugin;
1671   api->send = &tcp_plugin_send;
1672   api->disconnect = &tcp_plugin_disconnect;
1673   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1674   api->set_receive_quota = &tcp_plugin_set_receive_quota;
1675   api->check_address = &tcp_plugin_check_address;
1676   plugin->service = service;
1677   plugin->server = GNUNET_SERVICE_get_server (service);
1678   create_tcp_handlers (plugin);
1679   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1680                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1681   if (aport != bport)
1682     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1683                      "tcp",
1684                      _
1685                      ("TCP transport advertises itself as being on port %llu\n"),
1686                      aport);
1687   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1688                                    plugin);
1689   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1690   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1691                                                            env->cfg,
1692                                                            AF_UNSPEC,
1693                                                            HOSTNAME_RESOLVE_TIMEOUT,
1694                                                            &process_hostname_ips,
1695                                                            plugin);
1696   return api;
1697 }
1698
1699
1700 /**
1701  * Exit point from the plugin.
1702  */
1703 void *
1704 libgnunet_plugin_transport_tcp_done (void *cls)
1705 {
1706   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1707   struct Plugin *plugin = api->cls;
1708   struct Session *session;
1709
1710   while (NULL != (session = plugin->sessions))
1711     disconnect_session (session);
1712   if (NULL != plugin->hostname_dns)
1713     {
1714       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1715       plugin->hostname_dns = NULL;
1716     }
1717   GNUNET_SERVICE_stop (plugin->service);
1718   GNUNET_free (plugin->handlers);
1719   GNUNET_free (plugin);
1720   GNUNET_free (api);
1721   return NULL;
1722 }
1723
1724 /* end of plugin_transport_tcp.c */