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