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