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