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