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