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