fix #3664: during PS_RECONNECT_ATS, primary address may be NULL, causing an NPE if...
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/transport_api.c
23  * @brief library to access the low-level P2P IO service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - test test test
28  */
29 #include "platform.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_arm_service.h"
33 #include "gnunet_hello_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_transport_service.h"
36 #include "transport.h"
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "transport-api",__VA_ARGS__)
39
40 /**
41  * How large to start with for the hashmap of neighbours.
42  */
43 #define STARTING_NEIGHBOURS_SIZE 16
44
45 /**
46  * Handle for a message that should be transmitted to the service.
47  * Used for both control messages and normal messages.
48  */
49 struct GNUNET_TRANSPORT_TransmitHandle
50 {
51
52   /**
53    * We keep all requests in a DLL.
54    */
55   struct GNUNET_TRANSPORT_TransmitHandle *next;
56
57   /**
58    * We keep all requests in a DLL.
59    */
60   struct GNUNET_TRANSPORT_TransmitHandle *prev;
61
62   /**
63    * Neighbour for this handle, NULL for control messages.
64    */
65   struct Neighbour *neighbour;
66
67   /**
68    * Function to call when @e notify_size bytes are available
69    * for transmission.
70    */
71   GNUNET_TRANSPORT_TransmitReadyNotify notify;
72
73   /**
74    * Closure for @e notify.
75    */
76   void *notify_cls;
77
78   /**
79    * Timeout for this request, 0 for control messages.
80    */
81   struct GNUNET_TIME_Absolute timeout;
82
83   /**
84    * Task to trigger request timeout if the request is stalled due to
85    * congestion.
86    */
87   struct GNUNET_SCHEDULER_Task * timeout_task;
88
89   /**
90    * How many bytes is our notify callback waiting for?
91    */
92   size_t notify_size;
93
94 };
95
96
97 /**
98  * Entry in hash table of all of our current (connected) neighbours.
99  */
100 struct Neighbour
101 {
102   /**
103    * Overall transport handle.
104    */
105   struct GNUNET_TRANSPORT_Handle *h;
106
107   /**
108    * Active transmit handle or NULL.
109    */
110   struct GNUNET_TRANSPORT_TransmitHandle *th;
111
112   /**
113    * Identity of this neighbour.
114    */
115   struct GNUNET_PeerIdentity id;
116
117   /**
118    * Outbound bandwidh tracker.
119    */
120   struct GNUNET_BANDWIDTH_Tracker out_tracker;
121
122   /**
123    * Entry in our readyness heap (which is sorted by @e next_ready
124    * value).  NULL if there is no pending transmission request for
125    * this neighbour or if we're waiting for @e is_ready to become
126    * true AFTER the @e out_tracker suggested that this peer's quota
127    * has been satisfied (so once @e is_ready goes to #GNUNET_YES,
128    * we should immediately go back into the heap).
129    */
130   struct GNUNET_CONTAINER_HeapNode *hn;
131
132   /**
133    * Is this peer currently ready to receive a message?
134    */
135   int is_ready;
136
137   /**
138    * Sending consumed more bytes on wire than payload was announced
139    * This overhead is added to the delay of next sending operation
140    */
141   size_t traffic_overhead;
142 };
143
144
145 /**
146  * Linked list of functions to call whenever our HELLO is updated.
147  */
148 struct GNUNET_TRANSPORT_GetHelloHandle
149 {
150
151   /**
152    * This is a doubly linked list.
153    */
154   struct GNUNET_TRANSPORT_GetHelloHandle *next;
155
156   /**
157    * This is a doubly linked list.
158    */
159   struct GNUNET_TRANSPORT_GetHelloHandle *prev;
160
161   /**
162    * Transport handle.
163    */
164   struct GNUNET_TRANSPORT_Handle *handle;
165
166   /**
167    * Callback to call once we got our HELLO.
168    */
169   GNUNET_TRANSPORT_HelloUpdateCallback rec;
170
171   /**
172    * Task for calling the HelloUpdateCallback when we already have a HELLO
173    */
174   struct GNUNET_SCHEDULER_Task * notify_task;
175
176   /**
177    * Closure for @e rec.
178    */
179   void *rec_cls;
180
181 };
182
183
184 /**
185  * Entry in linked list for a try-connect request.
186  */
187 struct GNUNET_TRANSPORT_TryConnectHandle
188 {
189   /**
190    * For the DLL.
191    */
192   struct GNUNET_TRANSPORT_TryConnectHandle *prev;
193
194   /**
195    * For the DLL.
196    */
197   struct GNUNET_TRANSPORT_TryConnectHandle *next;
198
199   /**
200    * Peer we should try to connect to.
201    */
202   struct GNUNET_PeerIdentity pid;
203
204   /**
205    * Transport service handle this request is part of.
206    */
207   struct GNUNET_TRANSPORT_Handle *th;
208
209   /**
210    * Message transmission request to communicate to service.
211    */
212   struct GNUNET_TRANSPORT_TransmitHandle *tth;
213
214   /**
215    * Function to call upon completion (of request transmission).
216    */
217   GNUNET_TRANSPORT_TryConnectCallback cb;
218
219   /**
220    * Closure for @e cb.
221    */
222   void *cb_cls;
223
224 };
225
226
227 /**
228  * Entry in linked list for all try-disconnect requests
229  */
230 struct GNUNET_TRANSPORT_TryDisconnectHandle
231 {
232   /**
233    * For the DLL.
234    */
235   struct GNUNET_TRANSPORT_TryDisconnectHandle *prev;
236
237   /**
238    * For the DLL.
239    */
240   struct GNUNET_TRANSPORT_TryDisconnectHandle *next;
241
242   /**
243    * Peer we should try to connect to.
244    */
245   struct GNUNET_PeerIdentity pid;
246
247   /**
248    * Transport service handle this request is part of.
249    */
250   struct GNUNET_TRANSPORT_Handle *th;
251
252   /**
253    * Message transmission request to communicate to service.
254    */
255   struct GNUNET_TRANSPORT_TransmitHandle *tth;
256
257   /**
258    * Function to call upon completion (of request transmission).
259    */
260   GNUNET_TRANSPORT_TryDisconnectCallback cb;
261
262   /**
263    * Closure for @e cb.
264    */
265   void *cb_cls;
266
267 };
268
269
270 /**
271  * Entry in linked list for all offer-HELLO requests.
272  */
273 struct GNUNET_TRANSPORT_OfferHelloHandle
274 {
275   /**
276    * For the DLL.
277    */
278   struct GNUNET_TRANSPORT_OfferHelloHandle *prev;
279
280   /**
281    * For the DLL.
282    */
283   struct GNUNET_TRANSPORT_OfferHelloHandle *next;
284
285   /**
286    * Transport service handle we use for transmission.
287    */
288   struct GNUNET_TRANSPORT_Handle *th;
289
290   /**
291    * Transmission handle for this request.
292    */
293   struct GNUNET_TRANSPORT_TransmitHandle *tth;
294
295   /**
296    * Function to call once we are done.
297    */
298   GNUNET_SCHEDULER_TaskCallback cont;
299
300   /**
301    * Closure for @e cont
302    */
303   void *cls;
304
305   /**
306    * The HELLO message to be transmitted.
307    */
308   struct GNUNET_MessageHeader *msg;
309 };
310
311
312 /**
313  * Handle for the transport service (includes all of the
314  * state for the transport service).
315  */
316 struct GNUNET_TRANSPORT_Handle
317 {
318
319   /**
320    * Closure for the callbacks.
321    */
322   void *cls;
323
324   /**
325    * Function to call for received data.
326    */
327   GNUNET_TRANSPORT_ReceiveCallback rec;
328
329   /**
330    * function to call on connect events
331    */
332   GNUNET_TRANSPORT_NotifyConnect nc_cb;
333
334   /**
335    * function to call on disconnect events
336    */
337   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
338
339   /**
340    * function to call on excess bandwidth events
341    */
342   GNUNET_TRANSPORT_NotifyExcessBandwidth neb_cb;
343
344   /**
345    * Head of DLL of control messages.
346    */
347   struct GNUNET_TRANSPORT_TransmitHandle *control_head;
348
349   /**
350    * Tail of DLL of control messages.
351    */
352   struct GNUNET_TRANSPORT_TransmitHandle *control_tail;
353
354   /**
355    * The current HELLO message for this peer.  Updated
356    * whenever transports change their addresses.
357    */
358   struct GNUNET_MessageHeader *my_hello;
359
360   /**
361    * My client connection to the transport service.
362    */
363   struct GNUNET_CLIENT_Connection *client;
364
365   /**
366    * Handle to our registration with the client for notification.
367    */
368   struct GNUNET_CLIENT_TransmitHandle *cth;
369
370   /**
371    * Linked list of pending requests for our HELLO.
372    */
373   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_head;
374
375   /**
376    * Linked list of pending requests for our HELLO.
377    */
378   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_tail;
379
380   /**
381    * Linked list of pending try connect requests head
382    */
383   struct GNUNET_TRANSPORT_TryConnectHandle *tc_head;
384
385   /**
386    * Linked list of pending try connect requests tail
387    */
388   struct GNUNET_TRANSPORT_TryConnectHandle *tc_tail;
389
390   /**
391    * Linked list of pending try disconnect requests head
392    */
393   struct GNUNET_TRANSPORT_TryDisconnectHandle *td_head;
394
395   /**
396    * Linked list of pending try connect requests tail
397    */
398   struct GNUNET_TRANSPORT_TryDisconnectHandle *td_tail;
399
400   /**
401    * Linked list of pending offer HELLO requests head
402    */
403   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_head;
404
405   /**
406    * Linked list of pending offer HELLO requests tail
407    */
408   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_tail;
409
410   /**
411    * My configuration.
412    */
413   const struct GNUNET_CONFIGURATION_Handle *cfg;
414
415   /**
416    * Hash map of the current connected neighbours of this peer.
417    * Maps peer identities to 'struct Neighbour' entries.
418    */
419   struct GNUNET_CONTAINER_MultiPeerMap *neighbours;
420
421   /**
422    * Heap sorting peers with pending messages by the timestamps that
423    * specify when we could next send a message to the respective peer.
424    * Excludes control messages (which can always go out immediately).
425    * Maps time stamps to 'struct Neighbour' entries.
426    */
427   struct GNUNET_CONTAINER_Heap *ready_heap;
428
429   /**
430    * Peer identity as assumed by this process, or all zeros.
431    */
432   struct GNUNET_PeerIdentity self;
433
434   /**
435    * ID of the task trying to reconnect to the service.
436    */
437   struct GNUNET_SCHEDULER_Task * reconnect_task;
438
439   /**
440    * ID of the task trying to trigger transmission for a peer while
441    * maintaining bandwidth quotas.  In use if there are no control
442    * messages and the smallest entry in the 'ready_heap' has a time
443    * stamp in the future.
444    */
445   struct GNUNET_SCHEDULER_Task * quota_task;
446
447   /**
448    * Delay until we try to reconnect.
449    */
450   struct GNUNET_TIME_Relative reconnect_delay;
451
452   /**
453    * Should we check that @e self matches what the service thinks?
454    * (if #GNUNET_NO, then @e self is all zeros!).
455    */
456   int check_self;
457
458   /**
459    * Reconnect in progress
460    */
461   int reconnecting;
462 };
463
464
465 /**
466  * Schedule the task to send one message, either from the control
467  * list or the peer message queues  to the service.
468  *
469  * @param h transport service to schedule a transmission for
470  */
471 static void
472 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
473
474
475 /**
476  * Function that will schedule the job that will try
477  * to connect us again to the client.
478  *
479  * @param h transport service to reconnect
480  */
481 static void
482 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h);
483
484
485 /**
486  * Get the neighbour list entry for the given peer
487  *
488  * @param h our context
489  * @param peer peer to look up
490  * @return NULL if no such peer entry exists
491  */
492 static struct Neighbour *
493 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
494                 const struct GNUNET_PeerIdentity *peer)
495 {
496   return GNUNET_CONTAINER_multipeermap_get (h->neighbours, peer);
497 }
498
499
500 /**
501  * The outbound quota has changed in a way that may require
502  * us to reset the timeout.  Update the timeout.
503  *
504  * @param cls the `struct Neighbour` for which the timeout changed
505  */
506 static void
507 outbound_bw_tracker_update (void *cls)
508 {
509   struct Neighbour *n = cls;
510   struct GNUNET_TIME_Relative delay;
511
512   if (NULL == n->hn)
513     return;
514   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
515                                               n->th->notify_size + n->traffic_overhead);
516   LOG (GNUNET_ERROR_TYPE_DEBUG,
517        "New outbound delay %llu us\n",
518        GNUNET_STRINGS_relative_time_to_string (delay,
519                                                GNUNET_NO));
520   GNUNET_CONTAINER_heap_update_cost (n->h->ready_heap,
521       n->hn, delay.rel_value_us);
522   schedule_transmission (n->h);
523 }
524
525
526 /**
527  * Function called by the bandwidth tracker if we have excess
528  * bandwidth.
529  *
530  * @param cls the `struct Neighbour` that has excess bandwidth
531  */
532 static void
533 notify_excess_cb (void *cls)
534 {
535   struct Neighbour *n = cls;
536   struct GNUNET_TRANSPORT_Handle *h = n->h;
537
538   if (NULL != h->neb_cb)
539     h->neb_cb (h->cls,
540                &n->id);
541 }
542
543
544 /**
545  * Add neighbour to our list
546  *
547  * @return NULL if this API is currently disconnecting from the service
548  */
549 static struct Neighbour *
550 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
551                const struct GNUNET_PeerIdentity *pid)
552 {
553   struct Neighbour *n;
554
555   LOG (GNUNET_ERROR_TYPE_DEBUG,
556        "Creating entry for neighbour `%4s'.\n",
557        GNUNET_i2s (pid));
558   n = GNUNET_new (struct Neighbour);
559   n->id = *pid;
560   n->h = h;
561   n->is_ready = GNUNET_YES;
562   n->traffic_overhead = 0;
563   GNUNET_BANDWIDTH_tracker_init2 (&n->out_tracker,
564                                   &outbound_bw_tracker_update, n,
565                                   GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
566                                   MAX_BANDWIDTH_CARRY_S,
567                                   &notify_excess_cb,
568                                   n);
569   GNUNET_assert (GNUNET_OK ==
570                  GNUNET_CONTAINER_multipeermap_put (h->neighbours,
571                                                     &n->id, n,
572                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
573   return n;
574 }
575
576
577 /**
578  * Iterator over hash map entries, for deleting state of a neighbour.
579  *
580  * @param cls the `struct GNUNET_TRANSPORT_Handle *`
581  * @param key peer identity
582  * @param value value in the hash map, the neighbour entry to delete
583  * @return #GNUNET_YES if we should continue to
584  *         iterate,
585  *         #GNUNET_NO if not.
586  */
587 static int
588 neighbour_delete (void *cls,
589                   const struct GNUNET_PeerIdentity *key, void *value)
590 {
591   struct GNUNET_TRANSPORT_Handle *handle = cls;
592   struct Neighbour *n = value;
593
594   if (NULL != handle->nd_cb)
595     handle->nd_cb (handle->cls, &n->id);
596   GNUNET_assert (NULL == n->th);
597   GNUNET_assert (NULL == n->hn);
598   GNUNET_assert (GNUNET_YES ==
599                  GNUNET_CONTAINER_multipeermap_remove (handle->neighbours, key,
600                                                        n));
601   GNUNET_BANDWIDTH_tracker_notification_stop (&n->out_tracker);
602   GNUNET_free (n);
603   return GNUNET_YES;
604 }
605
606
607 /**
608  * Function we use for handling incoming messages.
609  *
610  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
611  * @param msg message received, NULL on timeout or fatal error
612  */
613 static void
614 demultiplexer (void *cls,
615                const struct GNUNET_MessageHeader *msg)
616 {
617   struct GNUNET_TRANSPORT_Handle *h = cls;
618   const struct DisconnectInfoMessage *dim;
619   const struct ConnectInfoMessage *cim;
620   const struct InboundMessage *im;
621   const struct GNUNET_MessageHeader *imm;
622   const struct SendOkMessage *okm;
623   const struct QuotaSetMessage *qm;
624   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
625   struct GNUNET_TRANSPORT_GetHelloHandle *next_hwl;
626   struct Neighbour *n;
627   struct GNUNET_PeerIdentity me;
628   uint16_t size;
629   uint32_t bytes_msg;
630   uint32_t bytes_physical;
631
632   GNUNET_assert (NULL != h->client);
633   if (GNUNET_YES == h->reconnecting)
634   {
635     return;
636   }
637   if (NULL == msg)
638   {
639     LOG (GNUNET_ERROR_TYPE_DEBUG,
640          "Error receiving from transport service, disconnecting temporarily.\n");
641     h->reconnecting = GNUNET_YES;
642     disconnect_and_schedule_reconnect (h);
643     return;
644   }
645   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
646                          GNUNET_TIME_UNIT_FOREVER_REL);
647   size = ntohs (msg->size);
648   switch (ntohs (msg->type))
649   {
650   case GNUNET_MESSAGE_TYPE_HELLO:
651     if (GNUNET_OK !=
652         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
653     {
654       GNUNET_break (0);
655       break;
656     }
657     LOG (GNUNET_ERROR_TYPE_DEBUG,
658          "Receiving (my own) HELLO message (%u bytes), I am `%4s'.\n",
659          (unsigned int) size,
660          GNUNET_i2s (&me));
661     GNUNET_free_non_null (h->my_hello);
662     h->my_hello = NULL;
663     if (size < sizeof (struct GNUNET_MessageHeader))
664     {
665       GNUNET_break (0);
666       break;
667     }
668     h->my_hello = GNUNET_copy_message (msg);
669     hwl = h->hwl_head;
670     while (NULL != hwl)
671     {
672       next_hwl = hwl->next;
673       hwl->rec (hwl->rec_cls,
674                 h->my_hello);
675       hwl = next_hwl;
676     }
677     break;
678   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
679     if (size < sizeof (struct ConnectInfoMessage))
680     {
681       GNUNET_break (0);
682       break;
683     }
684     cim = (const struct ConnectInfoMessage *) msg;
685     if (size !=
686         sizeof (struct ConnectInfoMessage))
687     {
688       GNUNET_break (0);
689       break;
690     }
691     LOG (GNUNET_ERROR_TYPE_DEBUG,
692          "Receiving CONNECT message for `%4s'.\n",
693          GNUNET_i2s (&cim->id));
694     n = neighbour_find (h, &cim->id);
695     if (NULL != n)
696     {
697       GNUNET_break (0);
698       break;
699     }
700     n = neighbour_add (h, &cim->id);
701     LOG (GNUNET_ERROR_TYPE_DEBUG,
702          "Receiving CONNECT message for `%4s' with quota %u\n",
703          GNUNET_i2s (&cim->id),
704          ntohl (cim->quota_out.value__));
705     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
706                                            cim->quota_out);
707     if (h->nc_cb != NULL)
708       h->nc_cb (h->cls, &n->id);
709     break;
710   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
711     if (size != sizeof (struct DisconnectInfoMessage))
712     {
713       GNUNET_break (0);
714       break;
715     }
716     dim = (const struct DisconnectInfoMessage *) msg;
717     GNUNET_break (ntohl (dim->reserved) == 0);
718     LOG (GNUNET_ERROR_TYPE_DEBUG,
719          "Receiving DISCONNECT message for `%4s'.\n",
720          GNUNET_i2s (&dim->peer));
721     n = neighbour_find (h, &dim->peer);
722     if (NULL == n)
723     {
724       GNUNET_break (0);
725       break;
726     }
727     neighbour_delete (h, &dim->peer, n);
728     break;
729   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
730     if (size != sizeof (struct SendOkMessage))
731     {
732       GNUNET_break (0);
733       break;
734     }
735     okm = (const struct SendOkMessage *) msg;
736     bytes_msg = ntohl (okm->bytes_msg);
737     bytes_physical = ntohl (okm->bytes_physical);
738     LOG (GNUNET_ERROR_TYPE_DEBUG,
739          "Receiving SEND_OK message, transmission %s.\n",
740          ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
741
742     n = neighbour_find (h, &okm->peer);
743     if (NULL == n)
744       break;
745
746     if (bytes_physical >= bytes_msg)
747     {
748       LOG (GNUNET_ERROR_TYPE_DEBUG,
749            "Overhead for %u byte message: %u\n",
750            bytes_msg,
751            bytes_physical - bytes_msg);
752       n->traffic_overhead += bytes_physical - bytes_msg;
753     }
754     GNUNET_break (GNUNET_NO == n->is_ready);
755     n->is_ready = GNUNET_YES;
756     if ((NULL != n->th) && (NULL == n->hn))
757     {
758       GNUNET_assert (NULL != n->th->timeout_task);
759       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
760       n->th->timeout_task = NULL;
761       /* we've been waiting for this (congestion, not quota,
762        * caused delayed transmission) */
763       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
764       schedule_transmission (h);
765     }
766     break;
767   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
768     if (size <
769         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
770     {
771       GNUNET_break (0);
772       break;
773     }
774     im = (const struct InboundMessage *) msg;
775     imm = (const struct GNUNET_MessageHeader *) &im[1];
776     if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
777     {
778       GNUNET_break (0);
779       break;
780     }
781     LOG (GNUNET_ERROR_TYPE_DEBUG,
782          "Received message of type %u from `%4s'.\n",
783          ntohs (imm->type), GNUNET_i2s (&im->peer));
784     n = neighbour_find (h, &im->peer);
785     if (NULL == n)
786     {
787       GNUNET_break (0);
788       break;
789     }
790     if (NULL != h->rec)
791       h->rec (h->cls, &im->peer, imm);
792     break;
793   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
794     if (size != sizeof (struct QuotaSetMessage))
795     {
796       GNUNET_break (0);
797       break;
798     }
799     qm = (const struct QuotaSetMessage *) msg;
800     n = neighbour_find (h, &qm->peer);
801     if (NULL == n)
802       break;
803     LOG (GNUNET_ERROR_TYPE_DEBUG,
804          "Receiving SET_QUOTA message for `%4s' with quota %u\n",
805          GNUNET_i2s (&qm->peer),
806          ntohl (qm->quota.value__));
807     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
808                                            qm->quota);
809     break;
810   default:
811     LOG (GNUNET_ERROR_TYPE_ERROR,
812          _("Received unexpected message of type %u in %s:%u\n"),
813          ntohs (msg->type),
814          __FILE__,
815          __LINE__);
816     GNUNET_break (0);
817     break;
818   }
819 }
820
821
822 /**
823  * A transmission request could not be satisfied because of
824  * network congestion.  Notify the initiator and clean up.
825  *
826  * @param cls the `struct GNUNET_TRANSPORT_TransmitHandle`
827  * @param tc scheduler context
828  */
829 static void
830 timeout_request_due_to_congestion (void *cls,
831                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
832 {
833   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
834   struct Neighbour *n = th->neighbour;
835
836   n->th->timeout_task = NULL;
837   GNUNET_assert (th == n->th);
838   GNUNET_assert (NULL == n->hn);
839   n->th = NULL;
840   th->notify (th->notify_cls, 0, NULL);
841   GNUNET_free (th);
842 }
843
844
845 /**
846  * Transmit message(s) to service.
847  *
848  * @param cls handle to transport
849  * @param size number of bytes available in @a buf
850  * @param buf where to copy the message
851  * @return number of bytes copied to @a buf
852  */
853 static size_t
854 transport_notify_ready (void *cls, size_t size, void *buf)
855 {
856   struct GNUNET_TRANSPORT_Handle *h = cls;
857   struct GNUNET_TRANSPORT_TransmitHandle *th;
858   struct Neighbour *n;
859   char *cbuf;
860   struct OutboundMessage obm;
861   size_t ret;
862   size_t nret;
863   size_t mret;
864
865   GNUNET_assert (NULL != h->client);
866   h->cth = NULL;
867   if (NULL == buf)
868   {
869     /* transmission failed */
870     disconnect_and_schedule_reconnect (h);
871     return 0;
872   }
873
874   cbuf = buf;
875   ret = 0;
876   /* first send control messages */
877   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
878   {
879     GNUNET_CONTAINER_DLL_remove (h->control_head,
880                                  h->control_tail,
881                                  th);
882     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
883     LOG (GNUNET_ERROR_TYPE_DEBUG,
884          "Added %u bytes of control message at %u\n",
885          nret,
886          ret);
887     GNUNET_free (th);
888     ret += nret;
889     size -= nret;
890   }
891
892   /* then, if possible and no control messages pending, send data messages */
893   while ((NULL == h->control_head) &&
894          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
895   {
896     if (GNUNET_YES != n->is_ready)
897     {
898       /* peer not ready, wait for notification! */
899       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
900       n->hn = NULL;
901       GNUNET_assert (NULL == n->th->timeout_task);
902       n->th->timeout_task =
903           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
904                                         (n->th->timeout),
905                                         &timeout_request_due_to_congestion,
906                                         n->th);
907       continue;
908     }
909     th = n->th;
910     if (th->notify_size + sizeof (struct OutboundMessage) > size)
911       break;                    /* does not fit */
912     if (GNUNET_BANDWIDTH_tracker_get_delay
913         (&n->out_tracker, th->notify_size).rel_value_us > 0)
914       break;                    /* too early */
915     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
916     n->hn = NULL;
917     n->th = NULL;
918     n->is_ready = GNUNET_NO;
919     GNUNET_assert (size >= sizeof (struct OutboundMessage));
920     mret =
921         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
922                     &cbuf[ret + sizeof (struct OutboundMessage)]);
923     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
924     if (mret != 0)
925     {
926       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
927                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
928       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
929       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
930       obm.reserved = htonl (0);
931       obm.timeout =
932           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
933                                      (th->timeout));
934       obm.peer = n->id;
935       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
936       ret += (mret + sizeof (struct OutboundMessage));
937       size -= (mret + sizeof (struct OutboundMessage));
938       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
939     }
940     GNUNET_free (th);
941   }
942   /* if there are more pending messages, try to schedule those */
943   schedule_transmission (h);
944   LOG (GNUNET_ERROR_TYPE_DEBUG,
945        "Transmitting %u bytes to transport service\n",
946        ret);
947   return ret;
948 }
949
950
951 /**
952  * Schedule the task to send one message, either from the control
953  * list or the peer message queues  to the service.
954  *
955  * @param cls transport service to schedule a transmission for
956  * @param tc scheduler context
957  */
958 static void
959 schedule_transmission_task (void *cls,
960                             const struct GNUNET_SCHEDULER_TaskContext *tc)
961 {
962   struct GNUNET_TRANSPORT_Handle *h = cls;
963   size_t size;
964   struct GNUNET_TRANSPORT_TransmitHandle *th;
965   struct Neighbour *n;
966
967   h->quota_task = NULL;
968   GNUNET_assert (NULL != h->client);
969   /* destroy all requests that have timed out */
970   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
971          (0 == GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value_us))
972   {
973     /* notify client that the request could not be satisfied within
974      * the given time constraints */
975     th = n->th;
976     n->th = NULL;
977     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
978     n->hn = NULL;
979     LOG (GNUNET_ERROR_TYPE_DEBUG,
980          "Signalling timeout for transmission to peer %s due to congestion\n",
981          GNUNET_i2s (&n->id));
982     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
983     GNUNET_free (th);
984   }
985   if (NULL != h->cth)
986     return;
987   if (NULL != h->control_head)
988   {
989     size = h->control_head->notify_size;
990   }
991   else
992   {
993     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
994     if (NULL == n)
995       return;                   /* no pending messages */
996     size = n->th->notify_size + sizeof (struct OutboundMessage);
997   }
998   LOG (GNUNET_ERROR_TYPE_DEBUG,
999        "Calling notify_transmit_ready\n");
1000   h->cth =
1001       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1002                                            GNUNET_TIME_UNIT_FOREVER_REL,
1003                                            GNUNET_NO, &transport_notify_ready,
1004                                            h);
1005   GNUNET_assert (NULL != h->cth);
1006 }
1007
1008
1009 /**
1010  * Schedule the task to send one message, either from the control
1011  * list or the peer message queues  to the service.
1012  *
1013  * @param h transport service to schedule a transmission for
1014  */
1015 static void
1016 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
1017 {
1018   struct GNUNET_TIME_Relative delay;
1019   struct Neighbour *n;
1020
1021   GNUNET_assert (NULL != h->client);
1022   if (h->quota_task != NULL)
1023   {
1024     GNUNET_SCHEDULER_cancel (h->quota_task);
1025     h->quota_task = NULL;
1026   }
1027   if (NULL != h->control_head)
1028     delay = GNUNET_TIME_UNIT_ZERO;
1029   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
1030   {
1031     delay =
1032         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
1033                                             n->th->notify_size + n->traffic_overhead);
1034     n->traffic_overhead = 0;
1035   }
1036   else
1037     return;                     /* no work to be done */
1038   LOG (GNUNET_ERROR_TYPE_DEBUG,
1039        "Scheduling next transmission to service in %s\n",
1040        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1041   h->quota_task =
1042       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
1043 }
1044
1045
1046 /**
1047  * Queue control request for transmission to the transport
1048  * service.
1049  *
1050  * @param h handle to the transport service
1051  * @param size number of bytes to be transmitted
1052  * @param notify function to call to get the content
1053  * @param notify_cls closure for @a notify
1054  * @return a `struct GNUNET_TRANSPORT_TransmitHandle`
1055  */
1056 static struct GNUNET_TRANSPORT_TransmitHandle *
1057 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
1058                            GNUNET_TRANSPORT_TransmitReadyNotify notify,
1059                            void *notify_cls)
1060 {
1061   struct GNUNET_TRANSPORT_TransmitHandle *th;
1062
1063   LOG (GNUNET_ERROR_TYPE_DEBUG,
1064        "Control transmit of %u bytes requested\n",
1065        size);
1066   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1067   th->notify = notify;
1068   th->notify_cls = notify_cls;
1069   th->notify_size = size;
1070   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
1071   schedule_transmission (h);
1072   return th;
1073 }
1074
1075
1076 /**
1077  * Transmit START message to service.
1078  *
1079  * @param cls unused
1080  * @param size number of bytes available in @a buf
1081  * @param buf where to copy the message
1082  * @return number of bytes copied to @a buf
1083  */
1084 static size_t
1085 send_start (void *cls, size_t size, void *buf)
1086 {
1087   struct GNUNET_TRANSPORT_Handle *h = cls;
1088   struct StartMessage s;
1089   uint32_t options;
1090
1091   if (NULL == buf)
1092   {
1093     /* Can only be shutdown, just give up */
1094     LOG (GNUNET_ERROR_TYPE_DEBUG,
1095          "Shutdown while trying to transmit START request.\n");
1096     return 0;
1097   }
1098   LOG (GNUNET_ERROR_TYPE_DEBUG,
1099        "Transmitting START request.\n");
1100   GNUNET_assert (size >= sizeof (struct StartMessage));
1101   s.header.size = htons (sizeof (struct StartMessage));
1102   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1103   options = 0;
1104   if (h->check_self)
1105     options |= 1;
1106   if (h->rec != NULL)
1107     options |= 2;
1108   s.options = htonl (options);
1109   s.self = h->self;
1110   memcpy (buf, &s, sizeof (struct StartMessage));
1111   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
1112                          GNUNET_TIME_UNIT_FOREVER_REL);
1113   return sizeof (struct StartMessage);
1114 }
1115
1116
1117 /**
1118  * Try again to connect to transport service.
1119  *
1120  * @param cls the handle to the transport service
1121  * @param tc scheduler context
1122  */
1123 static void
1124 reconnect (void *cls,
1125            const struct GNUNET_SCHEDULER_TaskContext *tc)
1126 {
1127   struct GNUNET_TRANSPORT_Handle *h = cls;
1128
1129   h->reconnect_task = NULL;
1130   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1131   {
1132     /* shutdown, just give up */
1133     return;
1134   }
1135   LOG (GNUNET_ERROR_TYPE_DEBUG,
1136        "Connecting to transport service.\n");
1137   GNUNET_assert (NULL == h->client);
1138   GNUNET_assert (NULL == h->control_head);
1139   GNUNET_assert (NULL == h->control_tail);
1140   h->reconnecting = GNUNET_NO;
1141   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1142
1143   GNUNET_assert (NULL != h->client);
1144   schedule_control_transmit (h, sizeof (struct StartMessage),
1145                              &send_start, h);
1146 }
1147
1148
1149 /**
1150  * Function that will schedule the job that will try
1151  * to connect us again to the client.
1152  *
1153  * @param h transport service to reconnect
1154  */
1155 static void
1156 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1157 {
1158   struct GNUNET_TRANSPORT_TransmitHandle *th;
1159
1160   GNUNET_assert (h->reconnect_task == NULL);
1161   if (NULL != h->cth)
1162   {
1163     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1164     h->cth = NULL;
1165   }
1166   if (NULL != h->client)
1167   {
1168     GNUNET_CLIENT_disconnect (h->client);
1169     h->client = NULL;
1170 /*    LOG (GNUNET_ERROR_TYPE_ERROR,
1171          "Client disconnect done \n");*/
1172   }
1173   /* Forget about all neighbours that we used to be connected to */
1174   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
1175                                          &neighbour_delete, h);
1176   if (h->quota_task != NULL)
1177   {
1178     GNUNET_SCHEDULER_cancel (h->quota_task);
1179     h->quota_task = NULL;
1180   }
1181   while ((NULL != (th = h->control_head)))
1182   {
1183     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
1184     th->notify (th->notify_cls, 0, NULL);
1185     GNUNET_free (th);
1186   }
1187   LOG (GNUNET_ERROR_TYPE_DEBUG,
1188        "Scheduling task to reconnect to transport service in %s.\n",
1189        GNUNET_STRINGS_relative_time_to_string(h->reconnect_delay, GNUNET_YES));
1190   h->reconnect_task =
1191       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
1192   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
1193 }
1194
1195
1196 /**
1197  * Cancel control request for transmission to the transport service.
1198  *
1199  * @param th handle to the transport service
1200  * @param tth transmit handle to cancel
1201  */
1202 static void
1203 cancel_control_transmit (struct GNUNET_TRANSPORT_Handle *th,
1204                          struct GNUNET_TRANSPORT_TransmitHandle *tth)
1205 {
1206   LOG (GNUNET_ERROR_TYPE_DEBUG,
1207        "Canceling transmit of contral transmission requested\n");
1208   GNUNET_CONTAINER_DLL_remove (th->control_head, th->control_tail, tth);
1209   GNUNET_free (tth);
1210 }
1211
1212
1213 /**
1214  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT message to the
1215  * service.
1216  *
1217  * @param cls the `struct GNUNET_TRANSPORT_TryConnectHandle`
1218  * @param size number of bytes available in @a buf
1219  * @param buf where to copy the message
1220  * @return number of bytes copied to @a buf
1221  */
1222 static size_t
1223 send_try_connect (void *cls,
1224                   size_t size,
1225                   void *buf)
1226 {
1227   struct GNUNET_TRANSPORT_TryConnectHandle *tch = cls;
1228   struct TransportRequestConnectMessage msg;
1229
1230   tch->tth = NULL;
1231   if (NULL == buf)
1232   {
1233     LOG (GNUNET_ERROR_TYPE_DEBUG,
1234          "Discarding  `%s' request to `%4s' due to error in transport service connection.\n",
1235          "REQUEST_CONNECT",
1236          GNUNET_i2s (&tch->pid));
1237     if (NULL != tch->cb)
1238       tch->cb (tch->cb_cls,
1239                GNUNET_SYSERR);
1240     GNUNET_TRANSPORT_try_connect_cancel (tch);
1241     return 0;
1242   }
1243   LOG (GNUNET_ERROR_TYPE_DEBUG,
1244        "Transmitting `%s' request with respect to `%4s'.\n",
1245        "REQUEST_CONNECT",
1246        GNUNET_i2s (&tch->pid));
1247   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1248   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1249   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1250   msg.reserved = htonl (0);
1251   msg.peer = tch->pid;
1252   memcpy (buf, &msg, sizeof (msg));
1253   if (NULL != tch->cb)
1254     tch->cb (tch->cb_cls, GNUNET_OK);
1255   GNUNET_TRANSPORT_try_connect_cancel (tch);
1256   return sizeof (struct TransportRequestConnectMessage);
1257 }
1258
1259
1260 /**
1261  * Ask the transport service to establish a connection to
1262  * the given peer.
1263  *
1264  * @param handle connection to transport service
1265  * @param target who we should try to connect to
1266  * @param cb callback to be called when request was transmitted to transport
1267  *         service
1268  * @param cb_cls closure for the callback
1269  * @return a `struct GNUNET_TRANSPORT_TryConnectHandle` handle or
1270  *         NULL on failure (cb will not be called)
1271  */
1272 struct GNUNET_TRANSPORT_TryConnectHandle *
1273 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1274                               const struct GNUNET_PeerIdentity *target,
1275                               GNUNET_TRANSPORT_TryConnectCallback cb,
1276                               void *cb_cls)
1277 {
1278   struct GNUNET_TRANSPORT_TryConnectHandle *tch;
1279
1280   if (NULL == handle->client)
1281     return NULL;
1282   tch = GNUNET_new (struct GNUNET_TRANSPORT_TryConnectHandle);
1283   tch->th = handle;
1284   tch->pid = *target;
1285   tch->cb = cb;
1286   tch->cb_cls = cb_cls;
1287   tch->tth = schedule_control_transmit (handle,
1288                                         sizeof (struct TransportRequestConnectMessage),
1289                                         &send_try_connect, tch);
1290   GNUNET_CONTAINER_DLL_insert (handle->tc_head,
1291                                handle->tc_tail,
1292                                tch);
1293   return tch;
1294 }
1295
1296
1297 /**
1298  * Cancel the request to transport to try a connect
1299  * Callback will not be called
1300  *
1301  * @param tch the handle to cancel
1302  */
1303 void
1304 GNUNET_TRANSPORT_try_connect_cancel (struct GNUNET_TRANSPORT_TryConnectHandle *tch)
1305 {
1306   struct GNUNET_TRANSPORT_Handle *th;
1307
1308   th = tch->th;
1309   if (NULL != tch->tth)
1310     cancel_control_transmit (th, tch->tth);
1311   GNUNET_CONTAINER_DLL_remove (th->tc_head,
1312                                th->tc_tail,
1313                                tch);
1314   GNUNET_free (tch);
1315 }
1316
1317
1318 /**
1319  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT message to the
1320  * service.
1321  *
1322  * @param cls the `struct GNUNET_TRANSPORT_TryDisconnectHandle`
1323  * @param size number of bytes available in @a buf
1324  * @param buf where to copy the message
1325  * @return number of bytes copied to @a buf
1326  */
1327 static size_t
1328 send_try_disconnect (void *cls,
1329                      size_t size,
1330                      void *buf)
1331 {
1332   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh = cls;
1333   struct TransportRequestConnectMessage msg;
1334
1335   tdh->th = NULL;
1336   if (NULL == buf)
1337   {
1338     LOG (GNUNET_ERROR_TYPE_DEBUG,
1339          "Discarding  `%s' request to `%4s' due to error in transport service connection.\n",
1340          "REQUEST_DISCONNECT",
1341          GNUNET_i2s (&tdh->pid));
1342     if (NULL != tdh->cb)
1343       tdh->cb (tdh->cb_cls,
1344                GNUNET_SYSERR);
1345     GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1346     return 0;
1347   }
1348   LOG (GNUNET_ERROR_TYPE_DEBUG,
1349        "Transmitting `%s' request with respect to `%4s'.\n",
1350        "REQUEST_DISCONNECT",
1351        GNUNET_i2s (&tdh->pid));
1352   GNUNET_assert (size >= sizeof (struct TransportRequestDisconnectMessage));
1353   msg.header.size = htons (sizeof (struct TransportRequestDisconnectMessage));
1354   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT);
1355   msg.reserved = htonl (0);
1356   msg.peer = tdh->pid;
1357   memcpy (buf, &msg, sizeof (msg));
1358   if (NULL != tdh->cb)
1359     tdh->cb (tdh->cb_cls, GNUNET_OK);
1360   GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1361   return sizeof (struct TransportRequestDisconnectMessage);
1362 }
1363
1364
1365 /**
1366  * Ask the transport service to shutdown a connection to
1367  * the given peer.
1368  *
1369  * @param handle connection to transport service
1370  * @param target who we should try to connect to
1371  * @param cb callback to be called when request was transmitted to transport
1372  *         service
1373  * @param cb_cls closure for the callback @a cb
1374  * @return a `struct GNUNET_TRANSPORT_TryDisconnectHandle` handle or
1375  *         NULL on failure (cb will not be called)
1376  */
1377 struct GNUNET_TRANSPORT_TryDisconnectHandle *
1378 GNUNET_TRANSPORT_try_disconnect (struct GNUNET_TRANSPORT_Handle *handle,
1379                                  const struct GNUNET_PeerIdentity *target,
1380                                  GNUNET_TRANSPORT_TryDisconnectCallback cb,
1381                                  void *cb_cls)
1382 {
1383   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh;
1384
1385   if (NULL == handle->client)
1386     return NULL;
1387   tdh = GNUNET_new (struct GNUNET_TRANSPORT_TryDisconnectHandle);
1388   tdh->th = handle;
1389   tdh->pid = *target;
1390   tdh->cb = cb;
1391   tdh->cb_cls = cb_cls;
1392   tdh->tth = schedule_control_transmit (handle,
1393                                         sizeof (struct TransportRequestDisconnectMessage),
1394                                         &send_try_disconnect, tdh);
1395   GNUNET_CONTAINER_DLL_insert (handle->td_head,
1396                                handle->td_tail,
1397                                tdh);
1398   return tdh;
1399 }
1400
1401
1402 /**
1403  * Cancel the request to transport to try a disconnect
1404  * Callback will not be called
1405  *
1406  * @param tdh the handle to cancel
1407  */
1408 void
1409 GNUNET_TRANSPORT_try_disconnect_cancel (struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh)
1410 {
1411   struct GNUNET_TRANSPORT_Handle *th;
1412
1413   th = tdh->th;
1414   if (NULL != tdh->tth)
1415     cancel_control_transmit (th, tdh->tth);
1416   GNUNET_CONTAINER_DLL_remove (th->td_head,
1417                                th->td_tail,
1418                                tdh);
1419   GNUNET_free (tdh);
1420 }
1421
1422
1423 /**
1424  * Send HELLO message to the service.
1425  *
1426  * @param cls the HELLO message to send
1427  * @param size number of bytes available in @a buf
1428  * @param buf where to copy the message
1429  * @return number of bytes copied to @a buf
1430  */
1431 static size_t
1432 send_hello (void *cls, size_t size, void *buf)
1433 {
1434   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh = cls;
1435   struct GNUNET_MessageHeader *msg = ohh->msg;
1436   uint16_t ssize;
1437   struct GNUNET_SCHEDULER_TaskContext tc;
1438
1439   tc.read_ready = NULL;
1440   tc.write_ready = NULL;
1441   tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
1442   if (NULL == buf)
1443   {
1444     LOG (GNUNET_ERROR_TYPE_DEBUG,
1445          "Timeout while trying to transmit `%s' request.\n",
1446          "HELLO");
1447     if (NULL != ohh->cont)
1448       ohh->cont (ohh->cls, &tc);
1449     GNUNET_free (msg);
1450     GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1451     GNUNET_free (ohh);
1452     return 0;
1453   }
1454   LOG (GNUNET_ERROR_TYPE_DEBUG,
1455        "Transmitting `%s' request.\n",
1456        "HELLO");
1457   ssize = ntohs (msg->size);
1458   GNUNET_assert (size >= ssize);
1459   memcpy (buf, msg, ssize);
1460   GNUNET_free (msg);
1461   tc.reason = GNUNET_SCHEDULER_REASON_READ_READY;
1462   if (NULL != ohh->cont)
1463     ohh->cont (ohh->cls, &tc);
1464   GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1465   GNUNET_free (ohh);
1466   return ssize;
1467 }
1468
1469
1470 /**
1471  * Send traffic metric message to the service.
1472  *
1473  * @param cls the message to send
1474  * @param size number of bytes available in @a buf
1475  * @param buf where to copy the message
1476  * @return number of bytes copied to @a buf
1477  */
1478 static size_t
1479 send_metric (void *cls, size_t size, void *buf)
1480 {
1481   struct TrafficMetricMessage *msg = cls;
1482   uint16_t ssize;
1483
1484   if (NULL == buf)
1485   {
1486     LOG (GNUNET_ERROR_TYPE_DEBUG,
1487          "Timeout while trying to transmit `%s' request.\n",
1488          "TRAFFIC_METRIC");
1489     GNUNET_free (msg);
1490     return 0;
1491   }
1492   LOG (GNUNET_ERROR_TYPE_DEBUG,
1493        "Transmitting `%s' request.\n",
1494        "TRAFFIC_METRIC");
1495   ssize = ntohs (msg->header.size);
1496   GNUNET_assert (size >= ssize);
1497   memcpy (buf, msg, ssize);
1498   GNUNET_free (msg);
1499   return ssize;
1500 }
1501
1502
1503 /**
1504  * Set transport metrics for a peer and a direction
1505  *
1506  * @param handle transport handle
1507  * @param peer the peer to set the metric for
1508  * @param inbound set inbound direction (#GNUNET_YES or #GNUNET_NO)
1509  * @param outbound set outbound direction (#GNUNET_YES or #GNUNET_NO)
1510  * @param ats the metric as ATS information
1511  * @param ats_count the number of metrics
1512  *
1513  * Supported ATS values:
1514  * #GNUNET_ATS_QUALITY_NET_DELAY  (value in ms)
1515  * #GNUNET_ATS_QUALITY_NET_DISTANCE (value in count(hops))
1516  *
1517  * Example:
1518  * To enforce a delay of 10 ms for peer p1 in sending direction use:
1519  * <code>
1520  * struct GNUNET_ATS_Information ats;
1521  * ats.type = ntohl (GNUNET_ATS_QUALITY_NET_DELAY);
1522  * ats.value = ntohl (10);
1523  * GNUNET_TRANSPORT_set_traffic_metric (th, p1, TM_SEND, &ats, 1);
1524  * </code>
1525  * Note:
1526  * Delay restrictions in receiving direction will be enforced with
1527  * 1 message delay.
1528  */
1529 void
1530 GNUNET_TRANSPORT_set_traffic_metric (struct GNUNET_TRANSPORT_Handle *handle,
1531                                      const struct GNUNET_PeerIdentity *peer,
1532                                      int inbound,
1533                                      int outbound,
1534                                      const struct GNUNET_ATS_Information *ats,
1535                                      size_t ats_count)
1536 {
1537   struct TrafficMetricMessage *msg;
1538
1539   GNUNET_assert ((outbound == GNUNET_YES) || (outbound == GNUNET_NO));
1540   GNUNET_assert ((inbound == GNUNET_YES) || (inbound == GNUNET_NO));
1541   if ((GNUNET_NO == inbound) && (GNUNET_NO == outbound))
1542     return;
1543   if (0 == ats_count)
1544     return;
1545
1546   size_t len = sizeof (struct TrafficMetricMessage) +
1547     ats_count * sizeof (struct GNUNET_ATS_Information);
1548
1549   msg = GNUNET_malloc (len);
1550   msg->header.size = htons (len);
1551   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC);
1552   msg->direction = htons (0 + outbound + 2 * inbound);
1553   msg->ats_count = htons (ats_count);
1554   msg->peer = (*peer);
1555   memcpy (&msg[1], ats, ats_count * sizeof (struct GNUNET_ATS_Information));
1556   schedule_control_transmit (handle, len,
1557                              &send_metric, msg);
1558 }
1559
1560
1561 /**
1562  * Offer the transport service the HELLO of another peer.  Note that
1563  * the transport service may just ignore this message if the HELLO is
1564  * malformed or useless due to our local configuration.
1565  *
1566  * @param handle connection to transport service
1567  * @param hello the hello message
1568  * @param cont continuation to call when HELLO has been sent,
1569  *      tc reason #GNUNET_SCHEDULER_REASON_TIMEOUT for fail
1570  *      tc reasong #GNUNET_SCHEDULER_REASON_READ_READY for success
1571  * @param cls closure for continuation
1572  * @return a `struct GNUNET_TRANSPORT_OfferHelloHandle` handle or NULL on failure,
1573  *      in case of failure cont will not be called
1574  *
1575  */
1576 struct GNUNET_TRANSPORT_OfferHelloHandle *
1577 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1578                               const struct GNUNET_MessageHeader *hello,
1579                               GNUNET_SCHEDULER_TaskCallback cont, void *cls)
1580 {
1581   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh;
1582   struct GNUNET_MessageHeader *msg;
1583   struct GNUNET_PeerIdentity peer;
1584   uint16_t size;
1585
1586   if (NULL == handle->client)
1587     return NULL;
1588   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1589   size = ntohs (hello->size);
1590   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1591   if (GNUNET_OK !=
1592       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1593   {
1594     GNUNET_break (0);
1595     return NULL;
1596   }
1597
1598   msg = GNUNET_malloc (size);
1599   memcpy (msg, hello, size);
1600   LOG (GNUNET_ERROR_TYPE_DEBUG,
1601        "Offering `%s' message of `%4s' to transport for validation.\n", "HELLO",
1602        GNUNET_i2s (&peer));
1603
1604   ohh = GNUNET_new (struct GNUNET_TRANSPORT_OfferHelloHandle);
1605   ohh->th = handle;
1606   ohh->cont = cont;
1607   ohh->cls = cls;
1608   ohh->msg = msg;
1609   ohh->tth = schedule_control_transmit (handle, size,
1610                                         &send_hello, ohh);
1611   GNUNET_CONTAINER_DLL_insert (handle->oh_head, handle->oh_tail, ohh);
1612   return ohh;
1613 }
1614
1615
1616 /**
1617  * Cancel the request to transport to offer the HELLO message
1618  *
1619  * @param ohh the GNUNET_TRANSPORT_OfferHelloHandle to cancel
1620  */
1621 void
1622 GNUNET_TRANSPORT_offer_hello_cancel (struct GNUNET_TRANSPORT_OfferHelloHandle *ohh)
1623 {
1624   struct GNUNET_TRANSPORT_Handle *th = ohh->th;
1625
1626   cancel_control_transmit (ohh->th, ohh->tth);
1627   GNUNET_CONTAINER_DLL_remove (th->oh_head, th->oh_tail, ohh);
1628   GNUNET_free (ohh->msg);
1629   GNUNET_free (ohh);
1630 }
1631
1632
1633 /**
1634  * Checks if a given peer is connected to us
1635  *
1636  * @param handle connection to transport service
1637  * @param peer the peer to check
1638  * @return #GNUNET_YES (connected) or #GNUNET_NO (disconnected)
1639  */
1640 int
1641 GNUNET_TRANSPORT_check_peer_connected (struct GNUNET_TRANSPORT_Handle *handle,
1642                                        const struct GNUNET_PeerIdentity *peer)
1643 {
1644   if (GNUNET_YES ==
1645       GNUNET_CONTAINER_multipeermap_contains (handle->neighbours,
1646                                               peer))
1647     return GNUNET_YES;
1648   return GNUNET_NO;
1649 }
1650
1651
1652 /**
1653  * Task to call the HelloUpdateCallback of the GetHelloHandle
1654  *
1655  * @param cls the `struct GNUNET_TRANSPORT_GetHelloHandle`
1656  * @param tc the scheduler task context
1657  */
1658 static void
1659 call_hello_update_cb_async (void *cls,
1660                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1661 {
1662   struct GNUNET_TRANSPORT_GetHelloHandle *ghh = cls;
1663
1664   GNUNET_assert (NULL != ghh->handle->my_hello);
1665   GNUNET_assert (NULL != ghh->notify_task);
1666   ghh->notify_task = NULL;
1667   ghh->rec (ghh->rec_cls,
1668             ghh->handle->my_hello);
1669 }
1670
1671
1672 /**
1673  * Obtain the HELLO message for this peer.  The callback given in this function
1674  * is never called synchronously.
1675  *
1676  * @param handle connection to transport service
1677  * @param rec function to call with the HELLO, sender will be our peer
1678  *            identity; message and sender will be NULL on timeout
1679  *            (handshake with transport service pending/failed).
1680  *             cost estimate will be 0.
1681  * @param rec_cls closure for @a rec
1682  * @return handle to cancel the operation
1683  */
1684 struct GNUNET_TRANSPORT_GetHelloHandle *
1685 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1686                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1687                             void *rec_cls)
1688 {
1689   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1690
1691   hwl = GNUNET_new (struct GNUNET_TRANSPORT_GetHelloHandle);
1692   hwl->rec = rec;
1693   hwl->rec_cls = rec_cls;
1694   hwl->handle = handle;
1695   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1696   if (NULL != handle->my_hello)
1697     hwl->notify_task = GNUNET_SCHEDULER_add_now (&call_hello_update_cb_async,
1698                                                  hwl);
1699   return hwl;
1700 }
1701
1702
1703 /**
1704  * Stop receiving updates about changes to our HELLO message.
1705  *
1706  * @param ghh handle to cancel
1707  */
1708 void
1709 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1710 {
1711   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1712
1713   if (NULL != ghh->notify_task)
1714     GNUNET_SCHEDULER_cancel (ghh->notify_task);
1715   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1716   GNUNET_free (ghh);
1717 }
1718
1719
1720 /**
1721  * Connect to the transport service.  Note that the connection may
1722  * complete (or fail) asynchronously.
1723  *
1724  * @param cfg configuration to use
1725  * @param self our own identity (API should check that it matches
1726  *             the identity found by transport), or NULL (no check)
1727  * @param cls closure for the callbacks
1728  * @param rec receive function to call
1729  * @param nc function to call on connect events
1730  * @param nd function to call on disconnect events
1731  * @return NULL on error
1732  */
1733 struct GNUNET_TRANSPORT_Handle *
1734 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1735                           const struct GNUNET_PeerIdentity *self, void *cls,
1736                           GNUNET_TRANSPORT_ReceiveCallback rec,
1737                           GNUNET_TRANSPORT_NotifyConnect nc,
1738                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1739 {
1740   return GNUNET_TRANSPORT_connect2 (cfg, self, cls,
1741                                     rec, nc, nd, NULL);
1742 }
1743
1744
1745 /**
1746  * Connect to the transport service.  Note that the connection may
1747  * complete (or fail) asynchronously.
1748  *
1749  * @param cfg configuration to use
1750  * @param self our own identity (API should check that it matches
1751  *             the identity found by transport), or NULL (no check)
1752  * @param cls closure for the callbacks
1753  * @param rec receive function to call
1754  * @param nc function to call on connect events
1755  * @param nd function to call on disconnect events
1756  * @param neb function to call if we have excess bandwidth to a peer
1757  * @return NULL on error
1758  */
1759 struct GNUNET_TRANSPORT_Handle *
1760 GNUNET_TRANSPORT_connect2 (const struct GNUNET_CONFIGURATION_Handle *cfg,
1761                            const struct GNUNET_PeerIdentity *self, void *cls,
1762                            GNUNET_TRANSPORT_ReceiveCallback rec,
1763                            GNUNET_TRANSPORT_NotifyConnect nc,
1764                            GNUNET_TRANSPORT_NotifyDisconnect nd,
1765                            GNUNET_TRANSPORT_NotifyExcessBandwidth neb)
1766 {
1767   struct GNUNET_TRANSPORT_Handle *ret;
1768
1769   ret = GNUNET_new (struct GNUNET_TRANSPORT_Handle);
1770   if (NULL != self)
1771   {
1772     ret->self = *self;
1773     ret->check_self = GNUNET_YES;
1774   }
1775   ret->cfg = cfg;
1776   ret->cls = cls;
1777   ret->rec = rec;
1778   ret->nc_cb = nc;
1779   ret->nd_cb = nd;
1780   ret->neb_cb = neb;
1781   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1782   LOG (GNUNET_ERROR_TYPE_DEBUG,
1783        "Connecting to transport service.\n");
1784   ret->client = GNUNET_CLIENT_connect ("transport", cfg);
1785   if (NULL == ret->client)
1786   {
1787     GNUNET_free (ret);
1788     return NULL;
1789   }
1790   ret->neighbours =
1791     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
1792                                           GNUNET_YES);
1793   ret->ready_heap =
1794       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1795  schedule_control_transmit (ret, sizeof (struct StartMessage),
1796                             &send_start, ret);
1797   return ret;
1798 }
1799
1800
1801 /**
1802  * Disconnect from the transport service.
1803  *
1804  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_connect()
1805  */
1806 void
1807 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1808 {
1809   LOG (GNUNET_ERROR_TYPE_DEBUG,
1810        "Transport disconnect called!\n");
1811   /* this disconnects all neighbours... */
1812   if (handle->reconnect_task == NULL)
1813     disconnect_and_schedule_reconnect (handle);
1814   /* and now we stop trying to connect again... */
1815   if (handle->reconnect_task != NULL)
1816   {
1817     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1818     handle->reconnect_task = NULL;
1819   }
1820   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
1821   handle->neighbours = NULL;
1822   if (handle->quota_task != NULL)
1823   {
1824     GNUNET_SCHEDULER_cancel (handle->quota_task);
1825     handle->quota_task = NULL;
1826   }
1827   GNUNET_free_non_null (handle->my_hello);
1828   handle->my_hello = NULL;
1829   GNUNET_assert (NULL == handle->tc_head);
1830   GNUNET_assert (NULL == handle->tc_tail);
1831   GNUNET_assert (NULL == handle->hwl_head);
1832   GNUNET_assert (NULL == handle->hwl_tail);
1833   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1834   handle->ready_heap = NULL;
1835   GNUNET_free (handle);
1836 }
1837
1838
1839 /**
1840  * Check if we could queue a message of the given size for
1841  * transmission.  The transport service will take both its
1842  * internal buffers and bandwidth limits imposed by the
1843  * other peer into consideration when answering this query.
1844  *
1845  * @param handle connection to transport service
1846  * @param target who should receive the message
1847  * @param size how big is the message we want to transmit?
1848  * @param timeout after how long should we give up (and call
1849  *        notify with buf NULL and size 0)?
1850  * @param notify function to call when we are ready to
1851  *        send such a message
1852  * @param notify_cls closure for @a notify
1853  * @return NULL if someone else is already waiting to be notified
1854  *         non-NULL if the notify callback was queued (can be used to cancel
1855  *         using #GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1856  */
1857 struct GNUNET_TRANSPORT_TransmitHandle *
1858 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1859                                         const struct GNUNET_PeerIdentity *target,
1860                                         size_t size,
1861                                         struct GNUNET_TIME_Relative timeout,
1862                                         GNUNET_TRANSPORT_TransmitReadyNotify notify,
1863                                         void *notify_cls)
1864 {
1865   struct Neighbour *n;
1866   struct GNUNET_TRANSPORT_TransmitHandle *th;
1867   struct GNUNET_TIME_Relative delay;
1868
1869   n = neighbour_find (handle, target);
1870   if (NULL == n)
1871   {
1872     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1873      * once a connection has been established */
1874     GNUNET_assert (0);
1875     return NULL;
1876   }
1877   if (NULL != n->th)
1878   {
1879     /* attempt to send two messages at the same time to the same peer */
1880     GNUNET_assert (0);
1881     return NULL;
1882   }
1883   GNUNET_assert (NULL == n->hn);
1884   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1885   th->neighbour = n;
1886   th->notify = notify;
1887   th->notify_cls = notify_cls;
1888   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1889   th->notify_size = size;
1890   n->th = th;
1891   /* calculate when our transmission should be ready */
1892   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size + n->traffic_overhead);
1893   n->traffic_overhead = 0;
1894   if (delay.rel_value_us > timeout.rel_value_us)
1895     delay.rel_value_us = 0;        /* notify immediately (with failure) */
1896   LOG (GNUNET_ERROR_TYPE_DEBUG,
1897        "Bandwidth tracker allows next transmission to peer %s in %s\n",
1898        GNUNET_i2s (target),
1899        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1900   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value_us);
1901   schedule_transmission (handle);
1902   return th;
1903 }
1904
1905
1906 /**
1907  * Cancel the specified transmission-ready notification.
1908  *
1909  * @param th handle returned from #GNUNET_TRANSPORT_notify_transmit_ready()
1910  */
1911 void
1912 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct GNUNET_TRANSPORT_TransmitHandle *th)
1913 {
1914   struct Neighbour *n;
1915
1916   GNUNET_assert (NULL == th->next);
1917   GNUNET_assert (NULL == th->prev);
1918   n = th->neighbour;
1919   GNUNET_assert (th == n->th);
1920   n->th = NULL;
1921   if (NULL != n->hn)
1922   {
1923     GNUNET_CONTAINER_heap_remove_node (n->hn);
1924     n->hn = NULL;
1925   }
1926   else
1927   {
1928     GNUNET_assert (NULL != th->timeout_task);
1929     GNUNET_SCHEDULER_cancel (th->timeout_task);
1930     th->timeout_task = NULL;
1931   }
1932   GNUNET_free (th);
1933 }
1934
1935
1936 /* end of transport_api.c */