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