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