Check that you are not present in trail twice
[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_util_lib.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_core_service.h"
31 #include "core.h"
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "core-api",__VA_ARGS__)
34
35
36 /**
37  * Handle for a transmission request.
38  */
39 struct GNUNET_CORE_TransmitHandle
40 {
41
42   /**
43    * Corresponding peer record.
44    */
45   struct PeerRecord *peer;
46
47   /**
48    * Corresponding SEND_REQUEST message.  Only non-NULL
49    * while SEND_REQUEST message is pending.
50    */
51   struct ControlMessage *cm;
52
53   /**
54    * Function that will be called to get the actual request
55    * (once we are ready to transmit this request to the core).
56    * The function will be called with a NULL buffer to signal
57    * timeout.
58    */
59   GNUNET_CONNECTION_TransmitReadyNotify get_message;
60
61   /**
62    * Closure for get_message.
63    */
64   void *get_message_cls;
65
66   /**
67    * Timeout for this handle.
68    */
69   struct GNUNET_TIME_Absolute timeout;
70
71   /**
72    * How important is this message?
73    */
74   enum GNUNET_CORE_Priority priority;
75
76   /**
77    * Size of this request.
78    */
79   uint16_t msize;
80
81   /**
82    * Send message request ID for this request.
83    */
84   uint16_t smr_id;
85
86   /**
87    * Is corking allowed?
88    */
89   int cork;
90
91 };
92
93
94 /**
95  * Information we track for each peer.
96  */
97 struct PeerRecord
98 {
99
100   /**
101    * We generally do NOT keep peer records in a DLL; this
102    * DLL is only used IF this peer's 'pending_head' message
103    * is ready for transmission.
104    */
105   struct PeerRecord *prev;
106
107   /**
108    * We generally do NOT keep peer records in a DLL; this
109    * DLL is only used IF this peer's 'pending_head' message
110    * is ready for transmission.
111    */
112   struct PeerRecord *next;
113
114   /**
115    * Peer the record is about.
116    */
117   struct GNUNET_PeerIdentity peer;
118
119   /**
120    * Corresponding core handle.
121    */
122   struct GNUNET_CORE_Handle *ch;
123
124   /**
125    * Pending request, if any.  'th->peer' is set to NULL if the
126    * request is not active.
127    */
128   struct GNUNET_CORE_TransmitHandle th;
129
130   /**
131    * ID of timeout task for the 'pending_head' handle
132    * which is the one with the smallest timeout.
133    */
134   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
135
136   /**
137    * ID of task to run 'next_request_transmission'.
138    */
139   GNUNET_SCHEDULER_TaskIdentifier ntr_task;
140
141   /**
142    * SendMessageRequest ID generator for this peer.
143    */
144   uint16_t smr_id_gen;
145
146 };
147
148 struct CoreMQState
149 {
150   struct GNUNET_PeerIdentity target;
151   struct GNUNET_CORE_Handle *core;
152   struct GNUNET_CORE_TransmitHandle *th;
153 };
154
155
156 /**
157  * Type of function called upon completion.
158  *
159  * @param cls closure
160  * @param success GNUNET_OK on success (which for request_connect
161  *        ONLY means that we transmitted the connect request to CORE,
162  *        it does not mean that we are actually now connected!);
163  *        GNUNET_NO on timeout,
164  *        GNUNET_SYSERR if core was shut down
165  */
166 typedef void (*GNUNET_CORE_ControlContinuation) (void *cls, int success);
167
168
169 /**
170  * Entry in a doubly-linked list of control messages to be transmitted
171  * to the core service.  Control messages include traffic allocation,
172  * connection requests and of course our initial 'init' request.
173  *
174  * The actual message is allocated at the end of this struct.
175  */
176 struct ControlMessage
177 {
178   /**
179    * This is a doubly-linked list.
180    */
181   struct ControlMessage *next;
182
183   /**
184    * This is a doubly-linked list.
185    */
186   struct ControlMessage *prev;
187
188   /**
189    * Function to run after transmission failed/succeeded.
190    */
191   GNUNET_CORE_ControlContinuation cont;
192
193   /**
194    * Closure for @e cont.
195    */
196   void *cont_cls;
197
198   /**
199    * Transmit handle (if one is associated with this ControlMessage), or NULL.
200    */
201   struct GNUNET_CORE_TransmitHandle *th;
202 };
203
204
205
206 /**
207  * Context for the core service connection.
208  */
209 struct GNUNET_CORE_Handle
210 {
211
212   /**
213    * Configuration we're using.
214    */
215   const struct GNUNET_CONFIGURATION_Handle *cfg;
216
217   /**
218    * Closure for the various callbacks.
219    */
220   void *cls;
221
222   /**
223    * Function to call once we've handshaked with the core service.
224    */
225   GNUNET_CORE_StartupCallback init;
226
227   /**
228    * Function to call whenever we're notified about a peer connecting.
229    */
230   GNUNET_CORE_ConnectEventHandler connects;
231
232   /**
233    * Function to call whenever we're notified about a peer disconnecting.
234    */
235   GNUNET_CORE_DisconnectEventHandler disconnects;
236
237   /**
238    * Function to call whenever we receive an inbound message.
239    */
240   GNUNET_CORE_MessageCallback inbound_notify;
241
242   /**
243    * Function to call whenever we receive an outbound message.
244    */
245   GNUNET_CORE_MessageCallback outbound_notify;
246
247   /**
248    * Function handlers for messages of particular type.
249    */
250   const struct GNUNET_CORE_MessageHandler *handlers;
251
252   /**
253    * Our connection to the service.
254    */
255   struct GNUNET_CLIENT_Connection *client;
256
257   /**
258    * Handle for our current transmission request.
259    */
260   struct GNUNET_CLIENT_TransmitHandle *cth;
261
262   /**
263    * Head of doubly-linked list of pending requests.
264    */
265   struct ControlMessage *control_pending_head;
266
267   /**
268    * Tail of doubly-linked list of pending requests.
269    */
270   struct ControlMessage *control_pending_tail;
271
272   /**
273    * Head of doubly-linked list of peers that are core-approved
274    * to send their next message.
275    */
276   struct PeerRecord *ready_peer_head;
277
278   /**
279    * Tail of doubly-linked list of peers that are core-approved
280    * to send their next message.
281    */
282   struct PeerRecord *ready_peer_tail;
283
284   /**
285    * Hash map listing all of the peers that we are currently
286    * connected to.
287    */
288   struct GNUNET_CONTAINER_MultiPeerMap *peers;
289
290   /**
291    * Identity of this peer.
292    */
293   struct GNUNET_PeerIdentity me;
294
295   /**
296    * ID of reconnect task (if any).
297    */
298   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
299
300   /**
301    * Current delay we use for re-trying to connect to core.
302    */
303   struct GNUNET_TIME_Relative retry_backoff;
304
305   /**
306    * Number of entries in the handlers array.
307    */
308   unsigned int hcnt;
309
310   /**
311    * For inbound notifications without a specific handler, do
312    * we expect to only receive headers?
313    */
314   int inbound_hdr_only;
315
316   /**
317    * For outbound notifications without a specific handler, do
318    * we expect to only receive headers?
319    */
320   int outbound_hdr_only;
321
322   /**
323    * Are we currently disconnected and hence unable to forward
324    * requests?
325    */
326   int currently_down;
327
328 };
329
330
331 /**
332  * Our current client connection went down.  Clean it up
333  * and try to reconnect!
334  *
335  * @param h our handle to the core service
336  */
337 static void
338 reconnect (struct GNUNET_CORE_Handle *h);
339
340
341 /**
342  * Task schedule to try to re-connect to core.
343  *
344  * @param cls the `struct GNUNET_CORE_Handle`
345  * @param tc task context
346  */
347 static void
348 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
349 {
350   struct GNUNET_CORE_Handle *h = cls;
351
352   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
353   LOG (GNUNET_ERROR_TYPE_DEBUG,
354        "Connecting to CORE service after delay\n");
355   reconnect (h);
356 }
357
358
359 /**
360  * Notify clients about disconnect and free
361  * the entry for connected peer.
362  *
363  * @param cls the `struct GNUNET_CORE_Handle *`
364  * @param key the peer identity (not used)
365  * @param value the `struct PeerRecord` to free.
366  * @return #GNUNET_YES (continue)
367  */
368 static int
369 disconnect_and_free_peer_entry (void *cls,
370                                 const struct GNUNET_PeerIdentity *key,
371                                 void *value)
372 {
373   struct GNUNET_CORE_Handle *h = cls;
374   struct GNUNET_CORE_TransmitHandle *th;
375   struct PeerRecord *pr = value;
376
377   if (GNUNET_SCHEDULER_NO_TASK != pr->timeout_task)
378   {
379     GNUNET_SCHEDULER_cancel (pr->timeout_task);
380     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
381   }
382   if (GNUNET_SCHEDULER_NO_TASK != pr->ntr_task)
383   {
384     GNUNET_SCHEDULER_cancel (pr->ntr_task);
385     pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
386   }
387   if ((NULL != pr->prev) || (NULL != pr->next) || (h->ready_peer_head == pr))
388     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
389   if (NULL != h->disconnects)
390     h->disconnects (h->cls, &pr->peer);
391   /* all requests should have been cancelled, clean up anyway, just in case */
392   th = &pr->th;
393   if (NULL != th->peer)
394   {
395     GNUNET_break (0);
396     th->peer = NULL;
397     if (NULL != th->cm)
398       th->cm->th = NULL;
399   }
400   /* done with 'voluntary' cleanups, now on to normal freeing */
401   GNUNET_assert (GNUNET_YES ==
402                  GNUNET_CONTAINER_multipeermap_remove (h->peers, key, pr));
403   GNUNET_assert (pr->ch == h);
404   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pr->timeout_task);
405   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pr->ntr_task);
406   GNUNET_free (pr);
407   return GNUNET_YES;
408 }
409
410
411 /**
412  * Close down any existing connection to the CORE service and
413  * try re-establishing it later.
414  *
415  * @param h our handle
416  */
417 static void
418 reconnect_later (struct GNUNET_CORE_Handle *h)
419 {
420   struct ControlMessage *cm;
421   struct PeerRecord *pr;
422
423   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->reconnect_task);
424   if (NULL != h->cth)
425   {
426     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
427     h->cth = NULL;
428   }
429   if (NULL != h->client)
430   {
431     GNUNET_CLIENT_disconnect (h->client);
432     h->client = NULL;
433   }
434   h->currently_down = GNUNET_YES;
435   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
436   h->reconnect_task =
437       GNUNET_SCHEDULER_add_delayed (h->retry_backoff,
438                                     &reconnect_task, h);
439   while (NULL != (cm = h->control_pending_head))
440   {
441     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
442                                  h->control_pending_tail, cm);
443     if (NULL != cm->th)
444       cm->th->cm = NULL;
445     if (NULL != cm->cont)
446       cm->cont (cm->cont_cls, GNUNET_NO);
447     GNUNET_free (cm);
448   }
449   GNUNET_CONTAINER_multipeermap_iterate (h->peers,
450                                          &disconnect_and_free_peer_entry, h);
451   while (NULL != (pr = h->ready_peer_head))
452     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
453   GNUNET_assert (h->control_pending_head == NULL);
454   h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff);
455 }
456
457
458 /**
459  * Check the list of pending requests, send the next
460  * one to the core.
461  *
462  * @param h core handle
463  * @param ignore_currently_down transmit message even if not initialized?
464  */
465 static void
466 trigger_next_request (struct GNUNET_CORE_Handle *h, int ignore_currently_down);
467
468
469 /**
470  * The given request hit its timeout.  Remove from the
471  * doubly-linked list and call the respective continuation.
472  *
473  * @param cls the transmit handle of the request that timed out
474  * @param tc context, can be NULL (!)
475  */
476 static void
477 transmission_timeout (void *cls,
478                       const struct GNUNET_SCHEDULER_TaskContext *tc);
479
480
481 /**
482  * Send a control message to the peer asking for transmission
483  * of the message in the given peer record.
484  *
485  * @param pr peer to request transmission to
486  */
487 static void
488 request_next_transmission (struct PeerRecord *pr)
489 {
490   struct GNUNET_CORE_Handle *h = pr->ch;
491   struct ControlMessage *cm;
492   struct SendMessageRequest *smr;
493   struct GNUNET_CORE_TransmitHandle *th;
494
495   if (pr->timeout_task != GNUNET_SCHEDULER_NO_TASK)
496   {
497     GNUNET_SCHEDULER_cancel (pr->timeout_task);
498     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
499   }
500   th = &pr->th;
501   if (NULL == th->peer)
502   {
503     trigger_next_request (h, GNUNET_NO);
504     return;
505   }
506   if (th->cm != NULL)
507     return;                     /* already done */
508   GNUNET_assert (pr->prev == NULL);
509   GNUNET_assert (pr->next == NULL);
510   pr->timeout_task =
511       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
512                                     (th->timeout), &transmission_timeout, pr);
513   cm = GNUNET_malloc (sizeof (struct ControlMessage) +
514                       sizeof (struct SendMessageRequest));
515   th->cm = cm;
516   cm->th = th;
517   smr = (struct SendMessageRequest *) &cm[1];
518   smr->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST);
519   smr->header.size = htons (sizeof (struct SendMessageRequest));
520   smr->priority = htonl ((uint32_t) th->priority);
521   smr->deadline = GNUNET_TIME_absolute_hton (th->timeout);
522   smr->peer = pr->peer;
523   smr->reserved = htonl (0);
524   smr->size = htons (th->msize);
525   smr->smr_id = htons (th->smr_id = pr->smr_id_gen++);
526   GNUNET_CONTAINER_DLL_insert_tail (h->control_pending_head,
527                                     h->control_pending_tail, cm);
528   LOG (GNUNET_ERROR_TYPE_DEBUG,
529        "Adding SEND REQUEST for peer `%s' to message queue\n",
530        GNUNET_i2s (&pr->peer));
531   trigger_next_request (h, GNUNET_NO);
532 }
533
534
535 /**
536  * The given request hit its timeout.  Remove from the
537  * doubly-linked list and call the respective continuation.
538  *
539  * @param cls the transmit handle of the request that timed out
540  * @param tc context, can be NULL (!)
541  */
542 static void
543 transmission_timeout (void *cls,
544                       const struct GNUNET_SCHEDULER_TaskContext *tc)
545 {
546   struct PeerRecord *pr = cls;
547   struct GNUNET_CORE_Handle *h = pr->ch;
548   struct GNUNET_CORE_TransmitHandle *th;
549
550   pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
551   if (GNUNET_SCHEDULER_NO_TASK != pr->ntr_task)
552   {
553     GNUNET_SCHEDULER_cancel (pr->ntr_task);
554     pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
555   }
556   th = &pr->th;
557   th->peer = NULL;
558   if ((NULL != pr->prev) || (NULL != pr->next) || (pr == h->ready_peer_head))
559   {
560     /* the request that was 'approved' by core was
561      * canceled before it could be transmitted; remove
562      * us from the 'ready' list */
563     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
564   }
565   if (NULL != th->cm)
566   {
567      /* we're currently in the control queue, remove */
568     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
569                                  h->control_pending_tail, th->cm);
570     GNUNET_free (th->cm);
571   }
572   LOG (GNUNET_ERROR_TYPE_DEBUG,
573        "Signalling timeout of request for transmission to peer `%s' via CORE\n",
574        GNUNET_i2s (&pr->peer));
575   trigger_next_request (h, GNUNET_NO);
576
577   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
578 }
579
580
581 /**
582  * Transmit the next message to the core service.
583  *
584  * @param cls closure with the `struct GNUNET_CORE_Handle`
585  * @param size number of bytes available in @a buf
586  * @param buf where the callee should write the message
587  * @return number of bytes written to @a buf
588  */
589 static size_t
590 transmit_message (void *cls, size_t size, void *buf)
591 {
592   struct GNUNET_CORE_Handle *h = cls;
593   struct ControlMessage *cm;
594   struct GNUNET_CORE_TransmitHandle *th;
595   struct PeerRecord *pr;
596   struct SendMessage *sm;
597   const struct GNUNET_MessageHeader *hdr;
598   uint16_t msize;
599   size_t ret;
600
601   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
602   h->cth = NULL;
603   if (NULL == buf)
604   {
605     LOG (GNUNET_ERROR_TYPE_DEBUG,
606          "Transmission failed, initiating reconnect\n");
607     reconnect_later (h);
608     return 0;
609   }
610   /* first check for control messages */
611   if (NULL != (cm = h->control_pending_head))
612   {
613     hdr = (const struct GNUNET_MessageHeader *) &cm[1];
614     msize = ntohs (hdr->size);
615     if (size < msize)
616     {
617       trigger_next_request (h, GNUNET_NO);
618       return 0;
619     }
620     LOG (GNUNET_ERROR_TYPE_DEBUG,
621          "Transmitting control message with %u bytes of type %u to core.\n",
622          (unsigned int) msize, (unsigned int) ntohs (hdr->type));
623     memcpy (buf, hdr, msize);
624     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
625                                  h->control_pending_tail, cm);
626     if (NULL != cm->th)
627       cm->th->cm = NULL;
628     if (NULL != cm->cont)
629       cm->cont (cm->cont_cls, GNUNET_OK);
630     GNUNET_free (cm);
631     trigger_next_request (h, GNUNET_NO);
632     return msize;
633   }
634   /* now check for 'ready' P2P messages */
635   if (NULL == (pr = h->ready_peer_head))
636     return 0;
637   GNUNET_assert (NULL != pr->th.peer);
638   th = &pr->th;
639   if (size < th->msize + sizeof (struct SendMessage))
640   {
641     trigger_next_request (h, GNUNET_NO);
642     return 0;
643   }
644   GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
645   th->peer = NULL;
646   if (GNUNET_SCHEDULER_NO_TASK != pr->timeout_task)
647   {
648     GNUNET_SCHEDULER_cancel (pr->timeout_task);
649     pr->timeout_task = GNUNET_SCHEDULER_NO_TASK;
650   }
651   LOG (GNUNET_ERROR_TYPE_DEBUG,
652        "Transmitting SEND request to `%s' with %u bytes.\n",
653        GNUNET_i2s (&pr->peer), (unsigned int) th->msize);
654   sm = (struct SendMessage *) buf;
655   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
656   sm->priority = htonl ((uint32_t) th->priority);
657   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
658   sm->peer = pr->peer;
659   sm->cork = htonl ((uint32_t) th->cork);
660   sm->reserved = htonl (0);
661   ret =
662     th->get_message (th->get_message_cls,
663                      size - sizeof (struct SendMessage), &sm[1]);
664
665   LOG (GNUNET_ERROR_TYPE_DEBUG,
666        "Transmitting SEND request to `%s' yielded %u bytes.\n",
667        GNUNET_i2s (&pr->peer), ret);
668   if (0 == ret)
669   {
670     LOG (GNUNET_ERROR_TYPE_DEBUG,
671          "Size of clients message to peer %s is 0!\n",
672          GNUNET_i2s (&pr->peer));
673     /* client decided to send nothing! */
674     request_next_transmission (pr);
675     return 0;
676   }
677   LOG (GNUNET_ERROR_TYPE_DEBUG,
678        "Produced SEND message to core with %u bytes payload\n",
679        (unsigned int) ret);
680   GNUNET_assert (ret >= sizeof (struct GNUNET_MessageHeader));
681   if (ret + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
682   {
683     GNUNET_break (0);
684     request_next_transmission (pr);
685     return 0;
686   }
687   ret += sizeof (struct SendMessage);
688   sm->header.size = htons (ret);
689   GNUNET_assert (ret <= size);
690   request_next_transmission (pr);
691   return ret;
692 }
693
694
695 /**
696  * Check the list of pending requests, send the next
697  * one to the core.
698  *
699  * @param h core handle
700  * @param ignore_currently_down transmit message even if not initialized?
701  */
702 static void
703 trigger_next_request (struct GNUNET_CORE_Handle *h,
704                       int ignore_currently_down)
705 {
706   uint16_t msize;
707
708   if ((GNUNET_YES == h->currently_down) && (ignore_currently_down == GNUNET_NO))
709   {
710     LOG (GNUNET_ERROR_TYPE_DEBUG,
711          "Core connection down, not processing queue\n");
712     return;
713   }
714   if (NULL != h->cth)
715   {
716     LOG (GNUNET_ERROR_TYPE_DEBUG, "Request pending, not processing queue\n");
717     return;
718   }
719   if (NULL != h->control_pending_head)
720     msize =
721         ntohs (((struct GNUNET_MessageHeader *) &h->
722                 control_pending_head[1])->size);
723   else if (h->ready_peer_head != NULL)
724     msize =
725       h->ready_peer_head->th.msize + sizeof (struct SendMessage);
726   else
727   {
728     LOG (GNUNET_ERROR_TYPE_DEBUG,
729          "Request queue empty, not processing queue\n");
730     return;                     /* no pending message */
731   }
732   h->cth =
733       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
734                                            GNUNET_TIME_UNIT_FOREVER_REL,
735                                            GNUNET_NO, &transmit_message, h);
736 }
737
738
739 /**
740  * Handler for notification messages received from the core.
741  *
742  * @param cls our `struct GNUNET_CORE_Handle`
743  * @param msg the message received from the core service
744  */
745 static void
746 main_notify_handler (void *cls,
747                      const struct GNUNET_MessageHeader *msg)
748 {
749   struct GNUNET_CORE_Handle *h = cls;
750   const struct InitReplyMessage *m;
751   const struct ConnectNotifyMessage *cnm;
752   const struct DisconnectNotifyMessage *dnm;
753   const struct NotifyTrafficMessage *ntm;
754   const struct GNUNET_MessageHeader *em;
755   const struct SendMessageReady *smr;
756   const struct GNUNET_CORE_MessageHandler *mh;
757   GNUNET_CORE_StartupCallback init;
758   struct PeerRecord *pr;
759   struct GNUNET_CORE_TransmitHandle *th;
760   unsigned int hpos;
761   int trigger;
762   uint16_t msize;
763   uint16_t et;
764
765   if (NULL == msg)
766   {
767     LOG (GNUNET_ERROR_TYPE_INFO,
768          _("Client was disconnected from core service, trying to reconnect.\n"));
769     reconnect_later (h);
770     return;
771   }
772   msize = ntohs (msg->size);
773   LOG (GNUNET_ERROR_TYPE_DEBUG,
774        "Processing message of type %u and size %u from core service\n",
775        ntohs (msg->type), msize);
776   switch (ntohs (msg->type))
777   {
778   case GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY:
779     if (ntohs (msg->size) != sizeof (struct InitReplyMessage))
780     {
781       GNUNET_break (0);
782       reconnect_later (h);
783       return;
784     }
785     m = (const struct InitReplyMessage *) msg;
786     GNUNET_break (0 == ntohl (m->reserved));
787     /* start our message processing loop */
788     if (GNUNET_YES == h->currently_down)
789     {
790       h->currently_down = GNUNET_NO;
791       trigger_next_request (h, GNUNET_NO);
792     }
793     h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
794     h->me = m->my_identity;
795     if (NULL != (init = h->init))
796     {
797       /* mark so we don't call init on reconnect */
798       h->init = NULL;
799       LOG (GNUNET_ERROR_TYPE_DEBUG,
800            "Connected to core service of peer `%s'.\n",
801            GNUNET_i2s (&h->me));
802       init (h->cls, &h->me);
803     }
804     else
805     {
806       LOG (GNUNET_ERROR_TYPE_DEBUG,
807            "Successfully reconnected to core service.\n");
808     }
809     /* fake 'connect to self' */
810     pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &h->me);
811     GNUNET_assert (NULL == pr);
812     pr = GNUNET_new (struct PeerRecord);
813     pr->peer = h->me;
814     pr->ch = h;
815     GNUNET_assert (GNUNET_YES ==
816                    GNUNET_CONTAINER_multipeermap_put (h->peers,
817                                                       &h->me, pr,
818                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
819     if (NULL != h->connects)
820       h->connects (h->cls, &h->me);
821     break;
822   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
823     if (msize < sizeof (struct ConnectNotifyMessage))
824     {
825       GNUNET_break (0);
826       reconnect_later (h);
827       return;
828     }
829     cnm = (const struct ConnectNotifyMessage *) msg;
830     if (msize !=
831         sizeof (struct ConnectNotifyMessage))
832     {
833       GNUNET_break (0);
834       reconnect_later (h);
835       return;
836     }
837     LOG (GNUNET_ERROR_TYPE_DEBUG,
838          "Received notification about connection from `%s'.\n",
839          GNUNET_i2s (&cnm->peer));
840     if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity)))
841     {
842       /* connect to self!? */
843       GNUNET_break (0);
844       return;
845     }
846     pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &cnm->peer);
847     if (NULL != pr)
848     {
849       GNUNET_break (0);
850       reconnect_later (h);
851       return;
852     }
853     pr = GNUNET_new (struct PeerRecord);
854     pr->peer = cnm->peer;
855     pr->ch = h;
856     GNUNET_assert (GNUNET_YES ==
857                    GNUNET_CONTAINER_multipeermap_put (h->peers,
858                                                       &cnm->peer, pr,
859                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
860     if (NULL != h->connects)
861       h->connects (h->cls, &cnm->peer);
862     break;
863   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
864     if (msize != sizeof (struct DisconnectNotifyMessage))
865     {
866       GNUNET_break (0);
867       reconnect_later (h);
868       return;
869     }
870     dnm = (const struct DisconnectNotifyMessage *) msg;
871     if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity)))
872     {
873       /* connection to self!? */
874       GNUNET_break (0);
875       return;
876     }
877     GNUNET_break (0 == ntohl (dnm->reserved));
878     LOG (GNUNET_ERROR_TYPE_DEBUG,
879          "Received notification about disconnect from `%s'.\n",
880          GNUNET_i2s (&dnm->peer));
881     pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &dnm->peer);
882     if (NULL == pr)
883     {
884       GNUNET_break (0);
885       reconnect_later (h);
886       return;
887     }
888     trigger = ((pr->prev != NULL) || (pr->next != NULL) ||
889                (h->ready_peer_head == pr));
890     disconnect_and_free_peer_entry (h, &dnm->peer, pr);
891     if (trigger)
892       trigger_next_request (h, GNUNET_NO);
893     break;
894   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
895     if (msize < sizeof (struct NotifyTrafficMessage))
896     {
897       GNUNET_break (0);
898       reconnect_later (h);
899       return;
900     }
901     ntm = (const struct NotifyTrafficMessage *) msg;
902     if ((msize <
903          sizeof (struct NotifyTrafficMessage) +
904          sizeof (struct GNUNET_MessageHeader)) )
905     {
906       GNUNET_break (0);
907       reconnect_later (h);
908       return;
909     }
910     em = (const struct GNUNET_MessageHeader *) &ntm[1];
911     LOG (GNUNET_ERROR_TYPE_DEBUG,
912          "Received message of type %u and size %u from peer `%4s'\n",
913          ntohs (em->type), ntohs (em->size), GNUNET_i2s (&ntm->peer));
914     if ((GNUNET_NO == h->inbound_hdr_only) &&
915         (msize !=
916          ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
917     {
918       GNUNET_break (0);
919       reconnect_later (h);
920       return;
921     }
922     et = ntohs (em->type);
923     for (hpos = 0; hpos < h->hcnt; hpos++)
924     {
925       mh = &h->handlers[hpos];
926       if (mh->type != et)
927         continue;
928       if ((mh->expected_size != ntohs (em->size)) && (mh->expected_size != 0))
929       {
930         LOG (GNUNET_ERROR_TYPE_ERROR,
931              "Unexpected message size %u for message of type %u from peer `%4s'\n",
932              htons (em->size), mh->type, GNUNET_i2s (&ntm->peer));
933         GNUNET_break_op (0);
934         continue;
935       }
936       pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &ntm->peer);
937       if (NULL == pr)
938       {
939         GNUNET_break (0);
940         reconnect_later (h);
941         return;
942       }
943       if (GNUNET_OK !=
944           h->handlers[hpos].callback (h->cls, &ntm->peer, em))
945       {
946         /* error in processing, do not process other messages! */
947         break;
948       }
949     }
950     if (NULL != h->inbound_notify)
951       h->inbound_notify (h->cls, &ntm->peer, em);
952     break;
953   case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
954     if (msize < sizeof (struct NotifyTrafficMessage))
955     {
956       GNUNET_break (0);
957       reconnect_later (h);
958       return;
959     }
960     ntm = (const struct NotifyTrafficMessage *) msg;
961     if ((msize <
962          sizeof (struct NotifyTrafficMessage) +
963          sizeof (struct GNUNET_MessageHeader)) )
964     {
965       GNUNET_break (0);
966       reconnect_later (h);
967       return;
968     }
969     em = (const struct GNUNET_MessageHeader *) &ntm[1];
970     LOG (GNUNET_ERROR_TYPE_DEBUG,
971          "Received notification about transmission to `%s'.\n",
972          GNUNET_i2s (&ntm->peer));
973     if ((GNUNET_NO == h->outbound_hdr_only) &&
974         (msize !=
975          ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
976     {
977       GNUNET_break (0);
978       reconnect_later (h);
979       return;
980     }
981     if (NULL == h->outbound_notify)
982     {
983       GNUNET_break (0);
984       break;
985     }
986     h->outbound_notify (h->cls, &ntm->peer, em);
987     break;
988   case GNUNET_MESSAGE_TYPE_CORE_SEND_READY:
989     if (msize != sizeof (struct SendMessageReady))
990     {
991       GNUNET_break (0);
992       reconnect_later (h);
993       return;
994     }
995     smr = (const struct SendMessageReady *) msg;
996     pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &smr->peer);
997     if (NULL == pr)
998     {
999       GNUNET_break (0);
1000       reconnect_later (h);
1001       return;
1002     }
1003     LOG (GNUNET_ERROR_TYPE_DEBUG,
1004          "Received notification about transmission readiness to `%s'.\n",
1005          GNUNET_i2s (&smr->peer));
1006     if (NULL == pr->th.peer)
1007     {
1008       /* request must have been cancelled between the original request
1009        * and the response from core, ignore core's readiness */
1010       break;
1011     }
1012
1013     th = &pr->th;
1014     if (ntohs (smr->smr_id) != th->smr_id)
1015     {
1016       /* READY message is for expired or cancelled message,
1017        * ignore! (we should have already sent another request) */
1018       break;
1019     }
1020     if ((NULL != pr->prev) || (NULL != pr->next) || (h->ready_peer_head == pr))
1021     {
1022       /* we should not already be on the ready list... */
1023       GNUNET_break (0);
1024       reconnect_later (h);
1025       return;
1026     }
1027     GNUNET_CONTAINER_DLL_insert (h->ready_peer_head, h->ready_peer_tail, pr);
1028     trigger_next_request (h, GNUNET_NO);
1029     break;
1030   default:
1031     reconnect_later (h);
1032     return;
1033   }
1034   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1035                          GNUNET_TIME_UNIT_FOREVER_REL);
1036 }
1037
1038
1039 /**
1040  * Task executed once we are done transmitting the INIT message.
1041  * Starts our 'receive' loop.
1042  *
1043  * @param cls the 'struct GNUNET_CORE_Handle'
1044  * @param success were we successful
1045  */
1046 static void
1047 init_done_task (void *cls, int success)
1048 {
1049   struct GNUNET_CORE_Handle *h = cls;
1050
1051   if (GNUNET_SYSERR == success)
1052     return;                     /* shutdown */
1053   if (GNUNET_NO == success)
1054   {
1055     LOG (GNUNET_ERROR_TYPE_DEBUG,
1056          "Failed to exchange INIT with core, retrying\n");
1057     if (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1058       reconnect_later (h);
1059     return;
1060   }
1061   GNUNET_CLIENT_receive (h->client, &main_notify_handler, h,
1062                          GNUNET_TIME_UNIT_FOREVER_REL);
1063 }
1064
1065
1066 /**
1067  * Our current client connection went down.  Clean it up
1068  * and try to reconnect!
1069  *
1070  * @param h our handle to the core service
1071  */
1072 static void
1073 reconnect (struct GNUNET_CORE_Handle *h)
1074 {
1075   struct ControlMessage *cm;
1076   struct InitMessage *init;
1077   uint32_t opt;
1078   uint16_t msize;
1079   uint16_t *ts;
1080   unsigned int hpos;
1081
1082   GNUNET_assert (NULL == h->client);
1083   GNUNET_assert (GNUNET_YES == h->currently_down);
1084   GNUNET_assert (NULL != h->cfg);
1085   h->client = GNUNET_CLIENT_connect ("core", h->cfg);
1086   if (NULL == h->client)
1087   {
1088     reconnect_later (h);
1089     return;
1090   }
1091   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
1092   cm = GNUNET_malloc (sizeof (struct ControlMessage) + msize);
1093   cm->cont = &init_done_task;
1094   cm->cont_cls = h;
1095   init = (struct InitMessage *) &cm[1];
1096   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
1097   init->header.size = htons (msize);
1098   opt = 0;
1099   if (h->inbound_notify != NULL)
1100   {
1101     if (h->inbound_hdr_only)
1102       opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
1103     else
1104       opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
1105   }
1106   if (h->outbound_notify != NULL)
1107   {
1108     if (h->outbound_hdr_only)
1109       opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
1110     else
1111       opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
1112   }
1113   LOG (GNUNET_ERROR_TYPE_INFO,
1114        "(Re)connecting to CORE service, monitoring messages of type %u\n",
1115        opt);
1116
1117   init->options = htonl (opt);
1118   ts = (uint16_t *) & init[1];
1119   for (hpos = 0; hpos < h->hcnt; hpos++)
1120     ts[hpos] = htons (h->handlers[hpos].type);
1121   GNUNET_CONTAINER_DLL_insert (h->control_pending_head, h->control_pending_tail,
1122                                cm);
1123   trigger_next_request (h, GNUNET_YES);
1124 }
1125
1126
1127
1128 /**
1129  * Connect to the core service.  Note that the connection may
1130  * complete (or fail) asynchronously.
1131  *
1132  * @param cfg configuration to use
1133  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
1134  * @param init callback to call once we have successfully
1135  *        connected to the core service
1136  * @param connects function to call on peer connect, can be NULL
1137  * @param disconnects function to call on peer disconnect / timeout, can be NULL
1138  * @param inbound_notify function to call for all inbound messages, can be NULL
1139  * @param inbound_hdr_only set to #GNUNET_YES if inbound_notify will only read the
1140  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
1141  *                can be used to improve efficiency, ignored if @a inbound_notify is NULLL
1142  * @param outbound_notify function to call for all outbound messages, can be NULL
1143  * @param outbound_hdr_only set to #GNUNET_YES if outbound_notify will only read the
1144  *                GNUNET_MessageHeader and hence we do not need to give it the full message
1145  *                can be used to improve efficiency, ignored if @a outbound_notify is NULLL
1146  * @param handlers callbacks for messages we care about, NULL-terminated
1147  * @return handle to the core service (only useful for disconnect until 'init' is called);
1148  *                NULL on error (in this case, init is never called)
1149  */
1150 struct GNUNET_CORE_Handle *
1151 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1152                      void *cls,
1153                      GNUNET_CORE_StartupCallback init,
1154                      GNUNET_CORE_ConnectEventHandler connects,
1155                      GNUNET_CORE_DisconnectEventHandler disconnects,
1156                      GNUNET_CORE_MessageCallback inbound_notify,
1157                      int inbound_hdr_only,
1158                      GNUNET_CORE_MessageCallback outbound_notify,
1159                      int outbound_hdr_only,
1160                      const struct GNUNET_CORE_MessageHandler *handlers)
1161 {
1162   struct GNUNET_CORE_Handle *h;
1163
1164   GNUNET_assert (NULL != cfg);
1165   h = GNUNET_new (struct GNUNET_CORE_Handle);
1166   h->cfg = cfg;
1167   h->cls = cls;
1168   h->init = init;
1169   h->connects = connects;
1170   h->disconnects = disconnects;
1171   h->inbound_notify = inbound_notify;
1172   h->outbound_notify = outbound_notify;
1173   h->inbound_hdr_only = inbound_hdr_only;
1174   h->outbound_hdr_only = outbound_hdr_only;
1175   h->handlers = handlers;
1176   h->hcnt = 0;
1177   h->currently_down = GNUNET_YES;
1178   h->peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1179   if (NULL != handlers)
1180     while (handlers[h->hcnt].callback != NULL)
1181       h->hcnt++;
1182   GNUNET_assert (h->hcnt <
1183                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
1184                   sizeof (struct InitMessage)) / sizeof (uint16_t));
1185   LOG (GNUNET_ERROR_TYPE_DEBUG,
1186        "Connecting to CORE service\n");
1187   reconnect (h);
1188   return h;
1189 }
1190
1191
1192 /**
1193  * Disconnect from the core service.  This function can only
1194  * be called *after* all pending #GNUNET_CORE_notify_transmit_ready()
1195  * requests have been explicitly canceled.
1196  *
1197  * @param handle connection to core to disconnect
1198  */
1199 void
1200 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
1201 {
1202   struct ControlMessage *cm;
1203
1204   GNUNET_assert (NULL != handle);
1205
1206   LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n");
1207   if (NULL != handle->cth)
1208   {
1209     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
1210     handle->cth = NULL;
1211   }
1212   while (NULL != (cm = handle->control_pending_head))
1213   {
1214     GNUNET_CONTAINER_DLL_remove (handle->control_pending_head,
1215                                  handle->control_pending_tail, cm);
1216     if (NULL != cm->th)
1217       cm->th->cm = NULL;
1218     if (NULL != cm->cont)
1219       cm->cont (cm->cont_cls, GNUNET_SYSERR);
1220     GNUNET_free (cm);
1221   }
1222   if (NULL != handle->client)
1223   {
1224     GNUNET_CLIENT_disconnect (handle->client);
1225     handle->client = NULL;
1226   }
1227   GNUNET_CONTAINER_multipeermap_iterate (handle->peers,
1228                                          &disconnect_and_free_peer_entry,
1229                                          handle);
1230   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1231   {
1232     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1233     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1234   }
1235   GNUNET_CONTAINER_multipeermap_destroy (handle->peers);
1236   handle->peers = NULL;
1237   GNUNET_break (handle->ready_peer_head == NULL);
1238   GNUNET_free (handle);
1239 }
1240
1241
1242 /**
1243  * Task that calls 'request_next_transmission'.
1244  *
1245  * @param cls the 'struct PeerRecord *'
1246  * @param tc scheduler context
1247  */
1248 static void
1249 run_request_next_transmission (void *cls,
1250                                const struct GNUNET_SCHEDULER_TaskContext *tc)
1251 {
1252   struct PeerRecord *pr = cls;
1253
1254   pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1255   request_next_transmission (pr);
1256 }
1257
1258
1259 /**
1260  * Ask the core to call @a notify once it is ready to transmit the
1261  * given number of bytes to the specified @a target.  Must only be
1262  * called after a connection to the respective peer has been
1263  * established (and the client has been informed about this).  You may
1264  * have one request of this type pending for each connected peer at
1265  * any time.  If a peer disconnects, the application MUST call
1266  * #GNUNET_CORE_notify_transmit_ready_cancel on the respective
1267  * transmission request, if one such request is pending.
1268  *
1269  * @param handle connection to core service
1270  * @param cork is corking allowed for this transmission?
1271  * @param priority how important is the message?
1272  * @param maxdelay how long can the message wait? Only effective if @a cork is #GNUNET_YES
1273  * @param target who should receive the message, never NULL (can be this peer's identity for loopback)
1274  * @param notify_size how many bytes of buffer space does @a notify want?
1275  * @param notify function to call when buffer space is available;
1276  *        will be called with NULL on timeout; clients MUST cancel
1277  *        all pending transmission requests DURING the disconnect
1278  *        handler
1279  * @param notify_cls closure for notify
1280  * @return non-NULL if the notify callback was queued,
1281  *         NULL if we can not even queue the request (request already pending);
1282  *         if NULL is returned, @a notify will NOT be called.
1283  */
1284 struct GNUNET_CORE_TransmitHandle *
1285 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1286                                    int cork,
1287                                    enum GNUNET_CORE_Priority priority,
1288                                    struct GNUNET_TIME_Relative maxdelay,
1289                                    const struct GNUNET_PeerIdentity *target,
1290                                    size_t notify_size,
1291                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1292                                    void *notify_cls)
1293 {
1294   struct PeerRecord *pr;
1295   struct GNUNET_CORE_TransmitHandle *th;
1296
1297   if (notify_size > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1298   {
1299      GNUNET_break (0);
1300      return NULL;
1301   }
1302   GNUNET_assert (NULL != notify);
1303   LOG (GNUNET_ERROR_TYPE_DEBUG,
1304        "Asking core for transmission of %u bytes to `%s'\n",
1305        (unsigned int) notify_size,
1306        GNUNET_i2s (target));
1307   pr = GNUNET_CONTAINER_multipeermap_get (handle->peers, target);
1308   if (NULL == pr)
1309   {
1310     /* attempt to send to peer that is not connected */
1311     GNUNET_break (0);
1312     return NULL;
1313   }
1314   if (NULL != pr->th.peer)
1315   {
1316     /* attempting to queue a second request for the same destination */
1317     GNUNET_break (0);
1318     return NULL;
1319   }
1320   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1321                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1322   th = &pr->th;
1323   memset (th, 0, sizeof (struct GNUNET_CORE_TransmitHandle));
1324   th->peer = pr;
1325   th->get_message = notify;
1326   th->get_message_cls = notify_cls;
1327   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1328   th->priority = priority;
1329   th->msize = notify_size;
1330   th->cork = cork;
1331   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pr->ntr_task);
1332   pr->ntr_task =
1333     GNUNET_SCHEDULER_add_now (&run_request_next_transmission, pr);
1334   LOG (GNUNET_ERROR_TYPE_DEBUG,
1335        "Transmission request added to queue\n");
1336   return th;
1337 }
1338
1339
1340 /**
1341  * Cancel the specified transmission-ready notification.
1342  *
1343  * @param th handle that was returned by "notify_transmit_ready".
1344  */
1345 void
1346 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle *th)
1347 {
1348   struct PeerRecord *pr = th->peer;
1349   struct GNUNET_CORE_Handle *h;
1350
1351   GNUNET_assert (NULL != th);
1352   GNUNET_assert (NULL != pr);
1353   LOG (GNUNET_ERROR_TYPE_DEBUG,
1354        "Aborting transmission request to core for %u bytes to `%s'\n",
1355        (unsigned int) th->msize,
1356        GNUNET_i2s (&pr->peer));
1357   th->peer = NULL;
1358   h = pr->ch;
1359   if (NULL != th->cm)
1360   {
1361     /* we're currently in the control queue, remove */
1362     GNUNET_CONTAINER_DLL_remove (h->control_pending_head,
1363                                  h->control_pending_tail, th->cm);
1364     GNUNET_free (th->cm);
1365     th->cm = NULL;
1366   }
1367   if ((NULL != pr->prev) || (NULL != pr->next) || (pr == h->ready_peer_head))
1368   {
1369     /* the request that was 'approved' by core was
1370      * canceled before it could be transmitted; remove
1371      * us from the 'ready' list */
1372     GNUNET_CONTAINER_DLL_remove (h->ready_peer_head, h->ready_peer_tail, pr);
1373   }
1374   if (GNUNET_SCHEDULER_NO_TASK != pr->ntr_task)
1375   {
1376     GNUNET_SCHEDULER_cancel (pr->ntr_task);
1377     pr->ntr_task = GNUNET_SCHEDULER_NO_TASK;
1378   }
1379 }
1380
1381
1382 /**
1383  * Check if the given peer is currently connected. This function is for special
1384  * cirumstances (GNUNET_TESTBED uses it), normal users of the CORE API are
1385  * expected to track which peers are connected based on the connect/disconnect
1386  * callbacks from GNUNET_CORE_connect.  This function is NOT part of the
1387  * 'versioned', 'official' API. The difference between this function and the
1388  * function GNUNET_CORE_is_peer_connected() is that this one returns
1389  * synchronously after looking in the CORE API cache. The function
1390  * GNUNET_CORE_is_peer_connected() sends a message to the CORE service and hence
1391  * its response is given asynchronously.
1392  *
1393  * @param h the core handle
1394  * @param pid the identity of the peer to check if it has been connected to us
1395  * @return GNUNET_YES if the peer is connected to us; GNUNET_NO if not
1396  */
1397 int
1398 GNUNET_CORE_is_peer_connected_sync (const struct GNUNET_CORE_Handle *h,
1399                                     const struct GNUNET_PeerIdentity *pid)
1400 {
1401   GNUNET_assert (NULL != h);
1402   GNUNET_assert (NULL != pid);
1403   return GNUNET_CONTAINER_multipeermap_contains (h->peers, pid);
1404 }
1405
1406
1407 /**
1408  * Function called to notify a client about the connection
1409  * begin ready to queue more data.  "buf" will be
1410  * NULL and "size" zero if the connection was closed for
1411  * writing in the meantime.
1412  *
1413  * @param cls closure
1414  * @param size number of bytes available in buf
1415  * @param buf where the callee should write the message
1416  * @return number of bytes written to buf
1417  */
1418 static size_t
1419 core_mq_ntr (void *cls, size_t size,
1420              void *buf)
1421 {
1422   struct GNUNET_MQ_Handle *mq = cls;
1423   struct CoreMQState *mqs = GNUNET_MQ_impl_state (mq);
1424   const struct GNUNET_MessageHeader *mh = GNUNET_MQ_impl_current (mq);
1425   size_t msg_size = ntohs (mh->size);
1426   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "core-mq", "ntr called (size %u, type %u)\n",
1427                    msg_size, ntohs (mh->type));
1428   mqs->th = NULL;
1429   if (NULL == buf)
1430   {
1431     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "core-mq", "send error\n");
1432     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_WRITE);
1433     return 0;
1434   }
1435   memcpy (buf, mh, msg_size);
1436   GNUNET_MQ_impl_send_continue (mq);
1437   return msg_size;
1438 }
1439
1440
1441 /**
1442  * Signature of functions implementing the
1443  * sending functionality of a message queue.
1444  *
1445  * @param mq the message queue
1446  * @param msg the message to send
1447  * @param impl_state state of the implementation
1448  */
1449 static void
1450 core_mq_send (struct GNUNET_MQ_Handle *mq,
1451               const struct GNUNET_MessageHeader *msg,
1452               void *impl_state)
1453 {
1454   struct CoreMQState *mqs = impl_state;
1455   GNUNET_assert (NULL == mqs->th);
1456   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "core-mq", "Sending queued message (size %u)\n",
1457              ntohs (msg->size));
1458   mqs->th = GNUNET_CORE_notify_transmit_ready (mqs->core, GNUNET_YES, 0,
1459                                                GNUNET_TIME_UNIT_FOREVER_REL,
1460                                                &mqs->target,
1461                                                ntohs (msg->size), core_mq_ntr, mq);
1462 }
1463
1464
1465 /**
1466  * Signature of functions implementing the
1467  * destruction of a message queue.
1468  * Implementations must not free @a mq, but should
1469  * take care of @a impl_state.
1470  *
1471  * @param mq the message queue to destroy
1472  * @param impl_state state of the implementation
1473  */
1474 static void
1475 core_mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
1476 {
1477   struct CoreMQState *mqs = impl_state;
1478   if (NULL != mqs->th)
1479   {
1480     GNUNET_CORE_notify_transmit_ready_cancel (mqs->th);
1481     mqs->th = NULL;
1482   }
1483   GNUNET_free (mqs);
1484 }
1485
1486
1487 /**
1488  * Implementation function that cancels the currently sent message.
1489  *
1490  * @param mq message queue
1491  * @param impl_state state specific to the implementation
1492  */
1493 static void
1494 core_mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
1495 {
1496   struct CoreMQState *mqs = impl_state;
1497   GNUNET_assert (NULL != mqs->th);
1498   GNUNET_CORE_notify_transmit_ready_cancel (mqs->th);
1499 }
1500
1501
1502 /**
1503  * Create a message queue for sending messages to a peer with CORE.
1504  * Messages may only be queued with #GNUNET_MQ_send once the init callback has
1505  * been called for the given handle.
1506  * There must only be one queue per peer for each core handle.
1507  * The message queue can only be used to transmit messages,
1508  * not to receive them.
1509  *
1510  * @param h the core handle
1511  * @param target the target peer for this queue, may not be NULL
1512  * @return a message queue for sending messages over the core handle
1513  *         to the target peer
1514  */
1515 struct GNUNET_MQ_Handle *
1516 GNUNET_CORE_mq_create (struct GNUNET_CORE_Handle *h,
1517                        const struct GNUNET_PeerIdentity *target)
1518 {
1519   struct CoreMQState *mqs = GNUNET_new (struct CoreMQState);
1520   mqs->core = h;
1521   mqs->target = *target;
1522   return GNUNET_MQ_queue_for_callbacks (core_mq_send, core_mq_destroy,
1523                                         core_mq_cancel, mqs,
1524                                         NULL, NULL, NULL);
1525 }
1526
1527 /* end of core_api.c */