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