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