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