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