hxing typemap
[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     h->me = m->my_identity;
874     if (NULL != (init = h->init))
875     {
876       /* mark so we don't call init on reconnect */
877       h->init = NULL;
878 #if DEBUG_CORE
879       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880                   "Connected to core service of peer `%s'.\n",
881                   GNUNET_i2s (&h->me));
882 #endif
883       init (h->cls, h, &h->me);
884     }
885     else
886     {
887 #if DEBUG_CORE
888       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889                   "Successfully reconnected to core service.\n");
890 #endif
891     }
892     /* fake 'connect to self' */
893     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &h->me.hashPubKey);
894     GNUNET_assert (pr == NULL);
895     pr = GNUNET_malloc (sizeof (struct PeerRecord));
896     pr->peer = h->me;
897     pr->ch = h;
898     GNUNET_assert (GNUNET_YES ==
899                    GNUNET_CONTAINER_multihashmap_put (h->peers,
900                                                       &h->me.hashPubKey, pr,
901                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
902     if (NULL != h->connects)
903       h->connects (h->cls, &h->me, NULL);
904     break;
905   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
906     if (msize < sizeof (struct ConnectNotifyMessage))
907     {
908       GNUNET_break (0);
909       reconnect_later (h);
910       return;
911     }
912     cnm = (const struct ConnectNotifyMessage *) msg;
913     ats_count = ntohl (cnm->ats_count);
914     if ((msize !=
915          sizeof (struct ConnectNotifyMessage) +
916          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
917         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
918          ntohl ((&cnm->ats)[ats_count].type)))
919     {
920       GNUNET_break (0);
921       reconnect_later (h);
922       return;
923     }
924 #if DEBUG_CORE
925     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
926                 "Received notification about connection from `%s'.\n",
927                 GNUNET_i2s (&cnm->peer));
928 #endif
929     if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity)))
930     {
931       /* connect to self!? */
932       GNUNET_break (0);
933       return;
934     }
935     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &cnm->peer.hashPubKey);
936     if (pr != NULL)
937     {
938       GNUNET_break (0);
939       reconnect_later (h);
940       return;
941     }
942     pr = GNUNET_malloc (sizeof (struct PeerRecord));
943     pr->peer = cnm->peer;
944     pr->ch = h;
945     GNUNET_assert (GNUNET_YES ==
946                    GNUNET_CONTAINER_multihashmap_put (h->peers,
947                                                       &cnm->peer.hashPubKey, pr,
948                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
949     if (NULL != h->connects)
950       h->connects (h->cls, &cnm->peer, &cnm->ats);
951     break;
952   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
953     if (msize != sizeof (struct DisconnectNotifyMessage))
954     {
955       GNUNET_break (0);
956       reconnect_later (h);
957       return;
958     }
959     dnm = (const struct DisconnectNotifyMessage *) msg;
960     if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity)))
961     {
962       /* connection to self!? */
963       GNUNET_break (0);
964       return;
965     }
966     GNUNET_break (0 == ntohl (dnm->reserved));
967 #if DEBUG_CORE
968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969                 "Received notification about disconnect from `%s'.\n",
970                 GNUNET_i2s (&dnm->peer));
971 #endif
972     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &dnm->peer.hashPubKey);
973     if (pr == NULL)
974     {
975       GNUNET_break (0);
976       reconnect_later (h);
977       return;
978     }
979     trigger = ((pr->prev != NULL) || (pr->next != NULL) ||
980                (h->ready_peer_head == pr));
981     disconnect_and_free_peer_entry (h, &dnm->peer.hashPubKey, pr);
982     if (trigger)
983       trigger_next_request (h, GNUNET_NO);
984     break;
985   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_STATUS_CHANGE:
986     if (NULL == h->status_events)
987     {
988       GNUNET_break (0);
989       return;
990     }
991     if (msize < sizeof (struct PeerStatusNotifyMessage))
992     {
993       GNUNET_break (0);
994       reconnect_later (h);
995       return;
996     }
997     psnm = (const struct PeerStatusNotifyMessage *) msg;
998     if (0 == memcmp (&h->me, &psnm->peer, sizeof (struct GNUNET_PeerIdentity)))
999     {
1000       /* self-change!? */
1001       GNUNET_break (0);
1002       return;
1003     }
1004     ats_count = ntohl (psnm->ats_count);
1005     if ((msize !=
1006          sizeof (struct PeerStatusNotifyMessage) +
1007          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)) ||
1008         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
1009          ntohl ((&psnm->ats)[ats_count].type)))
1010     {
1011       GNUNET_break (0);
1012       reconnect_later (h);
1013       return;
1014     }
1015 #if DEBUG_CORE > 1
1016     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1017                 "Received notification about status change by `%s'.\n",
1018                 GNUNET_i2s (&psnm->peer));
1019 #endif
1020     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &psnm->peer.hashPubKey);
1021     if (pr == NULL)
1022     {
1023       GNUNET_break (0);
1024       reconnect_later (h);
1025       return;
1026     }
1027     h->status_events (h->cls, &psnm->peer, psnm->bandwidth_in,
1028                       psnm->bandwidth_out,
1029                       GNUNET_TIME_absolute_ntoh (psnm->timeout), &psnm->ats);
1030     break;
1031   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
1032     if (msize < sizeof (struct NotifyTrafficMessage))
1033     {
1034       GNUNET_break (0);
1035       reconnect_later (h);
1036       return;
1037     }
1038     ntm = (const struct NotifyTrafficMessage *) msg;
1039
1040     ats_count = ntohl (ntm->ats_count);
1041     if ((msize <
1042          sizeof (struct NotifyTrafficMessage) +
1043          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) +
1044          sizeof (struct GNUNET_MessageHeader)) ||
1045         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
1046          ntohl ((&ntm->ats)[ats_count].type)))
1047     {
1048       GNUNET_break (0);
1049       reconnect_later (h);
1050       return;
1051     }
1052     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
1053 #if DEBUG_CORE
1054     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1055                 "Received message of type %u and size %u from peer `%4s'\n",
1056                 ntohs (em->type), ntohs (em->size), GNUNET_i2s (&ntm->peer));
1057 #endif
1058     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
1059     if (pr == NULL)
1060     {
1061       GNUNET_break (0);
1062       reconnect_later (h);
1063       return;
1064     }
1065     if ((GNUNET_NO == h->inbound_hdr_only) &&
1066         (msize !=
1067          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
1068          +ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)))
1069     {
1070       GNUNET_break (0);
1071       reconnect_later (h);
1072       return;
1073     }
1074     et = ntohs (em->type);
1075     for (hpos = 0; hpos < h->hcnt; hpos++)
1076     {
1077       mh = &h->handlers[hpos];
1078       if (mh->type != et)
1079         continue;
1080       if ((mh->expected_size != ntohs (em->size)) && (mh->expected_size != 0))
1081       {
1082         GNUNET_break (0);
1083         continue;
1084       }
1085       if (GNUNET_OK !=
1086           h->handlers[hpos].callback (h->cls, &ntm->peer, em, &ntm->ats))
1087       {
1088         /* error in processing, do not process other messages! */
1089         break;
1090       }
1091     }
1092     if (NULL != h->inbound_notify)
1093       h->inbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
1094     break;
1095   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
1096     if (msize < sizeof (struct NotifyTrafficMessage))
1097     {
1098       GNUNET_break (0);
1099       reconnect_later (h);
1100       return;
1101     }
1102     ntm = (const struct NotifyTrafficMessage *) msg;
1103     if (0 == memcmp (&h->me, &ntm->peer, sizeof (struct GNUNET_PeerIdentity)))
1104     {
1105       /* self-change!? */
1106       GNUNET_break (0);
1107       return;
1108     }
1109     ats_count = ntohl (ntm->ats_count);
1110     if ((msize <
1111          sizeof (struct NotifyTrafficMessage) +
1112          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) +
1113          sizeof (struct GNUNET_MessageHeader)) ||
1114         (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR !=
1115          ntohl ((&ntm->ats)[ats_count].type)))
1116     {
1117       GNUNET_break (0);
1118       reconnect_later (h);
1119       return;
1120     }
1121     em = (const struct GNUNET_MessageHeader *) &(&ntm->ats)[ats_count + 1];
1122     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &ntm->peer.hashPubKey);
1123     if (pr == NULL)
1124     {
1125       GNUNET_break (0);
1126       reconnect_later (h);
1127       return;
1128     }
1129 #if DEBUG_CORE
1130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131                 "Received notification about transmission to `%s'.\n",
1132                 GNUNET_i2s (&ntm->peer));
1133 #endif
1134     if ((GNUNET_NO == h->outbound_hdr_only) &&
1135         (msize !=
1136          ntohs (em->size) + sizeof (struct NotifyTrafficMessage) +
1137          ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information)))
1138     {
1139       GNUNET_break (0);
1140       reconnect_later (h);
1141       return;
1142     }
1143     if (NULL == h->outbound_notify)
1144     {
1145       GNUNET_break (0);
1146       break;
1147     }
1148     h->outbound_notify (h->cls, &ntm->peer, em, &ntm->ats);
1149     break;
1150   case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
1151     if (msize != sizeof (struct SendMessageReady))
1152     {
1153       GNUNET_break (0);
1154       reconnect_later (h);
1155       return;
1156     }
1157     smr = (const struct SendMessageReady *) msg;
1158     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &smr->peer.hashPubKey);
1159     if (pr == NULL)
1160     {
1161       GNUNET_break (0);
1162       reconnect_later (h);
1163       return;
1164     }
1165 #if DEBUG_CORE
1166     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1167                 "Received notification about transmission readiness to `%s'.\n",
1168                 GNUNET_i2s (&smr->peer));
1169 #endif
1170     if (pr->pending_head == NULL)
1171     {
1172       /* request must have been cancelled between the original request
1173        * and the response from core, ignore core's readiness */
1174       break;
1175     }
1176
1177     th = pr->pending_head;
1178     if (ntohs (smr->smr_id) != th->smr_id)
1179     {
1180       /* READY message is for expired or cancelled message,
1181        * ignore! (we should have already sent another request) */
1182       break;
1183     }
1184     if ((pr->prev != NULL) || (pr->next != NULL) || (h->ready_peer_head == pr))
1185     {
1186       /* we should not already be on the ready list... */
1187       GNUNET_break (0);
1188       reconnect_later (h);
1189       return;
1190     }
1191     GNUNET_CONTAINER_DLL_insert (h->ready_peer_head, h->ready_peer_tail, pr);
1192     trigger_next_request (h, GNUNET_NO);
1193     break;
1194   case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
1195     if (ntohs (msg->size) != sizeof (struct ConfigurationInfoMessage))
1196     {
1197       GNUNET_break (0);
1198       reconnect_later (h);
1199       return;
1200     }
1201     cim = (const struct ConfigurationInfoMessage *) msg;
1202     if (0 == memcmp (&h->me, &cim->peer, sizeof (struct GNUNET_PeerIdentity)))
1203     {
1204       /* self-change!? */
1205       GNUNET_break (0);
1206       return;
1207     }
1208 #if DEBUG_CORE
1209     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1210                 "Received notification about configuration update for `%s' with RIM %u.\n",
1211                 GNUNET_i2s (&cim->peer), (unsigned int) ntohl (cim->rim_id));
1212 #endif
1213     pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &cim->peer.hashPubKey);
1214     if (pr == NULL)
1215     {
1216       GNUNET_break (0);
1217       reconnect_later (h);
1218       return;
1219     }
1220     if (pr->rim_id != ntohl (cim->rim_id))
1221     {
1222 #if DEBUG_CORE
1223       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1224                   "Reservation ID mismatch in notification...\n");
1225 #endif
1226       break;
1227     }
1228     pcic = pr->pcic;
1229     pr->pcic = NULL;
1230     GNUNET_free_non_null (pr->pcic_ptr);
1231     pr->pcic_ptr = NULL;
1232     if (pcic != NULL)
1233       pcic (pr->pcic_cls, &pr->peer, cim->bw_out, ntohl (cim->reserved_amount),
1234             GNUNET_TIME_relative_ntoh (cim->reserve_delay),
1235             GNUNET_ntohll (cim->preference));
1236     break;
1237   default:
1238     reconnect_later (h);
1239     return;
1240   }
1241   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1242                          GNUNET_TIME_UNIT_FOREVER_REL);
1243 }
1244
1245
1246 /**
1247  * Task executed once we are done transmitting the INIT message.
1248  * Starts our 'receive' loop.
1249  *
1250  * @param cls the 'struct GNUNET_CORE_Handle'
1251  * @param success were we successful
1252  */
1253 static void
1254 init_done_task (void *cls, int success)
1255 {
1256   struct GNUNET_CORE_Handle *h = cls;
1257
1258   if (success == GNUNET_SYSERR)
1259     return;                     /* shutdown */
1260   if (success == GNUNET_NO)
1261   {
1262 #if DEBUG_CORE
1263     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264                 "Failed to exchange INIT with core, retrying\n");
1265 #endif
1266     if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1267       reconnect_later (h);
1268     return;
1269   }
1270   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1271                          GNUNET_TIME_UNIT_FOREVER_REL);
1272 }
1273
1274
1275 /**
1276  * Our current client connection went down.  Clean it up
1277  * and try to reconnect!
1278  *
1279  * @param h our handle to the core service
1280  */
1281 static void
1282 reconnect (struct GNUNET_CORE_Handle *h)
1283 {
1284   struct ControlMessage *cm;
1285   struct InitMessage *init;
1286   uint32_t opt;
1287   uint16_t msize;
1288   uint16_t *ts;
1289   unsigned int hpos;
1290
1291 #if DEBUG_CORE
1292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting to CORE service\n");
1293 #endif
1294   GNUNET_assert (h->client == NULL);
1295   GNUNET_assert (h->currently_down == GNUNET_YES);
1296   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1297   if (h->client == NULL)
1298   {
1299     reconnect_later (h);
1300     return;
1301   }
1302   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1303   cm = GNUNET_malloc (sizeof (struct ControlMessage) + msize);
1304   cm->cont = &init_done_task;
1305   cm->cont_cls = h;
1306   init = (struct InitMessage *) &cm[1];
1307   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1308   init->header.size = htons (msize);
1309   opt = GNUNET_CORE_OPTION_SEND_CONNECT | GNUNET_CORE_OPTION_SEND_DISCONNECT;
1310   if (h->status_events != NULL)
1311     opt |= GNUNET_CORE_OPTION_SEND_STATUS_CHANGE;
1312   if (h->inbound_notify != NULL)
1313   {
1314     if (h->inbound_hdr_only)
1315       opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1316     else
1317       opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1318   }
1319   if (h->outbound_notify != NULL)
1320   {
1321     if (h->outbound_hdr_only)
1322       opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1323     else
1324       opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1325   }
1326   init->options = htonl (opt);
1327   ts = (uint16_t *) & init[1];
1328   for (hpos = 0; hpos < h->hcnt; hpos++)
1329     ts[hpos] = htons (h->handlers[hpos].type);
1330   GNUNET_CONTAINER_DLL_insert (h->control_pending_head, h->control_pending_tail,
1331                                cm);
1332   trigger_next_request (h, GNUNET_YES);
1333 }
1334
1335
1336
1337 /**
1338  * Connect to the core service.  Note that the connection may
1339  * complete (or fail) asynchronously.
1340  *
1341  * @param cfg configuration to use
1342  * @param queue_size size of the per-peer message queue
1343  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1344  * @param init callback to call on timeout or once we have successfully
1345  *        connected to the core service; note that timeout is only meaningful if init is not NULL
1346  * @param connects function to call on peer connect, can be NULL
1347  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1348  * @param status_events function to call on changes to peer connection status, can be NULL
1349  * @param inbound_notify function to call for all inbound messages, can be NULL
1350  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
1351  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1352  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
1353  * @param outbound_notify function to call for all outbound messages, can be NULL
1354  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
1355  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1356  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
1357  * @param handlers callbacks for messages we care about, NULL-terminated
1358  * @return handle to the core service (only useful for disconnect until 'init' is called);
1359  *                NULL on error (in this case, init is never called)
1360  */
1361 struct GNUNET_CORE_Handle *
1362 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1363                      unsigned int queue_size, void *cls,
1364                      GNUNET_CORE_StartupCallback init,
1365                      GNUNET_CORE_ConnectEventHandler connects,
1366                      GNUNET_CORE_DisconnectEventHandler disconnects,
1367                      GNUNET_CORE_PeerStatusEventHandler status_events,
1368                      GNUNET_CORE_MessageCallback inbound_notify,
1369                      int inbound_hdr_only,
1370                      GNUNET_CORE_MessageCallback outbound_notify,
1371                      int outbound_hdr_only,
1372                      const struct GNUNET_CORE_MessageHandler *handlers)
1373 {
1374   struct GNUNET_CORE_Handle *h;
1375
1376   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
1377   h->cfg = cfg;
1378   h->queue_size = queue_size;
1379   h->cls = cls;
1380   h->init = init;
1381   h->connects = connects;
1382   h->disconnects = disconnects;
1383   h->status_events = status_events;
1384   h->inbound_notify = inbound_notify;
1385   h->outbound_notify = outbound_notify;
1386   h->inbound_hdr_only = inbound_hdr_only;
1387   h->outbound_hdr_only = outbound_hdr_only;
1388   h->handlers = handlers;
1389   h->hcnt = 0;
1390   h->currently_down = GNUNET_YES;
1391   h->peers = GNUNET_CONTAINER_multihashmap_create (128);
1392   h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1393   if (NULL != handlers)
1394     while (handlers[h->hcnt].callback != NULL)
1395       h->hcnt++;
1396   GNUNET_assert (h->hcnt <
1397                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1398                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1399 #if DEBUG_CORE
1400   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n");
1401 #endif
1402   reconnect (h);
1403   return h;
1404 }
1405
1406
1407 /**
1408  * Disconnect from the core service.  This function can only
1409  * be called *after* all pending 'GNUNET_CORE_notify_transmit_ready'
1410  * requests have been explicitly canceled.
1411  *
1412  * @param handle connection to core to disconnect
1413  */
1414 void
1415 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1416 {
1417   struct ControlMessage *cm;
1418
1419 #if DEBUG_CORE
1420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n");
1421 #endif
1422   if (handle->cth != NULL)
1423   {
1424     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1425     handle->cth = NULL;
1426   }
1427   while (NULL != (cm = handle->control_pending_head))
1428   {
1429     GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1430                                  handle->control_pending_tail, cm);
1431     if (cm->th != NULL)
1432       cm->th->cm = NULL;
1433     if (cm->cont != NULL)
1434       cm->cont (cm->cont_cls, GNUNET_SYSERR);
1435     GNUNET_free (cm);
1436   }
1437   if (handle->client != NULL)
1438   {
1439     GNUNET_CLIENT_disconnect (handle->client, GNUNET_NO);
1440     handle->client = NULL;
1441   }
1442   GNUNET_CONTAINER_multihashmap_iterate (handle->peers,
1443                                          &disconnect_and_free_peer_entry,
1444                                          handle);
1445   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1446   {
1447     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1448     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1449   }
1450   GNUNET_CONTAINER_multihashmap_destroy (handle->peers);
1451   handle->peers = NULL;
1452   GNUNET_break (handle->ready_peer_head == NULL);
1453   GNUNET_free (handle);
1454 }
1455
1456
1457 /**
1458  * Task that calls 'request_next_transmission'.
1459  *
1460  * @param cls the 'struct PeerRecord*'
1461  * @param tc scheduler context
1462  */
1463 static void
1464 run_request_next_transmission (void *cls,
1465                                const struct GNUNET_SCHEDULER_TaskContext *tc)
1466 {
1467   struct PeerRecord *pr = cls;
1468
1469   pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1470   request_next_transmission (pr);
1471 }
1472
1473
1474 /**
1475  * Ask the core to call "notify" once it is ready to transmit the
1476  * given number of bytes to the specified "target".    Must only be
1477  * called after a connection to the respective peer has been
1478  * established (and the client has been informed about this).
1479  *
1480  * @param handle connection to core service
1481  * @param cork is corking allowed for this transmission?
1482  * @param priority how important is the message?
1483  * @param maxdelay how long can the message wait?
1484  * @param target who should receive the message,
1485  *        use NULL for this peer (loopback)
1486  * @param notify_size how many bytes of buffer space does notify want?
1487  * @param notify function to call when buffer space is available
1488  * @param notify_cls closure for notify
1489  * @return non-NULL if the notify callback was queued,
1490  *         NULL if we can not even queue the request (insufficient
1491  *         memory); if NULL is returned, "notify" will NOT be called.
1492  */
1493 struct GNUNET_CORE_TransmitHandle *
1494 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle, int cork,
1495                                    uint32_t priority,
1496                                    struct GNUNET_TIME_Relative maxdelay,
1497                                    const struct GNUNET_PeerIdentity *target,
1498                                    size_t notify_size,
1499                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1500                                    void *notify_cls)
1501 {
1502   struct PeerRecord *pr;
1503   struct GNUNET_CORE_TransmitHandle *th;
1504   struct GNUNET_CORE_TransmitHandle *pos;
1505   struct GNUNET_CORE_TransmitHandle *prev;
1506   struct GNUNET_CORE_TransmitHandle *minp;
1507
1508   pr = GNUNET_CONTAINER_multihashmap_get (handle->peers, &target->hashPubKey);
1509   if (NULL == pr)
1510   {
1511     /* attempt to send to peer that is not connected */
1512     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1513                 "Attempting to send to peer `%s' from peer `%s', but not connected!\n",
1514                 GNUNET_i2s (target), GNUNET_h2s (&handle->me.hashPubKey));
1515     GNUNET_break (0);
1516     return NULL;
1517   }
1518   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1519                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1520   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1521   th->peer = pr;
1522   GNUNET_assert (NULL != notify);
1523   th->get_message = notify;
1524   th->get_message_cls = notify_cls;
1525   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1526   th->priority = priority;
1527   th->msize = notify_size;
1528   th->cork = cork;
1529   /* bound queue size */
1530   if (pr->queue_size == handle->queue_size)
1531   {
1532     /* find lowest-priority entry, but skip the head of the list */
1533     minp = pr->pending_head->next;
1534     prev = minp;
1535     while (prev != NULL)
1536     {
1537       if (prev->priority < minp->priority)
1538         minp = prev;
1539       prev = prev->next;
1540     }
1541     if (minp == NULL)
1542     {
1543       GNUNET_break (handle->queue_size != 0);
1544       GNUNET_break (pr->queue_size == 1);
1545       GNUNET_free (th);
1546 #if DEBUG_CORE
1547       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1548                   "Dropping transmission request: cannot drop queue head and limit is one\n");
1549 #endif
1550       return NULL;
1551     }
1552     if (priority <= minp->priority)
1553     {
1554 #if DEBUG_CORE
1555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1556                   "Dropping transmission request: priority too low\n");
1557 #endif
1558       GNUNET_free (th);
1559       return NULL;              /* priority too low */
1560     }
1561     GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, minp);
1562     pr->queue_size--;
1563     GNUNET_assert (0 == minp->get_message (minp->get_message_cls, 0, NULL));
1564     GNUNET_free (minp);
1565   }
1566
1567   /* Order entries by deadline, but SKIP 'HEAD' if
1568    * we're in the 'ready_peer_*' DLL */
1569   pos = pr->pending_head;
1570   if ((pr->prev != NULL) || (pr->next != NULL) ||
1571       (pr == handle->ready_peer_head))
1572   {
1573     GNUNET_assert (pos != NULL);
1574     pos = pos->next;            /* skip head */
1575   }
1576
1577   /* insertion sort */
1578   prev = pos;
1579   while ((pos != NULL) && (pos->timeout.abs_value < th->timeout.abs_value))
1580   {
1581     prev = pos;
1582     pos = pos->next;
1583   }
1584   GNUNET_CONTAINER_DLL_insert_after (pr->pending_head, pr->pending_tail, prev,
1585                                      th);
1586   pr->queue_size++;
1587   /* was the request queue previously empty? */
1588 #if DEBUG_CORE
1589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmission request added to queue\n");
1590 #endif
1591   if ((pr->pending_head == th) && (pr->ntr_task == GNUNET_SCHEDULER_NO_TASK) &&
1592       (pr->next == NULL) && (pr->prev == NULL) &&
1593       (handle->ready_peer_head != pr))
1594     pr->ntr_task =
1595         GNUNET_SCHEDULER_add_now (&run_request_next_transmission, pr);
1596   return th;
1597 }
1598
1599
1600 /**
1601  * Cancel the specified transmission-ready notification.
1602  *
1603  * @param th handle that was returned by "notify_transmit_ready".
1604  */
1605 void
1606 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle *th)
1607 {
1608   struct PeerRecord *pr = th->peer;
1609   struct GNUNET_CORE_Handle *h = pr->ch;
1610   int was_head;
1611
1612   was_head = (pr->pending_head == th);
1613   GNUNET_CONTAINER_DLL_remove (pr->pending_head, pr->pending_tail, th);
1614   pr->queue_size--;
1615   if (th->cm != NULL)
1616   {
1617     /* we're currently in the control queue, remove */
1618     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1619                                  h->control_pending_tail, th->cm);
1620     GNUNET_free (th->cm);
1621   }
1622   GNUNET_free (th);
1623   if (was_head)
1624   {
1625     if ((pr->prev != NULL) || (pr->next != NULL) || (pr == h->ready_peer_head))
1626     {
1627       /* the request that was 'approved' by core was
1628        * canceled before it could be transmitted; remove
1629        * us from the 'ready' list */
1630       GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
1631     }
1632     request_next_transmission (pr);
1633   }
1634 }
1635
1636
1637 /* ****************** GNUNET_CORE_peer_change_preference ******************** */
1638
1639
1640 struct GNUNET_CORE_InformationRequestContext
1641 {
1642
1643   /**
1644    * Our connection to the service.
1645    */
1646   struct GNUNET_CORE_Handle *h;
1647
1648   /**
1649    * Link to control message, NULL if CM was sent.
1650    */
1651   struct ControlMessage *cm;
1652
1653   /**
1654    * Link to peer record.
1655    */
1656   struct PeerRecord *pr;
1657 };
1658
1659
1660 /**
1661  * CM was sent, remove link so we don't double-free.
1662  *
1663  * @param cls the 'struct GNUNET_CORE_InformationRequestContext'
1664  * @param success were we successful?
1665  */
1666 static void
1667 change_preference_send_continuation (void *cls, int success)
1668 {
1669   struct GNUNET_CORE_InformationRequestContext *irc = cls;
1670
1671   irc->cm = NULL;
1672 }
1673
1674
1675 /**
1676  * Obtain statistics and/or change preferences for the given peer.
1677  *
1678  * @param h core handle
1679  * @param peer identifies the peer
1680  * @param timeout after how long should we give up (and call "info" with NULL
1681  *                for "peer" to signal an error)?
1682  * @param bw_out set to the current bandwidth limit (sending) for this peer,
1683  *                caller should set "bw_out" to "-1" to avoid changing
1684  *                the current value; otherwise "bw_out" will be lowered to
1685  *                the specified value; passing a pointer to "0" can be used to force
1686  *                us to disconnect from the peer; "bw_out" might not increase
1687  *                as specified since the upper bound is generally
1688  *                determined by the other peer!
1689  * @param amount reserve N bytes for receiving, negative
1690  *                amounts can be used to undo a (recent) reservation;
1691  * @param preference increase incoming traffic share preference by this amount;
1692  *                in the absence of "amount" reservations, we use this
1693  *                preference value to assign proportional bandwidth shares
1694  *                to all connected peers
1695  * @param info function to call with the resulting configuration information
1696  * @param info_cls closure for info
1697  * @return NULL on error
1698  */
1699 struct GNUNET_CORE_InformationRequestContext *
1700 GNUNET_CORE_peer_change_preference (struct GNUNET_CORE_Handle *h,
1701                                     const struct GNUNET_PeerIdentity *peer,
1702                                     struct GNUNET_TIME_Relative timeout,
1703                                     struct GNUNET_BANDWIDTH_Value32NBO bw_out,
1704                                     int32_t amount, uint64_t preference,
1705                                     GNUNET_CORE_PeerConfigurationInfoCallback
1706                                     info, void *info_cls)
1707 {
1708   struct GNUNET_CORE_InformationRequestContext *irc;
1709   struct PeerRecord *pr;
1710   struct RequestInfoMessage *rim;
1711   struct ControlMessage *cm;
1712
1713   pr = GNUNET_CONTAINER_multihashmap_get (h->peers, &peer->hashPubKey);
1714   if (NULL == pr)
1715   {
1716     /* attempt to change preference on peer that is not connected */
1717     GNUNET_assert (0);
1718     return NULL;
1719   }
1720   if (pr->pcic != NULL)
1721   {
1722     /* second change before first one is done */
1723     GNUNET_break (0);
1724     return NULL;
1725   }
1726   irc = GNUNET_malloc (sizeof (struct GNUNET_CORE_InformationRequestContext));
1727   irc->h = h;
1728   irc->pr = pr;
1729   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
1730                       sizeof (struct RequestInfoMessage));
1731   cm->cont = &change_preference_send_continuation;
1732   cm->cont_cls = irc;
1733   irc->cm = cm;
1734   rim = (struct RequestInfoMessage *) &cm[1];
1735   rim->header.size = htons (sizeof (struct RequestInfoMessage));
1736   rim->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_INFO);
1737   rim->rim_id = htonl (pr->rim_id = h->rim_id_gen++);
1738   rim->limit_outbound = bw_out;
1739   rim->reserve_inbound = htonl (amount);
1740   rim->preference_change = GNUNET_htonll (preference);
1741   rim->peer = *peer;
1742 #if DEBUG_CORE
1743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1744               "Queueing CHANGE PREFERENCE request for peer `%s' with RIM %u\n",
1745               GNUNET_i2s (peer), (unsigned int) pr->rim_id);
1746 #endif
1747   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
1748                                     h->control_pending_tail, cm);
1749   pr->pcic = info;
1750   pr->pcic_cls = info_cls;
1751   pr->pcic_ptr = irc;           /* for free'ing irc */
1752   if (NULL != h->client)
1753     trigger_next_request (h, GNUNET_NO);
1754   return irc;
1755 }
1756
1757
1758 /**
1759  * Cancel request for getting information about a peer.
1760  * Note that an eventual change in preference, trust or bandwidth
1761  * assignment MAY have already been committed at the time,
1762  * so cancelling a request is NOT sure to undo the original
1763  * request.  The original request may or may not still commit.
1764  * The only thing cancellation ensures is that the callback
1765  * from the original request will no longer be called.
1766  *
1767  * @param irc context returned by the original GNUNET_CORE_peer_get_info call
1768  */
1769 void
1770 GNUNET_CORE_peer_change_preference_cancel (struct
1771                                            GNUNET_CORE_InformationRequestContext
1772                                            *irc)
1773 {
1774   struct GNUNET_CORE_Handle *h = irc->h;
1775   struct PeerRecord *pr = irc->pr;
1776
1777   GNUNET_assert (pr->pcic_ptr == irc);
1778   if (irc->cm != NULL)
1779   {
1780     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1781                                  h->control_pending_tail, irc->cm);
1782     GNUNET_free (irc->cm);
1783   }
1784   pr->pcic = NULL;
1785   pr->pcic_cls = NULL;
1786   pr->pcic_ptr = NULL;
1787   GNUNET_free (irc);
1788 }
1789
1790
1791 /* end of core_api.c */