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