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