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