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