fixed coverity bug #10042
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/transport_api.c
23  * @brief library to access the low-level P2P IO service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_bandwidth_lib.h"
28 #include "gnunet_client_lib.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_container_lib.h"
31 #include "gnunet_arm_service.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_time_lib.h"
36 #include "gnunet_transport_service.h"
37 #include "transport.h"
38
39 /**
40  * After how long do we give up on transmitting a HELLO
41  * to the service?
42  */
43 #define OFFER_HELLO_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
44
45 /**
46  * After how long do we automatically retry an unsuccessful
47  * CONNECT request?
48  */
49 #define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 750)
50
51 /**
52  * How long should ARM wait when starting up the
53  * transport service before reporting back?
54  */
55 #define START_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
56
57 /**
58  * How long should ARM wait when stopping the
59  * transport service before reporting back?
60  */
61 #define STOP_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
62
63
64 /**
65  * What stage are we in for transmission processing?
66  */
67 enum TransmitStage
68   {
69     /**
70      * No active message.
71      */
72     TS_NEW = 0,
73
74     /**
75      * Message in local queue, not given to service.
76      */
77     TS_QUEUED = 1,
78
79     /**
80      * Message given to service, not confirmed (no SEND_OK).
81      */
82     TS_TRANSMITTED = 2,
83
84     /**
85      * One message was given to service and before it was confirmed,
86      * another one was already queued (waiting for SEND_OK to pass on
87      * to service).
88      */
89     TS_TRANSMITTED_QUEUED = 3
90   };
91
92
93 /**
94  * Handle for a transmission-ready request.
95  */
96 struct GNUNET_TRANSPORT_TransmitHandle
97 {
98
99   /**
100    * Neighbour for this handle, NULL for control-traffic.
101    */
102   struct NeighbourList *neighbour;
103
104   /**
105    * Function to call when notify_size bytes are available
106    * for transmission.
107    */
108   GNUNET_CONNECTION_TransmitReadyNotify notify;
109
110   /**
111    * Closure for notify.
112    */
113   void *notify_cls;
114
115   /**
116    * transmit_ready task Id.  The task is used to introduce the
117    * artificial delay that may be required to maintain the bandwidth
118    * limits.  Later, this will be the ID of the "transmit_timeout"
119    * task which is used to signal a timeout if the transmission could
120    * not be done in a timely fashion.
121    */
122   GNUNET_SCHEDULER_TaskIdentifier notify_delay_task;
123
124   /**
125    * Timeout for this request.
126    */
127   struct GNUNET_TIME_Absolute timeout;
128
129   /**
130    * How many bytes is our notify callback waiting for?
131    */
132   size_t notify_size;
133
134   /**
135    * How important is this message?
136    */
137   unsigned int priority;
138
139 };
140
141
142 /**
143  * Handle for a control message queue entry.
144  */
145 struct ControlMessage
146 {
147
148   /**
149    * This is a doubly-linked list.
150    */
151   struct ControlMessage *next;
152
153   /**
154    * This is a doubly-linked list.
155    */
156   struct ControlMessage *prev;
157
158   /**
159    * Overall transport handle.
160    */
161   struct GNUNET_TRANSPORT_Handle *h;
162
163   /**
164    * Function to call when notify_size bytes are available
165    * for transmission.
166    */
167   GNUNET_CONNECTION_TransmitReadyNotify notify;
168
169   /**
170    * Closure for notify.
171    */
172   void *notify_cls;
173
174   /**
175    * transmit_ready task Id.  The task is used to introduce the
176    * artificial delay that may be required to maintain the bandwidth
177    * limits.  Later, this will be the ID of the "transmit_timeout"
178    * task which is used to signal a timeout if the transmission could
179    * not be done in a timely fashion.
180    */
181   GNUNET_SCHEDULER_TaskIdentifier notify_delay_task;
182
183   /**
184    * How many bytes is our notify callback waiting for?
185    */
186   size_t notify_size;
187
188 };
189
190
191 /**
192  * Entry in linked list of all of our current neighbours.
193  */
194 struct NeighbourList
195 {
196
197   /**
198    * This is a linked list.
199    */
200   struct NeighbourList *next;
201
202   /**
203    * Overall transport handle.
204    */
205   struct GNUNET_TRANSPORT_Handle *h;
206
207   /**
208    * Active transmit handle; available if 'transmit_forbidden'
209    * is GNUNET_NO.
210    */
211   struct GNUNET_TRANSPORT_TransmitHandle transmit_handle;
212
213   /**
214    * Identity of this neighbour.
215    */
216   struct GNUNET_PeerIdentity id;
217
218   /**
219    * Outbound bandwidh tracker.
220    */
221   struct GNUNET_BANDWIDTH_Tracker out_tracker;
222
223   /**
224    * Set to GNUNET_NO if we are currently allowed to accept a
225    * message to the transport service for this peer, GNUNET_YES
226    * if we have one and are waiting for transmission, GNUNET_SYSERR
227    * if we are waiting for confirmation AND have already accepted
228    * yet another message.
229    */
230   enum TransmitStage transmit_stage;
231
232   /**
233    * Have we received a notification that this peer is connected
234    * to us right now?
235    */
236   int is_connected;
237
238 };
239
240
241 /**
242  * Linked list of requests from clients for our HELLO that were
243  * deferred.
244  */
245 struct HelloWaitList
246 {
247
248   /**
249    * This is a linked list.
250    */
251   struct HelloWaitList *next;
252
253   /**
254    * Reference back to our transport handle.
255    */
256   struct GNUNET_TRANSPORT_Handle *handle;
257
258   /**
259    * Callback to call once we got our HELLO.
260    */
261   GNUNET_TRANSPORT_HelloUpdateCallback rec;
262
263   /**
264    * Closure for rec.
265    */
266   void *rec_cls;
267
268 };
269
270
271 /**
272  * Handle for the transport service (includes all of the
273  * state for the transport service).
274  */
275 struct GNUNET_TRANSPORT_Handle
276 {
277
278   /**
279    * Closure for the callbacks.
280    */
281   void *cls;
282
283   /**
284    * Function to call for received data.
285    */
286   GNUNET_TRANSPORT_ReceiveCallback rec;
287
288   /**
289    * function to call on connect events
290    */
291   GNUNET_TRANSPORT_NotifyConnect nc_cb;
292
293   /**
294    * function to call on disconnect events
295    */
296   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
297
298   /**
299    * Head of DLL of control messages.
300    */
301   struct ControlMessage *control_head;
302
303   /**
304    * Tail of DLL of control messages.
305    */
306   struct ControlMessage *control_tail;
307
308   /**
309    * The current HELLO message for this peer.  Updated
310    * whenever transports change their addresses.
311    */
312   struct GNUNET_HELLO_Message *my_hello;
313
314   /**
315    * My client connection to the transport service.
316    */
317   struct GNUNET_CLIENT_Connection *client;
318
319   /**
320    * Handle to our registration with the client for notification.
321    */
322   struct GNUNET_CLIENT_TransmitHandle *network_handle;
323
324   /**
325    * Linked list of pending requests for our HELLO.
326    */
327   struct HelloWaitList *hwl_head;
328
329   /**
330    * My configuration.
331    */
332   const struct GNUNET_CONFIGURATION_Handle *cfg;
333
334   /**
335    * Linked list of the current neighbours of this peer.
336    */
337   struct NeighbourList *neighbours;
338
339   /**
340    * Peer identity as assumed by this process, or all zeros.
341    */
342   struct GNUNET_PeerIdentity self;
343
344   /**
345    * ID of the task trying to reconnect to the service.
346    */
347   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
348
349   /**
350    * ID of the task trying to trigger transmission for a peer
351    * while maintaining bandwidth quotas.
352    */
353   GNUNET_SCHEDULER_TaskIdentifier quota_task;
354
355   /**
356    * Delay until we try to reconnect.
357    */
358   struct GNUNET_TIME_Relative reconnect_delay;
359
360   /**
361    * Set once we are in the process of disconnecting from the
362    * service.
363    */
364   int in_disconnect;
365
366   /**
367    * Should we check that 'self' matches what the service thinks?
368    * (if GNUNET_NO, then 'self' is all zeros!).
369    */
370   int check_self;
371 };
372
373
374 // FIXME: replace with hash map!
375 /**
376  * Get the neighbour list entry for the given peer
377  *
378  * @param h our context
379  * @param peer peer to look up
380  * @return NULL if no such peer entry exists
381  */
382 static struct NeighbourList *
383 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
384                 const struct GNUNET_PeerIdentity *peer)
385 {
386   struct NeighbourList *pos;
387
388   pos = h->neighbours;
389   while ((pos != NULL) &&
390          (0 != memcmp (peer, &pos->id, sizeof (struct GNUNET_PeerIdentity))))
391     pos = pos->next;
392   return pos;
393 }
394
395
396 /**
397  * Schedule the task to send one message, either from the control
398  * list or the peer message queues  to the service.
399  */
400 static void schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
401
402
403 /**
404  * Function called by the scheduler when the timeout for bandwidth
405  * availablility for the target neighbour is reached.
406  *
407  * @param cls the 'struct GNUNET_TRANSPORT_Handle*'
408  * @param tc scheduler context
409  */
410 static void
411 quota_transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
412 {
413   struct GNUNET_TRANSPORT_Handle *h = cls;
414
415   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
416   schedule_transmission (h);
417 }
418
419
420 /**
421  * Figure out which transmission to a peer can be done right now.
422  * If none can, schedule a task to call 'schedule_transmission'
423  * whenever a peer transmission can be done in the future and
424  * return NULL.  Otherwise return the next transmission to be
425  * performed.
426  *
427  * @param h handle to transport
428  * @return NULL to wait longer before doing any peer transmissions
429  */
430 static struct GNUNET_TRANSPORT_TransmitHandle *
431 schedule_peer_transmission (struct GNUNET_TRANSPORT_Handle *h)
432 {
433   struct GNUNET_TRANSPORT_TransmitHandle *ret;
434   struct GNUNET_TRANSPORT_TransmitHandle *th;
435   struct NeighbourList *n;
436   struct NeighbourList *next;
437   struct GNUNET_TIME_Relative retry_time;
438   struct GNUNET_TIME_Relative duration;
439
440   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
441     {
442       GNUNET_SCHEDULER_cancel (h->quota_task);
443       h->quota_task = GNUNET_SCHEDULER_NO_TASK;
444     }
445   retry_time = GNUNET_TIME_UNIT_FOREVER_REL;
446   ret = NULL;
447   next = h->neighbours;
448   while (NULL != (n = next))
449     {
450       next = n->next;
451       if (n->transmit_stage != TS_QUEUED)
452         continue; /* not eligible */
453       if (n->is_connected != GNUNET_YES)
454         continue;
455
456       th = &n->transmit_handle;
457       GNUNET_break (n == th->neighbour);
458       /* check outgoing quota */
459       duration = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
460                                                      th->notify_size - sizeof (struct OutboundMessage));
461       struct GNUNET_TIME_Absolute duration_abs = GNUNET_TIME_relative_to_absolute (duration);
462       if (th->timeout.abs_value < duration_abs.abs_value)
463         {
464           /* signal timeout! */
465 #if DEBUG_TRANSPORT
466           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
467                       "Would need %llu ms before bandwidth is available for delivery to `%4s', that is too long.  Signaling timeout.\n",
468                       duration.rel_value,
469                       GNUNET_i2s (&n->id));
470 #endif
471           if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
472             {
473               GNUNET_SCHEDULER_cancel (th->notify_delay_task);
474               th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
475             }   
476           n->transmit_stage = TS_NEW;
477           if (NULL != th->notify)
478             GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
479           continue;
480         }
481       if (duration.rel_value > 0)
482         {
483 #if DEBUG_TRANSPORT
484           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485                       "Need more bandwidth (%u b/s allowed, %u b needed), delaying delivery to `%4s' by %llu ms\n",
486                       (unsigned int) n->out_tracker.available_bytes_per_s__,
487                       (unsigned int) th->notify_size - sizeof (struct OutboundMessage),
488                       GNUNET_i2s (&n->id),
489                       duration.rel_value);
490 #endif
491           retry_time = GNUNET_TIME_relative_min (retry_time,
492                                                  duration);
493           continue;
494         }
495 #if DEBUG_TRANSPORT
496       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497                   "Have %u bytes of bandwidth available for transmission to `%4s' right now\n",
498                   th->notify_size - sizeof (struct OutboundMessage),
499                   GNUNET_i2s (&n->id));
500 #endif  
501
502       if ( (ret == NULL) ||
503            (ret->priority < th->priority) )
504         ret = th;
505     }
506   if (ret == NULL)
507     h->quota_task = GNUNET_SCHEDULER_add_delayed (retry_time,
508                                                   &quota_transmit_ready,
509                                                   h);
510   return ret;
511 }
512
513
514 /**
515  * Transmit message(s) to service.
516  *
517  * @param cls handle to transport
518  * @param size number of bytes available in buf
519  * @param buf where to copy the message
520  * @return number of bytes copied to buf
521  */
522 static size_t
523 transport_notify_ready (void *cls, size_t size, void *buf)
524 {
525   struct GNUNET_TRANSPORT_Handle *h = cls;
526   struct ControlMessage *cm;
527   struct GNUNET_TRANSPORT_TransmitHandle *th;
528   struct NeighbourList *n;
529   struct OutboundMessage obm;
530   size_t ret;
531   size_t mret;
532   size_t nret;
533   char *cbuf;
534
535   h->network_handle = NULL;
536   if (buf == NULL)
537     {
538       schedule_transmission (h);
539       return 0;
540     }
541 #if DEBUG_TRANSPORT
542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
543               "Ready to transmit %u bytes to transport service\n", size);
544 #endif
545   cbuf = buf;
546   ret = 0;
547   while ( (NULL != (cm = h->control_head)) &&
548           (cm->notify_size <= size) )
549     {
550       if (cm->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
551         {
552           GNUNET_SCHEDULER_cancel (cm->notify_delay_task);
553           cm->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
554         }
555       GNUNET_CONTAINER_DLL_remove (h->control_head,
556                                    h->control_tail,
557                                    cm);
558       nret = cm->notify (cm->notify_cls, size, &cbuf[ret]);
559 #if DEBUG_TRANSPORT
560       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
561                   "Added %u bytes of control message at %u\n",
562                   nret,
563                   ret);
564 #endif
565       GNUNET_free (cm);
566       ret += nret;
567       size -= nret;
568     }
569   while ( (NULL != (th = schedule_peer_transmission (h))) &&
570           (th->notify_size <= size) )
571     {
572       if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
573         {
574           GNUNET_SCHEDULER_cancel (th->notify_delay_task);
575           th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
576         }
577       n = th->neighbour;
578       switch (n->transmit_stage)
579         {
580         case TS_NEW:
581           GNUNET_break (0);
582           break;
583         case TS_QUEUED:
584           n->transmit_stage = TS_TRANSMITTED;
585           break;
586         case TS_TRANSMITTED:
587           GNUNET_break (0);
588           break;
589         case TS_TRANSMITTED_QUEUED:
590           GNUNET_break (0);
591           break;
592         default:
593           GNUNET_break (0);
594         }
595       GNUNET_assert (size >= sizeof (struct OutboundMessage));
596       mret = th->notify (th->notify_cls,
597                          size - sizeof (struct OutboundMessage),
598                          &cbuf[ret + sizeof (struct OutboundMessage)]);
599       GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
600 #if DEBUG_TRANSPORT
601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
602                   "Message of %u bytes with timeout %llums constructed for `%4s'\n",
603                   (unsigned int) mret,
604                   (unsigned long long) GNUNET_TIME_absolute_get_remaining (th->timeout).rel_value,
605                   GNUNET_i2s (&n->id));
606 #endif
607       if (mret != 0)    
608         {
609           GNUNET_assert (mret + sizeof (struct OutboundMessage) < GNUNET_SERVER_MAX_MESSAGE_SIZE);
610           obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
611           obm.header.size = htons (mret + sizeof (struct OutboundMessage));
612           obm.priority = htonl (th->priority);
613           obm.timeout = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (th->timeout));
614           obm.peer = n->id;
615           memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
616           ret += (mret + sizeof (struct OutboundMessage));
617           size -= (mret + sizeof (struct OutboundMessage));
618           GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
619         }
620       else
621         {
622           switch (n->transmit_stage)
623             {
624             case TS_NEW:
625               GNUNET_break (0);
626               break;
627             case TS_QUEUED:
628               GNUNET_break (0);
629               break;
630             case TS_TRANSMITTED:
631               n->transmit_stage = TS_NEW;
632               break;
633             case TS_TRANSMITTED_QUEUED:
634               n->transmit_stage = TS_QUEUED;
635               continue;
636             default:
637               GNUNET_break (0);
638             }
639         }
640     }
641   schedule_transmission (h);
642 #if DEBUG_TRANSPORT
643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644               "Transmitting %u bytes to transport service\n", ret);
645 #endif
646   return ret;
647 }
648
649
650 /**
651  * Schedule the task to send one message, either from the control
652  * list or the peer message queues  to the service.
653  */
654 static void
655 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
656 {
657   size_t size;
658   struct GNUNET_TIME_Relative timeout;
659   struct GNUNET_TRANSPORT_TransmitHandle *th;
660
661   if (NULL != h->network_handle)
662     return;
663   if (h->client == NULL)
664     {
665       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666                   _("Could not yet schedule transmission: we are not yet connected to the transport service!\n"));
667       return;                   /* not yet connected */
668     }
669   if (NULL != h->control_head)
670     {
671       size = h->control_head->notify_size;
672       timeout = GNUNET_TIME_UNIT_FOREVER_REL;
673     }
674   else
675     {
676       th = schedule_peer_transmission (h);
677       if (th == NULL)
678         {
679           /* no transmission ready right now */
680 #if DEBUG_TRANSPORT
681           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682                       "Could not yet schedule transmission: none ready\n");
683 #endif
684           return;
685         }
686       size = th->notify_size;
687       timeout = GNUNET_TIME_absolute_get_remaining (th->timeout);
688     }
689 #if DEBUG_TRANSPORT
690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691                 "Calling notify_transmit_ready\n");
692 #endif
693   h->network_handle =
694     GNUNET_CLIENT_notify_transmit_ready (h->client,
695                                          size,
696                                          timeout,
697                                          GNUNET_NO,
698                                          &transport_notify_ready,
699                                          h);
700   GNUNET_assert (NULL != h->network_handle);
701 }
702
703
704 /**
705  * Called when our transmit request timed out before any transport
706  * reported success connecting to the desired peer or before the
707  * transport was ready to receive.  Signal error and free
708  * TransmitHandle.
709  */
710 static void
711 control_transmit_timeout (void *cls,
712                           const struct GNUNET_SCHEDULER_TaskContext *tc)
713 {
714   struct ControlMessage *th = cls;
715
716   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
717   if (NULL != th->notify)
718     th->notify (th->notify_cls, 0, NULL);
719   GNUNET_CONTAINER_DLL_remove (th->h->control_head,
720                                th->h->control_tail,
721                                th);
722   GNUNET_free (th);
723 }
724
725
726 /**
727  * Queue control request for transmission to the transport
728  * service.
729  *
730  * @param h handle to the transport service
731  * @param size number of bytes to be transmitted
732  * @param at_head request must be added to the head of the queue
733  *        (otherwise request will be appended)
734  * @param timeout how long this transmission can wait (at most)
735  * @param notify function to call to get the content
736  * @param notify_cls closure for notify
737  */
738 static void
739 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h,
740                            size_t size,
741                            int at_head,
742                            struct GNUNET_TIME_Relative timeout,
743                            GNUNET_CONNECTION_TransmitReadyNotify notify,
744                            void *notify_cls)
745 {
746   struct ControlMessage *th;
747
748 #if DEBUG_TRANSPORT
749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
750               "Control transmit of %u bytes within %llums requested\n",
751               size, (unsigned long long) timeout.rel_value);
752 #endif
753   th = GNUNET_malloc (sizeof (struct ControlMessage));
754   th->h = h;
755   th->notify = notify;
756   th->notify_cls = notify_cls;
757   th->notify_size = size;
758   th->notify_delay_task
759     = GNUNET_SCHEDULER_add_delayed (timeout, &control_transmit_timeout, th);
760   if (at_head)
761     GNUNET_CONTAINER_DLL_insert (h->control_head,
762                                  h->control_tail,
763                                  th);
764   else
765     GNUNET_CONTAINER_DLL_insert_after (h->control_head,
766                                        h->control_tail,
767                                        h->control_tail,
768                                        th);
769   schedule_transmission (h);
770 }
771
772
773 struct SetQuotaContext
774 {
775   struct GNUNET_TRANSPORT_Handle *handle;
776
777   struct GNUNET_PeerIdentity target;
778
779   GNUNET_SCHEDULER_Task cont;
780
781   void *cont_cls;
782
783   struct GNUNET_TIME_Absolute timeout;
784
785   struct GNUNET_BANDWIDTH_Value32NBO quota_in;
786 };
787
788
789 /**
790  * Send SET_QUOTA message to the service.
791  *
792  * @param cls the 'struct SetQuotaContext'
793  * @param size number of bytes available in buf
794  * @param buf where to copy the message
795  * @return number of bytes copied to buf
796  */
797 static size_t
798 send_set_quota (void *cls, size_t size, void *buf)
799 {
800   struct SetQuotaContext *sqc = cls;
801   struct QuotaSetMessage *msg;
802
803   if (buf == NULL)
804     {
805       GNUNET_SCHEDULER_add_continuation (sqc->cont,
806                                          sqc->cont_cls,
807                                          GNUNET_SCHEDULER_REASON_TIMEOUT);
808       GNUNET_free (sqc);
809       return 0;
810     }
811 #if DEBUG_TRANSPORT
812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813               "Transmitting `%s' request with respect to `%4s'.\n",
814               "SET_QUOTA",
815               GNUNET_i2s (&sqc->target));
816 #endif
817   GNUNET_assert (size >= sizeof (struct QuotaSetMessage));
818   msg = buf;
819   msg->header.size = htons (sizeof (struct QuotaSetMessage));
820   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
821   msg->quota = sqc->quota_in;
822   memcpy (&msg->peer, &sqc->target, sizeof (struct GNUNET_PeerIdentity));
823   if (sqc->cont != NULL)
824     GNUNET_SCHEDULER_add_continuation (sqc->cont,
825                                        sqc->cont_cls,
826                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
827   GNUNET_free (sqc);
828   return sizeof (struct QuotaSetMessage);
829 }
830
831
832 /**
833  * Set the share of incoming bandwidth for the given
834  * peer to the specified amount.
835  *
836  * @param handle connection to transport service
837  * @param target who's bandwidth quota is being changed
838  * @param quota_in incoming bandwidth quota in bytes per ms
839  * @param quota_out outgoing bandwidth quota in bytes per ms
840  * @param timeout how long to wait until signaling failure if
841  *        we can not communicate the quota change
842  * @param cont continuation to call when done, will be called
843  *        either with reason "TIMEOUT" or with reason "PREREQ_DONE"
844  * @param cont_cls closure for continuation
845  */
846 void
847 GNUNET_TRANSPORT_set_quota (struct GNUNET_TRANSPORT_Handle *handle,
848                             const struct GNUNET_PeerIdentity *target,
849                             struct GNUNET_BANDWIDTH_Value32NBO quota_in,
850                             struct GNUNET_BANDWIDTH_Value32NBO quota_out,
851                             struct GNUNET_TIME_Relative timeout,
852                             GNUNET_SCHEDULER_Task cont, void *cont_cls)
853 {
854   struct NeighbourList *n;
855   struct SetQuotaContext *sqc;
856
857   n = neighbour_find (handle, target);
858   if (n != NULL)
859     {
860 #if DEBUG_TRANSPORT
861       if (ntohl (quota_out.value__) != n->out_tracker.available_bytes_per_s__)
862         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863                     "Quota changed from %u to %u for peer `%s'\n",
864                     (unsigned int) n->out_tracker.available_bytes_per_s__,
865                     (unsigned int) ntohl (quota_out.value__),
866                     GNUNET_i2s (target));
867       else
868         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869                     "Quota remains at %u for peer `%s'\n",
870                     (unsigned int) n->out_tracker.available_bytes_per_s__,
871                     GNUNET_i2s (target));
872 #endif
873       GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
874                                              quota_out);
875     }
876   else
877     {
878 #if DEBUG_TRANSPORT
879       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880                   "Quota changed to %u for peer `%s', but I have no such neighbour!\n",
881                   (unsigned int) ntohl (quota_out.value__),
882                   GNUNET_i2s (target));
883 #endif
884     }
885   sqc = GNUNET_malloc (sizeof (struct SetQuotaContext));
886   sqc->handle = handle;
887   sqc->target = *target;
888   sqc->cont = cont;
889   sqc->cont_cls = cont_cls;
890   sqc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
891   sqc->quota_in = quota_in;
892   schedule_control_transmit (handle,
893                              sizeof (struct QuotaSetMessage),
894                              GNUNET_NO, timeout, &send_set_quota, sqc);
895 }
896
897
898 /**
899  * Obtain the HELLO message for this peer.
900  *
901  * @param handle connection to transport service
902  * @param rec function to call with the HELLO, sender will be our peer
903  *            identity; message and sender will be NULL on timeout
904  *            (handshake with transport service pending/failed).
905  *             cost estimate will be 0.
906  * @param rec_cls closure for rec
907  */
908 void
909 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
910                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
911                             void *rec_cls)
912 {
913   struct HelloWaitList *hwl;
914
915   hwl = GNUNET_malloc (sizeof (struct HelloWaitList));
916   hwl->next = handle->hwl_head;
917   handle->hwl_head = hwl;
918   hwl->handle = handle;
919   hwl->rec = rec;
920   hwl->rec_cls = rec_cls;
921   if (handle->my_hello == NULL)
922     return;
923   rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
924 }
925
926
927
928 /**
929  * Stop receiving updates about changes to our HELLO message.
930  *
931  * @param handle connection to transport service
932  * @param rec function previously registered to be called with the HELLOs
933  * @param rec_cls closure for rec
934  */
935 void
936 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_Handle *handle,
937                                    GNUNET_TRANSPORT_HelloUpdateCallback rec,
938                                    void *rec_cls)
939 {
940   struct HelloWaitList *pos;
941   struct HelloWaitList *prev;
942
943   prev = NULL;
944   pos = handle->hwl_head;
945   while (pos != NULL)
946     {
947       if ( (pos->rec == rec) &&
948            (pos->rec_cls == rec_cls) )
949         break;
950       prev = pos;
951       pos = pos->next;
952     }
953   GNUNET_break (pos != NULL);
954   if (pos == NULL)
955     return;
956   if (prev == NULL)
957     handle->hwl_head = pos->next;
958   else
959     prev->next = pos->next;
960   GNUNET_free (pos);
961 }
962
963
964 /**
965  * Send HELLO message to the service.
966  *
967  * @param cls the HELLO message to send
968  * @param size number of bytes available in buf
969  * @param buf where to copy the message
970  * @return number of bytes copied to buf
971  */
972 static size_t
973 send_hello (void *cls, size_t size, void *buf)
974 {
975   struct GNUNET_MessageHeader *hello = cls;
976   uint16_t msize;
977
978   if (buf == NULL)
979     {
980 #if DEBUG_TRANSPORT_TIMEOUT
981       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982                   "Timeout while trying to transmit `%s' request.\n",
983                   "HELLO");
984 #endif
985       GNUNET_free (hello);
986       return 0;
987     }
988 #if DEBUG_TRANSPORT
989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990               "Transmitting `%s' request.\n", "HELLO");
991 #endif
992   msize = ntohs (hello->size);
993   GNUNET_assert (size >= msize);
994   memcpy (buf, hello, msize);
995   GNUNET_free (hello);
996   return msize;
997 }
998
999
1000 /**
1001  * Offer the transport service the HELLO of another peer.  Note that
1002  * the transport service may just ignore this message if the HELLO is
1003  * malformed or useless due to our local configuration.
1004  *
1005  * @param handle connection to transport service
1006  * @param hello the hello message
1007  */
1008 void
1009 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1010                               const struct GNUNET_MessageHeader *hello)
1011 {
1012   struct GNUNET_MessageHeader *hc;
1013   uint16_t size;
1014   struct GNUNET_PeerIdentity peer;
1015
1016   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1017   size = ntohs (hello->size);
1018   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1019   if (GNUNET_OK != GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) hello,
1020                                         &peer))
1021     {
1022       GNUNET_break (0);
1023       return;
1024     }
1025 #if DEBUG_TRANSPORT
1026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1027               "Offering `%s' message of `%4s' to transport for validation.\n",
1028               "HELLO",
1029               GNUNET_i2s (&peer));
1030 #endif
1031   hc = GNUNET_malloc (size);
1032   memcpy (hc, hello, size);
1033   schedule_control_transmit (handle,
1034                              size,
1035                              GNUNET_NO, OFFER_HELLO_TIMEOUT, &send_hello, hc);
1036 }
1037
1038
1039 /**
1040  * Transmit START message to service.
1041  *
1042  * @param cls unused
1043  * @param size number of bytes available in buf
1044  * @param buf where to copy the message
1045  * @return number of bytes copied to buf
1046  */
1047 static size_t
1048 send_start (void *cls, size_t size, void *buf)
1049 {
1050   struct GNUNET_TRANSPORT_Handle *h = cls;
1051   struct StartMessage s;
1052
1053   if (buf == NULL)
1054     {
1055       /* Can only be shutdown, just give up */
1056 #if DEBUG_TRANSPORT
1057       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1058                   "Shutdown while trying to transmit `%s' request.\n",
1059                   "START");
1060 #endif
1061       return 0;
1062     }
1063 #if DEBUG_TRANSPORT
1064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1065               "Transmitting `%s' request.\n", "START");
1066 #endif
1067   GNUNET_assert (size >= sizeof (struct StartMessage));
1068   s.header.size = htons (sizeof (struct StartMessage));
1069   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1070   s.do_check = htonl (h->check_self);
1071   s.self = h->self;
1072   memcpy (buf, &s, sizeof (struct StartMessage));
1073   return sizeof (struct StartMessage);
1074 }
1075
1076
1077 /**
1078  * Free neighbour.
1079  *
1080  * @param n the entry to free
1081  */
1082 static void
1083 neighbour_free (struct NeighbourList *n)
1084 {
1085   struct GNUNET_TRANSPORT_Handle *h;
1086   struct NeighbourList *prev;
1087   struct NeighbourList *pos;
1088
1089   h = n->h;
1090 #if DEBUG_TRANSPORT
1091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1092               "Removing neighbour `%s' from list of connected peers.\n",
1093               GNUNET_i2s (&n->id));
1094 #endif
1095   GNUNET_break (n->is_connected == GNUNET_NO);
1096   GNUNET_break (n->transmit_stage == TS_NEW);
1097
1098   prev = NULL;
1099   pos = h->neighbours;
1100   while (pos != n)
1101     {
1102       prev = pos;
1103       pos = pos->next;
1104     }
1105   if (prev == NULL)
1106     h->neighbours = n->next;
1107   else
1108     prev->next = n->next;
1109   GNUNET_free (n);
1110 }
1111
1112
1113 /**
1114  * Mark neighbour as disconnected.
1115  *
1116  * @param n the entry to mark as disconnected
1117  */
1118 static void
1119 neighbour_disconnect (struct NeighbourList *n)
1120 {
1121   struct GNUNET_TRANSPORT_Handle *h = n->h;
1122 #if DEBUG_TRANSPORT
1123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1124               "Removing neighbour `%s' from list of connected peers.\n",
1125               GNUNET_i2s (&n->id));
1126 #endif
1127   GNUNET_break (n->is_connected == GNUNET_YES);
1128   n->is_connected = GNUNET_NO;
1129   if (h->nd_cb != NULL)
1130     h->nd_cb (h->cls, &n->id);
1131   if (n->transmit_stage == TS_NEW)
1132     neighbour_free (n);
1133 }
1134
1135
1136 /**
1137  * Function we use for handling incoming messages.
1138  *
1139  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
1140  * @param msg message received, NULL on timeout or fatal error
1141  */
1142 static void demultiplexer (void *cls,
1143                            const struct GNUNET_MessageHeader *msg);
1144
1145
1146 /**
1147  * Try again to connect to transport service.
1148  *
1149  * @param cls the handle to the transport service
1150  * @param tc scheduler context
1151  */
1152 static void
1153 reconnect (void *cls,
1154            const struct GNUNET_SCHEDULER_TaskContext *tc)
1155 {
1156   struct GNUNET_TRANSPORT_Handle *h = cls;
1157   struct ControlMessage *pos;
1158   struct NeighbourList *n;
1159   struct NeighbourList *next;
1160
1161   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1162   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1163     {
1164       /* shutdown, just give up */
1165       return;
1166     }
1167   /* Forget about all neighbours that we used to be connected to */
1168   n = h->neighbours;
1169   while (NULL != n)
1170     {
1171 #if DEBUG_TRANSPORT_DISCONNECT
1172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1173               "Disconnecting due to reconnect being called\n");
1174 #endif
1175       next = n->next;
1176       if (n->is_connected)
1177         neighbour_disconnect (n);
1178       n = next;
1179     }
1180 #if DEBUG_TRANSPORT
1181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1182               "Connecting to transport service.\n");
1183 #endif
1184   GNUNET_assert (h->client == NULL);
1185   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1186   GNUNET_assert (h->client != NULL);
1187   /* make sure we don't send "START" twice, remove existing entry from
1188      queue (if present) */
1189   pos = h->control_head;
1190   while (pos != NULL)
1191     {
1192       if (pos->notify == &send_start)
1193         {
1194           GNUNET_CONTAINER_DLL_remove (h->control_head,
1195                                        h->control_tail,
1196                                        pos);
1197           if (GNUNET_SCHEDULER_NO_TASK != pos->notify_delay_task)
1198             {
1199               GNUNET_SCHEDULER_cancel (pos->notify_delay_task);
1200               pos->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1201             }
1202           GNUNET_free (pos);
1203           break;
1204         }
1205       pos = pos->next;
1206     }
1207   schedule_control_transmit (h,
1208                              sizeof (struct StartMessage),
1209                              GNUNET_YES,
1210                              GNUNET_TIME_UNIT_FOREVER_REL, &send_start, h);
1211   GNUNET_CLIENT_receive (h->client,
1212                          &demultiplexer, h, GNUNET_TIME_UNIT_FOREVER_REL);
1213 }
1214
1215
1216 /**
1217  * Function that will schedule the job that will try
1218  * to connect us again to the client.
1219  *
1220  * @param h transport service to reconnect
1221  */
1222 static void
1223 schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1224 {
1225 #if DEBUG_TRANSPORT
1226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1227               "Scheduling task to reconnect to transport service in %llu ms.\n",
1228               h->reconnect_delay.rel_value);
1229 #endif
1230   GNUNET_assert (h->client == NULL);
1231   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
1232   h->reconnect_task
1233     = GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
1234   if (h->reconnect_delay.rel_value == 0)
1235     {
1236       h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1237     }
1238   else
1239     {
1240       h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
1241       h->reconnect_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
1242                                                      h->reconnect_delay);
1243     }
1244 }
1245
1246
1247 /**
1248  * Send request connect message to the service.
1249  *
1250  * @param cls the TransportRequestConnectMessage
1251  * @param size number of bytes available in buf
1252  * @param buf where to copy the message
1253  * @return number of bytes copied to buf
1254  */
1255 static size_t
1256 send_transport_request_connect (void *cls, size_t size, void *buf)
1257 {
1258   struct TransportRequestConnectMessage *trcm = cls;
1259
1260   if (buf == NULL)
1261     {
1262 #if DEBUG_TRANSPORT
1263       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264                   "Buffer null for %s\n",
1265                   "REQUEST_CONNECT");
1266 #endif
1267       GNUNET_free (trcm);
1268       return 0;
1269     }
1270 #if DEBUG_TRANSPORT
1271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272               "Transmitting `%s' request for `%4s'.\n",
1273               "REQUEST_CONNECT",
1274               GNUNET_i2s (&trcm->peer));
1275 #endif
1276   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1277   memcpy(buf, trcm, sizeof(struct TransportRequestConnectMessage));
1278   return sizeof(struct TransportRequestConnectMessage);
1279 }
1280
1281 /**
1282  * Create and send a request connect message to
1283  * the transport service for a particular peer.
1284  *
1285  * @param h handle to the transport service
1286  * @param n the neighbor to send the request connect message about
1287  *
1288  */
1289 static void send_request_connect_message(struct GNUNET_TRANSPORT_Handle *h, struct NeighbourList *n)
1290 {
1291   struct TransportRequestConnectMessage *trcm;
1292
1293   trcm = GNUNET_malloc(sizeof(struct TransportRequestConnectMessage));
1294   trcm->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1295   trcm->header.size = htons(sizeof(struct TransportRequestConnectMessage));
1296   memcpy(&trcm->peer, &n->id, sizeof(struct GNUNET_PeerIdentity));
1297   schedule_control_transmit (h,
1298                              sizeof (struct TransportRequestConnectMessage),
1299                              GNUNET_NO,
1300                              GNUNET_TIME_UNIT_FOREVER_REL, &send_transport_request_connect, trcm);
1301 }
1302
1303 /**
1304  * Add neighbour to our list
1305  *
1306  * @return NULL if this API is currently disconnecting from the service
1307  */
1308 static struct NeighbourList *
1309 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
1310                const struct GNUNET_PeerIdentity *pid)
1311 {
1312   struct NeighbourList *n;
1313
1314   if (GNUNET_YES == h->in_disconnect)
1315     return NULL;
1316   /* check for duplicates */
1317   if (NULL != (n = neighbour_find (h, pid)))
1318     {
1319       GNUNET_break (0);
1320       return n;
1321     }
1322 #if DEBUG_TRANSPORT
1323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1324               "Creating entry for neighbour `%4s'.\n",
1325               GNUNET_i2s (pid));
1326 #endif
1327   n = GNUNET_malloc (sizeof (struct NeighbourList));
1328   n->id = *pid;
1329   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
1330                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1331                                  MAX_BANDWIDTH_CARRY_S);
1332   n->next = h->neighbours;
1333   n->h = h;
1334   h->neighbours = n;
1335
1336
1337   return n;
1338 }
1339
1340
1341 /**
1342  * Connect to the transport service.  Note that the connection may
1343  * complete (or fail) asynchronously.
1344  *
1345  * @param cfg configuration to use
1346  * @param self our own identity (API should check that it matches
1347  *             the identity found by transport), or NULL (no check)
1348  * @param cls closure for the callbacks
1349  * @param rec receive function to call
1350  * @param nc function to call on connect events
1351  * @param nd function to call on disconnect events
1352  */
1353 struct GNUNET_TRANSPORT_Handle *
1354 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1355                           const struct GNUNET_PeerIdentity *self,
1356                           void *cls,
1357                           GNUNET_TRANSPORT_ReceiveCallback rec,
1358                           GNUNET_TRANSPORT_NotifyConnect nc,
1359                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1360 {
1361   struct GNUNET_TRANSPORT_Handle *ret;
1362
1363   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1364   if (self != NULL)
1365     {
1366       ret->self = *self;
1367       ret->check_self = GNUNET_YES;
1368     }
1369   ret->cfg = cfg;
1370   ret->cls = cls;
1371   ret->rec = rec;
1372   ret->nc_cb = nc;
1373   ret->nd_cb = nd;
1374   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1375   schedule_reconnect (ret);
1376   return ret;
1377 }
1378
1379
1380 /**
1381  * Disconnect from the transport service.
1382  */
1383 void
1384 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1385 {
1386   struct GNUNET_TRANSPORT_TransmitHandle *th;
1387   struct NeighbourList *n;
1388   struct HelloWaitList *hwl;
1389   struct GNUNET_CLIENT_Connection *client;
1390   struct ControlMessage *cm;
1391
1392 #if DEBUG_TRANSPORT
1393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1394 #endif
1395   handle->in_disconnect = GNUNET_YES;
1396   while (NULL != (n = handle->neighbours))
1397     {
1398       handle->neighbours = n->next;
1399       switch (n->transmit_stage)
1400         {
1401         case TS_NEW:
1402         case TS_TRANSMITTED:
1403           /* nothing to do */
1404           break;
1405         case TS_QUEUED:
1406         case TS_TRANSMITTED_QUEUED:
1407           th = &n->transmit_handle;
1408           if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1409             {
1410               GNUNET_SCHEDULER_cancel (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 (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->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->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       GNUNET_break (ntohl (dim->reserved) == 0);
1596 #if DEBUG_TRANSPORT_DISCONNECT
1597       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598                   "Receiving `%s' message for `%4s'.\n",
1599                   "DISCONNECT",
1600                   GNUNET_i2s (&dim->peer));
1601 #endif
1602       n = neighbour_find (h, &dim->peer);
1603       GNUNET_break (n != NULL);
1604       if (n != NULL)
1605         neighbour_disconnect (n);       
1606       break;
1607     case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
1608       if (size != sizeof (struct SendOkMessage))
1609         {
1610           GNUNET_break (0);
1611           break;
1612         }
1613       okm = (const struct SendOkMessage *) msg;
1614 #if DEBUG_TRANSPORT
1615       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1616                   "Receiving `%s' message, transmission %s.\n", "SEND_OK",
1617                   ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
1618 #endif
1619       n = neighbour_find (h, &okm->peer);
1620       GNUNET_assert (n != NULL);
1621       switch (n->transmit_stage)
1622         {
1623         case TS_NEW:
1624           GNUNET_break (0);
1625           break;
1626         case TS_QUEUED:
1627           GNUNET_break (0);
1628           break;
1629         case TS_TRANSMITTED:
1630           n->transmit_stage = TS_NEW;
1631           break;
1632         case TS_TRANSMITTED_QUEUED:
1633           n->transmit_stage = TS_QUEUED;
1634           schedule_transmission (h);
1635           break;
1636         default:
1637           GNUNET_break (0);
1638         }
1639       break;
1640     case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
1641 #if DEBUG_TRANSPORT
1642       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1643                   "Receiving `%s' message.\n", "RECV");
1644 #endif
1645       if (size <
1646           sizeof (struct InboundMessage) +
1647           sizeof (struct GNUNET_MessageHeader))
1648         {
1649           GNUNET_break (0);
1650           break;
1651         }
1652       im = (const struct InboundMessage *) msg;
1653       GNUNET_break (0 == ntohl (im->reserved));
1654       imm = (const struct GNUNET_MessageHeader *) &im[1];
1655       if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
1656         {
1657           GNUNET_break (0);
1658           break;
1659         }
1660 #if DEBUG_TRANSPORT
1661       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662                   "Received message of type %u from `%4s'.\n",
1663                   ntohs (imm->type), GNUNET_i2s (&im->peer));
1664 #endif
1665       n = neighbour_find (h, &im->peer);
1666       if (n == NULL)
1667         {
1668           GNUNET_break (0);
1669           break;
1670         }
1671       if (n->is_connected != GNUNET_YES)
1672         {
1673           GNUNET_break (0);
1674           break;
1675         }
1676       if (h->rec != NULL)
1677         h->rec (h->cls, &im->peer, imm,
1678                 GNUNET_TIME_relative_ntoh (im->latency), ntohl(im->distance));
1679       break;
1680     default:
1681       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1682                   _
1683                   ("Received unexpected message of type %u in %s:%u\n"),
1684                   ntohs (msg->type), __FILE__, __LINE__);
1685       GNUNET_break (0);
1686       break;
1687     }
1688 }
1689
1690
1691 /**
1692  * Called when our transmit request timed out before any transport
1693  * reported success connecting to the desired peer or before the
1694  * transport was ready to receive.  Signal error and free
1695  * TransmitHandle.
1696  *
1697  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle*' that is timing out
1698  * @param tc scheduler context
1699  */
1700 static void
1701 peer_transmit_timeout (void *cls,
1702                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1703 {
1704   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
1705   struct NeighbourList *n;
1706   GNUNET_CONNECTION_TransmitReadyNotify notify;
1707   void *notify_cls;
1708
1709   th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1710   n = th->neighbour;
1711 #if DEBUG_TRANSPORT
1712   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1713               "Triggering timeout for request to transmit to `%4s' (%d)\n",
1714               GNUNET_i2s (&n->id),
1715               n->transmit_stage);
1716 #endif
1717   notify = th->notify;
1718   notify_cls = th->notify_cls;
1719   switch (n->transmit_stage)
1720     {
1721     case TS_NEW:
1722       GNUNET_break (0);
1723       break;
1724     case TS_QUEUED:
1725       n->transmit_stage = TS_NEW;
1726       if (n->is_connected == GNUNET_NO)
1727         neighbour_free (n);
1728       break;
1729     case TS_TRANSMITTED:
1730       GNUNET_break (0);
1731       break;
1732     case TS_TRANSMITTED_QUEUED:
1733       n->transmit_stage = TS_TRANSMITTED;
1734       break;
1735     default:
1736       GNUNET_break (0);
1737     }
1738   if (NULL != notify)
1739     notify (notify_cls, 0, NULL);
1740 }
1741
1742
1743 /**
1744  * Check if we could queue a message of the given size for
1745  * transmission.  The transport service will take both its
1746  * internal buffers and bandwidth limits imposed by the
1747  * other peer into consideration when answering this query.
1748  *
1749  * @param handle connection to transport service
1750  * @param target who should receive the message
1751  * @param size how big is the message we want to transmit?
1752  * @param priority how important is the message?
1753  * @param timeout after how long should we give up (and call
1754  *        notify with buf NULL and size 0)?
1755  * @param notify function to call when we are ready to
1756  *        send such a message
1757  * @param notify_cls closure for notify
1758  * @return NULL if someone else is already waiting to be notified
1759  *         non-NULL if the notify callback was queued (can be used to cancel
1760  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1761  */
1762 struct GNUNET_TRANSPORT_TransmitHandle *
1763 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle
1764                                         *handle,
1765                                         const struct GNUNET_PeerIdentity
1766                                         *target, size_t size,
1767                                         unsigned int priority,
1768                                         struct GNUNET_TIME_Relative timeout,
1769                                         GNUNET_CONNECTION_TransmitReadyNotify
1770                                         notify, void *notify_cls)
1771 {
1772   struct GNUNET_TRANSPORT_TransmitHandle *th;
1773   struct NeighbourList *n;
1774
1775   if (size + sizeof (struct OutboundMessage) >=
1776       GNUNET_SERVER_MAX_MESSAGE_SIZE)
1777     {
1778 #if DEBUG_TRANSPORT
1779       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1780                   "Message size is %d, max allowed is %d.\n",
1781                   size + sizeof (struct OutboundMessage), GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
1782 #endif
1783       GNUNET_break (0);
1784       return NULL;
1785     }
1786 #if DEBUG_TRANSPORT
1787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1788               "Asking transport service for transmission of %u bytes to peer `%4s' within %llu ms.\n",
1789               size, GNUNET_i2s (target),
1790               (unsigned long long) timeout.rel_value);
1791 #endif
1792   n = neighbour_find (handle, target);
1793   if (n == NULL)
1794     {
1795       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796                   "Created neighbour entry for peer `%s'\n",
1797                   GNUNET_i2s (target));
1798       n = neighbour_add (handle, target);
1799
1800     }
1801   if (n == NULL)
1802     {
1803       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804                   "Could not create neighbour entry for peer `%s'\n",
1805                   GNUNET_i2s (target));
1806       return NULL;
1807     }
1808
1809   /**
1810    *  Send a request connect message if not connected,
1811    *  otherwise we will never send anything to
1812    *  transport service
1813    */
1814   if (n->is_connected == GNUNET_NO)
1815     {
1816       send_request_connect_message(handle, n);
1817     }
1818
1819   switch (n->transmit_stage)
1820     {
1821     case TS_NEW:
1822       n->transmit_stage = TS_QUEUED;
1823       break;
1824     case TS_QUEUED:
1825       GNUNET_break (0);
1826       return NULL;
1827     case TS_TRANSMITTED:
1828       n->transmit_stage = TS_TRANSMITTED_QUEUED;
1829       break;
1830     case TS_TRANSMITTED_QUEUED:
1831       GNUNET_break (0);
1832       return NULL;
1833     default:
1834       GNUNET_break (0);
1835       return NULL;
1836     }
1837   th = &n->transmit_handle;
1838   th->neighbour = n;
1839   th->notify = notify;
1840   th->notify_cls = notify_cls;
1841   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1842   th->notify_size = size + sizeof (struct OutboundMessage);
1843   th->priority = priority;
1844   th->notify_delay_task
1845     = GNUNET_SCHEDULER_add_delayed (timeout,
1846                                     &peer_transmit_timeout, th);
1847   schedule_transmission (handle);
1848   return th;
1849 }
1850
1851
1852 /**
1853  * Cancel the specified transmission-ready notification.
1854  */
1855 void
1856 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1857                                                GNUNET_TRANSPORT_TransmitHandle
1858                                                *th)
1859 {
1860   struct NeighbourList *n;
1861
1862   n = th->neighbour;
1863 #if DEBUG_TRANSPORT
1864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865               "Transmission request of %u bytes to `%4s' was cancelled.\n",
1866               th->notify_size - sizeof (struct OutboundMessage),
1867               GNUNET_i2s (&n->id));
1868 #endif
1869   switch (n->transmit_stage)
1870     {
1871     case TS_NEW:
1872       GNUNET_break (0);
1873       break;
1874     case TS_QUEUED:
1875       n->transmit_stage = TS_NEW;
1876       if (n->is_connected == GNUNET_NO)
1877         neighbour_free (n);
1878       break;
1879     case TS_TRANSMITTED:
1880       GNUNET_break (0);
1881       break;
1882     case TS_TRANSMITTED_QUEUED:
1883       n->transmit_stage = TS_TRANSMITTED;
1884       break;
1885     default:
1886       GNUNET_break (0);
1887     }
1888   if (th->notify_delay_task != GNUNET_SCHEDULER_NO_TASK)
1889     {
1890       GNUNET_SCHEDULER_cancel (th->notify_delay_task);
1891       th->notify_delay_task = GNUNET_SCHEDULER_NO_TASK;
1892     }
1893 }
1894
1895
1896 /* end of transport_api.c */