doxygen
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, 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/transport_api.c
23  * @brief library to access the low-level P2P IO service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_bandwidth_lib.h"
28 #include "gnunet_client_lib.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_container_lib.h"
31 #include "gnunet_arm_service.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_time_lib.h"
36 #include "gnunet_transport_service.h"
37 #include "transport.h"
38
39 /**
40  * After how long do we give up on transmitting a HELLO
41  * to the service?
42  */
43 #define OFFER_HELLO_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
44
45 /**
46  * After how long do we automatically retry an unsuccessful
47  * CONNECT request?
48  */
49 #define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 750)
50
51 /**
52  * How long should ARM wait when starting up the
53  * transport service before reporting back?
54  */
55 #define START_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
56
57 /**
58  * How long should ARM wait when stopping the
59  * transport service before reporting back?
60  */
61 #define STOP_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
62
63 /**
64  * How large to start with for the hashmap of neighbours.
65  */
66 #define STARTING_NEIGHBOURS_SIZE 10
67
68
69 /**
70  * What stage are we in for transmission processing?
71  */
72 enum TransmitStage
73   {
74     /**
75      * No active message.
76      */
77     TS_NEW = 0,
78
79     /**
80      * Message in local queue, not given to service.
81      */
82     TS_QUEUED = 1,
83
84     /**
85      * Message given to service, not confirmed (no SEND_OK).
86      */
87     TS_TRANSMITTED = 2,
88
89     /**
90      * One message was given to service and before it was confirmed,
91      * another one was already queued (waiting for SEND_OK to pass on
92      * to service).
93      */
94     TS_TRANSMITTED_QUEUED = 3
95   };
96
97
98 /**
99  * Handle for a transmission-ready request.
100  */
101 struct GNUNET_TRANSPORT_TransmitHandle
102 {
103
104   /**
105    * Neighbour for this handle, NULL for control-traffic.
106    */
107   struct NeighbourList *neighbour;
108
109   /**
110    * Function to call when notify_size bytes are available
111    * for transmission.
112    */
113   GNUNET_CONNECTION_TransmitReadyNotify notify;
114
115   /**
116    * Closure for notify.
117    */
118   void *notify_cls;
119
120   /**
121    * transmit_ready task Id.  The task is used to introduce the
122    * artificial delay that may be required to maintain the bandwidth
123    * limits.  Later, this will be the ID of the "transmit_timeout"
124    * task which is used to signal a timeout if the transmission could
125    * not be done in a timely fashion.
126    */
127   GNUNET_SCHEDULER_TaskIdentifier notify_delay_task;
128
129   /**
130    * Timeout for this request.
131    */
132   struct GNUNET_TIME_Absolute timeout;
133
134   /**
135    * How many bytes is our notify callback waiting for?
136    */
137   size_t notify_size;
138
139   /**
140    * How important is this message?
141    */
142   unsigned int priority;
143
144 };
145
146
147 /**
148  * Handle for a control message queue entry.
149  */
150 struct ControlMessage
151 {
152
153   /**
154    * This is a doubly-linked list.
155    */
156   struct ControlMessage *next;
157
158   /**
159    * This is a doubly-linked list.
160    */
161   struct ControlMessage *prev;
162
163   /**
164    * Overall transport handle.
165    */
166   struct GNUNET_TRANSPORT_Handle *h;
167
168   /**
169    * Function to call when notify_size bytes are available
170    * for transmission.
171    */
172   GNUNET_CONNECTION_TransmitReadyNotify notify;
173
174   /**
175    * Closure for notify.
176    */
177   void *notify_cls;
178
179   /**
180    * transmit_ready task Id.  The task is used to introduce the
181    * artificial delay that may be required to maintain the bandwidth
182    * limits.  Later, this will be the ID of the "transmit_timeout"
183    * task which is used to signal a timeout if the transmission could
184    * not be done in a timely fashion.
185    */
186   GNUNET_SCHEDULER_TaskIdentifier notify_delay_task;
187
188   /**
189    * How many bytes is our notify callback waiting for?
190    */
191   size_t notify_size;
192
193 };
194
195 /**
196  * Context for storing information about attempted next transmission.
197  */
198 struct TryTransmitContext
199 {
200
201   /**
202    * Main transport handle.
203    */
204   struct GNUNET_TRANSPORT_Handle *h;
205
206   /**
207    * Returned transmission handle.
208    */
209   struct GNUNET_TRANSPORT_TransmitHandle *ret;
210
211   /**
212    * Time to retry the send task.
213    */
214   struct GNUNET_TIME_Relative retry_time;
215 };
216
217 /**
218  * Entry in hash table of all of our current neighbours.
219  */
220 struct NeighbourList
221 {
222   /**
223    * Overall transport handle.
224    */
225   struct GNUNET_TRANSPORT_Handle *h;
226
227   /**
228    * Active transmit handle; available if 'transmit_forbidden'
229    * is GNUNET_NO.
230    */
231   struct GNUNET_TRANSPORT_TransmitHandle transmit_handle;
232
233   /**
234    * Identity of this neighbour.
235    */
236   struct GNUNET_PeerIdentity id;
237
238   /**
239    * Outbound bandwidh tracker.
240    */
241   struct GNUNET_BANDWIDTH_Tracker out_tracker;
242
243   /**
244    * Set to GNUNET_NO if we are currently allowed to accept a
245    * message to the transport service for this peer, GNUNET_YES
246    * if we have one and are waiting for transmission, GNUNET_SYSERR
247    * if we are waiting for confirmation AND have already accepted
248    * yet another message.
249    */
250   enum TransmitStage transmit_stage;
251
252   /**
253    * Have we received a notification that this peer is connected
254    * to us right now?
255    */
256   int is_connected;
257
258   /**
259    * Are we in the middle of disconnecting the peer already?
260    */
261   unsigned int in_disconnect;
262
263 };
264
265
266 /**
267  * Linked list of requests from clients for our HELLO that were
268  * deferred.
269  */
270 struct HelloWaitList
271 {
272
273   /**
274    * This is a linked list.
275    */
276   struct HelloWaitList *next;
277
278   /**
279    * Reference back to our transport handle.
280    */
281   struct GNUNET_TRANSPORT_Handle *handle;
282
283   /**
284    * Callback to call once we got our HELLO.
285    */
286   GNUNET_TRANSPORT_HelloUpdateCallback rec;
287
288   /**
289    * Closure for rec.
290    */
291   void *rec_cls;
292
293 };
294
295
296 /**
297  * Handle for the transport service (includes all of the
298  * state for the transport service).
299  */
300 struct GNUNET_TRANSPORT_Handle
301 {
302
303   /**
304    * Closure for the callbacks.
305    */
306   void *cls;
307
308   /**
309    * Function to call for received data.
310    */
311   GNUNET_TRANSPORT_ReceiveCallback rec;
312
313   /**
314    * function to call on connect events
315    */
316   GNUNET_TRANSPORT_NotifyConnect nc_cb;
317
318   /**
319    * function to call on disconnect events
320    */
321   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
322
323   /**
324    * Head of DLL of control messages.
325    */
326   struct ControlMessage *control_head;
327
328   /**
329    * Tail of DLL of control messages.
330    */
331   struct ControlMessage *control_tail;
332
333   /**
334    * The current HELLO message for this peer.  Updated
335    * whenever transports change their addresses.
336    */
337   struct GNUNET_HELLO_Message *my_hello;
338
339   /**
340    * My client connection to the transport service.
341    */
342   struct GNUNET_CLIENT_Connection *client;
343
344   /**
345    * Handle to our registration with the client for notification.
346    */
347   struct GNUNET_CLIENT_TransmitHandle *network_handle;
348
349   /**
350    * Linked list of pending requests for our HELLO.
351    */
352   struct HelloWaitList *hwl_head;
353
354   /**
355    * My configuration.
356    */
357   const struct GNUNET_CONFIGURATION_Handle *cfg;
358
359   /**
360    * Linked list of the current neighbours of this peer.
361    */
362   struct GNUNET_CONTAINER_MultiHashMap *neighbours;
363
364   /**
365    * Peer identity as assumed by this process, or all zeros.
366    */
367   struct GNUNET_PeerIdentity self;
368
369   /**
370    * ID of the task trying to reconnect to the service.
371    */
372   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
373
374   /**
375    * ID of the task trying to trigger transmission for a peer
376    * while maintaining bandwidth quotas.
377    */
378   GNUNET_SCHEDULER_TaskIdentifier quota_task;
379
380   /**
381    * Delay until we try to reconnect.
382    */
383   struct GNUNET_TIME_Relative reconnect_delay;
384
385   /**
386    * Set once we are in the process of disconnecting from the
387    * service.
388    */
389   int in_disconnect;
390
391   /**
392    * Should we check that 'self' matches what the service thinks?
393    * (if GNUNET_NO, then 'self' is all zeros!).
394    */
395   int check_self;
396 };
397
398
399 /**
400  * Get the neighbour list entry for the given peer
401  *
402  * @param h our context
403  * @param peer peer to look up
404  * @return NULL if no such peer entry exists
405  */
406 static struct NeighbourList *
407 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
408                 const struct GNUNET_PeerIdentity *peer)
409 {
410   return GNUNET_CONTAINER_multihashmap_get(h->neighbours, &peer->hashPubKey);
411 }
412
413
414 /**
415  * Schedule the task to send one message, either from the control
416  * list or the peer message queues  to the service.
417  */
418 static void schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
419
420
421 /**
422  * Function called by the scheduler when the timeout for bandwidth
423  * availablility for the target neighbour is reached.
424  *
425  * @param cls the 'struct GNUNET_TRANSPORT_Handle*'
426  * @param tc scheduler context
427  */
428 static void
429 quota_transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
430 {
431   struct GNUNET_TRANSPORT_Handle *h = cls;
432
433   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
434   schedule_transmission (h);
435 }
436
437
438 /**
439  * Iterator over hash map entries, attempt to schedule
440  * a transmission to entries in the neighbour hashmap.
441  *
442  * @param cls closure a TryTransmitContext
443  * @param key current key code
444  * @param value value in the hash map, the neighbour entry to consider
445  * @return GNUNET_YES if we should continue to
446  *         iterate,
447  *         GNUNET_NO if not.
448  */
449 static int
450 try_schedule_transmission (void *cls,
451                            const GNUNET_HashCode * key,
452                            void *value)
453 {
454   struct NeighbourList *n = value;
455   struct TryTransmitContext *try_transmit_ctx = cls;
456   struct GNUNET_TIME_Relative duration;
457   GNUNET_CONNECTION_TransmitReadyNotify notify;
458   struct GNUNET_TRANSPORT_TransmitHandle *th;
459   struct GNUNET_TIME_Absolute duration_abs;
460
461   if (n->transmit_stage != TS_QUEUED)
462     return GNUNET_YES; /* not eligible, keep iterating */
463   if (n->is_connected != GNUNET_YES)
464     return GNUNET_YES; /* keep iterating */
465
466   th = &n->transmit_handle;
467   GNUNET_break (n == th->neighbour);
468   /* check outgoing quota */
469   duration = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
470                                                  th->notify_size - sizeof (struct OutboundMessage));
471   duration_abs = GNUNET_TIME_relative_to_absolute (duration);
472   if (th->timeout.abs_value < duration_abs.abs_value)
473     {
474       /* signal timeout! */
475 #if DEBUG_TRANSPORT
476       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
477                   "Would need %llu ms before bandwidth is available for delivery to `%4s', that is too long.  Signaling timeout.\n",
478                   duration.rel_value,
479                   GNUNET_i2s (&n->id));
480 #endif
481       if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
482         {
483           GNUNET_SCHEDULER_cancel (th->notify_delay_task);
484           th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
485         }
486       n->transmit_stage = TS_NEW;
487       if (NULL != (notify = th->notify))
488         {
489           th->notify = NULL;
490           GNUNET_assert (0 == notify (th->notify_cls, 0, NULL));
491         }
492       return GNUNET_YES; /* keep iterating */
493     }
494   if (duration.rel_value > 0)
495     {
496 #if DEBUG_TRANSPORT
497       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
498                   "Need more bandwidth (%u b/s allowed, %u b needed), delaying delivery to `%4s' by %llu ms\n",
499                   (unsigned int) n->out_tracker.available_bytes_per_s__,
500                   (unsigned int) th->notify_size - sizeof (struct OutboundMessage),
501                   GNUNET_i2s (&n->id),
502                   (unsigned long long) duration.rel_value);
503 #endif
504       try_transmit_ctx->retry_time = GNUNET_TIME_relative_min (try_transmit_ctx->retry_time,
505                                                                duration);
506       return GNUNET_YES; /* keep iterating */
507     }
508 #if DEBUG_TRANSPORT
509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510               "Have %u bytes of bandwidth available for transmission to `%4s' right now\n",
511               th->notify_size - sizeof (struct OutboundMessage),
512               GNUNET_i2s (&n->id));
513 #endif
514
515   if ( (try_transmit_ctx->ret == NULL) ||
516        (try_transmit_ctx->ret->priority < th->priority) )
517     try_transmit_ctx->ret = th;
518   return GNUNET_YES;
519 }
520
521
522 /**
523  * Figure out which transmission to a peer can be done right now.
524  * If none can, schedule a task to call 'schedule_transmission'
525  * whenever a peer transmission can be done in the future and
526  * return NULL.  Otherwise return the next transmission to be
527  * performed.
528  *
529  * @param h handle to transport
530  * @return NULL to wait longer before doing any peer transmissions
531  */
532 static struct GNUNET_TRANSPORT_TransmitHandle *
533 schedule_peer_transmission (struct GNUNET_TRANSPORT_Handle *h)
534 {
535   struct TryTransmitContext try_transmit_ctx;
536
537   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
538     {
539       GNUNET_SCHEDULER_cancel (h->quota_task);
540       h->quota_task = GNUNET_SCHEDULER_NO_TASK;
541     }
542   try_transmit_ctx.h = h;
543   try_transmit_ctx.ret = NULL;
544   try_transmit_ctx.retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
545   GNUNET_CONTAINER_multihashmap_iterate(h->neighbours, 
546                                         &try_schedule_transmission, 
547                                         &try_transmit_ctx);
548   if (try_transmit_ctx.ret == NULL)
549     h->quota_task = GNUNET_SCHEDULER_add_delayed (try_transmit_ctx.retry_time,
550                                                   &quota_transmit_ready,
551                                                   h);
552   return try_transmit_ctx.ret;
553 }
554
555
556 /**
557  * Transmit message(s) to service.
558  *
559  * @param cls handle to transport
560  * @param size number of bytes available in buf
561  * @param buf where to copy the message
562  * @return number of bytes copied to buf
563  */
564 static size_t
565 transport_notify_ready (void *cls, size_t size, void *buf)
566 {
567   struct GNUNET_TRANSPORT_Handle *h = cls;
568   struct ControlMessage *cm;
569   struct GNUNET_TRANSPORT_TransmitHandle *th;
570   struct NeighbourList *n;
571   struct OutboundMessage obm;
572   GNUNET_CONNECTION_TransmitReadyNotify notify;
573   size_t ret;
574   size_t mret;
575   size_t nret;
576   char *cbuf;
577
578   h->network_handle = NULL;
579   if (buf == NULL)
580     {
581       schedule_transmission (h);
582       return 0;
583     }
584 #if DEBUG_TRANSPORT
585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
586               "Ready to transmit %u bytes to transport service\n", size);
587 #endif
588   cbuf = buf;
589   ret = 0;
590   while ( (NULL != (cm = h->control_head)) &&
591           (cm->notify_size <= size) )
592     {
593       if (cm->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
594         {
595           GNUNET_SCHEDULER_cancel (cm->notify_delay_task);
596           cm->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
597         }
598       GNUNET_CONTAINER_DLL_remove (h->control_head,
599                                    h->control_tail,
600                                    cm);
601       nret = cm->notify (cm->notify_cls, size, &cbuf[ret]);
602 #if DEBUG_TRANSPORT
603       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
604                   "Added %u bytes of control message at %u\n",
605                   nret,
606                   ret);
607 #endif
608       GNUNET_free (cm);
609       ret += nret;
610       size -= nret;
611     }
612   while ( (NULL != (th = schedule_peer_transmission (h))) &&
613           (th->notify_size <= size) )
614     {
615       if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
616         {
617           GNUNET_SCHEDULER_cancel (th->notify_delay_task);
618           th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
619         }
620       n = th->neighbour;
621       switch (n->transmit_stage)
622         {
623         case TS_NEW:
624           GNUNET_break (0);
625           break;
626         case TS_QUEUED:
627           n->transmit_stage = TS_TRANSMITTED;
628           break;
629         case TS_TRANSMITTED:
630           GNUNET_break (0);
631           break;
632         case TS_TRANSMITTED_QUEUED:
633           GNUNET_break (0);
634           break;
635         default:
636           GNUNET_break (0);
637         }
638       GNUNET_assert (size >= sizeof (struct OutboundMessage));
639       notify = th->notify;
640       th->notify = NULL;
641       mret = notify (th->notify_cls,
642                      size - sizeof (struct OutboundMessage),
643                      &cbuf[ret + sizeof (struct OutboundMessage)]);
644       GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
645 #if DEBUG_TRANSPORT
646       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
647                   "Message of %u bytes with timeout %llums constructed for `%4s'\n",
648                   (unsigned int) mret,
649                   (unsigned long long) GNUNET_TIME_absolute_get_remaining (th->timeout).rel_value,
650                   GNUNET_i2s (&n->id));
651 #endif
652       if (mret != 0)    
653         {
654           GNUNET_assert (mret + sizeof (struct OutboundMessage) < GNUNET_SERVER_MAX_MESSAGE_SIZE);
655           obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
656           obm.header.size = htons (mret + sizeof (struct OutboundMessage));
657           obm.priority = htonl (th->priority);
658           obm.timeout = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (th->timeout));
659           obm.peer = n->id;
660           memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
661           ret += (mret + sizeof (struct OutboundMessage));
662           size -= (mret + sizeof (struct OutboundMessage));
663           GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
664         }
665       else
666         {
667           switch (n->transmit_stage)
668             {
669             case TS_NEW:
670               GNUNET_break (0);
671               break;
672             case TS_QUEUED:
673               GNUNET_break (0);
674               break;
675             case TS_TRANSMITTED:
676               n->transmit_stage = TS_NEW;
677               break;
678             case TS_TRANSMITTED_QUEUED:
679               n->transmit_stage = TS_QUEUED;
680               continue;
681             default:
682               GNUNET_break (0);
683             }
684         }
685     }
686   schedule_transmission (h);
687 #if DEBUG_TRANSPORT
688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689               "Transmitting %u bytes to transport service\n", ret);
690 #endif
691   return ret;
692 }
693
694
695 /**
696  * Schedule the task to send one message, either from the control
697  * list or the peer message queues  to the service.
698  */
699 static void
700 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
701 {
702   size_t size;
703   struct GNUNET_TIME_Relative timeout;
704   struct GNUNET_TRANSPORT_TransmitHandle *th;
705
706   if (NULL != h->network_handle)
707     return;
708   if (h->client == NULL)
709     {
710       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
711                   _("Could not yet schedule transmission: we are not yet connected to the transport service!\n"));
712       return;                   /* not yet connected */
713     }
714   if (NULL != h->control_head)
715     {
716       size = h->control_head->notify_size;
717       timeout = GNUNET_TIME_UNIT_FOREVER_REL;
718     }
719   else
720     {
721       th = schedule_peer_transmission (h);
722       if (th == NULL)
723         {
724           /* no transmission ready right now */
725 #if DEBUG_TRANSPORT
726           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
727                       "Could not yet schedule transmission: none ready\n");
728 #endif
729           return;
730         }
731       size = th->notify_size;
732       timeout = GNUNET_TIME_absolute_get_remaining (th->timeout);
733     }
734 #if DEBUG_TRANSPORT
735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736                 "Calling notify_transmit_ready\n");
737 #endif
738   h->network_handle =
739     GNUNET_CLIENT_notify_transmit_ready (h->client,
740                                          size,
741                                          timeout,
742                                          GNUNET_NO,
743                                          &transport_notify_ready,
744                                          h);
745   GNUNET_assert (NULL != h->network_handle);
746 }
747
748
749 /**
750  * Called when our transmit request timed out before any transport
751  * reported success connecting to the desired peer or before the
752  * transport was ready to receive.  Signal error and free
753  * TransmitHandle.
754  */
755 static void
756 control_transmit_timeout (void *cls,
757                           const struct GNUNET_SCHEDULER_TaskContext *tc)
758 {
759   struct ControlMessage *th = cls;
760
761   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
762   if (NULL != th->notify)    
763     th->notify (th->notify_cls, 0, NULL);    
764   GNUNET_CONTAINER_DLL_remove (th->h->control_head,
765                                th->h->control_tail,
766                                th);
767   GNUNET_free (th);
768 }
769
770
771 /**
772  * Queue control request for transmission to the transport
773  * service.
774  *
775  * @param h handle to the transport service
776  * @param size number of bytes to be transmitted
777  * @param at_head request must be added to the head of the queue
778  *        (otherwise request will be appended)
779  * @param timeout how long this transmission can wait (at most)
780  * @param notify function to call to get the content
781  * @param notify_cls closure for notify
782  */
783 static void
784 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h,
785                            size_t size,
786                            int at_head,
787                            struct GNUNET_TIME_Relative timeout,
788                            GNUNET_CONNECTION_TransmitReadyNotify notify,
789                            void *notify_cls)
790 {
791   struct ControlMessage *cm;
792
793 #if DEBUG_TRANSPORT
794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795               "Control transmit of %u bytes within %llums requested\n",
796               size, (unsigned long long) timeout.rel_value);
797 #endif
798   cm = GNUNET_malloc (sizeof (struct ControlMessage));
799   cm->h = h;
800   cm->notify = notify;
801   cm->notify_cls = notify_cls;
802   cm->notify_size = size;
803   cm->notify_delay_task
804     = GNUNET_SCHEDULER_add_delayed (timeout, &control_transmit_timeout, cm);
805   if (at_head)
806     GNUNET_CONTAINER_DLL_insert (h->control_head,
807                                  h->control_tail,
808                                  cm);
809   else
810     GNUNET_CONTAINER_DLL_insert_after (h->control_head,
811                                        h->control_tail,
812                                        h->control_tail,
813                                        cm);
814   schedule_transmission (h);
815 }
816
817
818 /**
819  * FIXME: document
820  */
821 struct SetQuotaContext
822 {
823   /**
824    * FIXME: document
825    */
826   struct GNUNET_TRANSPORT_Handle *handle;
827
828   /**
829    * FIXME: document
830    */
831   struct GNUNET_PeerIdentity target;
832
833   /**
834    * FIXME: document
835    */
836   GNUNET_SCHEDULER_Task cont;
837
838   /**
839    * Closure for 'cont'.
840    */
841   void *cont_cls;
842
843   /**
844    * FIXME: document
845    */
846   struct GNUNET_TIME_Absolute timeout;
847
848   /**
849    * FIXME: document
850    */
851   struct GNUNET_BANDWIDTH_Value32NBO quota_in;
852 };
853
854
855 /**
856  * Send SET_QUOTA message to the service.
857  *
858  * @param cls the 'struct SetQuotaContext'
859  * @param size number of bytes available in buf
860  * @param buf where to copy the message
861  * @return number of bytes copied to buf
862  */
863 static size_t
864 send_set_quota (void *cls, size_t size, void *buf)
865 {
866   struct SetQuotaContext *sqc = cls;
867   struct QuotaSetMessage *msg;
868
869   if (buf == NULL)
870     {
871       if (sqc->cont != NULL)
872         GNUNET_SCHEDULER_add_continuation (sqc->cont,
873                                            sqc->cont_cls,
874                                            GNUNET_SCHEDULER_REASON_TIMEOUT);
875       GNUNET_free (sqc);
876       return 0;
877     }
878 #if DEBUG_TRANSPORT
879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880               "Transmitting `%s' request with respect to `%4s'.\n",
881               "SET_QUOTA",
882               GNUNET_i2s (&sqc->target));
883 #endif
884   GNUNET_assert (size >= sizeof (struct QuotaSetMessage));
885   msg = buf;
886   msg->header.size = htons (sizeof (struct QuotaSetMessage));
887   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
888   msg->quota = sqc->quota_in;
889   memcpy (&msg->peer, &sqc->target, sizeof (struct GNUNET_PeerIdentity));
890   if (sqc->cont != NULL)
891     GNUNET_SCHEDULER_add_continuation (sqc->cont,
892                                        sqc->cont_cls,
893                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
894   GNUNET_free (sqc);
895   return sizeof (struct QuotaSetMessage);
896 }
897
898
899 /**
900  * Set the share of incoming bandwidth for the given
901  * peer to the specified amount.
902  *
903  * @param handle connection to transport service
904  * @param target who's bandwidth quota is being changed
905  * @param quota_in incoming bandwidth quota in bytes per ms
906  * @param quota_out outgoing bandwidth quota in bytes per ms
907  * @param timeout how long to wait until signaling failure if
908  *        we can not communicate the quota change
909  * @param cont continuation to call when done, will be called
910  *        either with reason "TIMEOUT" or with reason "PREREQ_DONE"
911  * @param cont_cls closure for continuation
912  */
913 void
914 GNUNET_TRANSPORT_set_quota (struct GNUNET_TRANSPORT_Handle *handle,
915                             const struct GNUNET_PeerIdentity *target,
916                             struct GNUNET_BANDWIDTH_Value32NBO quota_in,
917                             struct GNUNET_BANDWIDTH_Value32NBO quota_out,
918                             struct GNUNET_TIME_Relative timeout,
919                             GNUNET_SCHEDULER_Task cont, void *cont_cls)
920 {
921   struct NeighbourList *n;
922   struct SetQuotaContext *sqc;
923
924   n = neighbour_find (handle, target);
925   if (n != NULL)
926     {
927 #if DEBUG_TRANSPORT
928       if (ntohl (quota_out.value__) != n->out_tracker.available_bytes_per_s__)
929         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930                     "Quota changed from %u to %u for peer `%s'\n",
931                     (unsigned int) n->out_tracker.available_bytes_per_s__,
932                     (unsigned int) ntohl (quota_out.value__),
933                     GNUNET_i2s (target));
934       else
935         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
936                     "Quota remains at %u for peer `%s'\n",
937                     (unsigned int) n->out_tracker.available_bytes_per_s__,
938                     GNUNET_i2s (target));
939 #endif
940       GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
941                                              quota_out);
942     }
943   else
944     {
945 #if DEBUG_TRANSPORT
946       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
947                   "Quota changed to %u for peer `%s', but I have no such neighbour!\n",
948                   (unsigned int) ntohl (quota_out.value__),
949                   GNUNET_i2s (target));
950 #endif
951     }
952   sqc = GNUNET_malloc (sizeof (struct SetQuotaContext));
953   sqc->handle = handle;
954   sqc->target = *target;
955   sqc->cont = cont;
956   sqc->cont_cls = cont_cls;
957   sqc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
958   sqc->quota_in = quota_in;
959   schedule_control_transmit (handle,
960                              sizeof (struct QuotaSetMessage),
961                              GNUNET_NO, timeout, &send_set_quota, sqc);
962 }
963
964
965 /**
966  * Obtain the HELLO message for this peer.
967  *
968  * @param handle connection to transport service
969  * @param rec function to call with the HELLO, sender will be our peer
970  *            identity; message and sender will be NULL on timeout
971  *            (handshake with transport service pending/failed).
972  *             cost estimate will be 0.
973  * @param rec_cls closure for rec
974  */
975 void
976 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
977                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
978                             void *rec_cls)
979 {
980   struct HelloWaitList *hwl;
981
982   hwl = GNUNET_malloc (sizeof (struct HelloWaitList));
983   hwl->next = handle->hwl_head;
984   handle->hwl_head = hwl;
985   hwl->handle = handle;
986   hwl->rec = rec;
987   hwl->rec_cls = rec_cls;
988   if (handle->my_hello == NULL)
989     return;
990   rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
991 }
992
993
994
995 /**
996  * Stop receiving updates about changes to our HELLO message.
997  *
998  * @param handle connection to transport service
999  * @param rec function previously registered to be called with the HELLOs
1000  * @param rec_cls closure for rec
1001  */
1002 void
1003 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_Handle *handle,
1004                                    GNUNET_TRANSPORT_HelloUpdateCallback rec,
1005                                    void *rec_cls)
1006 {
1007   struct HelloWaitList *pos;
1008   struct HelloWaitList *prev;
1009
1010   prev = NULL;
1011   pos = handle->hwl_head;
1012   while (pos != NULL)
1013     {
1014       if ( (pos->rec == rec) &&
1015            (pos->rec_cls == rec_cls) )
1016         break;
1017       prev = pos;
1018       pos = pos->next;
1019     }
1020   GNUNET_break (pos != NULL);
1021   if (pos == NULL)
1022     return;
1023   if (prev == NULL)
1024     handle->hwl_head = pos->next;
1025   else
1026     prev->next = pos->next;
1027   GNUNET_free (pos);
1028 }
1029
1030
1031 /**
1032  * Send HELLO message to the service.
1033  *
1034  * @param cls the HELLO message to send
1035  * @param size number of bytes available in buf
1036  * @param buf where to copy the message
1037  * @return number of bytes copied to buf
1038  */
1039 static size_t
1040 send_hello (void *cls, size_t size, void *buf)
1041 {
1042   struct GNUNET_MessageHeader *hello = cls;
1043   uint16_t msize;
1044
1045   if (buf == NULL)
1046     {
1047 #if DEBUG_TRANSPORT_TIMEOUT
1048       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1049                   "Timeout while trying to transmit `%s' request.\n",
1050                   "HELLO");
1051 #endif
1052       GNUNET_free (hello);
1053       return 0;
1054     }
1055 #if DEBUG_TRANSPORT
1056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057               "Transmitting `%s' request.\n", "HELLO");
1058 #endif
1059   msize = ntohs (hello->size);
1060   GNUNET_assert (size >= msize);
1061   memcpy (buf, hello, msize);
1062   GNUNET_free (hello);
1063   return msize;
1064 }
1065
1066
1067 /**
1068  * Offer the transport service the HELLO of another peer.  Note that
1069  * the transport service may just ignore this message if the HELLO is
1070  * malformed or useless due to our local configuration.
1071  *
1072  * @param handle connection to transport service
1073  * @param hello the hello message
1074  */
1075 void
1076 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1077                               const struct GNUNET_MessageHeader *hello)
1078 {
1079   struct GNUNET_MessageHeader *hc;
1080   uint16_t size;
1081   struct GNUNET_PeerIdentity peer;
1082
1083   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1084   size = ntohs (hello->size);
1085   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1086   if (GNUNET_OK != GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) hello,
1087                                         &peer))
1088     {
1089       GNUNET_break (0);
1090       return;
1091     }
1092 #if DEBUG_TRANSPORT
1093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1094               "Offering `%s' message of `%4s' to transport for validation.\n",
1095               "HELLO",
1096               GNUNET_i2s (&peer));
1097 #endif
1098   hc = GNUNET_malloc (size);
1099   memcpy (hc, hello, size);
1100   schedule_control_transmit (handle,
1101                              size,
1102                              GNUNET_NO, OFFER_HELLO_TIMEOUT, &send_hello, hc);
1103 }
1104
1105
1106 /**
1107  * Transmit START message to service.
1108  *
1109  * @param cls unused
1110  * @param size number of bytes available in buf
1111  * @param buf where to copy the message
1112  * @return number of bytes copied to buf
1113  */
1114 static size_t
1115 send_start (void *cls, size_t size, void *buf)
1116 {
1117   struct GNUNET_TRANSPORT_Handle *h = cls;
1118   struct StartMessage s;
1119
1120   if (buf == NULL)
1121     {
1122       /* Can only be shutdown, just give up */
1123 #if DEBUG_TRANSPORT
1124       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1125                   "Shutdown while trying to transmit `%s' request.\n",
1126                   "START");
1127 #endif
1128       return 0;
1129     }
1130 #if DEBUG_TRANSPORT
1131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1132               "Transmitting `%s' request.\n", "START");
1133 #endif
1134   GNUNET_assert (size >= sizeof (struct StartMessage));
1135   s.header.size = htons (sizeof (struct StartMessage));
1136   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1137   s.do_check = htonl (h->check_self);
1138   s.self = h->self;
1139   memcpy (buf, &s, sizeof (struct StartMessage));
1140   return sizeof (struct StartMessage);
1141 }
1142
1143
1144 /**
1145  * Free neighbour.
1146  *
1147  * @param n the entry to free
1148  */
1149 static void
1150 neighbour_free (struct NeighbourList *n)
1151 {
1152   struct GNUNET_TRANSPORT_Handle *h;
1153
1154   /* Added so task gets canceled when a disconnect is received! */
1155   /* Method 1
1156   if (n->transmit_handle.notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1157     {
1158       GNUNET_SCHEDULER_cancel(n->transmit_handle.notify_delay_task);
1159       n->transmit_handle.notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1160       n->transmit_handle.notify = NULL;
1161     }
1162   */
1163   /* NATE: if the above is not needed, then clearly this assertion
1164      should hold (I've checked the code and I'm pretty sure this is
1165      true. -CG 
1166      FIXME: remove above comments once we've seen tests pass with the assert... */
1167   GNUNET_assert (n->transmit_handle.notify_delay_task == GNUNET_SCHEDULER_NO_TASK);
1168   GNUNET_assert (n->transmit_handle.notify == NULL);
1169   h = n->h;
1170 #if DEBUG_TRANSPORT
1171   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172               "Removing neighbour `%s' from list of connected peers.\n",
1173               GNUNET_i2s (&n->id));
1174 #endif
1175   GNUNET_break (n->is_connected == GNUNET_NO);
1176   GNUNET_break (n->transmit_stage == TS_NEW);
1177
1178   GNUNET_assert(GNUNET_YES == 
1179                 GNUNET_CONTAINER_multihashmap_remove(h->neighbours, 
1180                                                      &n->id.hashPubKey, 
1181                                                      n));
1182   GNUNET_free (n);
1183 }
1184
1185
1186 /**
1187  * Mark neighbour as disconnected.
1188  *
1189  * @param n the entry to mark as disconnected
1190  */
1191 static void
1192 neighbour_disconnect (struct NeighbourList *n)
1193 {
1194   struct GNUNET_TRANSPORT_Handle *h = n->h;
1195 #if DEBUG_TRANSPORT
1196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1197               "Removing neighbour `%s' from list of connected peers.\n",
1198               GNUNET_i2s (&n->id));
1199 #endif
1200   GNUNET_break (n->is_connected == GNUNET_YES);
1201   n->is_connected = GNUNET_NO;
1202   /* FIXME: this 'in_disconnect' flag is dubious; we should define 
1203      clearly what disconnect means for pending 'notify_transmit_ready'
1204      requests; maybe a good approach is to REQUIRE clients to 
1205      call 'notify_transmit_ready_cancel' on pending requests on disconnect
1206      and otherwise FAIL HARD with an assertion failure before 
1207      'neighbour_free' right here (transmit_stage would be forced
1208      to 'TS_NEW') */
1209   n->in_disconnect = GNUNET_YES;
1210   if (h->nd_cb != NULL)
1211     h->nd_cb (h->cls, &n->id);
1212   if (n->transmit_stage == TS_NEW)    
1213     neighbour_free (n);
1214     
1215 }
1216
1217
1218 /**
1219  * Function we use for handling incoming messages.
1220  *
1221  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1222  * @param msg message received, NULL on timeout or fatal error
1223  */
1224 static void demultiplexer (void *cls,
1225                            const struct GNUNET_MessageHeader *msg);
1226
1227
1228 /**
1229  * Iterator over hash map entries, for getting rid of a neighbor
1230  * upon a reconnect call.
1231  *
1232  * @param cls closure (NULL)
1233  * @param key current key code
1234  * @param value value in the hash map, the neighbour entry to forget
1235  * @return GNUNET_YES if we should continue to
1236  *         iterate,
1237  *         GNUNET_NO if not.
1238  */
1239 static int
1240 forget_neighbours (void *cls,
1241                    const GNUNET_HashCode * key,
1242                    void *value)
1243 {
1244   struct NeighbourList *n = value;
1245
1246 #if DEBUG_TRANSPORT_DISCONNECT
1247   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248               "Disconnecting due to reconnect being called\n");
1249 #endif
1250   if (n->is_connected)
1251     neighbour_disconnect (n);
1252
1253   return GNUNET_YES;
1254 }
1255
1256
1257 /**
1258  * Try again to connect to transport service.
1259  *
1260  * @param cls the handle to the transport service
1261  * @param tc scheduler context
1262  */
1263 static void
1264 reconnect (void *cls,
1265            const struct GNUNET_SCHEDULER_TaskContext *tc)
1266 {
1267   struct GNUNET_TRANSPORT_Handle *h = cls;
1268   struct ControlMessage *pos;
1269
1270   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1271   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1272     {
1273       /* shutdown, just give up */
1274       return;
1275     }
1276   /* Forget about all neighbours that we used to be connected to */
1277   GNUNET_CONTAINER_multihashmap_iterate(h->neighbours, 
1278                                         &forget_neighbours, 
1279                                         NULL);
1280
1281 #if DEBUG_TRANSPORT
1282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283               "Connecting to transport service.\n");
1284 #endif
1285   GNUNET_assert (h->client == NULL);
1286   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1287   GNUNET_assert (h->client != NULL);
1288   /* make sure we don't send "START" twice, remove existing entry from
1289      queue (if present) */
1290   pos = h->control_head;
1291   while (pos != NULL)
1292     {
1293       if (pos->notify == &send_start)
1294         {
1295           GNUNET_CONTAINER_DLL_remove (h->control_head,
1296                                        h->control_tail,
1297                                        pos);
1298           if (GNUNET_SCHEDULER_NO_TASK != pos->notify_delay_task)
1299             {
1300               GNUNET_SCHEDULER_cancel (pos->notify_delay_task);
1301               pos->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1302             }
1303           GNUNET_free (pos);
1304           break;
1305         }
1306       pos = pos->next;
1307     }
1308   schedule_control_transmit (h,
1309                              sizeof (struct StartMessage),
1310                              GNUNET_YES,
1311                              GNUNET_TIME_UNIT_FOREVER_REL, &send_start, h);
1312   GNUNET_CLIENT_receive (h->client,
1313                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1314 }
1315
1316
1317 /**
1318  * Function that will schedule the job that will try
1319  * to connect us again to the client.
1320  *
1321  * @param h transport service to reconnect
1322  */
1323 static void
1324 schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1325 {
1326 #if DEBUG_TRANSPORT
1327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328               "Scheduling task to reconnect to transport service in %llu ms.\n",
1329               h->reconnect_delay.rel_value);
1330 #endif
1331   GNUNET_assert (h->client == NULL);
1332   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
1333   h->reconnect_task
1334     = GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
1335   if (h->reconnect_delay.rel_value == 0)
1336     {
1337       h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1338     }
1339   else
1340     {
1341       h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
1342       h->reconnect_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
1343                                                      h->reconnect_delay);
1344     }
1345 }
1346
1347
1348 /**
1349  * Send request connect message to the service.
1350  *
1351  * @param cls the TransportRequestConnectMessage
1352  * @param size number of bytes available in buf
1353  * @param buf where to copy the message
1354  * @return number of bytes copied to buf
1355  */
1356 static size_t
1357 send_transport_request_connect (void *cls, size_t size, void *buf)
1358 {
1359   struct TransportRequestConnectMessage *trcm = cls;
1360
1361   if (buf == NULL)
1362     {
1363 #if DEBUG_TRANSPORT
1364       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1365                   "Buffer null for %s\n",
1366                   "REQUEST_CONNECT");
1367 #endif
1368       GNUNET_free (trcm);
1369       return 0;
1370     }
1371 #if DEBUG_TRANSPORT
1372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373               "Transmitting `%s' request for `%4s'.\n",
1374               "REQUEST_CONNECT",
1375               GNUNET_i2s (&trcm->peer));
1376 #endif
1377   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1378   memcpy(buf, trcm, sizeof(struct TransportRequestConnectMessage));
1379   return sizeof(struct TransportRequestConnectMessage);
1380 }
1381
1382 /**
1383  * Create and send a request connect message to
1384  * the transport service for a particular peer.
1385  *
1386  * @param h handle to the transport service
1387  * @param n the neighbor to send the request connect message about
1388  *
1389  */
1390 static void 
1391 send_request_connect_message(struct GNUNET_TRANSPORT_Handle *h, struct NeighbourList *n)
1392 {
1393   struct TransportRequestConnectMessage *trcm;
1394
1395   trcm = GNUNET_malloc(sizeof(struct TransportRequestConnectMessage));
1396   trcm->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1397   trcm->header.size = htons(sizeof(struct TransportRequestConnectMessage));
1398   memcpy(&trcm->peer, &n->id, sizeof(struct GNUNET_PeerIdentity));
1399   schedule_control_transmit (h,
1400                              sizeof (struct TransportRequestConnectMessage),
1401                              GNUNET_NO,
1402                              GNUNET_TIME_UNIT_FOREVER_REL, &send_transport_request_connect, trcm);
1403 }
1404
1405
1406 /**
1407  * Add neighbour to our list
1408  *
1409  * @return NULL if this API is currently disconnecting from the service
1410  */
1411 static struct NeighbourList *
1412 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
1413                const struct GNUNET_PeerIdentity *pid)
1414 {
1415   struct NeighbourList *n;
1416
1417   if (GNUNET_YES == h->in_disconnect)
1418     return NULL;
1419   /* check for duplicates */
1420   if (NULL != (n = neighbour_find (h, pid)))
1421     {
1422       GNUNET_break (0);
1423       return n;
1424     }
1425 #if DEBUG_TRANSPORT
1426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1427               "Creating entry for neighbour `%4s'.\n",
1428               GNUNET_i2s (pid));
1429 #endif
1430   n = GNUNET_malloc (sizeof (struct NeighbourList));
1431   n->id = *pid;
1432   n->h = h;
1433   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
1434                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1435                                  MAX_BANDWIDTH_CARRY_S);
1436   GNUNET_CONTAINER_multihashmap_put (h->neighbours,
1437                                      &pid->hashPubKey,
1438                                      n,
1439                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1440
1441   return n;
1442 }
1443
1444
1445 /**
1446  * Iterator over hash map entries, for deleting state of a neighbor.
1447  *
1448  * @param cls closure (NULL)
1449  * @param key current key code
1450  * @param value value in the hash map, the neighbour entry to delete
1451  * @return GNUNET_YES if we should continue to
1452  *         iterate,
1453  *         GNUNET_NO if not.
1454  */
1455 static int
1456 delete_neighbours (void *cls,
1457                    const GNUNET_HashCode * key,
1458                    void *value)
1459 {
1460   struct NeighbourList *n = value;
1461   struct GNUNET_TRANSPORT_TransmitHandle *th;
1462
1463   switch (n->transmit_stage)
1464     {
1465     case TS_NEW:
1466     case TS_TRANSMITTED:
1467       /* nothing to do */
1468       break;
1469     case TS_QUEUED:
1470     case TS_TRANSMITTED_QUEUED:
1471       th = &n->transmit_handle;
1472       if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1473         {
1474           GNUNET_SCHEDULER_cancel (th->notify_delay_task);
1475           th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1476         }
1477       GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
1478       break;
1479     default:
1480       GNUNET_break (0);
1481     }
1482   GNUNET_free (n);
1483   return GNUNET_YES;
1484 }
1485
1486
1487 /**
1488  * Connect to the transport service.  Note that the connection may
1489  * complete (or fail) asynchronously.
1490  *
1491  * @param cfg configuration to use
1492  * @param self our own identity (API should check that it matches
1493  *             the identity found by transport), or NULL (no check)
1494  * @param cls closure for the callbacks
1495  * @param rec receive function to call
1496  * @param nc function to call on connect events
1497  * @param nd function to call on disconnect events
1498  */
1499 struct GNUNET_TRANSPORT_Handle *
1500 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1501                           const struct GNUNET_PeerIdentity *self,
1502                           void *cls,
1503                           GNUNET_TRANSPORT_ReceiveCallback rec,
1504                           GNUNET_TRANSPORT_NotifyConnect nc,
1505                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1506 {
1507   struct GNUNET_TRANSPORT_Handle *ret;
1508
1509   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1510   if (self != NULL)
1511     {
1512       ret->self = *self;
1513       ret->check_self = GNUNET_YES;
1514     }
1515   ret->cfg = cfg;
1516   ret->cls = cls;
1517   ret->rec = rec;
1518   ret->nc_cb = nc;
1519   ret->nd_cb = nd;
1520   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1521   ret->neighbours = GNUNET_CONTAINER_multihashmap_create(STARTING_NEIGHBOURS_SIZE);
1522   schedule_reconnect (ret);
1523   return ret;
1524 }
1525
1526
1527 /**
1528  * Disconnect from the transport service.
1529  */
1530 void
1531 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1532 {
1533   struct HelloWaitList *hwl;
1534   struct GNUNET_CLIENT_Connection *client;
1535   struct ControlMessage *cm;
1536
1537 #if DEBUG_TRANSPORT
1538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1539 #endif
1540   /* FIXME: this flag is dubious, we should be able to do this
1541      more cleanly; also, we should probably do 'disconnect'
1542      callbacks for every connected peer here, i.e. by calling
1543      the iterator with 'forget_neighbours' instead of 'delete_neighbours'.
1544   */
1545   
1546   handle->in_disconnect = GNUNET_YES;
1547
1548   GNUNET_assert (GNUNET_SYSERR !=
1549                  GNUNET_CONTAINER_multihashmap_iterate(handle->neighbours,
1550                                                        &delete_neighbours,
1551                                                        handle));
1552   GNUNET_CONTAINER_multihashmap_destroy (handle->neighbours);
1553
1554   while (NULL != (hwl = handle->hwl_head))
1555     {
1556       handle->hwl_head = hwl->next;
1557       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1558                   _
1559                   ("Disconnect while notification for `%s' still registered.\n"),
1560                   "HELLO");
1561       if (hwl->rec != NULL)
1562         hwl->rec (hwl->rec_cls, NULL);
1563       GNUNET_free (hwl);
1564     }
1565
1566   /* Check for still scheduled control messages, cancel delay tasks if so */
1567   /* Added because somehow a notify_delay_task is remaining scheduled and is ever so annoying */
1568   while ( (NULL != (cm = handle->control_head)))
1569     {
1570 #if DEBUG_TRANSPORT
1571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572                   "Disconnect before control message sent!\n");
1573 #endif
1574       if (cm->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1575         {
1576           GNUNET_SCHEDULER_cancel (cm->notify_delay_task);
1577           cm->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1578         }
1579       GNUNET_CONTAINER_DLL_remove (handle->control_head,
1580                                    handle->control_tail,
1581                                    cm);
1582       GNUNET_free (cm);
1583     }
1584   /* end check */
1585
1586   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1587     {
1588       GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1589       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1590     }
1591   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1592     {
1593       GNUNET_SCHEDULER_cancel (handle->quota_task);
1594       handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1595     }
1596   GNUNET_free_non_null (handle->my_hello);
1597   handle->my_hello = NULL;
1598
1599   if (NULL != handle->network_handle)
1600     {
1601       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->network_handle);
1602       handle->network_handle = NULL;
1603     }
1604   if (NULL != (client = handle->client))
1605     {
1606 #if DEBUG_TRANSPORT
1607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1608                   "Disconnecting from transport service for good.\n");
1609 #endif
1610       handle->client = NULL;
1611       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
1612     }
1613   GNUNET_free (handle);
1614 }
1615
1616
1617 /**
1618  * Function we use for handling incoming messages.
1619  *
1620  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1621  * @param msg message received, NULL on timeout or fatal error
1622  */
1623 static void
1624 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
1625 {
1626   struct GNUNET_TRANSPORT_Handle *h = cls;
1627   const struct DisconnectInfoMessage *dim;
1628   const struct ConnectInfoMessage *cim;
1629   const struct InboundMessage *im;
1630   const struct GNUNET_MessageHeader *imm;
1631   const struct SendOkMessage *okm;
1632   struct HelloWaitList *hwl;
1633   struct HelloWaitList *next_hwl;
1634   struct NeighbourList *n;
1635   struct GNUNET_PeerIdentity me;
1636   uint16_t size;
1637   uint32_t ats_count;
1638
1639   if (h->client == NULL)
1640     {
1641       /* shutdown initiated from 'GNUNET_TRANSPORT_disconnect',
1642          finish clean up work! */
1643       GNUNET_free (h);
1644       return;
1645     }
1646   if (msg == NULL)
1647     {
1648 #if DEBUG_TRANSPORT
1649       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1650                   "Error receiving from transport service, disconnecting temporarily.\n");
1651 #endif
1652       if (h->network_handle != NULL)
1653         {
1654           GNUNET_CLIENT_notify_transmit_ready_cancel (h->network_handle);
1655           h->network_handle = NULL;
1656         }
1657       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1658       h->client = NULL;
1659       schedule_reconnect (h);
1660       return;
1661     }
1662   GNUNET_CLIENT_receive (h->client,
1663                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1664   size = ntohs (msg->size);
1665   switch (ntohs (msg->type))
1666     {
1667     case GNUNET_MESSAGE_TYPE_HELLO:
1668       if (GNUNET_OK !=
1669           GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
1670                                &me))
1671         {
1672           GNUNET_break (0);
1673           break;
1674         }
1675 #if DEBUG_TRANSPORT
1676       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1677                   "Receiving (my own) `%s' message, I am `%4s'.\n",
1678                   "HELLO", GNUNET_i2s (&me));
1679 #endif
1680       GNUNET_free_non_null (h->my_hello);
1681       h->my_hello = NULL;
1682       if (size < sizeof (struct GNUNET_MessageHeader))
1683         {
1684           GNUNET_break (0);
1685           break;
1686         }
1687       h->my_hello = GNUNET_malloc (size);
1688       memcpy (h->my_hello, msg, size);
1689       hwl = h->hwl_head;
1690       while (NULL != hwl)
1691         {
1692           next_hwl = hwl->next;
1693           hwl->rec (hwl->rec_cls,
1694                     (const struct GNUNET_MessageHeader *) h->my_hello);
1695           hwl = next_hwl;
1696         }
1697       break;
1698     case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
1699
1700       if (size < sizeof (struct ConnectInfoMessage))
1701         {
1702           GNUNET_break (0);
1703           break;
1704         }
1705       cim = (const struct ConnectInfoMessage *) msg;
1706       ats_count = ntohl (cim->ats_count);
1707       if (size != sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information))
1708         {
1709           GNUNET_break (0);
1710           break;
1711         }
1712
1713 #if DEBUG_TRANSPORT
1714       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1715                   "Receiving `%s' message for `%4s'.\n",
1716                   "CONNECT", GNUNET_i2s (&cim->id));
1717 #endif
1718       n = neighbour_find (h, &cim->id);
1719       if (n == NULL)
1720           n = neighbour_add (h, &cim->id);
1721       if (n == NULL)
1722                  return;
1723       GNUNET_break (n->is_connected == GNUNET_NO);
1724       n->is_connected = GNUNET_YES;
1725       /* FIXME */
1726       if (h->nc_cb != NULL)
1727           h->nc_cb (h->cls, &n->id,
1728                   &cim->ats,ats_count);
1729       /* FIXEND */
1730       break;
1731     case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
1732       if (size != sizeof (struct DisconnectInfoMessage))
1733         {
1734           GNUNET_break (0);
1735           break;
1736         }
1737       dim = (const struct DisconnectInfoMessage *) msg;
1738       GNUNET_break (ntohl (dim->reserved) == 0);
1739 #if DEBUG_TRANSPORT_DISCONNECT
1740       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1741                   "Receiving `%s' message for `%4s'.\n",
1742                   "DISCONNECT",
1743                   GNUNET_i2s (&dim->peer));
1744 #endif
1745       n = neighbour_find (h, &dim->peer);
1746       GNUNET_break (n != NULL);
1747       if (n != NULL)
1748         neighbour_disconnect (n);       
1749       break;
1750     case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
1751       if (size != sizeof (struct SendOkMessage))
1752         {
1753           GNUNET_break (0);
1754           break;
1755         }
1756       okm = (const struct SendOkMessage *) msg;
1757 #if DEBUG_TRANSPORT
1758       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1759                   "Receiving `%s' message, transmission %s.\n", "SEND_OK",
1760                   ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
1761 #endif
1762       n = neighbour_find (h, &okm->peer);
1763       GNUNET_assert (n != NULL);
1764       switch (n->transmit_stage)
1765         {
1766         case TS_NEW:
1767           GNUNET_break (0);
1768           break;
1769         case TS_QUEUED:
1770           GNUNET_break (0);
1771           break;
1772         case TS_TRANSMITTED:
1773           n->transmit_stage = TS_NEW;
1774           break;
1775         case TS_TRANSMITTED_QUEUED:
1776           n->transmit_stage = TS_QUEUED;
1777           schedule_transmission (h);
1778           break;
1779         default:
1780           GNUNET_break (0);
1781         }
1782       break;
1783     case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
1784 #if DEBUG_TRANSPORT
1785       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1786                   "Receiving `%s' message.\n", "RECV");
1787 #endif
1788       if (size <
1789           sizeof (struct InboundMessage) +
1790           sizeof (struct GNUNET_MessageHeader))
1791         {
1792           GNUNET_break (0);
1793           break;
1794         }
1795       im = (const struct InboundMessage *) msg;
1796       GNUNET_break (0 == ntohl (im->reserved));
1797       ats_count = ntohl(im->ats_count);
1798       //imm = (const struct GNUNET_MessageHeader *) &im[1];
1799       imm = (const struct GNUNET_MessageHeader *) &((&(im->ats))[ats_count+1]);
1800
1801       if (ntohs (imm->size) + sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) != size)
1802         {
1803           GNUNET_break (0);
1804           break;
1805         }
1806 #if DEBUG_TRANSPORT
1807       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1808                   "Received message of type %u from `%4s'.\n",
1809                   ntohs (imm->type), GNUNET_i2s (&im->peer));
1810 #endif
1811       n = neighbour_find (h, &im->peer);
1812       if (n == NULL)
1813         {
1814           GNUNET_break (0);
1815           break;
1816         }
1817       if (n->is_connected != GNUNET_YES)
1818         {
1819           GNUNET_break (0);
1820           break;
1821         }
1822       /* FIXME: */
1823       if (h->rec != NULL)
1824                 h->rec (h->cls, &im->peer, imm,
1825                         &im->ats, ats_count);
1826       /* ENDFIX */
1827       break;
1828     default:
1829       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1830                   _
1831                   ("Received unexpected message of type %u in %s:%u\n"),
1832                   ntohs (msg->type), __FILE__, __LINE__);
1833       GNUNET_break (0);
1834       break;
1835     }
1836 }
1837
1838
1839 /**
1840  * Called when our transmit request timed out before any transport
1841  * reported success connecting to the desired peer or before the
1842  * transport was ready to receive.  Signal error and free
1843  * TransmitHandle.
1844  *
1845  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle*' that is timing out
1846  * @param tc scheduler context
1847  */
1848 static void
1849 peer_transmit_timeout (void *cls,
1850                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1851 {
1852   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
1853   struct NeighbourList *n;
1854   GNUNET_CONNECTION_TransmitReadyNotify notify;
1855   void *notify_cls;
1856
1857   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1858   n = th->neighbour;
1859 #if DEBUG_TRANSPORT
1860   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1861               "Triggering timeout for request to transmit to `%4s' (%d)\n",
1862               GNUNET_i2s (&n->id),
1863               n->transmit_stage);
1864 #endif
1865   notify = th->notify;
1866   th->notify = NULL;
1867   notify_cls = th->notify_cls;
1868   switch (n->transmit_stage)
1869     {
1870     case TS_NEW:
1871       GNUNET_break (0);
1872       break;
1873     case TS_QUEUED:
1874       n->transmit_stage = TS_NEW;
1875       if (n->is_connected == GNUNET_NO)
1876         neighbour_free (n);
1877       break;
1878     case TS_TRANSMITTED:
1879       GNUNET_break (0);
1880       break;
1881     case TS_TRANSMITTED_QUEUED:
1882       n->transmit_stage = TS_TRANSMITTED;
1883       break;
1884     default:
1885       GNUNET_break (0);
1886     }
1887   if (NULL != notify)
1888     notify (notify_cls, 0, NULL);
1889 }
1890
1891
1892 /**
1893  * Check if we could queue a message of the given size for
1894  * transmission.  The transport service will take both its
1895  * internal buffers and bandwidth limits imposed by the
1896  * other peer into consideration when answering this query.
1897  *
1898  * @param handle connection to transport service
1899  * @param target who should receive the message
1900  * @param size how big is the message we want to transmit?
1901  * @param priority how important is the message?
1902  * @param timeout after how long should we give up (and call
1903  *        notify with buf NULL and size 0)?
1904  * @param notify function to call when we are ready to
1905  *        send such a message
1906  * @param notify_cls closure for notify
1907  * @return NULL if someone else is already waiting to be notified
1908  *         non-NULL if the notify callback was queued (can be used to cancel
1909  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1910  */
1911 struct GNUNET_TRANSPORT_TransmitHandle *
1912 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle
1913                                         *handle,
1914                                         const struct GNUNET_PeerIdentity
1915                                         *target, size_t size,
1916                                         unsigned int priority,
1917                                         struct GNUNET_TIME_Relative timeout,
1918                                         GNUNET_CONNECTION_TransmitReadyNotify
1919                                         notify, void *notify_cls)
1920 {
1921   struct GNUNET_TRANSPORT_TransmitHandle *th;
1922   struct NeighbourList *n;
1923
1924   if (size + sizeof (struct OutboundMessage) >=
1925       GNUNET_SERVER_MAX_MESSAGE_SIZE)
1926     {
1927 #if DEBUG_TRANSPORT
1928       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929                   "Message size is %d, max allowed is %d.\n",
1930                   size + sizeof (struct OutboundMessage), GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
1931 #endif
1932       GNUNET_break (0);
1933       return NULL;
1934     }
1935 #if DEBUG_TRANSPORT
1936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1937               "Asking transport service for transmission of %u bytes to peer `%4s' within %llu ms.\n",
1938               size, GNUNET_i2s (target),
1939               (unsigned long long) timeout.rel_value);
1940 #endif
1941   n = neighbour_find (handle, target);
1942   if (n == NULL)
1943     {
1944       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945                   "Created neighbour entry for peer `%s'\n",
1946                   GNUNET_i2s (target));
1947       n = neighbour_add (handle, target);
1948
1949     }
1950   if (n == NULL)
1951     {
1952       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953                   "Could not create neighbour entry for peer `%s'\n",
1954                   GNUNET_i2s (target));
1955       return NULL;
1956     }
1957
1958   /**
1959    *  Send a request connect message if not connected,
1960    *  otherwise we will never send anything to
1961    *  transport service
1962    */
1963   if (n->is_connected == GNUNET_NO)
1964     {
1965       send_request_connect_message(handle, n);
1966     }
1967
1968   switch (n->transmit_stage)
1969     {
1970     case TS_NEW:
1971       n->transmit_stage = TS_QUEUED;
1972       break;
1973     case TS_QUEUED:
1974       GNUNET_break (0);
1975       return NULL;
1976     case TS_TRANSMITTED:
1977       n->transmit_stage = TS_TRANSMITTED_QUEUED;
1978       break;
1979     case TS_TRANSMITTED_QUEUED:
1980       GNUNET_break (0);
1981       return NULL;
1982     default:
1983       GNUNET_break (0);
1984       return NULL;
1985     }
1986   th = &n->transmit_handle;
1987   th->neighbour = n;
1988   th->notify = notify;
1989   th->notify_cls = notify_cls;
1990   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1991   th->notify_size = size + sizeof (struct OutboundMessage);
1992   th->priority = priority;
1993   th->notify_delay_task
1994     = GNUNET_SCHEDULER_add_delayed (timeout,
1995                                     &peer_transmit_timeout, th);
1996   schedule_transmission (handle);
1997   return th;
1998 }
1999
2000
2001 /**
2002  * Cancel the specified transmission-ready notification.
2003  */
2004 void
2005 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
2006                                                GNUNET_TRANSPORT_TransmitHandle
2007                                                *th)
2008 {
2009   struct NeighbourList *n;
2010
2011   th->notify = NULL;
2012   n = th->neighbour;
2013 #if DEBUG_TRANSPORT
2014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015               "Transmission request of %u bytes to `%4s' was canceled.\n",
2016               th->notify_size - sizeof (struct OutboundMessage),
2017               GNUNET_i2s (&n->id));
2018 #endif
2019   if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
2020     {
2021       GNUNET_SCHEDULER_cancel (th->notify_delay_task);
2022       th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
2023     }
2024   switch (n->transmit_stage)
2025     {
2026     case TS_NEW:
2027       GNUNET_break (0);
2028       break;
2029     case TS_QUEUED:
2030       n->transmit_stage = TS_NEW;
2031       if ( (n->in_disconnect == GNUNET_NO) &&
2032            (n->is_connected == GNUNET_NO) )
2033         neighbour_free (n);
2034       break;
2035     case TS_TRANSMITTED:
2036       GNUNET_break (0);
2037       break;
2038     case TS_TRANSMITTED_QUEUED:
2039       n->transmit_stage = TS_TRANSMITTED;
2040       break;
2041     default:
2042       GNUNET_break (0);
2043     }
2044 }
2045
2046
2047 /* end of transport_api.c */