hxing
[oweals/gnunet.git] / src / core / core_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 core/core_api.c
23  * @brief core service; this is the main API for encrypted P2P
24  *        communications
25  * @author Christian Grothoff
26  *
27  * TODO:
28  * - implement atsi parsing and passing
29  */
30 #include "platform.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_core_service.h"
33 #include "core.h"
34
35
36 /**
37  * Information we track for each peer.
38  */
39 struct PeerRecord
40 {
41
42   /**
43    * We generally do NOT keep peer records in a DLL; this
44    * DLL is only used IF this peer's 'pending_head' message
45    * is ready for transmission.  
46    */
47   struct PeerRecord *prev;
48
49   /**
50    * We generally do NOT keep peer records in a DLL; this
51    * DLL is only used IF this peer's 'pending_head' message
52    * is ready for transmission. 
53    */
54   struct PeerRecord *next;
55
56   /**
57    * Peer the record is about.
58    */
59   struct GNUNET_PeerIdentity peer;
60
61   /**
62    * Corresponding core handle.
63    */
64   struct GNUNET_CORE_Handle *ch;
65
66   /**
67    * Head of doubly-linked list of pending requests.
68    * Requests are sorted by deadline *except* for HEAD,
69    * which is only modified upon transmission to core.
70    */
71   struct GNUNET_CORE_TransmitHandle *pending_head;
72
73   /**
74    * Tail of doubly-linked list of pending requests.
75    */
76   struct GNUNET_CORE_TransmitHandle *pending_tail;
77
78   /**
79    * Pending callback waiting for peer information, or NULL for none.
80    */
81   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
82
83   /**
84    * Closure for pcic.
85    */
86   void *pcic_cls;
87
88   /**
89    * Request information ID for the given pcic (needed in case a
90    * request is cancelled after being submitted to core and a new
91    * one is generated; in this case, we need to avoid matching the
92    * reply to the first (cancelled) request to the second request).
93    */
94   uint32_t rim_id;
95
96   /**
97    * ID of timeout task for the 'pending_head' handle
98    * which is the one with the smallest timeout. 
99    */
100   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
101
102   /**
103    * Current size of the queue of pending requests.
104    */
105   unsigned int queue_size;
106
107   /**
108    * SendMessageRequest ID generator for this peer.
109    */
110   uint16_t smr_id_gen;
111   
112 };
113
114
115 /**
116  * Entry in a doubly-linked list of control messages to be transmitted
117  * to the core service.  Control messages include traffic allocation,
118  * connection requests and of course our initial 'init' request.
119  * 
120  * The actual message is allocated at the end of this struct.
121  */
122 struct ControlMessage
123 {
124   /**
125    * This is a doubly-linked list.
126    */
127   struct ControlMessage *next;
128
129   /**
130    * This is a doubly-linked list.
131    */
132   struct ControlMessage *prev;
133
134   /**
135    * Function to run after successful transmission (or call with
136    * reason 'TIMEOUT' on error).
137    */
138   GNUNET_SCHEDULER_Task cont;
139
140   /**
141    * Closure for 'cont'.
142    */
143   void *cont_cls;
144
145 };
146
147
148
149 /**
150  * Context for the core service connection.
151  */
152 struct GNUNET_CORE_Handle
153 {
154
155   /**
156    * Configuration we're using.
157    */
158   const struct GNUNET_CONFIGURATION_Handle *cfg;
159
160   /**
161    * Closure for the various callbacks.
162    */
163   void *cls;
164
165   /**
166    * Function to call once we've handshaked with the core service.
167    */
168   GNUNET_CORE_StartupCallback init;
169
170   /**
171    * Function to call whenever we're notified about a peer connecting.
172    */
173   GNUNET_CORE_ConnectEventHandler connects;
174
175   /**
176    * Function to call whenever we're notified about a peer disconnecting.
177    */
178   GNUNET_CORE_DisconnectEventHandler disconnects;
179
180   /**
181    * Function to call whenever we're notified about a peer changing status.
182    */  
183   GNUNET_CORE_PeerStatusEventHandler status_events;
184   
185   /**
186    * Function to call whenever we receive an inbound message.
187    */
188   GNUNET_CORE_MessageCallback inbound_notify;
189
190   /**
191    * Function to call whenever we receive an outbound message.
192    */
193   GNUNET_CORE_MessageCallback outbound_notify;
194
195   /**
196    * Function handlers for messages of particular type.
197    */
198   const struct GNUNET_CORE_MessageHandler *handlers;
199
200   /**
201    * Our connection to the service.
202    */
203   struct GNUNET_CLIENT_Connection *client;
204
205   /**
206    * Handle for our current transmission request.
207    */
208   struct GNUNET_CLIENT_TransmitHandle *cth;
209
210   /**
211    * Head of doubly-linked list of pending requests.
212    */
213   struct ControlMessage *pending_head;
214
215   /**
216    * Tail of doubly-linked list of pending requests.
217    */
218   struct ControlMessage *pending_tail;
219
220   /**
221    * Head of doubly-linked list of peers that are core-approved
222    * to send their next message.
223    */
224   struct PeerRecord *ready_peer_head;
225
226   /**
227    * Tail of doubly-linked list of peers that are core-approved
228    * to send their next message.
229    */
230   struct PeerRecord *ready_peer_tail;
231
232   /**
233    * Hash map listing all of the peers that we are currently
234    * connected to.
235    */
236   struct GNUNET_CONTAINER_MultiHashMap *peers;
237
238   /**
239    * ID of reconnect task (if any).
240    */
241   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
242
243   /**
244    * Current delay we use for re-trying to connect to core.
245    */
246   struct GNUNET_TIME_Relative retry_backoff;
247
248   /**
249    * Request information ID generator.
250    */
251   uint32_t rim_id_gen;
252
253   /**
254    * Number of messages we are allowed to queue per target.
255    */
256   unsigned int queue_size;
257
258   /**
259    * Number of entries in the handlers array.
260    */
261   unsigned int hcnt;
262
263   /**
264    * For inbound notifications without a specific handler, do
265    * we expect to only receive headers?
266    */
267   int inbound_hdr_only;
268
269   /**
270    * For outbound notifications without a specific handler, do
271    * we expect to only receive headers?
272    */
273   int outbound_hdr_only;
274
275   /**
276    * Are we currently disconnected and hence unable to forward
277    * requests?
278    */
279   int currently_down;
280
281 };
282
283
284 /**
285  * Handle for a transmission request.
286  */
287 struct GNUNET_CORE_TransmitHandle
288 {
289
290   /**
291    * We keep active transmit handles in a doubly-linked list.
292    */
293   struct GNUNET_CORE_TransmitHandle *next;
294
295   /**
296    * We keep active transmit handles in a doubly-linked list.
297    */
298   struct GNUNET_CORE_TransmitHandle *prev;
299
300   /**
301    * Corresponding peer record.
302    */
303   struct PeerRecord *peer;
304
305   /**
306    * Corresponding SEND_REQUEST message.  Only non-NULL 
307    * while SEND_REQUEST message is pending.
308    */
309   struct ControlMessage *cm;
310
311   /**
312    * Function that will be called to get the actual request
313    * (once we are ready to transmit this request to the core).
314    * The function will be called with a NULL buffer to signal
315    * timeout.
316    */
317   GNUNET_CONNECTION_TransmitReadyNotify get_message;
318
319   /**
320    * Closure for get_message.
321    */
322   void *get_message_cls;
323
324   /**
325    * Timeout for this handle.
326    */
327   struct GNUNET_TIME_Absolute timeout;
328
329   /**
330    * How important is this message?
331    */
332   uint32_t priority;
333
334   /**
335    * Size of this request.
336    */
337   uint16_t msize;
338
339   /**
340    * Send message request ID for this request.
341    */
342   uint16_t smr_id;
343
344 };
345
346
347 /**
348  * Our current client connection went down.  Clean it up
349  * and try to reconnect!
350  *
351  * @param h our handle to the core service
352  */
353 static void
354 reconnect (struct GNUNET_CORE_Handle *h);
355
356
357 /**
358  * Task schedule to try to re-connect to core.
359  *
360  * @param cls the 'struct GNUNET_CORE_Handle'
361  * @param tc task context
362  */
363 static void
364 reconnect_task (void *cls, 
365                 const struct GNUNET_SCHEDULER_TaskContext *tc)
366 {
367   struct GNUNET_CORE_Handle *h = cls;
368
369   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
370 #if DEBUG_CORE
371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
372               "Connecting to CORE service after delay\n");
373 #endif
374   reconnect (h);
375 }
376
377
378 /**
379  * Notify clients about disconnect and free 
380  * the entry for connected peer.
381  *
382  * @param cls the 'struct GNUNET_CORE_Handle*'
383  * @param key the peer identity (not used)
384  * @param value the 'struct PeerRecord' to free.
385  * @return GNUNET_YES (continue)
386  */
387 static int
388 disconnect_and_free_peer_entry (void *cls,
389                                 const GNUNET_HashCode *key,
390                                 void *value)
391 {
392   static struct GNUNET_BANDWIDTH_Value32NBO zero;
393   struct GNUNET_CORE_Handle *h = cls;
394   struct GNUNET_CORE_TransmitHandle *th;
395   struct PeerRecord *pr = value;
396   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
397
398   while (NULL != (th = pr->pending_head))
399     {
400       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
401                                    pr->pending_tail,
402                                    th);
403       pr->queue_size--;
404       GNUNET_assert (0 == 
405                      th->get_message (th->get_message_cls,
406                                       0, NULL));
407       GNUNET_free (th);
408     }
409   if (NULL != (pcic = pr->pcic))
410     {
411       pr->pcic = NULL;
412       pcic (pr->pcic_cls,
413             &pr->peer,
414             zero,
415             0, 0);
416     }
417   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
418     {
419       GNUNET_SCHEDULER_cancel (pr->timeout_task);
420       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
421     }
422   GNUNET_assert (pr->queue_size == 0);
423   if ( (pr->prev != NULL) ||
424        (pr->next != NULL) ||
425        (h->ready_peer_head == pr) )
426     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
427                                  h->ready_peer_tail,
428                                  pr);
429   if (h->disconnects != NULL)
430     h->disconnects (h->cls,
431                     &pr->peer);    
432   GNUNET_assert (GNUNET_YES ==
433                  GNUNET_CONTAINER_multihashmap_remove (h->peers,
434                                                        key,
435                                                        pr));
436   GNUNET_assert (pr->pending_head == NULL);
437   GNUNET_assert (pr->pending_tail == NULL);
438   GNUNET_assert (pr->ch = h);
439   GNUNET_assert (pr->queue_size == 0);
440   GNUNET_assert (pr->timeout_task == GNUNET_SCHEDULER_NO_TASK);
441   GNUNET_free (pr);  
442   return GNUNET_YES;
443 }
444
445
446 /**
447  * Close down any existing connection to the CORE service and
448  * try re-establishing it later.
449  *
450  * @param h our handle
451  */
452 static void
453 reconnect_later (struct GNUNET_CORE_Handle *h)
454 {
455   if (h->client != NULL)
456     {
457       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
458       h->client = NULL;
459       GNUNET_CONTAINER_multihashmap_iterate (h->peers,
460                                              &disconnect_and_free_peer_entry,
461                                              h);
462     }
463   h->currently_down = GNUNET_YES;
464   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
465   h->retry_backoff = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
466                                                h->retry_backoff);
467   h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->retry_backoff,
468                                                     &reconnect_task,
469                                                     h);
470   h->retry_backoff = GNUNET_TIME_relative_multiply (h->retry_backoff, 2);
471 }
472
473
474 /**
475  * Check the list of pending requests, send the next
476  * one to the core.
477  *
478  * @param h core handle
479  * @param ignore_currently_down transmit message even if not initialized?
480  */
481 static void
482 trigger_next_request (struct GNUNET_CORE_Handle *h,
483                       int ignore_currently_down);
484
485
486 /**
487  * The given request hit its timeout.  Remove from the
488  * doubly-linked list and call the respective continuation.
489  *
490  * @param cls the transmit handle of the request that timed out
491  * @param tc context, can be NULL (!)
492  */
493 static void
494 transmission_timeout (void *cls, 
495                       const struct GNUNET_SCHEDULER_TaskContext *tc);
496
497
498 /**
499  * Control message was sent, mark it as such.
500  *
501  * @param cls the 'struct GNUNET_CORE_TransmitHandle*'
502  * @param tc scheduler context
503  */
504 static void
505 mark_control_message_sent (void *cls,
506                            const struct GNUNET_SCHEDULER_TaskContext *tc)
507 {
508   struct GNUNET_CORE_TransmitHandle *th = cls;
509
510   th->cm = NULL;
511 }
512
513
514 /**
515  * Send a control message to the peer asking for transmission
516  * of the message in the given peer record.
517  *
518  * @param pr peer to request transmission to
519  */
520 static void
521 request_next_transmission (struct PeerRecord *pr)
522 {
523   struct GNUNET_CORE_Handle *h = pr->ch;
524   struct ControlMessage *cm;
525   struct SendMessageRequest *smr;
526   struct GNUNET_CORE_TransmitHandle *th;
527
528   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
529     {
530       GNUNET_SCHEDULER_cancel (pr->timeout_task);
531       pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
532     }
533   if (NULL == (th = pr->pending_head))
534     {
535       trigger_next_request (h, GNUNET_NO);
536       return;
537     }
538   GNUNET_assert (pr->prev == NULL);
539   GNUNET_assert (pr->next == NULL);
540   pr->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (th->timeout),
541                                                    &transmission_timeout,
542                                                    pr);
543   cm = GNUNET_malloc (sizeof (struct ControlMessage) + 
544                       sizeof (struct SendMessageRequest));
545   cm->cont = &mark_control_message_sent;
546   cm->cont_cls = th;
547   th->cm = cm;
548   smr = (struct SendMessageRequest*) &cm[1];
549   smr->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST);
550   smr->header.size = htons (sizeof (struct SendMessageRequest));
551   smr->priority = htonl (th->priority);
552   smr->deadline = GNUNET_TIME_absolute_hton (th->timeout);
553   smr->peer = pr->peer;
554   smr->queue_size = htonl (pr->queue_size);
555   smr->size = htons (th->msize);
556   smr->smr_id = htons (th->smr_id = pr->smr_id_gen++);
557   GNUNET_CONTAINER_DLL_insert_after (h->pending_head,
558                                      h->pending_tail,
559                                      h->pending_tail,
560                                      cm);
561   trigger_next_request (h, GNUNET_NO);
562 }
563
564
565 /**
566  * The given request hit its timeout.  Remove from the
567  * doubly-linked list and call the respective continuation.
568  *
569  * @param cls the transmit handle of the request that timed out
570  * @param tc context, can be NULL (!)
571  */
572 static void
573 transmission_timeout (void *cls, 
574                       const struct GNUNET_SCHEDULER_TaskContext *tc)
575 {
576   struct PeerRecord *pr = cls;
577   struct GNUNET_CORE_TransmitHandle *th;
578
579   pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
580   th = pr->pending_head;
581   GNUNET_CONTAINER_DLL_remove (pr->pending_head,
582                                pr->pending_tail,
583                                th);
584   pr->queue_size--;
585 #if DEBUG_CORE
586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
587               "Signalling timeout of request for transmission to CORE service\n");
588 #endif
589   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
590   request_next_transmission (pr);
591 }
592
593
594 /**
595  * Transmit the next message to the core service.
596  */
597 static size_t
598 transmit_message (void *cls,
599                   size_t size, 
600                   void *buf)
601 {
602   struct GNUNET_CORE_Handle *h = cls;
603   struct ControlMessage *cm;
604   struct GNUNET_CORE_TransmitHandle *th;
605   struct PeerRecord *pr;
606   struct SendMessage *sm;
607   const struct GNUNET_MessageHeader *hdr;
608   uint16_t msize;
609   size_t ret;
610
611   h->cth = NULL;
612   if (buf == NULL)
613     {
614 #if DEBUG_CORE
615       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
616                   "Transmission failed, initiating reconnect\n");
617 #endif
618       reconnect_later (h);
619       return 0;
620     }
621   /* first check for control messages */
622   if (NULL != (cm = h->pending_head))
623     {
624       hdr = (const struct GNUNET_MessageHeader*) &cm[1];
625       msize = ntohs (hdr->size);
626       if (size < msize)
627         {
628           trigger_next_request (h, GNUNET_NO);
629           return 0;
630         }
631 #if DEBUG_CORE
632       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
633                   "Transmitting control message with %u bytes of type %u to core.\n",
634                   (unsigned int) msize,
635                   (unsigned int) ntohs (hdr->type));
636 #endif
637       memcpy (buf, hdr, msize);
638       GNUNET_CONTAINER_DLL_remove (h->pending_head,
639                                    h->pending_tail,
640                                    cm);
641       if (NULL != cm->cont)
642         GNUNET_SCHEDULER_add_continuation (cm->cont, 
643                                            cm->cont_cls,
644                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
645       GNUNET_free (cm);
646       trigger_next_request (h, GNUNET_NO);
647       return msize;
648     }
649   /* now check for 'ready' P2P messages */
650   if (NULL != (pr = h->ready_peer_head))
651     {
652       th = pr->pending_head;
653       if (size < th->msize + sizeof (struct SendMessage))
654         {
655           trigger_next_request (h, GNUNET_NO);
656           return 0;
657         }
658       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
659                                    h->ready_peer_tail,
660                                    pr);
661       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
662                                    pr->pending_tail,
663                                    th);
664       pr->queue_size--;
665       if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
666         {
667           GNUNET_SCHEDULER_cancel (pr->timeout_task);
668           pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
669         }
670 #if DEBUG_CORE
671       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
672                   "Transmitting SEND request to `%s' with %u bytes.\n",
673                   GNUNET_i2s (&pr->peer),
674                   (unsigned int) th->msize);
675 #endif
676       sm = (struct SendMessage *) buf;
677       sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
678       sm->priority = htonl (th->priority);
679       sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
680       sm->peer = pr->peer;
681       ret = th->get_message (th->get_message_cls,
682                              size - sizeof (struct SendMessage),
683                              &sm[1]);
684
685       if (0 == ret)
686         {
687 #if DEBUG_CORE
688           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689                       "Size of clients message to peer %s is 0!\n",
690                       GNUNET_i2s(&pr->peer));
691 #endif
692           /* client decided to send nothing! */
693           request_next_transmission (pr);
694           return 0;       
695         }
696 #if DEBUG_CORE
697       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
698                   "Produced SEND message to core with %u bytes payload\n",
699                   (unsigned int) ret);
700 #endif
701       GNUNET_assert (ret >= sizeof (struct GNUNET_MessageHeader));
702       if (ret + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
703         {
704           GNUNET_break (0);
705           request_next_transmission (pr);
706           return 0;
707         }
708       ret += sizeof (struct SendMessage);
709       sm->header.size = htons (ret);
710       GNUNET_assert (ret <= size);
711       GNUNET_free (th);
712       request_next_transmission (pr);
713       return ret;
714     }
715   return 0;
716 }
717
718
719 /**
720  * Check the list of pending requests, send the next
721  * one to the core.
722  *
723  * @param h core handle
724  * @param ignore_currently_down transmit message even if not initialized?
725  */
726 static void
727 trigger_next_request (struct GNUNET_CORE_Handle *h,
728                       int ignore_currently_down)
729 {
730   uint16_t msize;
731
732   if ( (GNUNET_YES == h->currently_down) &&
733        (ignore_currently_down == GNUNET_NO) )
734     return;
735   if (NULL != h->cth)
736     return;
737   if (h->pending_head != NULL)
738     msize = ntohs (((struct GNUNET_MessageHeader*) &h->pending_head[1])->size);    
739   else if (h->ready_peer_head != NULL)
740     msize = h->ready_peer_head->pending_head->msize + sizeof (struct SendMessage);    
741   else
742     return; /* no pending message */
743   h->cth = GNUNET_CLIENT_notify_transmit_ready (h->client,
744                                                 msize,
745                                                 GNUNET_TIME_UNIT_FOREVER_REL,
746                                                 GNUNET_NO,
747                                                 &transmit_message, h);
748 }
749
750
751 /**
752  * Handler for notification messages received from the core.
753  *
754  * @param cls our "struct GNUNET_CORE_Handle"
755  * @param msg the message received from the core service
756  */
757 static void
758 main_notify_handler (void *cls, 
759                      const struct GNUNET_MessageHeader *msg)
760 {
761   struct GNUNET_CORE_Handle *h = cls;
762   const struct InitReplyMessage *m;
763   const struct ConnectNotifyMessage *cnm;
764   const struct DisconnectNotifyMessage *dnm;
765   const struct NotifyTrafficMessage *ntm;
766   const struct GNUNET_MessageHeader *em;
767   const struct ConfigurationInfoMessage *cim;
768   const struct PeerStatusNotifyMessage *psnm;
769   const struct SendMessageReady *smr;
770   const struct GNUNET_CORE_MessageHandler *mh;
771   GNUNET_CORE_StartupCallback init;
772   GNUNET_CORE_PeerConfigurationInfoCallback pcic;
773   struct GNUNET_PeerIdentity my_identity;
774   struct PeerRecord *pr;
775   struct GNUNET_CORE_TransmitHandle *th;
776   unsigned int hpos;
777   int trigger;
778   uint16_t msize;
779   uint16_t et;
780
781   if (msg == NULL)
782     {
783       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
784                   _
785                   ("Client was disconnected from core service, trying to reconnect.\n"));
786       reconnect_later (h);
787       return;
788     }
789   msize = ntohs (msg->size);
790 #if DEBUG_CORE
791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
792               "Processing message of type %u and size %u from core service\n",
793               ntohs (msg->type), msize);
794 #endif
795   switch (ntohs (msg->type))
796     {
797     case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
798       if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
799         {
800           GNUNET_break (0);
801           reconnect (h);
802           return;
803         }
804       m = (const struct InitReplyMessage *) msg;
805       GNUNET_break (0 == ntohl (m->reserved));
806       /* start our message processing loop */
807 #if DEBUG_CORE
808       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809                   "Successfully connected to core service, starting processing loop.\n");
810 #endif
811       if (GNUNET_YES == h->currently_down)
812         {
813           h->currently_down = GNUNET_NO;
814           trigger_next_request (h, GNUNET_NO);
815         }
816       h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
817       if (NULL != (init = h->init))
818         {
819           /* mark so we don't call init on reconnect */
820           h->init = NULL;
821           GNUNET_CRYPTO_hash (&m->publicKey,
822                               sizeof (struct
823                                       GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
824                               &my_identity.hashPubKey);
825           init (h->cls, h, &my_identity, &m->publicKey);
826         }
827       break;
828     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
829       if (msize != sizeof (struct ConnectNotifyMessage))
830         {
831           GNUNET_break (0);
832           break;
833         }
834       cnm = (const struct ConnectNotifyMessage *) msg;
835 #if DEBUG_CORE
836       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
837                   "Received notification about connection from `%s'.\n",
838                   GNUNET_i2s (&cnm->peer));
839 #endif
840       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
841                                               &cnm->peer.hashPubKey);
842       if (pr != NULL)
843         {
844           GNUNET_break (0);
845           reconnect (h);
846           return;
847         }
848       pr = GNUNET_malloc (sizeof (struct PeerRecord));
849       pr->peer = cnm->peer;
850       pr->ch = h;
851       GNUNET_assert (GNUNET_YES ==
852                      GNUNET_CONTAINER_multihashmap_put (h->peers,
853                                                         &cnm->peer.hashPubKey,
854                                                         pr,
855                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
856       if (NULL != h->connects)
857         h->connects (h->cls,
858                      &cnm->peer,
859                      NULL /* FIXME: atsi! */);
860       break;
861     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
862       if (msize != sizeof (struct DisconnectNotifyMessage))
863         {
864           GNUNET_break (0);
865           break;
866         }
867       dnm = (const struct DisconnectNotifyMessage *) msg;
868 #if DEBUG_CORE
869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870                   "Received notification about disconnect from `%s'.\n",
871                   GNUNET_i2s (&dnm->peer));
872 #endif
873       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
874                                               &dnm->peer.hashPubKey);
875       if (pr == NULL)
876         {
877           GNUNET_break (0);
878           reconnect (h);
879           return;
880         }
881       trigger = ( (pr->prev != NULL) ||
882                   (pr->next != NULL) ||
883                   (h->ready_peer_head == pr) );
884       disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
885       if (trigger)
886         trigger_next_request (h, GNUNET_NO);
887       break;
888     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE:
889       if (NULL == h->status_events)
890         {
891           GNUNET_break (0);
892           break;
893         }
894       if (msize != sizeof (struct PeerStatusNotifyMessage))
895         {
896           GNUNET_break (0);
897           break;
898         }
899       psnm = (const struct PeerStatusNotifyMessage *) msg;
900 #if DEBUG_CORE
901       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
902                   "Received notification about status change by `%s'.\n",
903                   GNUNET_i2s (&psnm->peer));
904 #endif
905       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
906                                               &psnm->peer.hashPubKey);
907       if (pr == NULL)
908         {
909           GNUNET_break (0);
910           reconnect (h);
911           return;
912         }
913       h->status_events (h->cls,
914                         &psnm->peer,
915                         psnm->bandwidth_in,
916                         psnm->bandwidth_out,
917                         GNUNET_TIME_absolute_ntoh (psnm->timeout),
918                         NULL /* FIXME: atsi */);
919       break;
920     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
921       if (msize <
922           sizeof (struct NotifyTrafficMessage) +
923           sizeof (struct GNUNET_MessageHeader))
924         {
925           GNUNET_break (0);
926           break;
927         }
928       ntm = (const struct NotifyTrafficMessage *) msg;
929       em = (const struct GNUNET_MessageHeader *) &ntm[1];
930 #if DEBUG_CORE
931       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932                   "Received message of type %u and size %u from peer `%4s'\n",
933                   ntohs (em->type), 
934                   ntohs (em->size),
935                   GNUNET_i2s (&ntm->peer));
936 #endif
937       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
938                                               &ntm->peer.hashPubKey);
939       if (pr == NULL)
940         {
941           GNUNET_break (0);
942           reconnect (h);
943           return;
944         }
945       if ((GNUNET_NO == h->inbound_hdr_only) &&
946           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
947         {
948           GNUNET_break (0);
949           break;
950         }
951       et = ntohs (em->type);
952       for (hpos = 0; hpos < h->hcnt; hpos++)
953         {
954           mh = &h->handlers[hpos];
955           if (mh->type != et)
956             continue;
957           if ((mh->expected_size != ntohs (em->size)) &&
958               (mh->expected_size != 0))
959             {
960               GNUNET_break (0);
961               continue;
962             }
963           if (GNUNET_OK !=
964               h->handlers[hpos].callback (h->cls, &ntm->peer, em,
965                                           NULL /* FIXME: atsi */))
966             {
967               /* error in processing, do not process other messages! */
968               break;
969             }
970         }
971       if (NULL != h->inbound_notify)
972         h->inbound_notify (h->cls, &ntm->peer, em,
973                            NULL /* FIXME: atsi */);
974       break;
975     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
976       if (msize <
977           sizeof (struct NotifyTrafficMessage) +
978           sizeof (struct GNUNET_MessageHeader))
979         {
980           GNUNET_break (0);
981           break;
982         }
983       ntm = (const struct NotifyTrafficMessage *) msg;
984       em = (const struct GNUNET_MessageHeader *) &ntm[1];
985       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
986                                               &ntm->peer.hashPubKey);
987       if (pr == NULL)
988         {
989           GNUNET_break (0);
990           reconnect (h);
991           return;
992         }
993 #if DEBUG_CORE
994       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995                   "Received notification about transmission to `%s'.\n",
996                   GNUNET_i2s (&ntm->peer));
997 #endif
998       if ((GNUNET_NO == h->outbound_hdr_only) &&
999           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
1000         {
1001           GNUNET_break (0);
1002           break;
1003         }
1004       if (NULL == h->outbound_notify)
1005         {
1006           GNUNET_break (0);
1007           break;
1008         }
1009       h->outbound_notify (h->cls, &ntm->peer, em,
1010                           NULL /* FIXME: atsi? */);
1011       break;
1012     case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1013       if (msize != sizeof (struct SendMessageReady))
1014         {
1015           GNUNET_break (0);
1016           break;
1017         }
1018       smr = (const struct SendMessageReady *) msg;
1019       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1020                                               &smr->peer.hashPubKey);
1021       if (pr == NULL)
1022         {
1023           GNUNET_break (0);
1024           reconnect (h);
1025           return;
1026         }
1027 #if DEBUG_CORE
1028       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1029                   "Received notification about transmission readiness to `%s'.\n",
1030                   GNUNET_i2s (&smr->peer));
1031 #endif
1032       th = pr->pending_head;
1033       if (ntohs (smr->smr_id) != th->smr_id)
1034         {
1035           /* READY message is for expired or cancelled message,
1036              ignore! (we should have already sent another request) */
1037           break;
1038         }
1039       if ( (pr->prev != NULL) ||
1040            (pr->next != NULL) ||
1041            (h->ready_peer_head == pr) )
1042         {
1043           /* we should not already be on the ready list... */
1044           GNUNET_break (0);
1045           reconnect (h);
1046           return;
1047         }
1048       GNUNET_CONTAINER_DLL_insert (h->ready_peer_head,
1049                                    h->ready_peer_tail,
1050                                    pr);
1051       trigger_next_request (h, GNUNET_NO);
1052       break;
1053     case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
1054       if (ntohs (msg->size) != sizeof (struct ConfigurationInfoMessage))
1055         {
1056           GNUNET_break (0);
1057           break;
1058         }
1059       cim = (const struct ConfigurationInfoMessage*) msg;
1060 #if DEBUG_CORE
1061       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1062                   "Received notification about configuration update for `%s'.\n",
1063                   GNUNET_i2s (&cim->peer));
1064 #endif
1065       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1066                                               &cim->peer.hashPubKey);
1067       if (pr == NULL)
1068         {
1069           GNUNET_break (0);
1070           reconnect (h);
1071           return;
1072         }
1073       if (pr->rim_id != ntohl (cim->rim_id))
1074         break;
1075       pcic = pr->pcic;
1076       pr->pcic = NULL;
1077       if (pcic != NULL)
1078         pcic (pr->pcic_cls,
1079               &pr->peer,
1080               cim->bw_out,
1081               ntohl (cim->reserved_amount),
1082               GNUNET_ntohll (cim->preference));
1083       break;
1084     default:
1085       GNUNET_break (0);
1086       break;
1087     }
1088   GNUNET_CLIENT_receive (h->client,
1089                          &main_notify_handler, h, 
1090                          GNUNET_TIME_UNIT_FOREVER_REL);
1091 }
1092
1093
1094 /**
1095  * Task executed once we are done transmitting the INIT message.
1096  * Starts our 'receive' loop.
1097  *
1098  * @param cls the 'struct GNUNET_CORE_Handle'
1099  * @param tc task context
1100  */
1101 static void
1102 init_done_task (void *cls, 
1103                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1104 {
1105   struct GNUNET_CORE_Handle *h = cls;
1106
1107   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_PREREQ_DONE))
1108     {
1109 #if DEBUG_CORE
1110       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1111                   "Failed to exchange INIT with core, retrying\n");
1112 #endif
1113       reconnect_later (h);
1114       return;
1115     }
1116   GNUNET_CLIENT_receive (h->client,
1117                          &main_notify_handler, 
1118                          h, 
1119                          GNUNET_TIME_UNIT_FOREVER_REL);
1120 }
1121
1122
1123 /**
1124  * Our current client connection went down.  Clean it up
1125  * and try to reconnect!
1126  *
1127  * @param h our handle to the core service
1128  */
1129 static void
1130 reconnect (struct GNUNET_CORE_Handle *h)
1131 {
1132   struct ControlMessage *cm;
1133   struct InitMessage *init;
1134   uint32_t opt;
1135   uint16_t msize;
1136   uint16_t *ts;
1137   unsigned int hpos;
1138
1139 #if DEBUG_CORE
1140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1141               "Reconnecting to CORE service\n");
1142 #endif
1143   if (h->client != NULL)
1144     {
1145       GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1146       h->client = NULL;
1147       GNUNET_CONTAINER_multihashmap_iterate (h->peers,
1148                                              &disconnect_and_free_peer_entry,
1149                                              h);
1150     }
1151   h->currently_down = GNUNET_YES;
1152   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1153   if (h->client == NULL)
1154     {
1155       reconnect_later (h);
1156       return;
1157     }
1158   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1159   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1160                       msize);
1161   cm->cont = &init_done_task;
1162   cm->cont_cls = h;
1163   init = (struct InitMessage*) &cm[1];
1164   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1165   init->header.size = htons (msize);
1166   opt = GNUNET_CORE_OPTION_SEND_CONNECT | GNUNET_CORE_OPTION_SEND_DISCONNECT;
1167   if (h->status_events != NULL)
1168     opt |= GNUNET_CORE_OPTION_SEND_STATUS_CHANGE;
1169   if (h->inbound_notify != NULL)
1170     {
1171       if (h->inbound_hdr_only)
1172         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1173       else
1174         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1175     }
1176   if (h->outbound_notify != NULL)
1177     {
1178       if (h->outbound_hdr_only)
1179         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1180       else
1181         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1182     }
1183   init->options = htonl (opt);
1184   ts = (uint16_t *) &init[1];
1185   for (hpos = 0; hpos < h->hcnt; hpos++)
1186     ts[hpos] = htons (h->handlers[hpos].type);
1187   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1188                                h->pending_tail,
1189                                cm);
1190   trigger_next_request (h, GNUNET_YES);
1191 }
1192
1193
1194
1195 /**
1196  * Connect to the core service.  Note that the connection may
1197  * complete (or fail) asynchronously.
1198  *
1199  * @param cfg configuration to use
1200  * @param queue_size size of the per-peer message queue
1201  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1202  * @param init callback to call on timeout or once we have successfully
1203  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1204  * @param connects function to call on peer connect, can be NULL
1205  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1206  * @param status_events function to call on changes to peer connection status, can be NULL
1207  * @param inbound_notify function to call for all inbound messages, can be NULL
1208  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1209  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1210  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1211  * @param outbound_notify function to call for all outbound messages, can be NULL
1212  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1213  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1214  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1215  * @param handlers callbacks for messages we care about, NULL-terminated
1216  * @return handle to the core service (only useful for disconnect until 'init' is called);
1217  *                NULL on error (in this case, init is never called)
1218  */
1219 struct GNUNET_CORE_Handle *
1220 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1221                      unsigned int queue_size,
1222                      void *cls,
1223                      GNUNET_CORE_StartupCallback init,
1224                      GNUNET_CORE_ConnectEventHandler connects,
1225                      GNUNET_CORE_DisconnectEventHandler disconnects,
1226                      GNUNET_CORE_PeerStatusEventHandler status_events,
1227                      GNUNET_CORE_MessageCallback inbound_notify,
1228                      int inbound_hdr_only,
1229                      GNUNET_CORE_MessageCallback outbound_notify,
1230                      int outbound_hdr_only,
1231                      const struct GNUNET_CORE_MessageHandler *handlers)
1232 {
1233   struct GNUNET_CORE_Handle *h;
1234
1235   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1236   h->cfg = cfg;
1237   h->queue_size = queue_size;
1238   h->cls = cls;
1239   h->init = init;
1240   h->connects = connects;
1241   h->disconnects = disconnects;
1242   h->status_events = status_events;
1243   h->inbound_notify = inbound_notify;
1244   h->outbound_notify = outbound_notify;
1245   h->inbound_hdr_only = inbound_hdr_only;
1246   h->outbound_hdr_only = outbound_hdr_only;
1247   h->handlers = handlers;
1248   h->hcnt = 0;
1249   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1250   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1251   while (handlers[h->hcnt].callback != NULL)
1252     h->hcnt++;
1253   GNUNET_assert (h->hcnt <
1254                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1255                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1256 #if DEBUG_CORE
1257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258               "Connecting to CORE service\n");
1259 #endif
1260   reconnect (h);
1261   return h;
1262 }
1263
1264
1265 /**
1266  * Disconnect from the core service.  This function can only 
1267  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1268  * requests have been explicitly cancelled.
1269  *
1270  * @param handle connection to core to disconnect
1271  */
1272 void
1273 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1274 {
1275   struct ControlMessage *cm;
1276   
1277 #if DEBUG_CORE
1278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1279               "Disconnecting from CORE service\n");
1280 #endif
1281   if (handle->cth != NULL)
1282     {
1283       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1284       handle->cth = NULL;
1285     }
1286   if (handle->client != NULL)
1287     {
1288       GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1289       handle->client = NULL;
1290     }
1291   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1292     {
1293       GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1294       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1295     }
1296   while (NULL != (cm = handle->pending_head))
1297     {
1298       GNUNET_CONTAINER_DLL_remove (handle->pending_head,
1299                                    handle->pending_tail,
1300                                    cm);
1301       GNUNET_free (cm);
1302     }
1303   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1304                                          &disconnect_and_free_peer_entry,
1305                                          handle);
1306   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1307   GNUNET_break (handle->ready_peer_head == NULL);
1308   GNUNET_free (handle);
1309 }
1310
1311
1312 /**
1313  * Ask the core to call "notify" once it is ready to transmit the
1314  * given number of bytes to the specified "target".  If we are not yet
1315  * connected to the specified peer, a call to this function will cause
1316  * us to try to establish a connection.
1317  *
1318  * @param handle connection to core service
1319  * @param priority how important is the message?
1320  * @param maxdelay how long can the message wait?
1321  * @param target who should receive the message,
1322  *        use NULL for this peer (loopback)
1323  * @param notify_size how many bytes of buffer space does notify want?
1324  * @param notify function to call when buffer space is available
1325  * @param notify_cls closure for notify
1326  * @return non-NULL if the notify callback was queued,
1327  *         NULL if we can not even queue the request (insufficient
1328  *         memory); if NULL is returned, "notify" will NOT be called.
1329  */
1330 struct GNUNET_CORE_TransmitHandle *
1331 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1332                                    uint32_t priority,
1333                                    struct GNUNET_TIME_Relative maxdelay,
1334                                    const struct GNUNET_PeerIdentity *target,
1335                                    size_t notify_size,
1336                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1337                                    void *notify_cls)
1338 {
1339   struct PeerRecord *pr;
1340   struct GNUNET_CORE_TransmitHandle *th;
1341   struct GNUNET_CORE_TransmitHandle *pos;
1342   struct GNUNET_CORE_TransmitHandle *prev;
1343   struct GNUNET_CORE_TransmitHandle *minp;
1344
1345   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers,
1346                                           &target->hashPubKey);
1347   if (NULL == pr)
1348     {
1349       /* attempt to send to peer that is not connected */
1350       GNUNET_break (0);
1351       return NULL;
1352     }
1353   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1354                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1355   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1356   th->peer = pr;
1357   th->get_message = notify;
1358   th->get_message_cls = notify_cls;
1359   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1360   th->priority = priority;
1361   th->msize = notify_size;
1362   /* bound queue size */
1363   if (pr->queue_size == handle->queue_size)
1364     {
1365       /* find lowest-priority entry */
1366       minp = pr->pending_head;
1367       prev = minp->next;
1368       while (prev != NULL)
1369         {
1370           if (prev->priority < minp->priority)
1371             minp = prev;
1372           prev = prev->next;
1373         }
1374       if (minp == NULL) 
1375         {
1376           GNUNET_break (handle->queue_size != 0);
1377           GNUNET_break (pr->queue_size == 0);
1378           return NULL;
1379         }
1380       if (priority <= minp->priority)
1381         return NULL; /* priority too low */
1382       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1383                                    pr->pending_tail,
1384                                    minp);
1385       pr->queue_size--;
1386       GNUNET_assert (0 ==
1387                      minp->get_message (minp->get_message_cls,
1388                                         0, NULL));
1389       GNUNET_free (minp);
1390     }
1391
1392   /* Order entries by deadline, but SKIP 'HEAD' if
1393      we're in the 'ready_peer_*' DLL */
1394   pos = pr->pending_head;
1395   if ( (pr->prev != NULL) ||
1396        (pr->next != NULL) ||
1397        (pr == handle->ready_peer_head) )
1398     {
1399       GNUNET_assert (pos != NULL);
1400       pos = pos->next; /* skip head */
1401     }
1402
1403   /* insertion sort */
1404   prev = pos;
1405   while ( (pos != NULL) &&
1406           (pos->timeout.abs_value < th->timeout.abs_value) )      
1407     {
1408       prev = pos;
1409       pos = pos->next;
1410     }
1411   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head,
1412                                      pr->pending_tail,
1413                                      prev,
1414                                      th);
1415   pr->queue_size++;
1416   /* was the request queue previously empty? */
1417   if (pr->pending_head == th) 
1418     request_next_transmission (pr);
1419   return th;
1420 }
1421
1422
1423 /**
1424  * Cancel the specified transmission-ready notification.
1425  *
1426  * @param th handle that was returned by "notify_transmit_ready".
1427  */
1428 void
1429 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
1430                                           *th)
1431 {
1432   struct PeerRecord *pr = th->peer;
1433   struct GNUNET_CORE_Handle *h = pr->ch;
1434   int was_head;
1435   
1436   was_head = (pr->pending_head == th);
1437   GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1438                                pr->pending_tail,
1439                                th);    
1440   if (th->cm != NULL)
1441     {
1442       /* we're currently in the control queue, remove */
1443       GNUNET_CONTAINER_DLL_remove (h->pending_head,
1444                                    h->pending_tail,
1445                                    th->cm);
1446       GNUNET_free (th->cm);      
1447     }
1448   GNUNET_free (th);
1449   if (was_head)
1450     {
1451       if ( (pr->prev != NULL) ||
1452            (pr->next != NULL) ||
1453            (pr == h->ready_peer_head) )
1454         {
1455           /* the request that was 'approved' by core was
1456              cancelled before it could be transmitted; remove
1457              us from the 'ready' list */
1458           GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
1459                                        h->ready_peer_tail,
1460                                        pr);
1461         }
1462       request_next_transmission (pr);
1463     }
1464 }
1465
1466
1467 /* ****************** GNUNET_CORE_peer_request_connect ******************** */
1468
1469 /**
1470  * Handle for a request to the core to connect to
1471  * a particular peer.  Can be used to cancel the request
1472  * (before the 'cont'inuation is called).
1473  */
1474 struct GNUNET_CORE_PeerRequestHandle
1475 {
1476
1477   /**
1478    * Link to control message.
1479    */
1480   struct ControlMessage *cm;
1481
1482   /**
1483    * Core handle used.
1484    */
1485   struct GNUNET_CORE_Handle *h;
1486
1487   /**
1488    * Continuation to run when done.
1489    */
1490   GNUNET_SCHEDULER_Task cont;
1491
1492   /**
1493    * Closure for 'cont'.
1494    */
1495   void *cont_cls;
1496
1497 };
1498
1499
1500
1501 /**
1502  * Continuation called when the control message was transmitted.
1503  * Calls the original continuation and frees the remaining
1504  * resources.
1505  *
1506  * @param cls the 'struct GNUNET_CORE_PeerRequestHandle'
1507  * @param tc scheduler context
1508  */
1509 static void
1510 peer_request_connect_cont (void *cls,
1511                            const struct GNUNET_SCHEDULER_TaskContext *tc)
1512 {
1513   struct GNUNET_CORE_PeerRequestHandle *ret = cls;
1514   
1515   if (ret->cont != NULL)
1516     ret->cont (ret->cont_cls, tc);
1517   GNUNET_free (ret);
1518 }
1519
1520
1521 /**
1522  * Request that the core should try to connect to a particular peer.
1523  * Once the request has been transmitted to the core, the continuation
1524  * function will be called.  Note that this does NOT mean that a
1525  * connection was successfully established -- it only means that the
1526  * core will now try.  Successful establishment of the connection
1527  * will be signalled to the 'connects' callback argument of
1528  * 'GNUNET_CORE_connect' only.  If the core service does not respond
1529  * to our connection attempt within the given time frame, 'cont' will
1530  * be called with the TIMEOUT reason code.
1531  *
1532  * @param h core handle
1533  * @param timeout how long to try to talk to core
1534  * @param peer who should we connect to
1535  * @param cont function to call once the request has been completed (or timed out)
1536  * @param cont_cls closure for cont
1537  * @return NULL on error (cont will not be called), otherwise handle for cancellation
1538  */
1539 struct GNUNET_CORE_PeerRequestHandle *
1540 GNUNET_CORE_peer_request_connect (struct GNUNET_CORE_Handle *h,
1541                                   struct GNUNET_TIME_Relative timeout,
1542                                   const struct GNUNET_PeerIdentity * peer,
1543                                   GNUNET_SCHEDULER_Task cont,
1544                                   void *cont_cls)
1545 {
1546   struct GNUNET_CORE_PeerRequestHandle *ret;
1547   struct ControlMessage *cm;
1548   struct ConnectMessage *msg;
1549   
1550   cm = GNUNET_malloc (sizeof (struct ControlMessage) + 
1551                       sizeof (struct ConnectMessage));
1552   msg = (struct ConnectMessage*) &cm[1];
1553   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT);
1554   msg->header.size = htons (sizeof (struct ConnectMessage));
1555   msg->reserved = htonl (0);
1556   msg->timeout = GNUNET_TIME_relative_hton (timeout);
1557   msg->peer = *peer;
1558   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1559                                h->pending_tail,
1560                                cm);
1561   ret = GNUNET_malloc (sizeof (struct GNUNET_CORE_PeerRequestHandle));
1562   ret->h = h;
1563   ret->cm = cm;
1564   ret->cont = cont;
1565   ret->cont_cls = cont_cls;
1566   cm->cont = &peer_request_connect_cont;
1567   cm->cont_cls = ret;
1568   if (h->pending_head == cm)
1569     trigger_next_request (h, GNUNET_NO);
1570   return ret;
1571 }
1572
1573
1574 /**
1575  * Cancel a pending request to connect to a particular peer.  Must not
1576  * be called after the 'cont' function was invoked.
1577  *
1578  * @param req request handle that was returned for the original request
1579  */
1580 void
1581 GNUNET_CORE_peer_request_connect_cancel (struct GNUNET_CORE_PeerRequestHandle *req)
1582 {
1583   struct GNUNET_CORE_Handle *h = req->h;
1584   struct ControlMessage *cm = req->cm;
1585
1586   GNUNET_CONTAINER_DLL_remove (h->pending_head,
1587                                h->pending_tail,
1588                                cm);
1589   GNUNET_free (cm);
1590   GNUNET_free (req);
1591 }
1592
1593
1594 /* ****************** GNUNET_CORE_peer_change_preference ******************** */
1595
1596
1597 struct GNUNET_CORE_InformationRequestContext 
1598 {
1599   
1600   /**
1601    * Our connection to the service.
1602    */
1603   struct GNUNET_CORE_Handle *h;
1604
1605   /**
1606    * Function to call with the information.
1607    */
1608   GNUNET_CORE_PeerConfigurationInfoCallback info;
1609
1610   /**
1611    * Closure for info.
1612    */
1613   void *info_cls;
1614
1615   /**
1616    * Link to control message, NULL if CM was sent.
1617    */ 
1618   struct ControlMessage *cm;
1619
1620   /**
1621    * Link to peer record.
1622    */
1623   struct PeerRecord *pr;
1624 };
1625
1626
1627 /**
1628  * CM was sent, remove link so we don't double-free.
1629  *
1630  * @param cls the 'struct GNUNET_CORE_InformationRequestContext'
1631  * @param tc scheduler context
1632  */
1633 static void
1634 change_preference_send_continuation (void *cls,
1635                                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1636 {
1637   struct GNUNET_CORE_InformationRequestContext *irc = cls;
1638
1639   irc->cm = NULL;
1640 }
1641
1642
1643 /**
1644  * Obtain statistics and/or change preferences for the given peer.
1645  *
1646  * @param h core handle
1647  * @param peer identifies the peer
1648  * @param timeout after how long should we give up (and call "info" with NULL
1649  *                for "peer" to signal an error)?
1650  * @param bw_out set to the current bandwidth limit (sending) for this peer,
1651  *                caller should set "bw_out" to "-1" to avoid changing
1652  *                the current value; otherwise "bw_out" will be lowered to
1653  *                the specified value; passing a pointer to "0" can be used to force
1654  *                us to disconnect from the peer; "bw_out" might not increase
1655  *                as specified since the upper bound is generally
1656  *                determined by the other peer!
1657  * @param amount reserve N bytes for receiving, negative
1658  *                amounts can be used to undo a (recent) reservation;
1659  * @param preference increase incoming traffic share preference by this amount;
1660  *                in the absence of "amount" reservations, we use this
1661  *                preference value to assign proportional bandwidth shares
1662  *                to all connected peers
1663  * @param info function to call with the resulting configuration information
1664  * @param info_cls closure for info
1665  * @return NULL on error
1666  */
1667 struct GNUNET_CORE_InformationRequestContext *
1668 GNUNET_CORE_peer_change_preference (struct GNUNET_CORE_Handle *h,
1669                                     const struct GNUNET_PeerIdentity *peer,
1670                                     struct GNUNET_TIME_Relative timeout,
1671                                     struct GNUNET_BANDWIDTH_Value32NBO bw_out,
1672                                     int32_t amount,
1673                                     uint64_t preference,
1674                                     GNUNET_CORE_PeerConfigurationInfoCallback info,
1675                                     void *info_cls)
1676 {
1677   struct GNUNET_CORE_InformationRequestContext *irc;
1678   struct PeerRecord *pr;
1679   struct RequestInfoMessage *rim;
1680   struct ControlMessage *cm;
1681
1682   pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1683                                           &peer->hashPubKey);
1684   if (NULL == pr)
1685     {
1686       /* attempt to change preference on peer that is not connected */
1687       GNUNET_break (0);
1688       return NULL;
1689     }
1690   if (pr->pcic != NULL)
1691     {
1692       /* second change before first one is done */
1693       GNUNET_break (0);
1694       return NULL;
1695     }
1696   irc = GNUNET_malloc (sizeof (struct GNUNET_CORE_InformationRequestContext));
1697   irc->h = h;
1698   irc->info = info;
1699   irc->info_cls = info_cls;
1700   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1701                       sizeof (struct RequestInfoMessage));
1702   cm->cont = &change_preference_send_continuation;
1703   cm->cont_cls = irc;
1704   irc->cm = cm;
1705   rim = (struct RequestInfoMessage*) &cm[1];
1706   rim->header.size = htons (sizeof (struct RequestInfoMessage));
1707   rim->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO);
1708   rim->rim_id = htonl (pr->rim_id = h->rim_id_gen++);
1709   rim->limit_outbound = bw_out;
1710   rim->reserve_inbound = htonl (amount);
1711   rim->preference_change = GNUNET_htonll(preference);
1712   rim->peer = *peer;
1713   GNUNET_CONTAINER_DLL_insert (h->pending_head,
1714                                h->pending_tail,
1715                                cm); 
1716   pr->pcic = info;
1717   pr->pcic_cls = info_cls;
1718   return irc;
1719 }
1720
1721
1722 /**
1723  * Cancel request for getting information about a peer.
1724  * Note that an eventual change in preference, trust or bandwidth
1725  * assignment MAY have already been committed at the time, 
1726  * so cancelling a request is NOT sure to undo the original
1727  * request.  The original request may or may not still commit.
1728  * The only thing cancellation ensures is that the callback
1729  * from the original request will no longer be called.
1730  *
1731  * @param irc context returned by the original GNUNET_CORE_peer_get_info call
1732  */
1733 void
1734 GNUNET_CORE_peer_change_preference_cancel (struct GNUNET_CORE_InformationRequestContext *irc)
1735 {
1736   struct GNUNET_CORE_Handle *h = irc->h;
1737   struct PeerRecord *pr = irc->pr;
1738
1739   if (irc->cm != NULL)
1740     {
1741       GNUNET_CONTAINER_DLL_remove (h->pending_head,
1742                                    h->pending_tail,
1743                                    irc->cm);
1744       GNUNET_free (irc->cm);
1745     }
1746   pr->pcic = NULL;
1747   pr->pcic_cls = NULL;
1748   GNUNET_free (irc);
1749 }
1750
1751
1752 /* ********************* GNUNET_CORE_iterate_peers *********************** */
1753
1754 /**
1755  * Context for 'iterate_peers' helper function.
1756  */
1757 struct IterationContext
1758 {
1759   /**
1760    * Callback to call.
1761    */
1762   GNUNET_CORE_ConnectEventHandler peer_cb;
1763
1764   /**
1765    * Closure for 'peer_cb'.
1766    */
1767   void *cb_cls;
1768 };
1769
1770
1771 /**
1772  * Call callback for each peer.
1773  *
1774  * @param cls the 'struct IterationContext'
1775  * @param hc peer identity, not used
1776  * @param value the 'struct PeerRecord'
1777  * @return GNUNET_YES (continue iteration)
1778  */
1779 static int
1780 iterate_peers (void *cls,
1781                const GNUNET_HashCode *hc,
1782                void *value)
1783 {
1784   struct IterationContext *ic = cls;
1785   struct PeerRecord *pr = value;
1786
1787   ic->peer_cb (ic->cb_cls,
1788                &pr->peer,
1789                NULL /* FIXME: pass atsi? */);
1790   return GNUNET_YES;
1791 }
1792
1793
1794 /**
1795  * Obtain statistics and/or change preferences for the given peer.
1796  *
1797  * @param h handle to core
1798  * @param peer_cb function to call with the peer information
1799  * @param cb_cls closure for peer_cb
1800  * @return GNUNET_OK if iterating, GNUNET_SYSERR on error
1801  */
1802 int
1803 GNUNET_CORE_iterate_peers (struct GNUNET_CORE_Handle *h,
1804                            GNUNET_CORE_ConnectEventHandler peer_cb,
1805                            void *cb_cls)
1806 {
1807   struct IterationContext ic;
1808
1809   ic.peer_cb = peer_cb;
1810   ic.cb_cls = cb_cls;
1811   GNUNET_CONTAINER_multihashmap_iterate (h->peers,
1812                                          &iterate_peers,
1813                                          &ic);
1814   return GNUNET_OK;
1815 }
1816
1817
1818 /* end of core_api.c */