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