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