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