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