log
[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           return;
1000         }
1001       if (msize < sizeof (struct PeerStatusNotifyMessage))
1002         {
1003           GNUNET_break (0);
1004           reconnect_later (h);
1005           return;
1006         }
1007       psnm = (const struct PeerStatusNotifyMessage *) msg;
1008       if (0 == memcmp (&h->me,
1009                        &psnm->peer,
1010                        sizeof (struct GNUNET_PeerIdentity)))
1011         {
1012           /* self-change!? */
1013           GNUNET_break (0);
1014           return;
1015         }
1016       ats_count = ntohl (psnm->ats_count);
1017       if ( (msize != sizeof (struct PeerStatusNotifyMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
1018            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&psnm->ats)[ats_count].type)) )
1019         {
1020           GNUNET_break (0);
1021           reconnect_later (h);
1022           return;
1023         }
1024 #if DEBUG_CORE
1025       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026                   "Received notification about status change by `%s'.\n",
1027                   GNUNET_i2s (&psnm->peer));
1028 #endif
1029       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1030                                               &psnm->peer.hashPubKey);
1031       if (pr == NULL)
1032         {
1033           GNUNET_break (0);
1034           reconnect_later (h);
1035           return;
1036         }
1037       h->status_events (h->cls,
1038                         &psnm->peer,
1039                         psnm->bandwidth_in,
1040                         psnm->bandwidth_out,
1041                         GNUNET_TIME_absolute_ntoh (psnm->timeout),
1042                         &psnm->ats);
1043       break;
1044     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
1045       if (msize < sizeof (struct NotifyTrafficMessage))
1046         {
1047           GNUNET_break (0);
1048           reconnect_later (h);
1049           return;
1050         }
1051       ntm = (const struct NotifyTrafficMessage *) msg;
1052
1053       ats_count = ntohl (ntm->ats_count);
1054       if ( (msize < sizeof (struct NotifyTrafficMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)
1055             + sizeof (struct GNUNET_MessageHeader)) ||
1056            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&ntm->ats)[ats_count].type)) )
1057         {
1058           GNUNET_break (0);
1059           reconnect_later (h);
1060           return;
1061         }
1062       em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count+1];
1063 #if DEBUG_CORE
1064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1065                   "Received message of type %u and size %u from peer `%4s'\n",
1066                   ntohs (em->type), 
1067                   ntohs (em->size),
1068                   GNUNET_i2s (&ntm->peer));
1069 #endif
1070       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1071                                               &ntm->peer.hashPubKey);
1072       if (pr == NULL)
1073         {
1074           GNUNET_break (0);
1075           reconnect_later (h);
1076           return;
1077         }
1078       if ((GNUNET_NO == h->inbound_hdr_only) &&
1079           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage) + 
1080            + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) )
1081         {
1082           GNUNET_break (0);
1083           reconnect_later (h);
1084           return;
1085         }
1086       et = ntohs (em->type);
1087       for (hpos = 0; hpos < h->hcnt; hpos++)
1088         {
1089           mh = &h->handlers[hpos];
1090           if (mh->type != et)
1091             continue;
1092           if ((mh->expected_size != ntohs (em->size)) &&
1093               (mh->expected_size != 0))
1094             {
1095               GNUNET_break (0);
1096               continue;
1097             }
1098           if (GNUNET_OK !=
1099               h->handlers[hpos].callback (h->cls, &ntm->peer, em,
1100                                           &ntm->ats))
1101             {
1102               /* error in processing, do not process other messages! */
1103               break;
1104             }
1105         }
1106       if (NULL != h->inbound_notify)
1107         h->inbound_notify (h->cls, &ntm->peer, em,
1108                            &ntm->ats);
1109       break;
1110     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
1111       if (msize < sizeof (struct NotifyTrafficMessage))
1112         {
1113           GNUNET_break (0);
1114           reconnect_later (h);
1115           return;
1116         }
1117       ntm = (const struct NotifyTrafficMessage *) msg;
1118       if (0 == memcmp (&h->me,
1119                        &ntm->peer,
1120                        sizeof (struct GNUNET_PeerIdentity)))
1121         {
1122           /* self-change!? */
1123           GNUNET_break (0);
1124           return;
1125         }
1126       ats_count = ntohl (ntm->ats_count);
1127       if ( (msize < sizeof (struct NotifyTrafficMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)
1128             + sizeof (struct GNUNET_MessageHeader)) ||
1129            (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR != ntohl ((&ntm->ats)[ats_count].type)) )
1130         {
1131           GNUNET_break (0);
1132           reconnect_later (h);
1133           return;
1134         }
1135       em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count+1];
1136       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1137                                               &ntm->peer.hashPubKey);
1138       if (pr == NULL)
1139         {
1140           GNUNET_break (0);
1141           reconnect_later (h);
1142           return;
1143         }
1144 #if DEBUG_CORE
1145       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1146                   "Received notification about transmission to `%s'.\n",
1147                   GNUNET_i2s (&ntm->peer));
1148 #endif
1149       if ((GNUNET_NO == h->outbound_hdr_only) &&
1150           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage) 
1151            + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) )
1152         {
1153           GNUNET_break (0);
1154           reconnect_later (h);
1155           return;
1156         }
1157       if (NULL == h->outbound_notify)
1158         {
1159           GNUNET_break (0);
1160           break;
1161         }
1162       h->outbound_notify (h->cls, &ntm->peer, em,
1163                           &ntm->ats);
1164       break;
1165     case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1166       if (msize != sizeof (struct SendMessageReady))
1167         {
1168           GNUNET_break (0);
1169           reconnect_later (h);
1170           return;
1171         }
1172       smr = (const struct SendMessageReady *) msg;
1173       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1174                                               &smr->peer.hashPubKey);
1175       if (pr == NULL)
1176         {
1177           GNUNET_break (0);
1178           reconnect_later (h);
1179           return;
1180         }
1181 #if DEBUG_CORE
1182       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183                   "Received notification about transmission readiness to `%s'.\n",
1184                   GNUNET_i2s (&smr->peer));
1185 #endif
1186       if (pr->pending_head == NULL)
1187         {
1188           /* request must have been cancelled between the original request
1189              and the response from core, ignore core's readiness */
1190           return;
1191         }
1192
1193       th = pr->pending_head;
1194       if (ntohs (smr->smr_id) != th->smr_id)
1195         {
1196           /* READY message is for expired or cancelled message,
1197              ignore! (we should have already sent another request) */
1198           break;
1199         }
1200       if ( (pr->prev != NULL) ||
1201            (pr->next != NULL) ||
1202            (h->ready_peer_head == pr) )
1203         {
1204           /* we should not already be on the ready list... */
1205           GNUNET_break (0);
1206           reconnect_later (h);
1207           return;
1208         }
1209       GNUNET_CONTAINER_DLL_insert (h->ready_peer_head,
1210                                    h->ready_peer_tail,
1211                                    pr);
1212       trigger_next_request (h, GNUNET_NO);
1213       break;
1214     case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
1215       if (ntohs (msg->size) != sizeof (struct ConfigurationInfoMessage))
1216         {
1217           GNUNET_break (0);
1218           reconnect_later (h);
1219           return;
1220         }
1221       cim = (const struct ConfigurationInfoMessage*) msg;
1222       if (0 == memcmp (&h->me,
1223                        &cim->peer,
1224                        sizeof (struct GNUNET_PeerIdentity)))
1225         {
1226           /* self-change!? */
1227           GNUNET_break (0);
1228           return;
1229         }
1230 #if DEBUG_CORE
1231       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232                   "Received notification about configuration update for `%s'.\n",
1233                   GNUNET_i2s (&cim->peer));
1234 #endif
1235       pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1236                                               &cim->peer.hashPubKey);
1237       if (pr == NULL)
1238         {
1239           GNUNET_break (0);
1240           reconnect_later (h);
1241           return;
1242         }
1243       if (pr->rim_id != ntohl (cim->rim_id))
1244         {
1245 #if DEBUG_CORE
1246           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247                       "Reservation ID mismatch in notification...\n");
1248 #endif
1249           break;
1250         }
1251       pcic = pr->pcic;
1252       pr->pcic = NULL;
1253       if (pcic != NULL)
1254         pcic (pr->pcic_cls,
1255               &pr->peer,
1256               cim->bw_out,
1257               ntohl (cim->reserved_amount),
1258               GNUNET_TIME_relative_ntoh (cim->reserve_delay),
1259               GNUNET_ntohll (cim->preference));
1260       break;
1261     default:
1262       reconnect_later (h);
1263       return;
1264     }
1265   GNUNET_CLIENT_receive (h->client,
1266                          &main_notify_handler, h, 
1267                          GNUNET_TIME_UNIT_FOREVER_REL);
1268 }
1269
1270
1271 /**
1272  * Task executed once we are done transmitting the INIT message.
1273  * Starts our 'receive' loop.
1274  *
1275  * @param cls the 'struct GNUNET_CORE_Handle'
1276  * @param success were we successful
1277  */
1278 static void
1279 init_done_task (void *cls, 
1280                 int success)
1281 {
1282   struct GNUNET_CORE_Handle *h = cls;
1283
1284   if (success == GNUNET_SYSERR)
1285     return; /* shutdown */
1286   if (success == GNUNET_NO)
1287     {
1288 #if DEBUG_CORE
1289       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1290                   "Failed to exchange INIT with core, retrying\n");
1291 #endif
1292       if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1293         reconnect_later (h);
1294       return;
1295     }
1296   GNUNET_CLIENT_receive (h->client,
1297                          &main_notify_handler, 
1298                          h, 
1299                          GNUNET_TIME_UNIT_FOREVER_REL);
1300 }
1301
1302
1303 /**
1304  * Our current client connection went down.  Clean it up
1305  * and try to reconnect!
1306  *
1307  * @param h our handle to the core service
1308  */
1309 static void
1310 reconnect (struct GNUNET_CORE_Handle *h)
1311 {
1312   struct ControlMessage *cm;
1313   struct InitMessage *init;
1314   uint32_t opt;
1315   uint16_t msize;
1316   uint16_t *ts;
1317   unsigned int hpos;
1318
1319 #if DEBUG_CORE
1320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1321               "Reconnecting to CORE service\n");
1322 #endif
1323   GNUNET_assert (h->client == NULL);
1324   GNUNET_assert (h->currently_down == GNUNET_YES);
1325   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1326   if (h->client == NULL)
1327     {
1328       reconnect_later (h);
1329       return;
1330     }
1331   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1332   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1333                       msize);
1334   cm->cont = &init_done_task;
1335   cm->cont_cls = h;
1336   init = (struct InitMessage*) &cm[1];
1337   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1338   init->header.size = htons (msize);
1339   opt = GNUNET_CORE_OPTION_SEND_CONNECT | GNUNET_CORE_OPTION_SEND_DISCONNECT;
1340   if (h->status_events != NULL)
1341     opt |= GNUNET_CORE_OPTION_SEND_STATUS_CHANGE;
1342   if (h->inbound_notify != NULL)
1343     {
1344       if (h->inbound_hdr_only)
1345         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1346       else
1347         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1348     }
1349   if (h->outbound_notify != NULL)
1350     {
1351       if (h->outbound_hdr_only)
1352         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1353       else
1354         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1355     }
1356   init->options = htonl (opt);
1357   ts = (uint16_t *) &init[1];
1358   for (hpos = 0; hpos < h->hcnt; hpos++)
1359     ts[hpos] = htons (h->handlers[hpos].type);
1360   GNUNET_CONTAINER_DLL_insert (h->control_pending_head,
1361                                h->control_pending_tail,
1362                                cm);
1363   trigger_next_request (h, GNUNET_YES);
1364 }
1365
1366
1367
1368 /**
1369  * Connect to the core service.  Note that the connection may
1370  * complete (or fail) asynchronously.
1371  *
1372  * @param cfg configuration to use
1373  * @param queue_size size of the per-peer message queue
1374  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1375  * @param init callback to call on timeout or once we have successfully
1376  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1377  * @param connects function to call on peer connect, can be NULL
1378  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1379  * @param status_events function to call on changes to peer connection status, can be NULL
1380  * @param inbound_notify function to call for all inbound messages, can be NULL
1381  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1382  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1383  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1384  * @param outbound_notify function to call for all outbound messages, can be NULL
1385  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1386  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1387  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1388  * @param handlers callbacks for messages we care about, NULL-terminated
1389  * @return handle to the core service (only useful for disconnect until 'init' is called);
1390  *                NULL on error (in this case, init is never called)
1391  */
1392 struct GNUNET_CORE_Handle *
1393 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1394                      unsigned int queue_size,
1395                      void *cls,
1396                      GNUNET_CORE_StartupCallback init,
1397                      GNUNET_CORE_ConnectEventHandler connects,
1398                      GNUNET_CORE_DisconnectEventHandler disconnects,
1399                      GNUNET_CORE_PeerStatusEventHandler status_events,
1400                      GNUNET_CORE_MessageCallback inbound_notify,
1401                      int inbound_hdr_only,
1402                      GNUNET_CORE_MessageCallback outbound_notify,
1403                      int outbound_hdr_only,
1404                      const struct GNUNET_CORE_MessageHandler *handlers)
1405 {
1406   struct GNUNET_CORE_Handle *h;
1407
1408   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1409   h->cfg = cfg;
1410   h->queue_size = queue_size;
1411   h->cls = cls;
1412   h->init = init;
1413   h->connects = connects;
1414   h->disconnects = disconnects;
1415   h->status_events = status_events;
1416   h->inbound_notify = inbound_notify;
1417   h->outbound_notify = outbound_notify;
1418   h->inbound_hdr_only = inbound_hdr_only;
1419   h->outbound_hdr_only = outbound_hdr_only;
1420   h->handlers = handlers;
1421   h->hcnt = 0;
1422   h->currently_down = GNUNET_YES;
1423   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1424   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1425   while (handlers[h->hcnt].callback != NULL)
1426     h->hcnt++;
1427   GNUNET_assert (h->hcnt <
1428                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1429                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1430 #if DEBUG_CORE
1431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1432               "Connecting to CORE service\n");
1433 #endif
1434   reconnect (h);
1435   return h;
1436 }
1437
1438
1439 /**
1440  * Disconnect from the core service.  This function can only 
1441  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1442  * requests have been explicitly canceled.
1443  *
1444  * @param handle connection to core to disconnect
1445  */
1446 void
1447 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1448 {
1449   struct ControlMessage *cm;
1450   
1451 #if DEBUG_CORE
1452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453               "Disconnecting from CORE service\n");
1454 #endif
1455   if (handle->cth != NULL)
1456     {
1457       GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1458       handle->cth = NULL;
1459     }
1460   if (handle->client != NULL)
1461     {
1462       GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1463       handle->client = NULL;
1464     }
1465   while (NULL != (cm = handle->control_pending_head))
1466     {
1467       GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1468                                    handle->control_pending_tail,
1469                                    cm);
1470       if (cm->th != NULL)
1471         cm->th->cm = NULL;
1472       if (cm->cont != NULL)
1473         cm->cont (cm->cont_cls, GNUNET_SYSERR);
1474       GNUNET_free (cm);
1475     }
1476   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1477     {
1478       GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1479       handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1480     }
1481   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1482                                          &disconnect_and_free_peer_entry,
1483                                          handle);
1484   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1485   GNUNET_break (handle->ready_peer_head == NULL);
1486   GNUNET_free (handle);
1487 }
1488
1489
1490 /**
1491  * Ask the core to call "notify" once it is ready to transmit the
1492  * given number of bytes to the specified "target".    Must only be
1493  * called after a connection to the respective peer has been
1494  * established (and the client has been informed about this).
1495  *
1496  * @param handle connection to core service
1497  * @param cork is corking allowed for this transmission?
1498  * @param priority how important is the message?
1499  * @param maxdelay how long can the message wait?
1500  * @param target who should receive the message,
1501  *        use NULL for this peer (loopback)
1502  * @param notify_size how many bytes of buffer space does notify want?
1503  * @param notify function to call when buffer space is available
1504  * @param notify_cls closure for notify
1505  * @return non-NULL if the notify callback was queued,
1506  *         NULL if we can not even queue the request (insufficient
1507  *         memory); if NULL is returned, "notify" will NOT be called.
1508  */
1509 struct GNUNET_CORE_TransmitHandle *
1510 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1511                                    int cork,
1512                                    uint32_t priority,
1513                                    struct GNUNET_TIME_Relative maxdelay,
1514                                    const struct GNUNET_PeerIdentity *target,
1515                                    size_t notify_size,
1516                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1517                                    void *notify_cls)
1518 {
1519   struct PeerRecord *pr;
1520   struct GNUNET_CORE_TransmitHandle *th;
1521   struct GNUNET_CORE_TransmitHandle *pos;
1522   struct GNUNET_CORE_TransmitHandle *prev;
1523   struct GNUNET_CORE_TransmitHandle *minp;
1524
1525   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers,
1526                                           &target->hashPubKey);
1527   if (NULL == pr)
1528     {
1529       /* attempt to send to peer that is not connected */
1530       GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1531                  "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1532                  GNUNET_i2s(target), GNUNET_h2s(&handle->me.hashPubKey));
1533       GNUNET_break (0);
1534       return NULL;
1535     }
1536   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1537                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1538   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1539   th->peer = pr;
1540   GNUNET_assert(NULL != notify);
1541   th->get_message = notify;
1542   th->get_message_cls = notify_cls;
1543   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1544   th->priority = priority;
1545   th->msize = notify_size;
1546   th->cork = cork;
1547   /* bound queue size */
1548   if (pr->queue_size == handle->queue_size)
1549     {
1550       /* find lowest-priority entry, but skip the head of the list */
1551       minp = pr->pending_head->next;
1552       prev = minp;
1553       while (prev != NULL)
1554         {
1555           if (prev->priority < minp->priority)
1556             minp = prev;
1557           prev = prev->next;
1558         }
1559       if (minp == NULL) 
1560         {
1561           GNUNET_break (handle->queue_size != 0);
1562           GNUNET_break (pr->queue_size == 1);
1563           GNUNET_free(th);
1564 #if DEBUG_CORE
1565           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1566                       "Dropping transmission request: cannot drop queue head and limit is one\n");
1567 #endif
1568           return NULL;
1569         }
1570       if (priority <= minp->priority)
1571         {
1572 #if DEBUG_CORE
1573           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574                       "Dropping transmission request: priority too low\n");
1575 #endif
1576           return NULL; /* priority too low */
1577         }
1578       GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1579                                    pr->pending_tail,
1580                                    minp);
1581       pr->queue_size--;
1582       GNUNET_assert (0 ==
1583                      minp->get_message (minp->get_message_cls,
1584                                         0, NULL));
1585       GNUNET_free (minp);
1586     }
1587
1588   /* Order entries by deadline, but SKIP 'HEAD' if
1589      we're in the 'ready_peer_*' DLL */
1590   pos = pr->pending_head;
1591   if ( (pr->prev != NULL) ||
1592        (pr->next != NULL) ||
1593        (pr == handle->ready_peer_head) )
1594     {
1595       GNUNET_assert (pos != NULL);
1596       pos = pos->next; /* skip head */
1597     }
1598
1599   /* insertion sort */
1600   prev = pos;
1601   while ( (pos != NULL) &&
1602           (pos->timeout.abs_value < th->timeout.abs_value) )      
1603     {
1604       prev = pos;
1605       pos = pos->next;
1606     }
1607   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head,
1608                                      pr->pending_tail,
1609                                      prev,
1610                                      th);
1611   pr->queue_size++;
1612   /* was the request queue previously empty? */
1613 #if DEBUG_CORE
1614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1615               "Transmission request added to queue\n");
1616 #endif
1617   if (pr->pending_head == th) 
1618     request_next_transmission (pr);
1619   return th;
1620 }
1621
1622
1623 /**
1624  * Cancel the specified transmission-ready notification.
1625  *
1626  * @param th handle that was returned by "notify_transmit_ready".
1627  */
1628 void
1629 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
1630                                           *th)
1631 {
1632   struct PeerRecord *pr = th->peer;
1633   struct GNUNET_CORE_Handle *h = pr->ch;
1634   int was_head;
1635   
1636   was_head = (pr->pending_head == th);
1637   GNUNET_CONTAINER_DLL_remove (pr->pending_head,
1638                                pr->pending_tail,
1639                                th);    
1640   pr->queue_size--;
1641   if (th->cm != NULL)
1642     {
1643       /* we're currently in the control queue, remove */
1644       GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1645                                    h->control_pending_tail,
1646                                    th->cm);
1647       GNUNET_free (th->cm);      
1648     }
1649   GNUNET_free (th);
1650   if (was_head)
1651     {
1652       if ( (pr->prev != NULL) ||
1653            (pr->next != NULL) ||
1654            (pr == h->ready_peer_head) )
1655         {
1656           /* the request that was 'approved' by core was
1657              canceled before it could be transmitted; remove
1658              us from the 'ready' list */
1659           GNUNET_CONTAINER_DLL_remove (h->ready_peer_head,
1660                                        h->ready_peer_tail,
1661                                        pr);
1662         }
1663       request_next_transmission (pr);
1664     }
1665 }
1666
1667
1668 /* ****************** GNUNET_CORE_peer_request_connect ******************** */
1669
1670 /**
1671  * Handle for a request to the core to connect to
1672  * a particular peer.  Can be used to cancel the request
1673  * (before the 'cont'inuation is called).
1674  */
1675 struct GNUNET_CORE_PeerRequestHandle
1676 {
1677
1678   /**
1679    * Link to control message.
1680    */
1681   struct ControlMessage *cm;
1682
1683   /**
1684    * Core handle used.
1685    */
1686   struct GNUNET_CORE_Handle *h;
1687
1688   /**
1689    * Continuation to run when done.
1690    */
1691   GNUNET_CORE_ControlContinuation cont;
1692
1693   /**
1694    * Closure for 'cont'.
1695    */
1696   void *cont_cls;
1697
1698 };
1699
1700
1701 /**
1702  * Continuation called when the control message was transmitted.
1703  * Calls the original continuation and frees the remaining
1704  * resources.
1705  *
1706  * @param cls the 'struct GNUNET_CORE_PeerRequestHandle'
1707  * @param success was the request transmitted?
1708  */
1709 static void
1710 peer_request_connect_cont (void *cls,
1711                            int success)
1712 {
1713   struct GNUNET_CORE_PeerRequestHandle *ret = cls;
1714   
1715   if (ret->cont != NULL)
1716     ret->cont (ret->cont_cls, success);    
1717   GNUNET_free (ret);
1718 }
1719
1720
1721 /**
1722  * Request that the core should try to connect to a particular peer.
1723  * Once the request has been transmitted to the core, the continuation
1724  * function will be called.  Note that this does NOT mean that a
1725  * connection was successfully established -- it only means that the
1726  * core will now try.  Successful establishment of the connection
1727  * will be signalled to the 'connects' callback argument of
1728  * 'GNUNET_CORE_connect' only.  If the core service does not respond
1729  * to our connection attempt within the given time frame, 'cont' will
1730  * be called with the TIMEOUT reason code.
1731  *
1732  * @param h core handle
1733  * @param timeout how long to try to talk to core
1734  * @param peer who should we connect to
1735  * @param cont function to call once the request has been completed (or timed out)
1736  * @param cont_cls closure for cont
1737  *
1738  * @return NULL on error or already connected,
1739  *         otherwise handle for cancellation
1740  */
1741 struct GNUNET_CORE_PeerRequestHandle *
1742 GNUNET_CORE_peer_request_connect (struct GNUNET_CORE_Handle *h,
1743                                   struct GNUNET_TIME_Relative timeout,
1744                                   const struct GNUNET_PeerIdentity * peer,
1745                                   GNUNET_CORE_ControlContinuation cont,
1746                                   void *cont_cls)
1747 {
1748   struct GNUNET_CORE_PeerRequestHandle *ret;
1749   struct ControlMessage *cm;
1750   struct ConnectMessage *msg;
1751
1752   if (NULL != GNUNET_CONTAINER_multihashmap_get (h->peers,
1753                                           &peer->hashPubKey))
1754     {
1755 #if DEBUG_CORE
1756       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peers are already connected!\n");
1757 #endif
1758       return NULL;
1759     }
1760   
1761   cm = GNUNET_malloc (sizeof (struct ControlMessage) + 
1762                       sizeof (struct ConnectMessage));
1763   msg = (struct ConnectMessage*) &cm[1];
1764   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONNECT);
1765   msg->header.size = htons (sizeof (struct ConnectMessage));
1766   msg->reserved = htonl (0);
1767   msg->timeout = GNUNET_TIME_relative_hton (timeout);
1768   msg->peer = *peer;
1769   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
1770                                     h->control_pending_tail,
1771                                     cm);
1772   ret = GNUNET_malloc (sizeof (struct GNUNET_CORE_PeerRequestHandle));
1773   ret->h = h;
1774   ret->cm = cm;
1775   ret->cont = cont;
1776   ret->cont_cls = cont_cls;
1777   cm->cont = &peer_request_connect_cont;
1778   cm->cont_cls = ret;
1779 #if DEBUG_CORE
1780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1781               "Queueing REQUEST_CONNECT request\n");
1782 #endif
1783   if (h->control_pending_head == cm)
1784     trigger_next_request (h, GNUNET_NO);
1785   return ret;
1786 }
1787
1788
1789 /**
1790  * Cancel a pending request to connect to a particular peer.  Must not
1791  * be called after the 'cont' function was invoked.
1792  *
1793  * @param req request handle that was returned for the original request
1794  */
1795 void
1796 GNUNET_CORE_peer_request_connect_cancel (struct GNUNET_CORE_PeerRequestHandle *req)
1797 {
1798   struct GNUNET_CORE_Handle *h = req->h;
1799   struct ControlMessage *cm = req->cm;
1800
1801   GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1802                                h->control_pending_tail,
1803                                cm);
1804   GNUNET_free (cm);
1805   GNUNET_free (req);
1806 }
1807
1808
1809 /* ****************** GNUNET_CORE_peer_change_preference ******************** */
1810
1811
1812 struct GNUNET_CORE_InformationRequestContext 
1813 {
1814   
1815   /**
1816    * Our connection to the service.
1817    */
1818   struct GNUNET_CORE_Handle *h;
1819
1820   /**
1821    * Link to control message, NULL if CM was sent.
1822    */ 
1823   struct ControlMessage *cm;
1824
1825   /**
1826    * Link to peer record.
1827    */
1828   struct PeerRecord *pr;
1829 };
1830
1831
1832 /**
1833  * CM was sent, remove link so we don't double-free.
1834  *
1835  * @param cls the 'struct GNUNET_CORE_InformationRequestContext'
1836  * @param success were we successful?
1837  */
1838 static void
1839 change_preference_send_continuation (void *cls,
1840                                      int success)
1841 {
1842   struct GNUNET_CORE_InformationRequestContext *irc = cls;
1843
1844   irc->cm = NULL;
1845 }
1846
1847
1848 /**
1849  * Obtain statistics and/or change preferences for the given peer.
1850  *
1851  * @param h core handle
1852  * @param peer identifies the peer
1853  * @param timeout after how long should we give up (and call "info" with NULL
1854  *                for "peer" to signal an error)?
1855  * @param bw_out set to the current bandwidth limit (sending) for this peer,
1856  *                caller should set "bw_out" to "-1" to avoid changing
1857  *                the current value; otherwise "bw_out" will be lowered to
1858  *                the specified value; passing a pointer to "0" can be used to force
1859  *                us to disconnect from the peer; "bw_out" might not increase
1860  *                as specified since the upper bound is generally
1861  *                determined by the other peer!
1862  * @param amount reserve N bytes for receiving, negative
1863  *                amounts can be used to undo a (recent) reservation;
1864  * @param preference increase incoming traffic share preference by this amount;
1865  *                in the absence of "amount" reservations, we use this
1866  *                preference value to assign proportional bandwidth shares
1867  *                to all connected peers
1868  * @param info function to call with the resulting configuration information
1869  * @param info_cls closure for info
1870  * @return NULL on error
1871  */
1872 struct GNUNET_CORE_InformationRequestContext *
1873 GNUNET_CORE_peer_change_preference (struct GNUNET_CORE_Handle *h,
1874                                     const struct GNUNET_PeerIdentity *peer,
1875                                     struct GNUNET_TIME_Relative timeout,
1876                                     struct GNUNET_BANDWIDTH_Value32NBO bw_out,
1877                                     int32_t amount,
1878                                     uint64_t preference,
1879                                     GNUNET_CORE_PeerConfigurationInfoCallback info,
1880                                     void *info_cls)
1881 {
1882   struct GNUNET_CORE_InformationRequestContext *irc;
1883   struct PeerRecord *pr;
1884   struct RequestInfoMessage *rim;
1885   struct ControlMessage *cm;
1886
1887   pr = GNUNET_CONTAINER_multihashmap_get (h->peers,
1888                                           &peer->hashPubKey);
1889   if (NULL == pr)
1890     {
1891       /* attempt to change preference on peer that is not connected */
1892       GNUNET_break (0);
1893       return NULL;
1894     }
1895   if (pr->pcic != NULL)
1896     {
1897       /* second change before first one is done */
1898       GNUNET_break (0);
1899       return NULL;
1900     }
1901   irc = GNUNET_malloc (sizeof (struct GNUNET_CORE_InformationRequestContext));
1902   irc->h = h;
1903   irc->pr = pr;
1904   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1905                       sizeof (struct RequestInfoMessage));
1906   cm->cont = &change_preference_send_continuation;
1907   cm->cont_cls = irc;
1908   irc->cm = cm;
1909   rim = (struct RequestInfoMessage*) &cm[1];
1910   rim->header.size = htons (sizeof (struct RequestInfoMessage));
1911   rim->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO);
1912   rim->rim_id = htonl (pr->rim_id = h->rim_id_gen++);
1913   rim->limit_outbound = bw_out;
1914   rim->reserve_inbound = htonl (amount);
1915   rim->preference_change = GNUNET_htonll(preference);
1916   rim->peer = *peer;
1917 #if DEBUG_CORE
1918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919               "Queueing CHANGE PREFERENCE request\n");
1920 #endif
1921   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
1922                                     h->control_pending_tail,
1923                                     cm); 
1924   pr->pcic = info;
1925   pr->pcic_cls = info_cls;
1926   if (h->control_pending_head == cm)
1927     trigger_next_request (h, GNUNET_NO);
1928   return irc;
1929 }
1930
1931
1932 /**
1933  * Cancel request for getting information about a peer.
1934  * Note that an eventual change in preference, trust or bandwidth
1935  * assignment MAY have already been committed at the time, 
1936  * so cancelling a request is NOT sure to undo the original
1937  * request.  The original request may or may not still commit.
1938  * The only thing cancellation ensures is that the callback
1939  * from the original request will no longer be called.
1940  *
1941  * @param irc context returned by the original GNUNET_CORE_peer_get_info call
1942  */
1943 void
1944 GNUNET_CORE_peer_change_preference_cancel (struct GNUNET_CORE_InformationRequestContext *irc)
1945 {
1946   struct GNUNET_CORE_Handle *h = irc->h;
1947   struct PeerRecord *pr = irc->pr;
1948
1949   if (irc->cm != NULL)
1950     {
1951       GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1952                                    h->control_pending_tail,
1953                                    irc->cm);
1954       GNUNET_free (irc->cm);
1955     }
1956   pr->pcic = NULL;
1957   pr->pcic_cls = NULL;
1958   GNUNET_free (irc);
1959 }
1960
1961
1962 /* end of core_api.c */