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