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