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