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