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