removed malloc from curl_logger
[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  * Create and send a request connect message to
1293  * the transport service for a particular peer.
1294  *
1295  * @param h handle to the transport service
1296  * @param n the neighbor to send the request connect message about
1297  *
1298  */
1299 static void 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 sched scheduler to use
1356  * @param cfg configuration to use
1357  * @param self our own identity (API should check that it matches
1358  *             the identity found by transport), or NULL (no check)
1359  * @param cls closure for the callbacks
1360  * @param rec receive function to call
1361  * @param nc function to call on connect events
1362  * @param nd function to call on disconnect events
1363  */
1364 struct GNUNET_TRANSPORT_Handle *
1365 GNUNET_TRANSPORT_connect (struct GNUNET_SCHEDULER_Handle *sched,
1366                           const struct GNUNET_CONFIGURATION_Handle *cfg,
1367                           const struct GNUNET_PeerIdentity *self,
1368                           void *cls,
1369                           GNUNET_TRANSPORT_ReceiveCallback rec,
1370                           GNUNET_TRANSPORT_NotifyConnect nc,
1371                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1372 {
1373   struct GNUNET_TRANSPORT_Handle *ret;
1374
1375   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1376   if (self != NULL)
1377     {
1378       ret->self = *self;
1379       ret->check_self = GNUNET_YES;
1380     }
1381   ret->sched = sched;
1382   ret->cfg = cfg;
1383   ret->cls = cls;
1384   ret->rec = rec;
1385   ret->nc_cb = nc;
1386   ret->nd_cb = nd;
1387   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1388   schedule_reconnect (ret);
1389   return ret;
1390 }
1391
1392
1393 /**
1394  * Disconnect from the transport service.
1395  */
1396 void
1397 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1398 {
1399   struct GNUNET_TRANSPORT_TransmitHandle *th;
1400   struct NeighbourList *n;
1401   struct HelloWaitList *hwl;
1402   struct GNUNET_CLIENT_Connection *client;
1403   struct ControlMessage *cm;
1404
1405 #if DEBUG_TRANSPORT
1406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1407 #endif
1408   handle->in_disconnect = GNUNET_YES;
1409   while (NULL != (n = handle->neighbours))
1410     {
1411       handle->neighbours = n->next;
1412       switch (n->transmit_stage)
1413         {
1414         case TS_NEW:
1415         case TS_TRANSMITTED:
1416           /* nothing to do */
1417           break;
1418         case TS_QUEUED:
1419         case TS_TRANSMITTED_QUEUED:
1420           th = &n->transmit_handle;
1421           if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1422             {
1423               GNUNET_SCHEDULER_cancel (handle->sched,
1424                                        th->notify_delay_task);
1425               th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1426             }
1427           GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
1428           break;
1429         default:
1430           GNUNET_break (0);
1431         }
1432       GNUNET_free (n);
1433     }
1434   while (NULL != (hwl = handle->hwl_head))
1435     {
1436       handle->hwl_head = hwl->next;
1437       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1438                   _
1439                   ("Disconnect while notification for `%s' still registered.\n"),
1440                   "HELLO");
1441       if (hwl->rec != NULL)
1442         hwl->rec (hwl->rec_cls, NULL);
1443       GNUNET_free (hwl);
1444     }
1445
1446   /* Check for still scheduled control messages, cancel delay tasks if so */
1447   /* Added because somehow a notify_delay_task is remaining scheduled and is ever so annoying */
1448   while ( (NULL != (cm = handle->control_head)))
1449     {
1450 #if DEBUG_TRANSPORT
1451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1452                   "Disconnect before control message sent!\n");
1453 #endif
1454       if (cm->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1455         {
1456           GNUNET_SCHEDULER_cancel (handle->sched, cm->notify_delay_task);
1457           cm->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1458         }
1459       GNUNET_CONTAINER_DLL_remove (handle->control_head,
1460                                    handle->control_tail,
1461                                    cm);
1462       GNUNET_free (cm);
1463     }
1464   /* end check */
1465
1466   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1467     {
1468       GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
1469       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1470     }
1471   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1472     {
1473       GNUNET_SCHEDULER_cancel (handle->sched, handle->quota_task);
1474       handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1475     }
1476   GNUNET_free_non_null (handle->my_hello);
1477   handle->my_hello = NULL;
1478
1479   if (NULL != handle->network_handle)
1480     {
1481       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->network_handle);
1482       handle->network_handle = NULL;
1483     }
1484   if (NULL != (client = handle->client))
1485     {
1486 #if DEBUG_TRANSPORT
1487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1488                   "Disconnecting from transport service for good.\n");
1489 #endif
1490       handle->client = NULL;
1491       GNUNET_CLIENT_disconnect (client, GNUNET_NO);
1492     }
1493   GNUNET_free (handle);
1494 }
1495
1496
1497 /**
1498  * Function we use for handling incoming messages.
1499  *
1500  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1501  * @param msg message received, NULL on timeout or fatal error
1502  */
1503 static void
1504 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
1505 {
1506   struct GNUNET_TRANSPORT_Handle *h = cls;
1507   const struct DisconnectInfoMessage *dim;
1508   const struct ConnectInfoMessage *cim;
1509   const struct InboundMessage *im;
1510   const struct GNUNET_MessageHeader *imm;
1511   const struct SendOkMessage *okm;
1512   struct HelloWaitList *hwl;
1513   struct HelloWaitList *next_hwl;
1514   struct NeighbourList *n;
1515   struct GNUNET_PeerIdentity me;
1516   uint16_t size;
1517
1518   if (h->client == NULL)
1519     {
1520       /* shutdown initiated from 'GNUNET_TRANSPORT_disconnect',
1521          finish clean up work! */
1522       GNUNET_free (h);
1523       return;
1524     }
1525   if (msg == NULL)
1526     {
1527 #if DEBUG_TRANSPORT
1528       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1529                   "Error receiving from transport service, disconnecting temporarily.\n");
1530 #endif
1531       if (h->network_handle != NULL)
1532         {
1533           GNUNET_CLIENT_notify_transmit_ready_cancel (h->network_handle);
1534           h->network_handle = NULL;
1535         }
1536       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1537       h->client = NULL;
1538       schedule_reconnect (h);
1539       return;
1540     }
1541   GNUNET_CLIENT_receive (h->client,
1542                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1543   size = ntohs (msg->size);
1544   switch (ntohs (msg->type))
1545     {
1546     case GNUNET_MESSAGE_TYPE_HELLO:
1547       if (GNUNET_OK !=
1548           GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
1549                                &me))
1550         {
1551           GNUNET_break (0);
1552           break;
1553         }
1554 #if DEBUG_TRANSPORT
1555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1556                   "Receiving (my own) `%s' message, I am `%4s'.\n",
1557                   "HELLO", GNUNET_i2s (&me));
1558 #endif
1559       GNUNET_free_non_null (h->my_hello);
1560       h->my_hello = NULL;
1561       if (size < sizeof (struct GNUNET_MessageHeader))
1562         {
1563           GNUNET_break (0);
1564           break;
1565         }
1566       h->my_hello = GNUNET_malloc (size);
1567       memcpy (h->my_hello, msg, size);
1568       hwl = h->hwl_head;
1569       while (NULL != hwl)
1570         {
1571           next_hwl = hwl->next;
1572           hwl->rec (hwl->rec_cls,
1573                     (const struct GNUNET_MessageHeader *) h->my_hello);
1574           hwl = next_hwl;
1575         }
1576       break;
1577     case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
1578       if (size != sizeof (struct ConnectInfoMessage))
1579         {
1580           GNUNET_break (0);
1581           break;
1582         }
1583       cim = (const struct ConnectInfoMessage *) msg;
1584 #if DEBUG_TRANSPORT
1585       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1586                   "Receiving `%s' message for `%4s'.\n",
1587                   "CONNECT", GNUNET_i2s (&cim->id));
1588 #endif
1589       n = neighbour_find (h, &cim->id);
1590       if (n == NULL)
1591         n = neighbour_add (h,
1592                            &cim->id);
1593       if (n == NULL)
1594         return;
1595       GNUNET_break (n->is_connected == GNUNET_NO);
1596       n->is_connected = GNUNET_YES;
1597       if (h->nc_cb != NULL)
1598         h->nc_cb (h->cls, &n->id,
1599                   GNUNET_TIME_relative_ntoh (cim->latency),
1600                   ntohl (cim->distance));
1601       break;
1602     case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
1603       if (size != sizeof (struct DisconnectInfoMessage))
1604         {
1605           GNUNET_break (0);
1606           break;
1607         }
1608       dim = (const struct DisconnectInfoMessage *) msg;
1609 #if DEBUG_TRANSPORT_DISCONNECT
1610       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611                   "Receiving `%s' message for `%4s'.\n",
1612                   "DISCONNECT",
1613                   GNUNET_i2s (&dim->peer));
1614 #endif
1615       n = neighbour_find (h, &dim->peer);
1616       GNUNET_break (n != NULL);
1617       if (n != NULL)
1618         neighbour_disconnect (n);       
1619       break;
1620     case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
1621       if (size != sizeof (struct SendOkMessage))
1622         {
1623           GNUNET_break (0);
1624           break;
1625         }
1626       okm = (const struct SendOkMessage *) msg;
1627 #if DEBUG_TRANSPORT
1628       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629                   "Receiving `%s' message, transmission %s.\n", "SEND_OK",
1630                   ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
1631 #endif
1632       n = neighbour_find (h, &okm->peer);
1633       GNUNET_assert (n != NULL);
1634       switch (n->transmit_stage)
1635         {
1636         case TS_NEW:
1637           GNUNET_break (0);
1638           break;
1639         case TS_QUEUED:
1640           GNUNET_break (0);
1641           break;
1642         case TS_TRANSMITTED:
1643           n->transmit_stage = TS_NEW;
1644           break;
1645         case TS_TRANSMITTED_QUEUED:
1646           n->transmit_stage = TS_QUEUED;
1647           schedule_transmission (h);
1648           break;
1649         default:
1650           GNUNET_break (0);
1651         }
1652       break;
1653     case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
1654 #if DEBUG_TRANSPORT
1655       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1656                   "Receiving `%s' message.\n", "RECV");
1657 #endif
1658       if (size <
1659           sizeof (struct InboundMessage) +
1660           sizeof (struct GNUNET_MessageHeader))
1661         {
1662           GNUNET_break (0);
1663           break;
1664         }
1665       im = (const struct InboundMessage *) msg;
1666       imm = (const struct GNUNET_MessageHeader *) &im[1];
1667       if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
1668         {
1669           GNUNET_break (0);
1670           break;
1671         }
1672 #if DEBUG_TRANSPORT
1673       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1674                   "Received message of type %u from `%4s'.\n",
1675                   ntohs (imm->type), GNUNET_i2s (&im->peer));
1676 #endif
1677       n = neighbour_find (h, &im->peer);
1678       if (n == NULL)
1679         {
1680           GNUNET_break (0);
1681           break;
1682         }
1683       if (n->is_connected != GNUNET_YES)
1684         {
1685           GNUNET_break (0);
1686           break;
1687         }
1688       if (h->rec != NULL)
1689         h->rec (h->cls, &im->peer, imm,
1690                 GNUNET_TIME_relative_ntoh (im->latency), ntohl(im->distance));
1691       break;
1692     default:
1693       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1694                   _
1695                   ("Received unexpected message of type %u in %s:%u\n"),
1696                   ntohs (msg->type), __FILE__, __LINE__);
1697       GNUNET_break (0);
1698       break;
1699     }
1700 }
1701
1702
1703 /**
1704  * Called when our transmit request timed out before any transport
1705  * reported success connecting to the desired peer or before the
1706  * transport was ready to receive.  Signal error and free
1707  * TransmitHandle.
1708  *
1709  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle*' that is timing out
1710  * @param tc scheduler context
1711  */
1712 static void
1713 peer_transmit_timeout (void *cls,
1714                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1715 {
1716   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
1717   struct NeighbourList *n;
1718   GNUNET_CONNECTION_TransmitReadyNotify notify;
1719   void *notify_cls;
1720
1721   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1722   n = th->neighbour;
1723 #if DEBUG_TRANSPORT
1724   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1725               "Triggering timeout for request to transmit to `%4s' (%d)\n",
1726               GNUNET_i2s (&n->id),
1727               n->transmit_stage);
1728 #endif
1729   notify = th->notify;
1730   notify_cls = th->notify_cls;
1731   switch (n->transmit_stage)
1732     {
1733     case TS_NEW:
1734       GNUNET_break (0);
1735       break;
1736     case TS_QUEUED:
1737       n->transmit_stage = TS_NEW;
1738       if (n->is_connected == GNUNET_NO)
1739         neighbour_free (n);
1740       break;
1741     case TS_TRANSMITTED:
1742       GNUNET_break (0);
1743       break;
1744     case TS_TRANSMITTED_QUEUED:
1745       n->transmit_stage = TS_TRANSMITTED;
1746       break;
1747     default:
1748       GNUNET_break (0);
1749     }
1750   if (NULL != notify)
1751     notify (notify_cls, 0, NULL);
1752 }
1753
1754
1755 /**
1756  * Check if we could queue a message of the given size for
1757  * transmission.  The transport service will take both its
1758  * internal buffers and bandwidth limits imposed by the
1759  * other peer into consideration when answering this query.
1760  *
1761  * @param handle connection to transport service
1762  * @param target who should receive the message
1763  * @param size how big is the message we want to transmit?
1764  * @param priority how important is the message?
1765  * @param timeout after how long should we give up (and call
1766  *        notify with buf NULL and size 0)?
1767  * @param notify function to call when we are ready to
1768  *        send such a message
1769  * @param notify_cls closure for notify
1770  * @return NULL if someone else is already waiting to be notified
1771  *         non-NULL if the notify callback was queued (can be used to cancel
1772  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1773  */
1774 struct GNUNET_TRANSPORT_TransmitHandle *
1775 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle
1776                                         *handle,
1777                                         const struct GNUNET_PeerIdentity
1778                                         *target, size_t size,
1779                                         unsigned int priority,
1780                                         struct GNUNET_TIME_Relative timeout,
1781                                         GNUNET_CONNECTION_TransmitReadyNotify
1782                                         notify, void *notify_cls)
1783 {
1784   struct GNUNET_TRANSPORT_TransmitHandle *th;
1785   struct NeighbourList *n;
1786
1787   if (size + sizeof (struct OutboundMessage) >=
1788       GNUNET_SERVER_MAX_MESSAGE_SIZE)
1789     {
1790 #if DEBUG_TRANSPORT
1791       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1792                   "Message size is %d, max allowed is %d.\n",
1793                   size + sizeof (struct OutboundMessage), GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
1794 #endif
1795       GNUNET_break (0);
1796       return NULL;
1797     }
1798
1799   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1800               "Asking transport service for transmission of %u bytes to peer `%4s' within %llu ms.\n",
1801               size, GNUNET_i2s (target),
1802               (unsigned long long) timeout.value);
1803
1804   n = neighbour_find (handle, target);
1805   if (n == NULL)
1806     {
1807       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1808                   "Created neighbour entry for peer `%s'\n",
1809                   GNUNET_i2s (target));
1810       n = neighbour_add (handle, target);
1811
1812     }
1813
1814   /**
1815    *  Send a request connect message if not connected,
1816    *  otherwise we will never send anything to
1817    *  transport service
1818    */
1819   if (n->is_connected == GNUNET_NO)
1820     {
1821       send_request_connect_message(handle, n);
1822     }
1823
1824   if (n == NULL)
1825     {
1826       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827                   "Could not create neighbour entry for peer `%s'\n",
1828                   GNUNET_i2s (target));
1829       return NULL;
1830     }
1831   switch (n->transmit_stage)
1832     {
1833     case TS_NEW:
1834       n->transmit_stage = TS_QUEUED;
1835       break;
1836     case TS_QUEUED:
1837       GNUNET_break (0);
1838       return NULL;
1839     case TS_TRANSMITTED:
1840       n->transmit_stage = TS_TRANSMITTED_QUEUED;
1841       break;
1842     case TS_TRANSMITTED_QUEUED:
1843       GNUNET_break (0);
1844       return NULL;
1845     default:
1846       GNUNET_break (0);
1847       return NULL;
1848     }
1849   th = &n->transmit_handle;
1850   th->neighbour = n;
1851   th->notify = notify;
1852   th->notify_cls = notify_cls;
1853   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1854   th->notify_size = size + sizeof (struct OutboundMessage);
1855   th->priority = priority;
1856   th->notify_delay_task
1857     = GNUNET_SCHEDULER_add_delayed (handle->sched, timeout,
1858                                     &peer_transmit_timeout, th);
1859   schedule_transmission (handle);
1860   return th;
1861 }
1862
1863
1864 /**
1865  * Cancel the specified transmission-ready notification.
1866  */
1867 void
1868 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1869                                                GNUNET_TRANSPORT_TransmitHandle
1870                                                *th)
1871 {
1872   struct NeighbourList *n;
1873
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   switch (n->transmit_stage)
1882     {
1883     case TS_NEW:
1884       GNUNET_break (0);
1885       break;
1886     case TS_QUEUED:
1887       n->transmit_stage = TS_NEW;
1888       if (n->is_connected == GNUNET_NO)
1889         neighbour_free (n);
1890       break;
1891     case TS_TRANSMITTED:
1892       GNUNET_break (0);
1893       break;
1894     case TS_TRANSMITTED_QUEUED:
1895       n->transmit_stage = TS_TRANSMITTED;
1896       break;
1897     default:
1898       GNUNET_break (0);
1899     }
1900 }
1901
1902
1903 /* end of transport_api.c */