better messages
[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_free (cm);
552       ret += nret;
553       size -= nret;
554     }
555   while ( (NULL != (th = schedule_peer_transmission (h))) &&
556           (th->notify_size <= size) )
557     {
558       if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
559         {
560           GNUNET_SCHEDULER_cancel (h->sched, th->notify_delay_task);
561           th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
562         }
563       n = th->neighbour;
564       switch (n->transmit_stage)
565         {
566         case TS_NEW:
567           GNUNET_break (0);
568           break;
569         case TS_QUEUED:
570           n->transmit_stage = TS_TRANSMITTED;
571           break;
572         case TS_TRANSMITTED:
573           GNUNET_break (0);
574           break;
575         case TS_TRANSMITTED_QUEUED:
576           GNUNET_break (0);
577           break;
578         default:
579           GNUNET_break (0);
580         }
581       GNUNET_assert (size >= sizeof (struct OutboundMessage));
582       mret = th->notify (th->notify_cls, 
583                          size - sizeof (struct OutboundMessage),
584                          &cbuf[ret + sizeof (struct OutboundMessage)]);
585       GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
586 #if DEBUG_TRANSPORT
587       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588                   "Message of %u bytes with timeout %llums constructed for `%4s'\n",
589                   (unsigned int) mret, 
590                   (unsigned long long) GNUNET_TIME_absolute_get_remaining (th->timeout).value,
591                   GNUNET_i2s (&n->id));
592 #endif
593       if (mret != 0)    
594         {
595           obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
596           obm.header.size = htons (mret + sizeof (struct OutboundMessage));
597           obm.priority = htonl (th->priority);
598           obm.timeout = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (th->timeout));
599           obm.peer = n->id;
600           memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
601           ret += (mret + sizeof (struct OutboundMessage));
602           size -= (mret + sizeof (struct OutboundMessage));
603           GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
604         }
605       else
606         {
607           switch (n->transmit_stage)
608             {
609             case TS_NEW:
610               GNUNET_break (0);
611               break;
612             case TS_QUEUED:
613               GNUNET_break (0);
614               break;
615             case TS_TRANSMITTED:
616               n->transmit_stage = TS_NEW;
617               break;
618             case TS_TRANSMITTED_QUEUED:
619               n->transmit_stage = TS_QUEUED;
620               continue;
621             default:
622               GNUNET_break (0);
623             }
624         }
625     }
626   schedule_transmission (h);
627 #if DEBUG_TRANSPORT
628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
629               "Transmitting %u bytes to transport service\n", ret);
630 #endif
631   return ret;
632 }
633
634
635 /**
636  * Schedule the task to send one message, either from the control
637  * list or the peer message queues  to the service.
638  */
639 static void
640 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
641 {  
642   size_t size;
643   struct GNUNET_TIME_Relative timeout;
644   struct GNUNET_TRANSPORT_TransmitHandle *th;
645
646   if (NULL != h->network_handle)
647     return;
648   if (h->client == NULL)
649     {
650       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
651                   _("Could not yet schedule transmission: we are not yet connected to the transport service!\n"));
652       return;                   /* not yet connected */
653     }
654   if (NULL != h->control_head) 
655     {
656       size = h->control_head->notify_size;
657       timeout = GNUNET_TIME_UNIT_FOREVER_REL;
658     }
659   else
660     {
661       th = schedule_peer_transmission (h);
662       if (th == NULL)
663         {
664           /* no transmission ready right now */
665 #if DEBUG_TRANSPORT
666           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
667                       "Could not yet schedule transmission: none ready\n");
668 #endif
669           return;
670         }
671       size = th->notify_size;
672       timeout = GNUNET_TIME_absolute_get_remaining (th->timeout);
673     }
674   h->network_handle = 
675     GNUNET_CLIENT_notify_transmit_ready (h->client,
676                                          size,
677                                          timeout,
678                                          GNUNET_NO,
679                                          &transport_notify_ready,
680                                          h);
681   GNUNET_assert (NULL != h->network_handle);
682 }
683
684
685 /**
686  * Called when our transmit request timed out before any transport
687  * reported success connecting to the desired peer or before the
688  * transport was ready to receive.  Signal error and free
689  * TransmitHandle.
690  */
691 static void
692 control_transmit_timeout (void *cls,
693                           const struct GNUNET_SCHEDULER_TaskContext *tc)
694 {
695   struct ControlMessage *th = cls;
696
697   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
698   if (NULL != th->notify)
699     th->notify (th->notify_cls, 0, NULL);
700   GNUNET_CONTAINER_DLL_remove (th->h->control_head,
701                                th->h->control_tail,
702                                th);
703   GNUNET_free (th);
704 }
705
706
707 /**
708  * Queue control request for transmission to the transport
709  * service.
710  *
711  * @param h handle to the transport service
712  * @param size number of bytes to be transmitted
713  * @param at_head request must be added to the head of the queue
714  *        (otherwise request will be appended)
715  * @param timeout how long this transmission can wait (at most)
716  * @param notify function to call to get the content
717  * @param notify_cls closure for notify
718  */
719 static void
720 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h,
721                            size_t size,
722                            int at_head,
723                            struct GNUNET_TIME_Relative timeout,
724                            GNUNET_CONNECTION_TransmitReadyNotify notify,
725                            void *notify_cls)
726 {
727   struct ControlMessage *th;
728
729 #if DEBUG_TRANSPORT
730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731               "Control transmit of %u bytes within %llums requested\n",
732               size, (unsigned long long) timeout.value);
733 #endif
734   th = GNUNET_malloc (sizeof (struct ControlMessage));
735   th->h = h;
736   th->notify = notify;
737   th->notify_cls = notify_cls;
738   th->notify_size = size;
739   th->notify_delay_task
740     = GNUNET_SCHEDULER_add_delayed (h->sched,
741                                     timeout, &control_transmit_timeout, th);
742   if (at_head)    
743     GNUNET_CONTAINER_DLL_insert (h->control_head,
744                                  h->control_tail,
745                                  th);
746   else
747     GNUNET_CONTAINER_DLL_insert_after (h->control_head,
748                                        h->control_tail,
749                                        h->control_tail,
750                                        th);
751   schedule_transmission (h);
752 }
753
754
755 struct SetQuotaContext
756 {
757   struct GNUNET_TRANSPORT_Handle *handle;
758
759   struct GNUNET_PeerIdentity target;
760
761   GNUNET_SCHEDULER_Task cont;
762
763   void *cont_cls;
764
765   struct GNUNET_TIME_Absolute timeout;
766
767   struct GNUNET_BANDWIDTH_Value32NBO quota_in;
768 };
769
770
771 /**
772  * Send SET_QUOTA message to the service.
773  *
774  * @param cls the 'struct SetQuotaContext'
775  * @param size number of bytes available in buf
776  * @param buf where to copy the message
777  * @return number of bytes copied to buf
778  */
779 static size_t
780 send_set_quota (void *cls, size_t size, void *buf)
781 {
782   struct SetQuotaContext *sqc = cls;
783   struct QuotaSetMessage *msg;
784
785   if (buf == NULL)
786     {
787       GNUNET_SCHEDULER_add_continuation (sqc->handle->sched,
788                                          sqc->cont,
789                                          sqc->cont_cls,
790                                          GNUNET_SCHEDULER_REASON_TIMEOUT);
791       GNUNET_free (sqc);
792       return 0;
793     }
794 #if DEBUG_TRANSPORT
795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796               "Transmitting `%s' request with respect to `%4s'.\n",
797               "SET_QUOTA", 
798               GNUNET_i2s (&sqc->target));
799 #endif
800   GNUNET_assert (size >= sizeof (struct QuotaSetMessage));
801   msg = buf;
802   msg->header.size = htons (sizeof (struct QuotaSetMessage));
803   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
804   msg->quota = sqc->quota_in;
805   memcpy (&msg->peer, &sqc->target, sizeof (struct GNUNET_PeerIdentity));
806   if (sqc->cont != NULL)
807     GNUNET_SCHEDULER_add_continuation (sqc->handle->sched,
808                                        sqc->cont,
809                                        sqc->cont_cls,
810                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
811   GNUNET_free (sqc);
812   return sizeof (struct QuotaSetMessage);
813 }
814
815
816 /**
817  * Set the share of incoming bandwidth for the given
818  * peer to the specified amount.
819  *
820  * @param handle connection to transport service
821  * @param target who's bandwidth quota is being changed
822  * @param quota_in incoming bandwidth quota in bytes per ms
823  * @param quota_out outgoing bandwidth quota in bytes per ms
824  * @param timeout how long to wait until signaling failure if
825  *        we can not communicate the quota change
826  * @param cont continuation to call when done, will be called
827  *        either with reason "TIMEOUT" or with reason "PREREQ_DONE"
828  * @param cont_cls closure for continuation
829  */
830 void
831 GNUNET_TRANSPORT_set_quota (struct GNUNET_TRANSPORT_Handle *handle,
832                             const struct GNUNET_PeerIdentity *target,
833                             struct GNUNET_BANDWIDTH_Value32NBO quota_in,
834                             struct GNUNET_BANDWIDTH_Value32NBO quota_out,
835                             struct GNUNET_TIME_Relative timeout,
836                             GNUNET_SCHEDULER_Task cont, void *cont_cls)
837 {
838   struct NeighbourList *n;
839   struct SetQuotaContext *sqc;
840
841   n = neighbour_find (handle, target);
842   if (n != NULL)
843     {
844 #if DEBUG_TRANSPORT
845       if (ntohl (quota_out.value__) != n->out_tracker.available_bytes_per_s__)
846         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                     "Quota changed from %u to %u for peer `%s'\n",
848                     (unsigned int) n->out_tracker.available_bytes_per_s__,
849                     (unsigned int) ntohl (quota_out.value__),
850                     GNUNET_i2s (target));
851       else
852         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                     "Quota remains at %u for peer `%s'\n",
854                     (unsigned int) n->out_tracker.available_bytes_per_s__,
855                     GNUNET_i2s (target));
856 #endif
857       GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
858                                              quota_out);
859     }
860   else
861     {
862 #if DEBUG_TRANSPORT
863       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864                   "Quota changed to %u for peer `%s', but I have no such neighbour!\n",
865                   (unsigned int) ntohl (quota_out.value__),
866                   GNUNET_i2s (target));
867 #endif
868     }
869   sqc = GNUNET_malloc (sizeof (struct SetQuotaContext));
870   sqc->handle = handle;
871   sqc->target = *target;
872   sqc->cont = cont;
873   sqc->cont_cls = cont_cls;
874   sqc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
875   sqc->quota_in = quota_in;
876   schedule_control_transmit (handle,
877                              sizeof (struct QuotaSetMessage),
878                              GNUNET_NO, timeout, &send_set_quota, sqc);
879 }
880
881
882 /**
883  * Obtain the HELLO message for this peer.
884  *
885  * @param handle connection to transport service
886  * @param rec function to call with the HELLO, sender will be our peer
887  *            identity; message and sender will be NULL on timeout
888  *            (handshake with transport service pending/failed).
889  *             cost estimate will be 0.
890  * @param rec_cls closure for rec
891  */
892 void
893 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
894                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
895                             void *rec_cls)
896 {
897   struct HelloWaitList *hwl;
898
899   hwl = GNUNET_malloc (sizeof (struct HelloWaitList));
900   hwl->next = handle->hwl_head;
901   handle->hwl_head = hwl;
902   hwl->handle = handle;
903   hwl->rec = rec;
904   hwl->rec_cls = rec_cls;
905   if (handle->my_hello == NULL)
906     return;    
907   rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
908 }
909
910
911
912 /**
913  * Stop receiving updates about changes to our HELLO message.
914  *
915  * @param handle connection to transport service
916  * @param rec function previously registered to be called with the HELLOs
917  * @param rec_cls closure for rec
918  */
919 void
920 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_Handle *handle,
921                                    GNUNET_TRANSPORT_HelloUpdateCallback rec,
922                                    void *rec_cls)
923 {
924   struct HelloWaitList *pos;
925   struct HelloWaitList *prev;
926
927   prev = NULL;
928   pos = handle->hwl_head;
929   while (pos != NULL)
930     {
931       if ( (pos->rec == rec) &&
932            (pos->rec_cls == rec_cls) )
933         break;
934       prev = pos;
935       pos = pos->next;
936     }
937   GNUNET_break (pos != NULL);
938   if (pos == NULL)
939     return;
940   if (prev == NULL)
941     handle->hwl_head = pos->next;
942   else
943     prev->next = pos->next;
944   GNUNET_free (pos);
945 }
946
947
948 /**
949  * Send HELLO message to the service.
950  *
951  * @param cls the HELLO message to send
952  * @param size number of bytes available in buf
953  * @param buf where to copy the message
954  * @return number of bytes copied to buf
955  */
956 static size_t
957 send_hello (void *cls, size_t size, void *buf)
958 {
959   struct GNUNET_MessageHeader *hello = cls;
960   uint16_t msize;
961
962   if (buf == NULL)
963     {
964 #if DEBUG_TRANSPORT_TIMEOUT
965       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
966                   "Timeout while trying to transmit `%s' request.\n",
967                   "HELLO");
968 #endif
969       GNUNET_free (hello);
970       return 0;
971     }
972 #if DEBUG_TRANSPORT
973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974               "Transmitting `%s' request.\n", "HELLO");
975 #endif
976   msize = ntohs (hello->size);
977   GNUNET_assert (size >= msize);
978   memcpy (buf, hello, msize);
979   GNUNET_free (hello);
980   return msize;
981 }
982
983
984 /**
985  * Offer the transport service the HELLO of another peer.  Note that
986  * the transport service may just ignore this message if the HELLO is
987  * malformed or useless due to our local configuration.
988  *
989  * @param handle connection to transport service
990  * @param hello the hello message
991  */
992 void
993 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
994                               const struct GNUNET_MessageHeader *hello)
995 {
996   struct GNUNET_MessageHeader *hc;
997   uint16_t size;
998   struct GNUNET_PeerIdentity peer;
999
1000   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1001   size = ntohs (hello->size);
1002   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1003   if (GNUNET_OK != GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) hello,
1004                                         &peer))
1005     {
1006       GNUNET_break (0);
1007       return;
1008     }
1009 #if DEBUG_TRANSPORT 
1010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011               "Offering `%s' message of `%4s' to transport for validation.\n",
1012               "HELLO",
1013               GNUNET_i2s (&peer));
1014 #endif
1015   hc = GNUNET_malloc (size);
1016   memcpy (hc, hello, size);
1017   schedule_control_transmit (handle,
1018                              size,
1019                              GNUNET_NO, OFFER_HELLO_TIMEOUT, &send_hello, hc);
1020 }
1021
1022
1023 /**
1024  * Transmit START message to service.
1025  *
1026  * @param cls unused
1027  * @param size number of bytes available in buf
1028  * @param buf where to copy the message
1029  * @return number of bytes copied to buf
1030  */
1031 static size_t
1032 send_start (void *cls, size_t size, void *buf)
1033 {
1034   struct GNUNET_MessageHeader *s = buf;
1035
1036   if (buf == NULL)
1037     {
1038       /* Can only be shutdown, just give up */
1039 #if DEBUG_TRANSPORT
1040       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041                   "Shutdown while trying to transmit `%s' request.\n",
1042                   "START");
1043 #endif
1044       return 0;
1045     }
1046 #if DEBUG_TRANSPORT
1047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048               "Transmitting `%s' request.\n", "START");
1049 #endif
1050   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1051   s->size = htons (sizeof (struct GNUNET_MessageHeader));
1052   s->type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1053   return sizeof (struct GNUNET_MessageHeader);
1054 }
1055
1056
1057 /**
1058  * Free neighbour. 
1059  * 
1060  * @param n the entry to free
1061  */
1062 static void
1063 neighbour_free (struct NeighbourList *n)
1064 {
1065   struct GNUNET_TRANSPORT_Handle *h;
1066   struct NeighbourList *prev;
1067   struct NeighbourList *pos;
1068
1069   h = n->h;
1070 #if DEBUG_TRANSPORT
1071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072               "Removing neighbour `%s' from list of connected peers.\n",
1073               GNUNET_i2s (&n->id));
1074 #endif
1075   GNUNET_break (n->is_connected == GNUNET_NO);
1076   GNUNET_break (n->transmit_stage == TS_NEW);
1077
1078   prev = NULL;
1079   pos = h->neighbours;
1080   while (pos != n)
1081     {
1082       prev = pos;
1083       pos = pos->next;
1084     }
1085   if (prev == NULL)
1086     h->neighbours = n->next;
1087   else
1088     prev->next = n->next;
1089   GNUNET_free (n);
1090 }
1091
1092
1093 /**
1094  * Mark neighbour as disconnected. 
1095  * 
1096  * @param n the entry to mark as disconnected
1097  */
1098 static void
1099 neighbour_disconnect (struct NeighbourList *n)
1100 {
1101   struct GNUNET_TRANSPORT_Handle *h = n->h;
1102 #if DEBUG_TRANSPORT
1103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104               "Removing neighbour `%s' from list of connected peers.\n",
1105               GNUNET_i2s (&n->id));
1106 #endif
1107   GNUNET_break (n->is_connected == GNUNET_YES);
1108   n->is_connected = GNUNET_NO;
1109   if (h->nc_cb != NULL)
1110     h->nd_cb (h->cls, &n->id);
1111   if (n->transmit_stage == TS_NEW)
1112     neighbour_free (n);
1113 }
1114
1115
1116 /**
1117  * Function we use for handling incoming messages.
1118  *
1119  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1120  * @param msg message received, NULL on timeout or fatal error
1121  */
1122 static void demultiplexer (void *cls,
1123                            const struct GNUNET_MessageHeader *msg);
1124
1125
1126 /**
1127  * Try again to connect to transport service.
1128  *
1129  * @param cls the handle to the transport service
1130  * @param tc scheduler context
1131  */
1132 static void
1133 reconnect (void *cls, 
1134            const struct GNUNET_SCHEDULER_TaskContext *tc)
1135 {
1136   struct GNUNET_TRANSPORT_Handle *h = cls;
1137   struct ControlMessage *pos;
1138   struct NeighbourList *n;
1139   struct NeighbourList *next;
1140
1141   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1142   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1143     {
1144       /* shutdown, just give up */
1145       return;
1146     }
1147   /* Forget about all neighbours that we used to be connected to */
1148   n = h->neighbours;
1149   while (NULL != n)
1150     {
1151 #if DEBUG_TRANSPORT_DISCONNECT
1152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1153               "Disconnecting due to reconnect being called\n");
1154 #endif
1155       next = n->next;
1156       if (n->is_connected)
1157         neighbour_disconnect (n);
1158       n = next;
1159     }
1160 #if DEBUG_TRANSPORT
1161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1162               "Connecting to transport service.\n");
1163 #endif
1164   GNUNET_assert (h->client == NULL);
1165   h->client = GNUNET_CLIENT_connect (h->sched, "transport", h->cfg);
1166   GNUNET_assert (h->client != NULL);
1167   /* make sure we don't send "START" twice, remove existing entry from
1168      queue (if present) */
1169   pos = h->control_head;
1170   while (pos != NULL)
1171     {
1172       if (pos->notify == &send_start)
1173         {
1174           GNUNET_CONTAINER_DLL_remove (h->control_head,
1175                                        h->control_tail,
1176                                        pos);
1177           if (GNUNET_SCHEDULER_NO_TASK != pos->notify_delay_task)
1178             {
1179               GNUNET_SCHEDULER_cancel (h->sched, pos->notify_delay_task);
1180               pos->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1181             }
1182           GNUNET_free (pos);
1183           break;
1184         }
1185       pos = pos->next;
1186     }
1187   schedule_control_transmit (h,
1188                              sizeof (struct GNUNET_MessageHeader),
1189                              GNUNET_YES,
1190                              GNUNET_TIME_UNIT_FOREVER_REL, &send_start, NULL);
1191   GNUNET_CLIENT_receive (h->client,
1192                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1193 }
1194
1195
1196 /**
1197  * Function that will schedule the job that will try
1198  * to connect us again to the client.
1199  *
1200  * @param h transport service to reconnect
1201  */
1202 static void
1203 schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1204 {
1205 #if DEBUG_TRANSPORT
1206   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1207               "Scheduling task to reconnect to transport service in %llu ms.\n",
1208               h->reconnect_delay.value);
1209 #endif
1210   GNUNET_assert (h->client == NULL);
1211   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
1212   h->reconnect_task
1213     = GNUNET_SCHEDULER_add_delayed (h->sched,
1214                                     h->reconnect_delay, &reconnect, h);
1215   if (h->reconnect_delay.value == 0)
1216     {
1217       h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1218     }
1219   else 
1220     {
1221       h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
1222       h->reconnect_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
1223                                                      h->reconnect_delay);
1224     }
1225 }
1226
1227
1228 /**
1229  * Add neighbour to our list
1230  *
1231  * @return NULL if this API is currently disconnecting from the service
1232  */
1233 static struct NeighbourList *
1234 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
1235                const struct GNUNET_PeerIdentity *pid)
1236 {
1237   struct NeighbourList *n;
1238
1239   if (GNUNET_YES == h->in_disconnect)
1240     return NULL;
1241   /* check for duplicates */
1242   if (NULL != (n = neighbour_find (h, pid)))
1243     {
1244       GNUNET_break (0);
1245       return n;
1246     }
1247 #if DEBUG_TRANSPORT
1248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249               "Creating entry for neighbour `%4s'.\n", 
1250               GNUNET_i2s (pid));
1251 #endif
1252   n = GNUNET_malloc (sizeof (struct NeighbourList));
1253   n->id = *pid;
1254   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
1255                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1256                                  MAX_BANDWIDTH_CARRY_S);
1257   n->next = h->neighbours;
1258   n->h = h;
1259   h->neighbours = n;  
1260   return n;
1261 }
1262
1263
1264 /**
1265  * Connect to the transport service.  Note that the connection may
1266  * complete (or fail) asynchronously.
1267  *
1268  * @param sched scheduler to use
1269  * @param cfg configuration to use
1270  * @param cls closure for the callbacks
1271  * @param rec receive function to call
1272  * @param nc function to call on connect events
1273  * @param nd function to call on disconnect events
1274  */
1275 struct GNUNET_TRANSPORT_Handle *
1276 GNUNET_TRANSPORT_connect (struct GNUNET_SCHEDULER_Handle *sched,
1277                           const struct GNUNET_CONFIGURATION_Handle *cfg,
1278                           void *cls,
1279                           GNUNET_TRANSPORT_ReceiveCallback rec,
1280                           GNUNET_TRANSPORT_NotifyConnect nc,
1281                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1282 {
1283   struct GNUNET_TRANSPORT_Handle *ret;
1284
1285   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1286   ret->sched = sched;
1287   ret->cfg = cfg;
1288   ret->cls = cls;
1289   ret->rec = rec;
1290   ret->nc_cb = nc;
1291   ret->nd_cb = nd;
1292   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1293   schedule_reconnect (ret);
1294   return ret;
1295 }
1296
1297
1298 /**
1299  * Disconnect from the transport service.
1300  */
1301 void
1302 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1303 {
1304   struct GNUNET_TRANSPORT_TransmitHandle *th;
1305   struct NeighbourList *n;
1306   struct HelloWaitList *hwl;
1307   struct GNUNET_CLIENT_Connection *client;
1308   struct ControlMessage *cm;
1309
1310 #if DEBUG_TRANSPORT
1311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1312 #endif
1313   handle->in_disconnect = GNUNET_YES;
1314   while (NULL != (n = handle->neighbours))
1315     {
1316       handle->neighbours = n->next;
1317       switch (n->transmit_stage)
1318         {
1319         case TS_NEW:
1320         case TS_TRANSMITTED:
1321           /* nothing to do */
1322           break;
1323         case TS_QUEUED:
1324         case TS_TRANSMITTED_QUEUED:
1325           th = &n->transmit_handle;
1326           if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1327             {
1328               GNUNET_SCHEDULER_cancel (handle->sched,
1329                                        th->notify_delay_task);
1330               th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1331             }
1332           GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));        
1333           break;
1334         default:
1335           GNUNET_break (0);
1336         }
1337       GNUNET_free (n);
1338     }
1339   while (NULL != (hwl = handle->hwl_head))
1340     {
1341       handle->hwl_head = hwl->next;
1342       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1343                   _
1344                   ("Disconnect while notification for `%s' still registered.\n"),
1345                   "HELLO");
1346       if (hwl->rec != NULL)
1347         hwl->rec (hwl->rec_cls, NULL);
1348       GNUNET_free (hwl);
1349     }
1350
1351   /* Check for still scheduled control messages, cancel delay tasks if so */
1352   /* Added because somehow a notify_delay_task is remaining scheduled and is ever so annoying */
1353   while ( (NULL != (cm = handle->control_head)))
1354     {
1355       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1356                   _("Disconnect before control message sent!\n"));
1357       if (cm->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1358         {
1359           GNUNET_SCHEDULER_cancel (handle->sched, cm->notify_delay_task);
1360           cm->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1361         }
1362       GNUNET_CONTAINER_DLL_remove (handle->control_head,
1363                                    handle->control_tail,
1364                                    cm);
1365       GNUNET_free (cm);
1366     }
1367   /* end check */
1368
1369   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1370     {
1371       GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
1372       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1373     }
1374   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1375     {
1376       GNUNET_SCHEDULER_cancel (handle->sched, handle->quota_task);
1377       handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1378     }
1379   GNUNET_free_non_null (handle->my_hello);
1380   handle->my_hello = NULL;
1381
1382   if (NULL != handle->network_handle)
1383     {
1384       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->network_handle);
1385       handle->network_handle = NULL;
1386     }
1387   if (NULL != (client = handle->client))
1388     {
1389 #if DEBUG_TRANSPORT
1390       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391                   "Disconnecting from transport service for good.\n");
1392 #endif
1393       handle->client = NULL;
1394       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
1395     }
1396   GNUNET_free (handle);
1397 }
1398
1399
1400 /**
1401  * Function we use for handling incoming messages.
1402  *
1403  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1404  * @param msg message received, NULL on timeout or fatal error
1405  */
1406 static void
1407 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
1408 {
1409   struct GNUNET_TRANSPORT_Handle *h = cls;
1410   const struct DisconnectInfoMessage *dim;
1411   const struct ConnectInfoMessage *cim;
1412   const struct InboundMessage *im;
1413   const struct GNUNET_MessageHeader *imm;
1414   const struct SendOkMessage *okm;
1415   struct HelloWaitList *hwl;
1416   struct HelloWaitList *next_hwl;
1417   struct NeighbourList *n;
1418   struct GNUNET_PeerIdentity me;
1419   uint16_t size;
1420
1421   if (h->client == NULL)
1422     {
1423       /* shutdown initiated from 'GNUNET_TRANSPORT_disconnect',
1424          finish clean up work! */
1425       GNUNET_free (h);
1426       return;
1427     }
1428   if (msg == NULL) 
1429     {
1430 #if DEBUG_TRANSPORT
1431       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1432                   "Error receiving from transport service, disconnecting temporarily.\n");
1433 #endif
1434       if (h->network_handle != NULL)
1435         {
1436           GNUNET_CLIENT_notify_transmit_ready_cancel (h->network_handle);
1437           h->network_handle = NULL;
1438         }
1439       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1440       h->client = NULL;
1441       schedule_reconnect (h);
1442       return;
1443     }
1444   GNUNET_CLIENT_receive (h->client,
1445                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1446   size = ntohs (msg->size);
1447   switch (ntohs (msg->type))
1448     {
1449     case GNUNET_MESSAGE_TYPE_HELLO:
1450       if (GNUNET_OK !=
1451           GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
1452                                &me))
1453         {
1454           GNUNET_break (0);
1455           break;
1456         }
1457 #if DEBUG_TRANSPORT
1458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1459                   "Receiving (my own) `%s' message, I am `%4s'.\n",
1460                   "HELLO", GNUNET_i2s (&me));
1461 #endif
1462       GNUNET_free_non_null (h->my_hello);
1463       h->my_hello = NULL;
1464       if (size < sizeof (struct GNUNET_MessageHeader))
1465         {
1466           GNUNET_break (0);
1467           break;
1468         }
1469       h->my_hello = GNUNET_malloc (size);
1470       memcpy (h->my_hello, msg, size);
1471       hwl = h->hwl_head;
1472       while (NULL != hwl)
1473         {
1474           next_hwl = hwl->next;
1475           hwl->rec (hwl->rec_cls,
1476                     (const struct GNUNET_MessageHeader *) h->my_hello);
1477           hwl = next_hwl;
1478         }
1479       break;
1480     case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
1481       if (size != sizeof (struct ConnectInfoMessage))
1482         {
1483           GNUNET_break (0);
1484           break;
1485         }
1486       cim = (const struct ConnectInfoMessage *) msg;
1487 #if DEBUG_TRANSPORT
1488       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1489                   "Receiving `%s' message for `%4s'.\n",
1490                   "CONNECT", GNUNET_i2s (&cim->id));
1491 #endif
1492       n = neighbour_find (h, &cim->id);
1493       if (n == NULL)
1494         n = neighbour_add (h,
1495                            &cim->id);
1496       if (n == NULL)
1497         return;
1498       GNUNET_break (n->is_connected == GNUNET_NO);
1499       n->is_connected = GNUNET_YES;
1500       if (h->nc_cb != NULL)
1501         h->nc_cb (h->cls, &n->id,
1502                   GNUNET_TIME_relative_ntoh (cim->latency), 
1503                   ntohl (cim->distance));
1504       break;
1505     case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
1506       if (size != sizeof (struct DisconnectInfoMessage))
1507         {
1508           GNUNET_break (0);
1509           break;
1510         }
1511       dim = (const struct DisconnectInfoMessage *) msg;
1512 #if DEBUG_TRANSPORT_DISCONNECT
1513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514                   "Receiving `%s' message for `%4s'.\n",
1515                   "DISCONNECT",
1516                   GNUNET_i2s (&dim->peer));
1517 #endif
1518       n = neighbour_find (h, &dim->peer);
1519       GNUNET_break (n != NULL);      
1520       if (n != NULL)
1521         neighbour_disconnect (n);       
1522       break;
1523     case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
1524       if (size != sizeof (struct SendOkMessage))
1525         {
1526           GNUNET_break (0);
1527           break;
1528         }
1529       okm = (const struct SendOkMessage *) msg;
1530 #if DEBUG_TRANSPORT
1531       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532                   "Receiving `%s' message, transmission %s.\n", "SEND_OK",
1533                   ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
1534 #endif
1535       n = neighbour_find (h, &okm->peer);
1536       GNUNET_assert (n != NULL);
1537       switch (n->transmit_stage)
1538         {
1539         case TS_NEW:
1540           GNUNET_break (0);
1541           break;
1542         case TS_QUEUED:
1543           GNUNET_break (0);
1544           break;
1545         case TS_TRANSMITTED:
1546           n->transmit_stage = TS_NEW;
1547           break;
1548         case TS_TRANSMITTED_QUEUED:
1549           n->transmit_stage = TS_QUEUED;
1550           schedule_transmission (h);
1551           break;
1552         default:
1553           GNUNET_break (0);
1554         }
1555       break;
1556     case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
1557 #if DEBUG_TRANSPORT
1558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1559                   "Receiving `%s' message.\n", "RECV");
1560 #endif
1561       if (size <
1562           sizeof (struct InboundMessage) +
1563           sizeof (struct GNUNET_MessageHeader))
1564         {
1565           GNUNET_break (0);
1566           break;
1567         }
1568       im = (const struct InboundMessage *) msg;
1569       imm = (const struct GNUNET_MessageHeader *) &im[1];
1570       if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
1571         {
1572           GNUNET_break (0);
1573           break;
1574         }
1575 #if DEBUG_TRANSPORT
1576       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577                   "Received message of type %u from `%4s'.\n",
1578                   ntohs (imm->type), GNUNET_i2s (&im->peer));
1579 #endif      
1580       n = neighbour_find (h, &im->peer);
1581       if (n == NULL)
1582         {
1583           GNUNET_break (0);
1584           break;
1585         }
1586       if (n->is_connected != GNUNET_YES)
1587         {
1588           GNUNET_break (0);
1589           break;
1590         }
1591       if (h->rec != NULL)
1592         h->rec (h->cls, &im->peer, imm,
1593                 GNUNET_TIME_relative_ntoh (im->latency), ntohl(im->distance));
1594       break;
1595     default:
1596       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1597                   _
1598                   ("Received unexpected message of type %u in %s:%u\n"),
1599                   ntohs (msg->type), __FILE__, __LINE__);
1600       GNUNET_break (0);
1601       break;
1602     }
1603 }
1604
1605
1606 /**
1607  * Called when our transmit request timed out before any transport
1608  * reported success connecting to the desired peer or before the
1609  * transport was ready to receive.  Signal error and free
1610  * TransmitHandle.
1611  *
1612  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle*' that is timing out
1613  * @param tc scheduler context
1614  */
1615 static void
1616 peer_transmit_timeout (void *cls,
1617                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1618 {
1619   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
1620   struct NeighbourList *n;
1621   GNUNET_CONNECTION_TransmitReadyNotify notify;
1622   void *notify_cls;
1623
1624   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1625   n = th->neighbour;
1626 #if DEBUG_TRANSPORT
1627   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1628               "Triggering timeout for request to transmit to `%4s' (%d)\n",
1629               GNUNET_i2s (&n->id),
1630               n->transmit_stage);
1631 #endif  
1632   notify = th->notify;
1633   notify_cls = th->notify_cls;
1634   switch (n->transmit_stage)
1635     {
1636     case TS_NEW:
1637       GNUNET_break (0);
1638       break;
1639     case TS_QUEUED:
1640       n->transmit_stage = TS_NEW;
1641       if (n->is_connected == GNUNET_NO)
1642         neighbour_free (n);
1643       break;
1644     case TS_TRANSMITTED:
1645       GNUNET_break (0);
1646       break;
1647     case TS_TRANSMITTED_QUEUED:
1648       n->transmit_stage = TS_TRANSMITTED;
1649       break;
1650     default:
1651       GNUNET_break (0);
1652     }
1653   if (NULL != notify)
1654     notify (notify_cls, 0, NULL);
1655 }
1656
1657
1658 /**
1659  * Check if we could queue a message of the given size for
1660  * transmission.  The transport service will take both its
1661  * internal buffers and bandwidth limits imposed by the
1662  * other peer into consideration when answering this query.
1663  *
1664  * @param handle connection to transport service
1665  * @param target who should receive the message
1666  * @param size how big is the message we want to transmit?
1667  * @param priority how important is the message?
1668  * @param timeout after how long should we give up (and call
1669  *        notify with buf NULL and size 0)?
1670  * @param notify function to call when we are ready to
1671  *        send such a message
1672  * @param notify_cls closure for notify
1673  * @return NULL if someone else is already waiting to be notified
1674  *         non-NULL if the notify callback was queued (can be used to cancel
1675  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1676  */
1677 struct GNUNET_TRANSPORT_TransmitHandle *
1678 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle
1679                                         *handle,
1680                                         const struct GNUNET_PeerIdentity
1681                                         *target, size_t size,
1682                                         unsigned int priority,
1683                                         struct GNUNET_TIME_Relative timeout,
1684                                         GNUNET_CONNECTION_TransmitReadyNotify
1685                                         notify, void *notify_cls)
1686 {
1687   struct GNUNET_TRANSPORT_TransmitHandle *th;
1688   struct NeighbourList *n;
1689
1690   if (size + sizeof (struct OutboundMessage) >=
1691       GNUNET_SERVER_MAX_MESSAGE_SIZE)
1692     {
1693 #if DEBUG_TRANSPORT
1694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695                   "Message size is %d, max allowed is %d.\n",
1696                   size + sizeof (struct OutboundMessage), GNUNET_SERVER_MAX_MESSAGE_SIZE);
1697 #endif
1698       GNUNET_break (0);
1699       return NULL;
1700     }
1701 #if DEBUG_TRANSPORT
1702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703               "Asking transport service for transmission of %u bytes to peer `%4s' within %llu ms.\n",
1704               size, GNUNET_i2s (target),
1705               (unsigned long long) timeout.value);
1706 #endif
1707   n = neighbour_find (handle, target);
1708   if (n == NULL)
1709     n = neighbour_add (handle, target);
1710   if (n == NULL) 
1711     {
1712       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1713                   "Could not create neighbour entry for peer `%s'\n",
1714                   GNUNET_i2s (target));
1715       return NULL;
1716     }
1717   switch (n->transmit_stage)
1718     {
1719     case TS_NEW:
1720       n->transmit_stage = TS_QUEUED;
1721       break;
1722     case TS_QUEUED:
1723       GNUNET_break (0);
1724       return NULL;
1725     case TS_TRANSMITTED:
1726       n->transmit_stage = TS_TRANSMITTED_QUEUED;
1727       break;
1728     case TS_TRANSMITTED_QUEUED:
1729       GNUNET_break (0);
1730       return NULL;
1731     default:
1732       GNUNET_break (0);
1733       return NULL;
1734     }
1735   th = &n->transmit_handle;
1736   th->neighbour = n;
1737   th->notify = notify;
1738   th->notify_cls = notify_cls;
1739   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1740   th->notify_size = size + sizeof (struct OutboundMessage);
1741   th->priority = priority;
1742   th->notify_delay_task
1743     = GNUNET_SCHEDULER_add_delayed (handle->sched, timeout,
1744                                     &peer_transmit_timeout, th);
1745   schedule_transmission (handle);
1746   return th;
1747 }
1748
1749
1750 /**
1751  * Cancel the specified transmission-ready notification.
1752  */
1753 void
1754 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1755                                                GNUNET_TRANSPORT_TransmitHandle
1756                                                *th)
1757 {
1758   struct NeighbourList *n;
1759
1760   n = th->neighbour;
1761 #if DEBUG_TRANSPORT
1762   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763               "Transmission request of %u bytes to `%4s' was cancelled.\n",
1764               th->notify_size - sizeof (struct OutboundMessage),
1765               GNUNET_i2s (&n->id));
1766 #endif
1767   switch (n->transmit_stage)
1768     {
1769     case TS_NEW:
1770       GNUNET_break (0);
1771       break;
1772     case TS_QUEUED:
1773       n->transmit_stage = TS_NEW;
1774       if (n->is_connected == GNUNET_NO)
1775         neighbour_free (n);
1776       break;
1777     case TS_TRANSMITTED:
1778       GNUNET_break (0);
1779       break;
1780     case TS_TRANSMITTED_QUEUED:
1781       n->transmit_stage = TS_TRANSMITTED;
1782       break;
1783     default:
1784       GNUNET_break (0);
1785     }
1786 }
1787
1788
1789 /* end of transport_api.c */