- implementation for mantis 0002485
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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  * - adjust testcases to use new 'try connect' style (should be easy, breaks API compatibility!)
28  * - adjust core service to use new 'try connect' style (should be MUCH nicer there as well!)
29  * - test test test
30  */
31 #include "platform.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_bandwidth_lib.h"
34 #include "gnunet_client_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_container_lib.h"
37 #include "gnunet_arm_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_protocols.h"
40 #include "gnunet_server_lib.h"
41 #include "gnunet_time_lib.h"
42 #include "gnunet_transport_service.h"
43 #include "transport.h"
44
45 #define LOG(kind,...) GNUNET_log_from (kind, "transport-api",__VA_ARGS__)
46
47 /**
48  * How large to start with for the hashmap of neighbours.
49  */
50 #define STARTING_NEIGHBOURS_SIZE 16
51
52 /**
53  * Handle for a message that should be transmitted to the service.
54  * Used for both control messages and normal messages.
55  */
56 struct GNUNET_TRANSPORT_TransmitHandle
57 {
58
59   /**
60    * We keep all requests in a DLL.
61    */
62   struct GNUNET_TRANSPORT_TransmitHandle *next;
63
64   /**
65    * We keep all requests in a DLL.
66    */
67   struct GNUNET_TRANSPORT_TransmitHandle *prev;
68
69   /**
70    * Neighbour for this handle, NULL for control messages.
71    */
72   struct Neighbour *neighbour;
73
74   /**
75    * Function to call when notify_size bytes are available
76    * for transmission.
77    */
78   GNUNET_CONNECTION_TransmitReadyNotify notify;
79
80   /**
81    * Closure for notify.
82    */
83   void *notify_cls;
84
85   /**
86    * Timeout for this request, 0 for control messages.
87    */
88   struct GNUNET_TIME_Absolute timeout;
89
90   /**
91    * Task to trigger request timeout if the request is stalled due to
92    * congestion.
93    */
94   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
95
96   /**
97    * How many bytes is our notify callback waiting for?
98    */
99   size_t notify_size;
100
101   /**
102    * How important is this message? Not used for control messages.
103    */
104   uint32_t priority;
105
106 };
107
108
109 /**
110  * Entry in hash table of all of our current neighbours.
111  */
112 struct Neighbour
113 {
114   /**
115    * Overall transport handle.
116    */
117   struct GNUNET_TRANSPORT_Handle *h;
118
119   /**
120    * Active transmit handle or NULL.
121    */
122   struct GNUNET_TRANSPORT_TransmitHandle *th;
123
124   /**
125    * Identity of this neighbour.
126    */
127   struct GNUNET_PeerIdentity id;
128
129   /**
130    * Outbound bandwidh tracker.
131    */
132   struct GNUNET_BANDWIDTH_Tracker out_tracker;
133
134   /**
135    * Entry in our readyness heap (which is sorted by 'next_ready'
136    * value).  NULL if there is no pending transmission request for
137    * this neighbour or if we're waiting for 'is_ready' to become
138    * true AFTER the 'out_tracker' suggested that this peer's quota
139    * has been satisfied (so once 'is_ready' goes to GNUNET_YES,
140    * we should immediately go back into the heap).
141    */
142   struct GNUNET_CONTAINER_HeapNode *hn;
143
144   /**
145    * Is this peer currently ready to receive a message?
146    */
147   int is_ready;
148
149 };
150
151
152 /**
153  * Linked list of functions to call whenever our HELLO is updated.
154  */
155 struct GNUNET_TRANSPORT_GetHelloHandle
156 {
157
158   /**
159    * This is a doubly linked list.
160    */
161   struct GNUNET_TRANSPORT_GetHelloHandle *next;
162
163   /**
164    * This is a doubly linked list.
165    */
166   struct GNUNET_TRANSPORT_GetHelloHandle *prev;
167
168   /**
169    * Transport handle.
170    */
171   struct GNUNET_TRANSPORT_Handle *handle;
172
173   /**
174    * Callback to call once we got our HELLO.
175    */
176   GNUNET_TRANSPORT_HelloUpdateCallback rec;
177
178   /**
179    * Closure for rec.
180    */
181   void *rec_cls;
182
183 };
184
185
186 /**
187  * Handle for the transport service (includes all of the
188  * state for the transport service).
189  */
190 struct GNUNET_TRANSPORT_Handle
191 {
192
193   /**
194    * Closure for the callbacks.
195    */
196   void *cls;
197
198   /**
199    * Function to call for received data.
200    */
201   GNUNET_TRANSPORT_ReceiveCallback rec;
202
203   /**
204    * function to call on connect events
205    */
206   GNUNET_TRANSPORT_NotifyConnect nc_cb;
207
208   /**
209    * function to call on disconnect events
210    */
211   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
212
213   /**
214    * Head of DLL of control messages.
215    */
216   struct GNUNET_TRANSPORT_TransmitHandle *control_head;
217
218   /**
219    * Tail of DLL of control messages.
220    */
221   struct GNUNET_TRANSPORT_TransmitHandle *control_tail;
222
223   /**
224    * The current HELLO message for this peer.  Updated
225    * whenever transports change their addresses.
226    */
227   struct GNUNET_HELLO_Message *my_hello;
228
229   /**
230    * My client connection to the transport service.
231    */
232   struct GNUNET_CLIENT_Connection *client;
233
234   /**
235    * Handle to our registration with the client for notification.
236    */
237   struct GNUNET_CLIENT_TransmitHandle *cth;
238
239   /**
240    * Linked list of pending requests for our HELLO.
241    */
242   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_head;
243
244   /**
245    * Linked list of pending requests for our HELLO.
246    */
247   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_tail;
248
249   /**
250    * My configuration.
251    */
252   const struct GNUNET_CONFIGURATION_Handle *cfg;
253
254   /**
255    * Hash map of the current connected neighbours of this peer.
256    * Maps peer identities to 'struct Neighbour' entries.
257    */
258   struct GNUNET_CONTAINER_MultiHashMap *neighbours;
259
260   /**
261    * Heap sorting peers with pending messages by the timestamps that
262    * specify when we could next send a message to the respective peer.
263    * Excludes control messages (which can always go out immediately).
264    * Maps time stamps to 'struct Neighbour' entries.
265    */
266   struct GNUNET_CONTAINER_Heap *ready_heap;
267
268   /**
269    * Peer identity as assumed by this process, or all zeros.
270    */
271   struct GNUNET_PeerIdentity self;
272
273   /**
274    * ID of the task trying to reconnect to the service.
275    */
276   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
277
278   /**
279    * ID of the task trying to trigger transmission for a peer while
280    * maintaining bandwidth quotas.  In use if there are no control
281    * messages and the smallest entry in the 'ready_heap' has a time
282    * stamp in the future.
283    */
284   GNUNET_SCHEDULER_TaskIdentifier quota_task;
285
286   /**
287    * Delay until we try to reconnect.
288    */
289   struct GNUNET_TIME_Relative reconnect_delay;
290
291   /**
292    * Should we check that 'self' matches what the service thinks?
293    * (if GNUNET_NO, then 'self' is all zeros!).
294    */
295   int check_self;
296 };
297
298
299 /**
300  * Schedule the task to send one message, either from the control
301  * list or the peer message queues  to the service.
302  *
303  * @param h transport service to schedule a transmission for
304  */
305 static void
306 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
307
308
309 /**
310  * Function that will schedule the job that will try
311  * to connect us again to the client.
312  *
313  * @param h transport service to reconnect
314  */
315 static void
316 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h);
317
318
319 /**
320  * Get the neighbour list entry for the given peer
321  *
322  * @param h our context
323  * @param peer peer to look up
324  * @return NULL if no such peer entry exists
325  */
326 static struct Neighbour *
327 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
328                 const struct GNUNET_PeerIdentity *peer)
329 {
330   return GNUNET_CONTAINER_multihashmap_get (h->neighbours, &peer->hashPubKey);
331 }
332
333
334 /**
335  * Add neighbour to our list
336  *
337  * @return NULL if this API is currently disconnecting from the service
338  */
339 static struct Neighbour *
340 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
341                const struct GNUNET_PeerIdentity *pid)
342 {
343   struct Neighbour *n;
344
345   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating entry for neighbour `%4s'.\n",
346        GNUNET_i2s (pid));
347   n = GNUNET_malloc (sizeof (struct Neighbour));
348   n->id = *pid;
349   n->h = h;
350   n->is_ready = GNUNET_YES;
351   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
352                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
353                                  MAX_BANDWIDTH_CARRY_S);
354   GNUNET_assert (GNUNET_OK ==
355                  GNUNET_CONTAINER_multihashmap_put (h->neighbours,
356                                                     &pid->hashPubKey, n,
357                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
358   return n;
359 }
360
361
362 /**
363  * Iterator over hash map entries, for deleting state of a neighbour.
364  *
365  * @param cls the 'struct GNUNET_TRANSPORT_Handle*'
366  * @param key peer identity
367  * @param value value in the hash map, the neighbour entry to delete
368  * @return GNUNET_YES if we should continue to
369  *         iterate,
370  *         GNUNET_NO if not.
371  */
372 static int
373 neighbour_delete (void *cls, const struct GNUNET_HashCode * key, void *value)
374 {
375   struct GNUNET_TRANSPORT_Handle *handle = cls;
376   struct Neighbour *n = value;
377
378   if (NULL != handle->nd_cb)
379     handle->nd_cb (handle->cls, &n->id);
380   GNUNET_assert (NULL == n->th);
381   GNUNET_assert (NULL == n->hn);
382   GNUNET_assert (GNUNET_YES ==
383                  GNUNET_CONTAINER_multihashmap_remove (handle->neighbours, key,
384                                                        n));
385   GNUNET_free (n);
386   return GNUNET_YES;
387 }
388
389
390 /**
391  * Function we use for handling incoming messages.
392  *
393  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
394  * @param msg message received, NULL on timeout or fatal error
395  */
396 static void
397 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
398 {
399   struct GNUNET_TRANSPORT_Handle *h = cls;
400   const struct DisconnectInfoMessage *dim;
401   const struct ConnectInfoMessage *cim;
402   const struct InboundMessage *im;
403   const struct GNUNET_MessageHeader *imm;
404   const struct SendOkMessage *okm;
405   const struct QuotaSetMessage *qm;
406   const struct GNUNET_ATS_Information *ats;
407   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
408   struct GNUNET_TRANSPORT_GetHelloHandle *next_hwl;
409   struct Neighbour *n;
410   struct GNUNET_PeerIdentity me;
411   uint16_t size;
412   uint32_t ats_count;
413
414   GNUNET_assert (h->client != NULL);
415   if (msg == NULL)
416   {
417     LOG (GNUNET_ERROR_TYPE_DEBUG,
418          "Error receiving from transport service, disconnecting temporarily.\n");
419     disconnect_and_schedule_reconnect (h);
420     return;
421   }
422   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
423                          GNUNET_TIME_UNIT_FOREVER_REL);
424   size = ntohs (msg->size);
425   switch (ntohs (msg->type))
426   {
427   case GNUNET_MESSAGE_TYPE_HELLO:
428     if (GNUNET_OK !=
429         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
430     {
431       GNUNET_break (0);
432       break;
433     }
434     LOG (GNUNET_ERROR_TYPE_DEBUG,
435          "Receiving (my own) `%s' message, I am `%4s'.\n", "HELLO",
436          GNUNET_i2s (&me));
437     GNUNET_free_non_null (h->my_hello);
438     h->my_hello = NULL;
439     if (size < sizeof (struct GNUNET_MessageHeader))
440     {
441       GNUNET_break (0);
442       break;
443     }
444     h->my_hello = GNUNET_malloc (size);
445     memcpy (h->my_hello, msg, size);
446     hwl = h->hwl_head;
447     while (NULL != hwl)
448     {
449       next_hwl = hwl->next;
450       hwl->rec (hwl->rec_cls,
451                 (const struct GNUNET_MessageHeader *) h->my_hello);
452       hwl = next_hwl;
453     }
454     break;
455   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
456     if (size < sizeof (struct ConnectInfoMessage))
457     {
458       GNUNET_break (0);
459       break;
460     }
461     cim = (const struct ConnectInfoMessage *) msg;
462     ats_count = ntohl (cim->ats_count);
463     if (size !=
464         sizeof (struct ConnectInfoMessage) +
465         ats_count * sizeof (struct GNUNET_ATS_Information))
466     {
467       GNUNET_break (0);
468       break;
469     }
470     ats = (const struct GNUNET_ATS_Information *) &cim[1];
471     LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
472          "CONNECT", GNUNET_i2s (&cim->id));
473     n = neighbour_find (h, &cim->id);
474     if (n != NULL)
475     {
476       GNUNET_break (0);
477       break;
478     }
479     n = neighbour_add (h, &cim->id);
480     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, cim->quota_out);
481     if (h->nc_cb != NULL)
482       h->nc_cb (h->cls, &n->id, ats, ats_count);
483     break;
484   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
485     if (size != sizeof (struct DisconnectInfoMessage))
486     {
487       GNUNET_break (0);
488       break;
489     }
490     dim = (const struct DisconnectInfoMessage *) msg;
491     GNUNET_break (ntohl (dim->reserved) == 0);
492     LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
493          "DISCONNECT", GNUNET_i2s (&dim->peer));
494     n = neighbour_find (h, &dim->peer);
495     if (n == NULL)
496     {
497       GNUNET_break (0);
498       break;
499     }
500     neighbour_delete (h, &dim->peer.hashPubKey, n);
501     break;
502   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
503     if (size != sizeof (struct SendOkMessage))
504     {
505       GNUNET_break (0);
506       break;
507     }
508     okm = (const struct SendOkMessage *) msg;
509     LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message, transmission %s.\n",
510          "SEND_OK", ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
511     n = neighbour_find (h, &okm->peer);
512     if (n == NULL)
513       break;
514     GNUNET_break (GNUNET_NO == n->is_ready);
515     n->is_ready = GNUNET_YES;
516     if ((n->th != NULL) && (n->hn == NULL))
517     {
518       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->th->timeout_task);
519       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
520       n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
521       /* we've been waiting for this (congestion, not quota,
522        * caused delayed transmission) */
523       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
524       schedule_transmission (h);
525     }
526     break;
527   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
528     LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message.\n", "RECV");
529     if (size <
530         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
531     {
532       GNUNET_break (0);
533       break;
534     }
535     im = (const struct InboundMessage *) msg;
536     ats_count = ntohl (im->ats_count);
537     ats = (const struct GNUNET_ATS_Information *) &im[1];
538     imm = (const struct GNUNET_MessageHeader *) &ats[ats_count];
539     if (ntohs (imm->size) + sizeof (struct InboundMessage) +
540         ats_count * sizeof (struct GNUNET_ATS_Information) != size)
541     {
542       GNUNET_break (0);
543       break;
544     }
545     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u from `%4s'.\n",
546          ntohs (imm->type), GNUNET_i2s (&im->peer));
547     n = neighbour_find (h, &im->peer);
548     if (n == NULL)
549     {
550       GNUNET_break (0);
551       break;
552     }
553     if (h->rec != NULL)
554       h->rec (h->cls, &im->peer, imm, ats, ats_count);
555     break;
556   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
557     LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message.\n", "SET_QUOTA");
558     if (size != sizeof (struct QuotaSetMessage))
559     {
560       GNUNET_break (0);
561       break;
562     }
563     qm = (const struct QuotaSetMessage *) msg;
564     n = neighbour_find (h, &qm->peer);
565     if (n == NULL)
566       break;
567     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, qm->quota);
568     break;
569   default:
570     LOG (GNUNET_ERROR_TYPE_ERROR,
571          _("Received unexpected message of type %u in %s:%u\n"),
572          ntohs (msg->type), __FILE__, __LINE__);
573     GNUNET_break (0);
574     break;
575   }
576 }
577
578
579 /**
580  * A transmission request could not be satisfied because of
581  * network congestion.  Notify the initiator and clean up.
582  *
583  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle'
584  * @param tc scheduler context
585  */
586 static void
587 timeout_request_due_to_congestion (void *cls,
588                                    const struct GNUNET_SCHEDULER_TaskContext
589                                    *tc)
590 {
591   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
592   struct Neighbour *n = th->neighbour;
593
594   n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
595   GNUNET_assert (th == n->th);
596   GNUNET_assert (NULL == n->hn);
597   n->th = NULL;
598   th->notify (th->notify_cls, 0, NULL);
599   GNUNET_free (th);
600 }
601
602
603 /**
604  * Transmit message(s) to service.
605  *
606  * @param cls handle to transport
607  * @param size number of bytes available in buf
608  * @param buf where to copy the message
609  * @return number of bytes copied to buf
610  */
611 static size_t
612 transport_notify_ready (void *cls, size_t size, void *buf)
613 {
614   struct GNUNET_TRANSPORT_Handle *h = cls;
615   struct GNUNET_TRANSPORT_TransmitHandle *th;
616   struct Neighbour *n;
617   char *cbuf;
618   struct OutboundMessage obm;
619   size_t ret;
620   size_t nret;
621   size_t mret;
622
623   GNUNET_assert (NULL != h->client);
624   h->cth = NULL;
625   if (NULL == buf)
626   {
627     /* transmission failed */
628     disconnect_and_schedule_reconnect (h);
629     return 0;
630   }
631
632   cbuf = buf;
633   ret = 0;
634   /* first send control messages */
635   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
636   {
637     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
638     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
639     LOG (GNUNET_ERROR_TYPE_DEBUG, "Added %u bytes of control message at %u\n",
640          nret, ret);
641     GNUNET_free (th);
642     ret += nret;
643     size -= nret;
644   }
645
646   /* then, if possible and no control messages pending, send data messages */
647   while ((NULL == h->control_head) &&
648          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
649   {
650     if (GNUNET_YES != n->is_ready)
651     {
652       /* peer not ready, wait for notification! */
653       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
654       n->hn = NULL;
655       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->th->timeout_task);
656       n->th->timeout_task =
657           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
658                                         (n->th->timeout),
659                                         &timeout_request_due_to_congestion,
660                                         n->th);
661       continue;
662     }
663     th = n->th;
664     if (th->notify_size + sizeof (struct OutboundMessage) > size)
665       break;                    /* does not fit */
666     if (GNUNET_BANDWIDTH_tracker_get_delay
667         (&n->out_tracker, th->notify_size).rel_value > 0)
668       break;                    /* too early */
669     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
670     n->hn = NULL;
671     n->th = NULL;
672     n->is_ready = GNUNET_NO;
673     GNUNET_assert (size >= sizeof (struct OutboundMessage));
674     mret =
675         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
676                     &cbuf[ret + sizeof (struct OutboundMessage)]);
677     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
678     if (mret != 0)
679     {
680       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
681                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
682       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
683       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
684       obm.priority = htonl (th->priority);
685       obm.timeout =
686           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
687                                      (th->timeout));
688       obm.peer = n->id;
689       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
690       ret += (mret + sizeof (struct OutboundMessage));
691       size -= (mret + sizeof (struct OutboundMessage));
692       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
693     }
694     GNUNET_free (th);
695   }
696   /* if there are more pending messages, try to schedule those */
697   schedule_transmission (h);
698   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes to transport service\n",
699        ret);
700   return ret;
701 }
702
703
704 /**
705  * Schedule the task to send one message, either from the control
706  * list or the peer message queues  to the service.
707  *
708  * @param cls transport service to schedule a transmission for
709  * @param tc scheduler context
710  */
711 static void
712 schedule_transmission_task (void *cls,
713                             const struct GNUNET_SCHEDULER_TaskContext *tc)
714 {
715   struct GNUNET_TRANSPORT_Handle *h = cls;
716   size_t size;
717   struct GNUNET_TRANSPORT_TransmitHandle *th;
718   struct Neighbour *n;
719
720   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
721   GNUNET_assert (NULL != h->client);
722   /* destroy all requests that have timed out */
723   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
724          (GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value == 0))
725   {
726     /* notify client that the request could not be satisfied within
727      * the given time constraints */
728     th = n->th;
729     n->th = NULL;
730     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
731     n->hn = NULL;
732     LOG (GNUNET_ERROR_TYPE_DEBUG,
733          "Signalling timeout for transmission to peer %s due to congestion\n",
734          GNUNET_i2s (&n->id));
735     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
736     GNUNET_free (th);
737   }
738   if (NULL != h->cth)
739     return;
740   if (NULL != h->control_head)
741   {
742     size = h->control_head->notify_size;
743   }
744   else
745   {
746     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
747     if (NULL == n)
748       return;                   /* no pending messages */
749     size = n->th->notify_size + sizeof (struct OutboundMessage);
750   }
751   LOG (GNUNET_ERROR_TYPE_DEBUG, "Calling notify_transmit_ready\n");
752   h->cth =
753       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
754                                            GNUNET_TIME_UNIT_FOREVER_REL,
755                                            GNUNET_NO, &transport_notify_ready,
756                                            h);
757   GNUNET_assert (NULL != h->cth);
758 }
759
760
761 /**
762  * Schedule the task to send one message, either from the control
763  * list or the peer message queues  to the service.
764  *
765  * @param h transport service to schedule a transmission for
766  */
767 static void
768 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
769 {
770   struct GNUNET_TIME_Relative delay;
771   struct Neighbour *n;
772
773   GNUNET_assert (NULL != h->client);
774   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
775   {
776     GNUNET_SCHEDULER_cancel (h->quota_task);
777     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
778   }
779   if (NULL != h->control_head)
780     delay = GNUNET_TIME_UNIT_ZERO;
781   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
782     delay =
783         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
784                                             n->th->notify_size);
785   else
786     return;                     /* no work to be done */
787   LOG (GNUNET_ERROR_TYPE_DEBUG,
788        "Scheduling next transmission to service in %llu ms\n",
789        (unsigned long long) delay.rel_value);
790   h->quota_task =
791       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
792 }
793
794
795 /**
796  * Queue control request for transmission to the transport
797  * service.
798  *
799  * @param h handle to the transport service
800  * @param size number of bytes to be transmitted
801  * @param notify function to call to get the content
802  * @param notify_cls closure for notify
803  */
804 static void
805 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
806                            GNUNET_CONNECTION_TransmitReadyNotify notify,
807                            void *notify_cls)
808 {
809   struct GNUNET_TRANSPORT_TransmitHandle *th;
810
811   LOG (GNUNET_ERROR_TYPE_DEBUG, "Control transmit of %u bytes requested\n",
812        size);
813   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
814   th->notify = notify;
815   th->notify_cls = notify_cls;
816   th->notify_size = size;
817   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
818   schedule_transmission (h);
819 }
820
821
822 /**
823  * Transmit START message to service.
824  *
825  * @param cls unused
826  * @param size number of bytes available in buf
827  * @param buf where to copy the message
828  * @return number of bytes copied to buf
829  */
830 static size_t
831 send_start (void *cls, size_t size, void *buf)
832 {
833   struct GNUNET_TRANSPORT_Handle *h = cls;
834   struct StartMessage s;
835   uint32_t options;
836
837   if (buf == NULL)
838   {
839     /* Can only be shutdown, just give up */
840     LOG (GNUNET_ERROR_TYPE_DEBUG,
841          "Shutdown while trying to transmit `%s' request.\n", "START");
842     return 0;
843   }
844   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "START");
845   GNUNET_assert (size >= sizeof (struct StartMessage));
846   s.header.size = htons (sizeof (struct StartMessage));
847   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
848   options = 0;
849   if (h->check_self)
850     options |= 1;
851   if (h->rec != NULL)
852     options |= 2;
853   s.options = htonl (options);
854   s.self = h->self;
855   memcpy (buf, &s, sizeof (struct StartMessage));
856   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
857                          GNUNET_TIME_UNIT_FOREVER_REL);
858   return sizeof (struct StartMessage);
859 }
860
861
862 /**
863  * Try again to connect to transport service.
864  *
865  * @param cls the handle to the transport service
866  * @param tc scheduler context
867  */
868 static void
869 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
870 {
871   struct GNUNET_TRANSPORT_Handle *h = cls;
872
873   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
874   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
875   {
876     /* shutdown, just give up */
877     return;
878   }
879   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to transport service.\n");
880   GNUNET_assert (h->client == NULL);
881   GNUNET_assert (h->control_head == NULL);
882   GNUNET_assert (h->control_tail == NULL);
883   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
884   GNUNET_assert (h->client != NULL);
885   schedule_control_transmit (h, sizeof (struct StartMessage), &send_start, h);
886 }
887
888
889 /**
890  * Function that will schedule the job that will try
891  * to connect us again to the client.
892  *
893  * @param h transport service to reconnect
894  */
895 static void
896 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
897 {
898   struct GNUNET_TRANSPORT_TransmitHandle *th;
899
900   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
901   if (NULL != h->cth)
902   {
903     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
904     h->cth = NULL;
905   }
906   if (NULL != h->client)
907   {
908     GNUNET_CLIENT_disconnect (h->client);
909     h->client = NULL;
910   }
911   /* Forget about all neighbours that we used to be connected to */
912   GNUNET_CONTAINER_multihashmap_iterate (h->neighbours, &neighbour_delete, h);
913   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
914   {
915     GNUNET_SCHEDULER_cancel (h->quota_task);
916     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
917   }
918   while ((NULL != (th = h->control_head)))
919   {
920     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
921     th->notify (th->notify_cls, 0, NULL);
922     GNUNET_free (th);
923   }
924   LOG (GNUNET_ERROR_TYPE_DEBUG,
925        "Scheduling task to reconnect to transport service in %llu ms.\n",
926        h->reconnect_delay.rel_value);
927   h->reconnect_task =
928       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
929   if (h->reconnect_delay.rel_value == 0)
930   {
931     h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
932   }
933   else
934   {
935     h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
936     h->reconnect_delay =
937         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS, h->reconnect_delay);
938   }
939 }
940
941
942 /**
943  * Send REQUEST_CONNECT message to the service.
944  *
945  * @param cls the 'struct GNUNET_PeerIdentity'
946  * @param size number of bytes available in buf
947  * @param buf where to copy the message
948  * @return number of bytes copied to buf
949  */
950 static size_t
951 send_try_connect (void *cls, size_t size, void *buf)
952 {
953   struct GNUNET_PeerIdentity *pid = cls;
954   struct TransportRequestConnectMessage msg;
955
956   if (buf == NULL)
957   {
958     GNUNET_free (pid);
959     return 0;
960   }
961   LOG (GNUNET_ERROR_TYPE_DEBUG,
962        "Transmitting `%s' request with respect to `%4s'.\n", "REQUEST_CONNECT",
963        GNUNET_i2s (pid));
964   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
965   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
966   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
967   msg.reserved = htonl (0);
968   msg.peer = *pid;
969   memcpy (buf, &msg, sizeof (msg));
970   GNUNET_free (pid);
971   return sizeof (struct TransportRequestConnectMessage);
972 }
973
974
975 /**
976  * Ask the transport service to establish a connection to
977  * the given peer.
978  *
979  * @param handle connection to transport service
980  * @param target who we should try to connect to
981  */
982 void
983 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
984                               const struct GNUNET_PeerIdentity *target)
985 {
986   struct GNUNET_PeerIdentity *pid;
987
988   if (NULL == handle->client)
989     return;
990   pid = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
991   *pid = *target;
992   schedule_control_transmit (handle,
993                              sizeof (struct TransportRequestConnectMessage),
994                              &send_try_connect, pid);
995 }
996
997
998 /**
999  * Send HELLO message to the service.
1000  *
1001  * @param cls the HELLO message to send
1002  * @param size number of bytes available in buf
1003  * @param buf where to copy the message
1004  * @return number of bytes copied to buf
1005  */
1006 static size_t
1007 send_hello (void *cls, size_t size, void *buf)
1008 {
1009   struct GNUNET_MessageHeader *msg = cls;
1010   uint16_t ssize;
1011
1012   if (buf == NULL)
1013   {
1014     LOG (GNUNET_ERROR_TYPE_DEBUG,
1015          "Timeout while trying to transmit `%s' request.\n", "HELLO");
1016     GNUNET_free (msg);
1017     return 0;
1018   }
1019   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "HELLO");
1020   ssize = ntohs (msg->size);
1021   GNUNET_assert (size >= ssize);
1022   memcpy (buf, msg, ssize);
1023   GNUNET_free (msg);
1024   return ssize;
1025 }
1026
1027
1028 /**
1029  * Offer the transport service the HELLO of another peer.  Note that
1030  * the transport service may just ignore this message if the HELLO is
1031  * malformed or useless due to our local configuration.
1032  *
1033  * @param handle connection to transport service
1034  * @param hello the hello message
1035  * @param cont continuation to call when HELLO has been sent
1036  * @param cls closure for continuation
1037  *
1038  */
1039 void
1040 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1041                               const struct GNUNET_MessageHeader *hello,
1042                               GNUNET_SCHEDULER_Task cont, void *cls)
1043 {
1044   uint16_t size;
1045   struct GNUNET_PeerIdentity peer;
1046   struct GNUNET_MessageHeader *msg;
1047
1048   if (NULL == handle->client)
1049     return;
1050   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1051   size = ntohs (hello->size);
1052   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1053   if (GNUNET_OK !=
1054       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1055   {
1056     GNUNET_break (0);
1057     return;
1058   }
1059   msg = GNUNET_malloc (size);
1060   memcpy (msg, hello, size);
1061   LOG (GNUNET_ERROR_TYPE_DEBUG,
1062        "Offering `%s' message of `%4s' to transport for validation.\n", "HELLO",
1063        GNUNET_i2s (&peer));
1064   schedule_control_transmit (handle, size, &send_hello, msg);
1065 }
1066
1067
1068 /**
1069  * Obtain the HELLO message for this peer.
1070  *
1071  * @param handle connection to transport service
1072  * @param rec function to call with the HELLO, sender will be our peer
1073  *            identity; message and sender will be NULL on timeout
1074  *            (handshake with transport service pending/failed).
1075  *             cost estimate will be 0.
1076  * @param rec_cls closure for rec
1077  * @return handle to cancel the operation
1078  */
1079 struct GNUNET_TRANSPORT_GetHelloHandle *
1080 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1081                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1082                             void *rec_cls)
1083 {
1084   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1085
1086   hwl = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_GetHelloHandle));
1087   hwl->rec = rec;
1088   hwl->rec_cls = rec_cls;
1089   hwl->handle = handle;
1090   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1091   if (handle->my_hello != NULL)
1092     rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
1093   return hwl;
1094 }
1095
1096
1097 /**
1098  * Stop receiving updates about changes to our HELLO message.
1099  *
1100  * @param ghh handle to cancel
1101  */
1102 void
1103 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1104 {
1105   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1106
1107   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1108   GNUNET_free (ghh);
1109 }
1110
1111
1112 /**
1113  * Connect to the transport service.  Note that the connection may
1114  * complete (or fail) asynchronously.
1115  *
1116  * @param cfg configuration to use
1117  * @param self our own identity (API should check that it matches
1118  *             the identity found by transport), or NULL (no check)
1119  * @param cls closure for the callbacks
1120  * @param rec receive function to call
1121  * @param nc function to call on connect events
1122  * @param nd function to call on disconnect events
1123  */
1124 struct GNUNET_TRANSPORT_Handle *
1125 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1126                           const struct GNUNET_PeerIdentity *self, void *cls,
1127                           GNUNET_TRANSPORT_ReceiveCallback rec,
1128                           GNUNET_TRANSPORT_NotifyConnect nc,
1129                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1130 {
1131   struct GNUNET_TRANSPORT_Handle *ret;
1132
1133   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1134   if (self != NULL)
1135   {
1136     ret->self = *self;
1137     ret->check_self = GNUNET_YES;
1138   }
1139   ret->cfg = cfg;
1140   ret->cls = cls;
1141   ret->rec = rec;
1142   ret->nc_cb = nc;
1143   ret->nd_cb = nd;
1144   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1145   ret->neighbours =
1146       GNUNET_CONTAINER_multihashmap_create (STARTING_NEIGHBOURS_SIZE);
1147   ret->ready_heap =
1148       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1149   ret->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, ret);
1150   return ret;
1151 }
1152
1153
1154 /**
1155  * Disconnect from the transport service.
1156  *
1157  * @param handle handle to the service as returned from GNUNET_TRANSPORT_connect
1158  */
1159 void
1160 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1161 {
1162   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1163   /* this disconnects all neighbours... */
1164   if (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1165     disconnect_and_schedule_reconnect (handle);
1166   /* and now we stop trying to connect again... */
1167   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1168   {
1169     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1170     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1171   }
1172   GNUNET_CONTAINER_multihashmap_destroy (handle->neighbours);
1173   handle->neighbours = NULL;
1174   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1175   {
1176     GNUNET_SCHEDULER_cancel (handle->quota_task);
1177     handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1178   }
1179   GNUNET_free_non_null (handle->my_hello);
1180   handle->my_hello = NULL;
1181   GNUNET_assert (handle->hwl_head == NULL);
1182   GNUNET_assert (handle->hwl_tail == NULL);
1183   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1184   handle->ready_heap = NULL;
1185   GNUNET_free (handle);
1186 }
1187
1188
1189 /**
1190  * Check if we could queue a message of the given size for
1191  * transmission.  The transport service will take both its
1192  * internal buffers and bandwidth limits imposed by the
1193  * other peer into consideration when answering this query.
1194  *
1195  * @param handle connection to transport service
1196  * @param target who should receive the message
1197  * @param size how big is the message we want to transmit?
1198  * @param priority how important is the message?
1199  * @param timeout after how long should we give up (and call
1200  *        notify with buf NULL and size 0)?
1201  * @param notify function to call when we are ready to
1202  *        send such a message
1203  * @param notify_cls closure for notify
1204  * @return NULL if someone else is already waiting to be notified
1205  *         non-NULL if the notify callback was queued (can be used to cancel
1206  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1207  */
1208 struct GNUNET_TRANSPORT_TransmitHandle *
1209 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1210                                         const struct GNUNET_PeerIdentity
1211                                         *target, size_t size, uint32_t priority,
1212                                         struct GNUNET_TIME_Relative timeout,
1213                                         GNUNET_CONNECTION_TransmitReadyNotify
1214                                         notify, void *notify_cls)
1215 {
1216   struct Neighbour *n;
1217   struct GNUNET_TRANSPORT_TransmitHandle *th;
1218   struct GNUNET_TIME_Relative delay;
1219
1220   n = neighbour_find (handle, target);
1221   if (NULL == n)
1222   {
1223     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1224      * once a connection has been established */
1225     GNUNET_assert (0);
1226     return NULL;
1227   }
1228   if (NULL != n->th)
1229   {
1230     /* attempt to send two messages at the same time to the same peer */
1231     GNUNET_assert (0);
1232     return NULL;
1233   }
1234   GNUNET_assert (NULL == n->hn);
1235   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
1236   th->neighbour = n;
1237   th->notify = notify;
1238   th->notify_cls = notify_cls;
1239   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1240   th->notify_size = size;
1241   th->priority = priority;
1242   n->th = th;
1243   /* calculate when our transmission should be ready */
1244   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size);
1245   if (delay.rel_value > timeout.rel_value)
1246     delay.rel_value = 0;        /* notify immediately (with failure) */
1247   LOG (GNUNET_ERROR_TYPE_DEBUG,
1248        "Bandwidth tracker allows next transmission to peer %s in %llu ms\n",
1249        GNUNET_i2s (target), (unsigned long long) delay.rel_value);
1250   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value);
1251   schedule_transmission (handle);
1252   return th;
1253 }
1254
1255
1256 /**
1257  * Cancel the specified transmission-ready notification.
1258  *
1259  * @param th handle returned from GNUNET_TRANSPORT_notify_transmit_ready
1260  */
1261 void
1262 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1263                                                GNUNET_TRANSPORT_TransmitHandle
1264                                                *th)
1265 {
1266   struct Neighbour *n;
1267
1268   GNUNET_assert (NULL == th->next);
1269   GNUNET_assert (NULL == th->prev);
1270   n = th->neighbour;
1271   GNUNET_assert (th == n->th);
1272   n->th = NULL;
1273   if (n->hn != NULL)
1274   {
1275     GNUNET_CONTAINER_heap_remove_node (n->hn);
1276     n->hn = NULL;
1277   }
1278   else
1279   {
1280     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != th->timeout_task);
1281     GNUNET_SCHEDULER_cancel (th->timeout_task);
1282     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1283   }
1284   GNUNET_free (th);
1285 }
1286
1287
1288 /* end of transport_api.c */