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