gpl3
[oweals/gnunet.git] / src / core / core_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file core/core_api.c
23  * @brief core service; this is the main API for encrypted P2P
24  *        communications
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_core_service.h"
30 #include "core.h"
31
32
33 /**
34  * Context for the core service connection.
35  */
36 struct GNUNET_CORE_Handle
37 {
38
39   /**
40    * Our scheduler.
41    */
42   struct GNUNET_SCHEDULER_Handle *sched;
43
44   /**
45    * Configuration we're using.
46    */
47   const struct GNUNET_CONFIGURATION_Handle *cfg;
48
49   /**
50    * Closure for the various callbacks.
51    */
52   void *cls;
53
54   /**
55    * Function to call once we've handshaked with the core service.
56    */
57   GNUNET_CORE_StartupCallback init;
58
59   /**
60    * Function to call whenever we're notified about a peer connecting.
61    */
62   GNUNET_CORE_ConnectEventHandler connects;
63
64   /**
65    * Function to call whenever we're notified about a peer disconnecting.
66    */
67   GNUNET_CORE_DisconnectEventHandler disconnects;
68
69   /**
70    * Function to call whenever we receive an inbound message.
71    */
72   GNUNET_CORE_MessageCallback inbound_notify;
73
74   /**
75    * Function to call whenever we receive an outbound message.
76    */
77   GNUNET_CORE_MessageCallback outbound_notify;
78
79   /**
80    * Function handlers for messages of particular type.
81    */
82   const struct GNUNET_CORE_MessageHandler *handlers;
83
84   /**
85    * Our connection to the service for notifications.
86    */
87   struct GNUNET_CLIENT_Connection *client_notifications;
88
89   /**
90    * Handle for our current transmission request.
91    */
92   struct GNUNET_CLIENT_TransmitHandle *cth;
93
94   /**
95    * Head of doubly-linked list of pending requests.
96    */
97   struct GNUNET_CORE_TransmitHandle *pending_head;
98
99   /**
100    * Tail of doubly-linked list of pending requests.
101    */
102   struct GNUNET_CORE_TransmitHandle *pending_tail;
103
104   /**
105    * Currently submitted request (or NULL)
106    */
107   struct GNUNET_CORE_TransmitHandle *submitted;
108
109   /**
110    * Currently submitted request based on solicitation (or NULL)
111    */
112   struct GNUNET_CORE_TransmitHandle *solicit_transmit_req;
113
114   /**
115    * Buffer where we store a message for transmission in response
116    * to a traffic solicitation (or NULL).
117    */
118   char *solicit_buffer;
119
120   /**
121    * How long to wait until we time out the connection attempt?
122    */
123   struct GNUNET_TIME_Absolute startup_timeout;
124
125   /**
126    * ID of reconnect task (if any).
127    */
128   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
129
130   /**
131    * Number of entries in the handlers array.
132    */
133   unsigned int hcnt;
134
135   /**
136    * For inbound notifications without a specific handler, do
137    * we expect to only receive headers?
138    */
139   int inbound_hdr_only;
140
141   /**
142    * For outbound notifications without a specific handler, do
143    * we expect to only receive headers?
144    */
145   int outbound_hdr_only;
146
147   /**
148    * Are we currently disconnected and hence unable to forward
149    * requests?
150    */
151   int currently_down;
152 };
153
154
155 /**
156  * Handle for a transmission request.
157  */
158 struct GNUNET_CORE_TransmitHandle
159 {
160
161   /**
162    * We keep active transmit handles in a doubly-linked list.
163    */
164   struct GNUNET_CORE_TransmitHandle *next;
165
166   /**
167    * We keep active transmit handles in a doubly-linked list.
168    */
169   struct GNUNET_CORE_TransmitHandle *prev;
170
171   /**
172    * Corresponding core handle.
173    */
174   struct GNUNET_CORE_Handle *ch;
175
176   /**
177    * Function that will be called to get the actual request
178    * (once we are ready to transmit this request to the core).
179    * The function will be called with a NULL buffer to signal
180    * timeout.
181    */
182   GNUNET_CONNECTION_TransmitReadyNotify get_message;
183
184   /**
185    * Closure for get_message.
186    */
187   void *get_message_cls;
188
189   /**
190    * If this entry is for a transmission request, pointer
191    * to the notify callback; otherwise NULL.
192    */
193   GNUNET_CONNECTION_TransmitReadyNotify notify;
194
195   /**
196    * Closure for notify.
197    */
198   void *notify_cls;
199
200   /**
201    * Peer the request is about.
202    */
203   struct GNUNET_PeerIdentity peer;
204
205   /**
206    * Timeout for this handle.
207    */
208   struct GNUNET_TIME_Absolute timeout;
209
210   /**
211    * ID of timeout task.
212    */
213   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
214
215   /**
216    * How important is this message?
217    */
218   uint32_t priority;
219
220   /**
221    * Size of this request.
222    */
223   uint16_t msize;
224
225
226 };
227
228
229 static void
230 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
231
232
233 /**
234  * Function called when we are ready to transmit our
235  * "START" message (or when this operation timed out).
236  *
237  * @param cls closure
238  * @param size number of bytes available in buf
239  * @param buf where the callee should write the message
240  * @return number of bytes written to buf
241  */
242 static size_t transmit_start (void *cls, size_t size, void *buf);
243
244
245 /**
246  * Our current client connection went down.  Clean it up
247  * and try to reconnect!
248  *
249  * @param h our handle to the core service
250  */
251 static void
252 reconnect (struct GNUNET_CORE_Handle *h)
253 {
254 #if DEBUG_CORE
255   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
256               "Reconnecting to CORE service\n");
257 #endif
258   if (h->client_notifications != NULL)
259     GNUNET_CLIENT_disconnect (h->client_notifications, GNUNET_NO);
260   h->currently_down = GNUNET_YES;
261   h->client_notifications = GNUNET_CLIENT_connect (h->sched, "core", h->cfg);
262   if (h->client_notifications == NULL)
263     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->sched,
264                                                       GNUNET_TIME_UNIT_SECONDS,
265                                                       &reconnect_task,
266                                                       h);
267   else
268     h->cth = GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
269                                                   sizeof (struct InitMessage) +
270                                                   sizeof (uint16_t) * h->hcnt,
271                                                   GNUNET_TIME_UNIT_SECONDS,
272                                                   GNUNET_NO,
273                                                   &transmit_start, h);
274 }
275
276
277 /**
278  * The given request hit its timeout.  Remove from the
279  * doubly-linked list and call the respective continuation.
280  *
281  * @param cls the transmit handle of the request that timed out
282  * @param tc context, can be NULL (!)
283  */
284 static void
285 timeout_request (void *cls, 
286                  const struct GNUNET_SCHEDULER_TaskContext *tc)
287 {
288   struct GNUNET_CORE_TransmitHandle *th = cls;
289
290   th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
291 #if DEBUG_CORE
292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
293               "Signalling timeout of request for transmission to CORE service\n");
294 #endif
295   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
296 }
297
298
299 /**
300  * Function called when we are ready to transmit a request from our
301  * request list (or when this operation timed out).
302  *
303  * @param cls closure
304  * @param size number of bytes available in buf
305  * @param buf where the callee should write the message
306  * @return number of bytes written to buf
307  */
308 static size_t
309 request_start (void *cls, size_t size, void *buf)
310 {
311   struct GNUNET_CORE_Handle *h = cls;
312   struct GNUNET_CORE_TransmitHandle *th;
313   size_t ret;
314
315   h->cth = NULL;
316   th = h->pending_head;
317   if (buf == NULL)
318     {
319       timeout_request (th, NULL);
320       return 0;
321     }
322   GNUNET_CONTAINER_DLL_remove (h->pending_head,
323                                h->pending_tail,
324                                th);
325   GNUNET_assert (h->submitted == NULL);
326   h->submitted = th;
327   GNUNET_assert (size >= th->msize);
328   ret = th->get_message (th->get_message_cls, size, buf);
329   GNUNET_assert (ret <= size);
330 #if DEBUG_CORE
331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
332               "Transmitting %u bytes to core\n",
333               ret);
334 #endif
335   return ret;
336 }
337
338
339 /**
340  * Check the list of pending requests, send the next
341  * one to the core.
342  */
343 static void
344 trigger_next_request (struct GNUNET_CORE_Handle *h)
345 {
346   struct GNUNET_CORE_TransmitHandle *th;
347
348   if (h->currently_down)
349     {
350 #if DEBUG_CORE
351       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
352                   "In trigger_next_request, connection currently down...\n");
353 #endif
354       return;                     /* connection temporarily down */
355     }
356   if (NULL == (th = h->pending_head))
357     return;                     /* no requests pending */
358   GNUNET_assert (NULL == h->cth);
359   h->cth = GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
360                                                 th->msize,
361                                                 GNUNET_TIME_absolute_get_remaining
362                                                 (th->timeout), 
363                                                 GNUNET_NO,
364                                                 &request_start,
365                                                 h);
366 }
367
368
369 /**
370  * Handler for notification messages received from the core.
371  *
372  * @param cls our "struct GNUNET_CORE_Handle"
373  * @param msg the message received from the core service
374  */
375 static void
376 main_notify_handler (void *cls, const struct GNUNET_MessageHeader *msg)
377 {
378   struct GNUNET_CORE_Handle *h = cls;
379   unsigned int hpos;
380   const struct ConnectNotifyMessage *cnm;
381   const struct DisconnectNotifyMessage *dnm;
382   const struct NotifyTrafficMessage *ntm;
383   const struct GNUNET_MessageHeader *em;
384   uint16_t msize;
385   uint16_t et;
386   const struct GNUNET_CORE_MessageHandler *mh;
387
388   if (msg == NULL)
389     {
390       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
391                   _
392                   ("Client was disconnected from core service, trying to reconnect.\n"));
393       reconnect (h);
394       return;
395     }
396   msize = ntohs (msg->size);
397 #if DEBUG_CORE
398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
399               "Processing message of type %u and size %u from core service\n",
400               ntohs (msg->type), msize);
401 #endif
402   switch (ntohs (msg->type))
403     {
404     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
405       if (NULL == h->connects)
406         {
407           GNUNET_break (0);
408           break;
409         }
410       if (msize != sizeof (struct ConnectNotifyMessage))
411         {
412           GNUNET_break (0);
413           break;
414         }
415       cnm = (const struct ConnectNotifyMessage *) msg;
416       h->connects (h->cls,
417                    &cnm->peer,
418                    GNUNET_TIME_relative_ntoh (cnm->latency),
419                    ntohl (cnm->distance));
420       break;
421     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
422       if (NULL == h->disconnects)
423         {
424           GNUNET_break (0);
425           break;
426         }
427       if (msize != sizeof (struct DisconnectNotifyMessage))
428         {
429           GNUNET_break (0);
430           break;
431         }
432       dnm = (const struct DisconnectNotifyMessage *) msg;
433       h->disconnects (h->cls,
434                       &dnm->peer);
435       break;
436     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
437       if (msize <
438           sizeof (struct NotifyTrafficMessage) +
439           sizeof (struct GNUNET_MessageHeader))
440         {
441           GNUNET_break (0);
442           break;
443         }
444       ntm = (const struct NotifyTrafficMessage *) msg;
445       em = (const struct GNUNET_MessageHeader *) &ntm[1];
446 #if DEBUG_CORE
447       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
448                   "Received message of type %u and size %u from peer `%4s'\n",
449                   ntohs (em->type), 
450                   ntohs (em->size),
451                   GNUNET_i2s (&ntm->peer));
452 #endif
453       if ((GNUNET_NO == h->inbound_hdr_only) &&
454           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
455         {
456           GNUNET_break (0);
457           break;
458         }
459       et = ntohs (em->type);
460       for (hpos = 0; hpos < h->hcnt; hpos++)
461         {
462           mh = &h->handlers[hpos];
463           if (mh->type != et)
464             continue;
465           if ((mh->expected_size != ntohs (em->size)) &&
466               (mh->expected_size != 0))
467             {
468               GNUNET_break (0);
469               continue;
470             }
471           if (GNUNET_OK !=
472               h->handlers[hpos].callback (h->cls, &ntm->peer, em,
473                                           GNUNET_TIME_relative_ntoh (ntm->latency),
474                                           ntohl (ntm->distance)))
475             {
476               /* error in processing, disconnect ! */
477               reconnect (h);
478               return;
479             }
480         }
481       if (NULL != h->inbound_notify)
482         h->inbound_notify (h->cls, &ntm->peer, em,
483                            GNUNET_TIME_relative_ntoh (ntm->latency),
484                            ntohl (ntm->distance));
485       break;
486     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
487       if (msize <
488           sizeof (struct NotifyTrafficMessage) +
489           sizeof (struct GNUNET_MessageHeader))
490         {
491           GNUNET_break (0);
492           break;
493         }
494       ntm = (const struct NotifyTrafficMessage *) msg;
495       em = (const struct GNUNET_MessageHeader *) &ntm[1];
496       if ((GNUNET_NO == h->outbound_hdr_only) &&
497           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
498         {
499           GNUNET_break (0);
500           break;
501         }
502       if (NULL == h->outbound_notify)
503         {
504           GNUNET_break (0);
505           break;
506         }
507       h->outbound_notify (h->cls, &ntm->peer, em,
508                           GNUNET_TIME_relative_ntoh (ntm->latency),
509                           ntohl (ntm->distance));
510       break;
511     default:
512       GNUNET_break (0);
513       break;
514     }
515   GNUNET_CLIENT_receive (h->client_notifications,
516                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
517 }
518
519
520 /**
521  * Function called when we are ready to transmit our
522  * "START" message (or when this operation timed out).
523  *
524  * @param cls closure
525  * @param size number of bytes available in buf
526  * @param buf where the callee should write the message
527  * @return number of bytes written to buf
528  */
529 static size_t transmit_start (void *cls, size_t size, void *buf);
530
531
532 /**
533  * Function called on the first message received from
534  * the service (contains our public key, etc.).
535  * Should trigger calling the init callback
536  * and then start our regular message processing.
537  *
538  * @param cls closure
539  * @param msg message received, NULL on timeout or fatal error
540  */
541 static void
542 init_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg)
543 {
544   struct GNUNET_CORE_Handle *h = cls;
545   const struct InitReplyMessage *m;
546   GNUNET_CORE_StartupCallback init;
547   struct GNUNET_PeerIdentity my_identity;
548
549   if ((msg == NULL) ||
550       (ntohs (msg->size) != sizeof (struct InitReplyMessage)) ||
551       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY))
552     {
553       if (msg != NULL)
554         {
555           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
556                       _
557                       ("Error connecting to core service (failed to receive `%s' message, got message of type %u and size %u).\n"),
558                       "INIT_REPLY",
559                       ntohs (msg->type),
560                       ntohs (msg->size));
561           GNUNET_break (0);
562         }
563       else
564         {
565 #if DEBUG_CORE
566           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567                       _("Failed to connect to core service, will retry.\n"));
568 #endif
569         }
570       transmit_start (h, 0, NULL);
571       return;
572     }
573   m = (const struct InitReplyMessage *) msg;
574   /* start our message processing loop */
575 #if DEBUG_CORE
576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
577               "Successfully connected to core service, starting processing loop.\n");
578 #endif
579   h->currently_down = GNUNET_NO;
580   trigger_next_request (h);
581   GNUNET_CLIENT_receive (h->client_notifications,
582                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
583   if (NULL != (init = h->init))
584     {
585       /* mark so we don't call init on reconnect */
586       h->init = NULL;
587       GNUNET_CRYPTO_hash (&m->publicKey,
588                           sizeof (struct
589                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
590                           &my_identity.hashPubKey);
591       init (h->cls, h, &my_identity, &m->publicKey);
592     }
593 }
594
595
596 static void
597 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
598 {
599   struct GNUNET_CORE_Handle *h = cls;
600   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
601   reconnect (h);
602 }
603
604
605 /**
606  * Function called when we are ready to transmit our
607  * "START" message (or when this operation timed out).
608  *
609  * @param cls closure
610  * @param size number of bytes available in buf
611  * @param buf where the callee should write the message
612  * @return number of bytes written to buf
613  */
614 static size_t
615 transmit_start (void *cls, size_t size, void *buf)
616 {
617   struct GNUNET_CORE_Handle *h = cls;
618   struct InitMessage *init;
619   uint16_t *ts;
620   uint16_t msize;
621   uint32_t opt;
622   unsigned int hpos;
623   struct GNUNET_TIME_Relative delay;
624
625   h->cth = NULL;
626   if (size == 0)
627     {
628       if ((h->init == NULL) ||
629           (GNUNET_TIME_absolute_get ().value < h->startup_timeout.value))
630         {
631           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
632                       _("Failed to connect to core service, retrying.\n"));
633           delay = GNUNET_TIME_absolute_get_remaining (h->startup_timeout);
634           if ((h->init == NULL) || (delay.value > 1000))
635             delay = GNUNET_TIME_UNIT_SECONDS;
636           if (h->init == NULL)
637             h->startup_timeout =
638               GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
639           h->reconnect_task =
640             GNUNET_SCHEDULER_add_delayed (h->sched, 
641                                           delay, &reconnect_task, h);
642           return 0;
643         }
644       /* timeout on initial connect */
645       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
646                   _("Failed to connect to core service, giving up.\n"));
647       h->init (h->cls, NULL, NULL, NULL);
648       GNUNET_CORE_disconnect (h);
649       return 0;
650     }
651   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
652   GNUNET_assert (size >= msize);
653   init = buf;
654   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
655   init->header.size = htons (msize);
656   opt = GNUNET_CORE_OPTION_NOTHING;
657   if (h->connects != NULL)
658     opt |= GNUNET_CORE_OPTION_SEND_CONNECT;
659   if (h->disconnects != NULL)
660     opt |= GNUNET_CORE_OPTION_SEND_DISCONNECT;
661   if (h->inbound_notify != NULL)
662     {
663       if (h->inbound_hdr_only)
664         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
665       else
666         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
667     }
668   if (h->outbound_notify != NULL)
669     {
670       if (h->outbound_hdr_only)
671         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
672       else
673         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
674     }
675   init->options = htonl (opt);
676   ts = (uint16_t *) & init[1];
677   for (hpos = 0; hpos < h->hcnt; hpos++)
678     ts[hpos] = htons (h->handlers[hpos].type);
679   GNUNET_CLIENT_receive (h->client_notifications,
680                          &init_reply_handler,
681                          h,
682                          GNUNET_TIME_absolute_get_remaining
683                          (h->startup_timeout));
684   return sizeof (struct InitMessage) + h->hcnt * sizeof (uint16_t);
685 }
686
687
688 /**
689  * Connect to the core service.  Note that the connection may
690  * complete (or fail) asynchronously.
691  *
692  * @param sched scheduler to use
693  * @param cfg configuration to use
694  * @param timeout after how long should we give up trying to connect to the core service?
695  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
696  * @param init callback to call on timeout or once we have successfully
697  *        connected to the core service; note that timeout is only meaningful if init is not NULL
698  * @param connects function to call on peer connect, can be NULL
699  * @param disconnects function to call on peer disconnect / timeout, can be NULL
700  * @param inbound_notify function to call for all inbound messages, can be NULL
701  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
702  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
703  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
704  * @param outbound_notify function to call for all outbound messages, can be NULL
705  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
706  *                GNUNET_MessageHeader and hence we do not need to give it the full message
707  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
708  * @param handlers callbacks for messages we care about, NULL-terminated
709  * @return handle to the core service (only useful for disconnect until 'init' is called);
710  *                NULL on error (in this case, init is never called)
711  */
712 struct GNUNET_CORE_Handle *
713 GNUNET_CORE_connect (struct GNUNET_SCHEDULER_Handle *sched,
714                      const struct GNUNET_CONFIGURATION_Handle *cfg,
715                      struct GNUNET_TIME_Relative timeout,
716                      void *cls,
717                      GNUNET_CORE_StartupCallback init,
718                      GNUNET_CORE_ConnectEventHandler connects,
719                      GNUNET_CORE_DisconnectEventHandler disconnects,
720                      GNUNET_CORE_MessageCallback inbound_notify,
721                      int inbound_hdr_only,
722                      GNUNET_CORE_MessageCallback outbound_notify,
723                      int outbound_hdr_only,
724                      const struct GNUNET_CORE_MessageHandler *handlers)
725 {
726   struct GNUNET_CORE_Handle *h;
727
728   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
729   h->sched = sched;
730   h->cfg = cfg;
731   h->cls = cls;
732   h->init = init;
733   h->connects = connects;
734   h->disconnects = disconnects;
735   h->inbound_notify = inbound_notify;
736   h->outbound_notify = outbound_notify;
737   h->inbound_hdr_only = inbound_hdr_only;
738   h->outbound_hdr_only = outbound_hdr_only;
739   h->handlers = handlers;
740   h->client_notifications = GNUNET_CLIENT_connect (sched, "core", cfg);
741   if (h->client_notifications == NULL)
742     {
743       GNUNET_free (h);
744       return NULL;
745     }
746   h->startup_timeout = GNUNET_TIME_relative_to_absolute (timeout);
747   h->hcnt = 0;
748   while (handlers[h->hcnt].callback != NULL)
749     h->hcnt++;
750   GNUNET_assert (h->hcnt <
751                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
752                   sizeof (struct InitMessage)) / sizeof (uint16_t));
753 #if DEBUG_CORE
754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755               "Trying to connect to core service in next %llu ms.\n",
756               timeout.value);
757 #endif
758   h->cth =
759     GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
760                                          sizeof (struct InitMessage) +
761                                          sizeof (uint16_t) * h->hcnt, timeout,
762                                          GNUNET_YES,
763                                          &transmit_start, h);
764   return h;
765 }
766
767
768 /**
769  * Disconnect from the core service.
770  *
771  * @param handle connection to core to disconnect
772  */
773 void
774 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
775 {
776   if (handle->cth != NULL)
777     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
778   if (handle->solicit_transmit_req != NULL)
779     GNUNET_CORE_notify_transmit_ready_cancel (handle->solicit_transmit_req);
780   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
781     GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
782   if (handle->client_notifications != NULL)
783     GNUNET_CLIENT_disconnect (handle->client_notifications, GNUNET_NO);
784   GNUNET_free_non_null (handle->solicit_buffer);
785   GNUNET_free (handle);
786 }
787
788
789 /**
790  * Build the message requesting data transmission.
791  */
792 static size_t
793 produce_send (void *cls, size_t size, void *buf)
794 {
795   struct GNUNET_CORE_TransmitHandle *th = cls;
796   struct GNUNET_CORE_Handle *h;
797   struct SendMessage *sm;
798   size_t dt;
799   GNUNET_CONNECTION_TransmitReadyNotify notify;
800   void *notify_cls;
801
802   h = th->ch;
803   if (buf == NULL)
804     {
805       /* timeout or error */
806 #if DEBUG_CORE
807       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808                   "P2P transmission request for `%4s' timed out.\n",
809                   GNUNET_i2s(&th->peer));
810 #endif
811       GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
812       GNUNET_CORE_notify_transmit_ready_cancel (th);
813       trigger_next_request (h);
814       return 0;
815     }
816   sm = (struct SendMessage *) buf;
817   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
818   sm->priority = htonl (th->priority);
819   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
820   sm->peer = th->peer;
821   notify = th->notify;
822   notify_cls = th->notify_cls;
823   GNUNET_CORE_notify_transmit_ready_cancel (th);
824   trigger_next_request (h);
825   size = GNUNET_MIN (size,
826                      GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
827   GNUNET_assert (size >= sizeof (struct SendMessage));
828   dt = notify (notify_cls, size - sizeof (struct SendMessage), &sm[1]);
829   if (0 == dt)
830     {
831 #if DEBUG_CORE
832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
833               "Size of clients message to peer %s is 0!\n",
834               GNUNET_i2s(&th->peer));
835 #endif
836       /* client decided to send nothing! */
837       return 0;
838     }
839 #if DEBUG_CORE
840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
841               "Produced SEND message to core with %u bytes payload\n",
842               dt);
843 #endif
844   GNUNET_assert (dt >= sizeof (struct GNUNET_MessageHeader));
845   if (dt + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
846     {
847       GNUNET_break (0);
848       return 0;
849     }
850 #if DEBUG_CORE
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852               "Preparing for P2P transmission of %u bytes to `%4s'.\n",
853               dt,
854               GNUNET_i2s(&th->peer));
855 #endif
856   sm->header.size = htons (dt + sizeof (struct SendMessage));
857   GNUNET_assert (dt + sizeof (struct SendMessage) <= size);
858   return dt + sizeof (struct SendMessage);
859 }
860
861
862 /**
863  * Ask the core to call "notify" once it is ready to transmit the
864  * given number of bytes to the specified "target".  If we are not yet
865  * connected to the specified peer, a call to this function will cause
866  * us to try to establish a connection.
867  *
868  * @param handle connection to core service
869  * @param priority how important is the message?
870  * @param maxdelay how long can the message wait?
871  * @param target who should receive the message,
872  *        use NULL for this peer (loopback)
873  * @param notify_size how many bytes of buffer space does notify want?
874  * @param notify function to call when buffer space is available
875  * @param notify_cls closure for notify
876  * @return non-NULL if the notify callback was queued,
877  *         NULL if we can not even queue the request (insufficient
878  *         memory); if NULL is returned, "notify" will NOT be called.
879  */
880 struct GNUNET_CORE_TransmitHandle *
881 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
882                                    unsigned int priority,
883                                    struct GNUNET_TIME_Relative maxdelay,
884                                    const struct GNUNET_PeerIdentity *target,
885                                    size_t notify_size,
886                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
887                                    void *notify_cls)
888 {
889   struct GNUNET_CORE_TransmitHandle *th;
890
891   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
892                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
893   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
894   th->ch = handle;
895   GNUNET_CONTAINER_DLL_insert_after (handle->pending_head,
896                                      handle->pending_tail,
897                                      handle->pending_tail,
898                                      th);
899   th->get_message = &produce_send;
900   th->get_message_cls = th;
901   th->notify = notify;
902   th->notify_cls = notify_cls;
903   th->peer = *target;
904   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
905   th->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->sched,
906                                                    maxdelay,
907                                                    &timeout_request, th);
908   th->priority = priority;
909   th->msize = sizeof (struct SendMessage) + notify_size;
910   /* was the request queue previously empty? */
911   if ( (handle->pending_head == th) &&
912        (handle->cth == NULL) )
913     trigger_next_request (handle);
914   return th;
915 }
916
917
918 /**
919  * Cancel the specified transmission-ready notification.
920  *
921  * @param th handle that was returned by "notify_transmit_ready".
922  */
923 void
924 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
925                                           *th)
926 {
927   struct GNUNET_CORE_Handle *h = th->ch;
928   
929   if (h->submitted == th)
930     h->submitted = NULL;
931   else    
932     GNUNET_CONTAINER_DLL_remove (h->pending_head,
933                                  h->pending_tail,
934                                  th);    
935   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
936     GNUNET_SCHEDULER_cancel (h->sched, th->timeout_task);
937   GNUNET_free (th);
938 }
939
940
941 /* end of core_api.c */