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