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