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