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