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