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