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