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