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