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