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