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