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