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