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