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