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