b485b4181f277dea986e8d2df2c2aa502a69e784
[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 }
289
290
291 /**
292  * Function called when we are ready to transmit a request from our
293  * request list (or when this operation timed out).
294  *
295  * @param cls closure
296  * @param size number of bytes available in buf
297  * @param buf where the callee should write the message
298  * @return number of bytes written to buf
299  */
300 static size_t
301 request_start (void *cls, size_t size, void *buf)
302 {
303   struct GNUNET_CORE_Handle *h = cls;
304   struct GNUNET_CORE_TransmitHandle *th;
305   size_t ret;
306
307   h->th = NULL;
308   th = h->pending_head;
309   if (buf == NULL)
310     {
311       timeout_request (th, NULL);
312       return 0;
313     }
314   /* create new timeout task (in case core takes too long to respond!) */
315   th->timeout_task = GNUNET_SCHEDULER_add_delayed (h->sched,
316                                                    GNUNET_TIME_absolute_get_remaining
317                                                    (th->timeout),
318                                                    &timeout_request, th);
319   /* remove th from doubly-linked pending list, move to submitted */
320   GNUNET_assert (th->prev == NULL);
321   h->pending_head = th->next;
322   if (th->next == NULL)
323     h->pending_tail = NULL;
324   else
325     th->next->prev = NULL;
326   GNUNET_assert (h->submitted == NULL);
327   h->submitted = th;
328   GNUNET_assert (size >= th->msize);
329   ret = th->get_message (th->get_message_cls, size, buf);
330   GNUNET_assert (ret <= size);
331   return ret;
332 }
333
334
335 /**
336  * Check the list of pending requests, send the next
337  * one to the core.
338  */
339 static void
340 trigger_next_request (struct GNUNET_CORE_Handle *h)
341 {
342   struct GNUNET_CORE_TransmitHandle *th;
343   if (h->currently_down)
344     return;                     /* connection temporarily down */
345   if (NULL == (th = h->pending_head))
346     return;                     /* no requests pending */
347   GNUNET_assert (NULL == h->th);
348   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
349     {
350       GNUNET_SCHEDULER_cancel (h->sched, th->timeout_task);
351       th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
352     }
353   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
354                                                th->msize,
355                                                GNUNET_TIME_absolute_get_remaining
356                                                (th->timeout), 
357                                                GNUNET_NO,
358                                                &request_start,
359                                                h);
360 }
361
362
363 /**
364  * Handler for most messages received from the core.
365  *
366  * @param cls our "struct GNUNET_CORE_Handle"
367  * @param msg the message received from the core service
368  */
369 static void
370 main_handler (void *cls, const struct GNUNET_MessageHeader *msg)
371 {
372   struct GNUNET_CORE_Handle *h = cls;
373   unsigned int hpos;
374   const struct ConnectNotifyMessage *cnm;
375   const struct NotifyTrafficMessage *ntm;
376   const struct ConfigurationInfoMessage *cim;
377   const struct GNUNET_MessageHeader *em;
378   uint16_t msize;
379   uint16_t et;
380   const struct GNUNET_CORE_MessageHandler *mh;
381
382   if (msg == NULL)
383     {
384       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
385                   _
386                   ("Client was disconnected from core service, trying to reconnect.\n"));
387       reconnect (h);
388       return;
389     }
390   msize = ntohs (msg->size);
391 #if DEBUG_CORE
392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
393               "Processing message of type %u and size %u from core service\n",
394               ntohs (msg->type), msize);
395 #endif
396   switch (ntohs (msg->type))
397     {
398     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
399       if (NULL == h->connects)
400         {
401           GNUNET_break (0);
402           break;
403         }
404       if (msize != sizeof (struct ConnectNotifyMessage))
405         {
406           GNUNET_break (0);
407           break;
408         }
409       cnm = (const struct ConnectNotifyMessage *) msg;
410       h->connects (h->cls,
411                    &cnm->peer);
412       break;
413     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
414       if (NULL == h->disconnects)
415         {
416           GNUNET_break (0);
417           break;
418         }
419       if (msize != sizeof (struct ConnectNotifyMessage))
420         {
421           GNUNET_break (0);
422           break;
423         }
424       cnm = (const struct ConnectNotifyMessage *) msg;
425       h->disconnects (h->cls,
426                       &cnm->peer);
427       break;
428     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
429       if (msize <
430           sizeof (struct NotifyTrafficMessage) +
431           sizeof (struct GNUNET_MessageHeader))
432         {
433           GNUNET_break (0);
434           break;
435         }
436       ntm = (const struct NotifyTrafficMessage *) msg;
437       em = (const struct GNUNET_MessageHeader *) &ntm[1];
438 #if DEBUG_CORE
439       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
440                   "Received message of type %u from peer `%4s'\n",
441                   ntohs (em->type), GNUNET_i2s (&ntm->peer));
442 #endif
443       if ((GNUNET_NO == h->inbound_hdr_only) &&
444           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
445         {
446           GNUNET_break (0);
447           break;
448         }
449       et = ntohs (em->type);
450       for (hpos = 0; hpos < h->hcnt; hpos++)
451         {
452           mh = &h->handlers[hpos];
453           if (mh->type != et)
454             continue;
455           if ((mh->expected_size != ntohs (em->size)) &&
456               (mh->expected_size != 0))
457             {
458               GNUNET_break (0);
459               continue;
460             }
461           if (GNUNET_OK !=
462               h->handlers[hpos].callback (h->cls, &ntm->peer, em))
463             {
464               /* error in processing, disconnect ! */
465               reconnect (h);
466               return;
467             }
468         }
469       if (NULL != h->inbound_notify)
470         h->inbound_notify (h->cls, &ntm->peer, em);
471       break;
472     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
473       if (msize <
474           sizeof (struct NotifyTrafficMessage) +
475           sizeof (struct GNUNET_MessageHeader))
476         {
477           GNUNET_break (0);
478           break;
479         }
480       ntm = (const struct NotifyTrafficMessage *) msg;
481       em = (const struct GNUNET_MessageHeader *) &ntm[1];
482       if ((GNUNET_NO == h->outbound_hdr_only) &&
483           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
484         {
485           GNUNET_break (0);
486           break;
487         }
488       if (NULL == h->outbound_notify)
489         {
490           GNUNET_break (0);
491           break;
492         }
493       h->outbound_notify (h->cls, &ntm->peer, em);
494       break;
495     case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
496       if (msize != sizeof (struct ConfigurationInfoMessage))
497         {
498           GNUNET_break (0);
499           break;
500         }
501       if (NULL == h->submitted)
502         break;
503       cim = (const struct ConfigurationInfoMessage *) msg;
504
505       /* process configuration data */
506       if (h->submitted->info != NULL)
507         h->submitted->info (h->submitted->info_cls,
508                             &h->submitted->peer,
509                             ntohl (cim->bpm_in),
510                             ntohl (cim->bpm_out),
511                             GNUNET_TIME_relative_ntoh (cim->latency),
512                             (int) ntohl (cim->reserved_amount),
513                             cim->preference);
514       /* done, clean up! */      
515       GNUNET_CORE_notify_transmit_ready_cancel (h->submitted); // HUH?
516       trigger_next_request (h);
517       break;
518     default:
519       GNUNET_break (0);
520       break;
521     }
522   GNUNET_CLIENT_receive (h->client,
523                          &main_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
524 }
525
526
527
528 /**
529  * Function called when we are ready to transmit our
530  * "START" message (or when this operation timed out).
531  *
532  * @param cls closure
533  * @param size number of bytes available in buf
534  * @param buf where the callee should write the message
535  * @return number of bytes written to buf
536  */
537 static size_t transmit_start (void *cls, size_t size, void *buf);
538
539
540 /**
541  * Function called on the first message received from
542  * the service (contains our public key, etc.).
543  * Should trigger calling the init callback
544  * and then start our regular message processing.
545  *
546  * @param cls closure
547  * @param msg message received, NULL on timeout or fatal error
548  */
549 static void
550 init_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg)
551 {
552   struct GNUNET_CORE_Handle *h = cls;
553   const struct InitReplyMessage *m;
554   GNUNET_CORE_StartupCallback init;
555   struct GNUNET_PeerIdentity my_identity;
556
557   if ((msg == NULL) ||
558       (ntohs (msg->size) != sizeof (struct InitReplyMessage)) ||
559       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY))
560     {
561       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
562                   _
563                   ("Error connecting to core service (failed to receive `%s' message).\n"),
564                   "INIT_REPLY");
565       GNUNET_break (msg == NULL);
566       transmit_start (h, 0, NULL);
567       return;
568     }
569   m = (const struct InitReplyMessage *) msg;
570   /* start our message processing loop */
571 #if DEBUG_CORE
572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573               _
574               ("Successfully connected to core service, starting processing loop.\n"));
575 #endif
576   h->currently_down = GNUNET_NO;
577   trigger_next_request (h);
578   GNUNET_CLIENT_receive (h->client,
579                          &main_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
580   if (NULL != (init = h->init))
581     {
582       /* mark so we don't call init on reconnect */
583       h->init = NULL;
584 #if DEBUG_CORE
585       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
586                   _("Successfully connected to core service.\n"));
587 #endif
588       GNUNET_CRYPTO_hash (&m->publicKey,
589                           sizeof (struct
590                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
591                           &my_identity.hashPubKey);
592       init (h->cls, h, &my_identity, &m->publicKey);
593     }
594 }
595
596
597 static void
598 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
599 {
600   struct GNUNET_CORE_Handle *h = cls;
601   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
602   reconnect (h);
603 }
604
605
606 /**
607  * Function called when we are ready to transmit our
608  * "START" message (or when this operation timed out).
609  *
610  * @param cls closure
611  * @param size number of bytes available in buf
612  * @param buf where the callee should write the message
613  * @return number of bytes written to buf
614  */
615 static size_t
616 transmit_start (void *cls, size_t size, void *buf)
617 {
618   struct GNUNET_CORE_Handle *h = cls;
619   struct InitMessage *init;
620   uint16_t *ts;
621   uint16_t msize;
622   uint32_t opt;
623   unsigned int hpos;
624   struct GNUNET_TIME_Relative delay;
625
626   h->th = NULL;
627   if (size == 0)
628     {
629       if ((h->init == NULL) ||
630           (GNUNET_TIME_absolute_get ().value < h->startup_timeout.value))
631         {
632           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
633                       _("Failed to connect to core service, retrying.\n"));
634           delay = GNUNET_TIME_absolute_get_remaining (h->startup_timeout);
635           if ((h->init == NULL) || (delay.value > 1000))
636             delay = GNUNET_TIME_UNIT_SECONDS;
637           if (h->init == NULL)
638             h->startup_timeout =
639               GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
640           h->reconnect_task =
641             GNUNET_SCHEDULER_add_delayed (h->sched, 
642                                           delay, &reconnect_task, h);
643           return 0;
644         }
645       /* timeout on initial connect */
646       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
647                   _("Failed to connect to core service, giving up.\n"));
648       h->init (h->cls, NULL, NULL, NULL);
649       GNUNET_CORE_disconnect (h);
650       return 0;
651     }
652   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
653   GNUNET_assert (size >= msize);
654   init = buf;
655   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
656   init->header.size = htons (msize);
657   opt = GNUNET_CORE_OPTION_NOTHING;
658   if (h->connects != NULL)
659     opt |= GNUNET_CORE_OPTION_SEND_CONNECT;
660   if (h->disconnects != NULL)
661     opt |= GNUNET_CORE_OPTION_SEND_DISCONNECT;
662   if (h->inbound_notify != NULL)
663     {
664       if (h->inbound_hdr_only)
665         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
666       else
667         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
668     }
669   if (h->outbound_notify != NULL)
670     {
671       if (h->outbound_hdr_only)
672         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
673       else
674         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
675     }
676   init->options = htonl (opt);
677   ts = (uint16_t *) & init[1];
678   for (hpos = 0; hpos < h->hcnt; hpos++)
679     ts[hpos] = htons (h->handlers[hpos].type);
680   GNUNET_CLIENT_receive (h->client,
681                          &init_reply_handler,
682                          h,
683                          GNUNET_TIME_absolute_get_remaining
684                          (h->startup_timeout));
685   return sizeof (struct InitMessage) + h->hcnt * sizeof (uint16_t);
686 }
687
688
689 /**
690  * Connect to the core service.  Note that the connection may
691  * complete (or fail) asynchronously.
692  *
693  * @param sched scheduler to use
694  * @param cfg configuration to use
695  * @param timeout after how long should we give up trying to connect to the core service?
696  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
697  * @param init callback to call on timeout or once we have successfully
698  *        connected to the core service; note that timeout is only meaningful if init is not NULL
699  * @param connects function to call on peer connect, can be NULL
700  * @param disconnects function to call on peer disconnect / timeout, can be NULL
701  * @param inbound_notify function to call for all inbound messages, can be NULL
702  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
703  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
704  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
705  * @param outbound_notify function to call for all outbound messages, can be NULL
706  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
707  *                GNUNET_MessageHeader and hence we do not need to give it the full message
708  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
709  * @param handlers callbacks for messages we care about, NULL-terminated
710  * @return handle to the core service (only useful for disconnect until 'init' is called);
711  *                NULL on error (in this case, init is never called)
712  */
713 struct GNUNET_CORE_Handle *
714 GNUNET_CORE_connect (struct GNUNET_SCHEDULER_Handle *sched,
715                      const struct GNUNET_CONFIGURATION_Handle *cfg,
716                      struct GNUNET_TIME_Relative timeout,
717                      void *cls,
718                      GNUNET_CORE_StartupCallback init,
719                      GNUNET_CORE_ClientEventHandler connects,
720                      GNUNET_CORE_ClientEventHandler disconnects,
721                      GNUNET_CORE_MessageCallback inbound_notify,
722                      int inbound_hdr_only,
723                      GNUNET_CORE_MessageCallback outbound_notify,
724                      int outbound_hdr_only,
725                      const struct GNUNET_CORE_MessageHandler *handlers)
726 {
727   struct GNUNET_CORE_Handle *h;
728
729   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
730   h->sched = sched;
731   h->cfg = cfg;
732   h->cls = cls;
733   h->init = init;
734   h->connects = connects;
735   h->disconnects = disconnects;
736   h->inbound_notify = inbound_notify;
737   h->outbound_notify = outbound_notify;
738   h->inbound_hdr_only = inbound_hdr_only;
739   h->outbound_hdr_only = outbound_hdr_only;
740   h->handlers = handlers;
741   h->client = GNUNET_CLIENT_connect (sched, "core", cfg);
742   if (h->client == NULL)
743     {
744       GNUNET_free (h);
745       return NULL;
746     }
747   h->startup_timeout = GNUNET_TIME_relative_to_absolute (timeout);
748   h->hcnt = 0;
749   while (handlers[h->hcnt].callback != NULL)
750     h->hcnt++;
751   GNUNET_assert (h->hcnt <
752                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
753                   sizeof (struct InitMessage)) / sizeof (uint16_t));
754 #if DEBUG_CORE
755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
756               "Trying to connect to core service in next %llu ms.\n",
757               timeout.value);
758 #endif
759   h->th =
760     GNUNET_CLIENT_notify_transmit_ready (h->client,
761                                          sizeof (struct InitMessage) +
762                                          sizeof (uint16_t) * h->hcnt, timeout,
763                                          GNUNET_YES,
764                                          &transmit_start, h);
765   return h;
766 }
767
768
769 /**
770  * Disconnect from the core service.
771  *
772  * @param handle connection to core to disconnect
773  */
774 void
775 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
776 {
777   if (handle->th != NULL)
778     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
779   if (handle->solicit_transmit_req != NULL)
780     GNUNET_CORE_notify_transmit_ready_cancel (handle->solicit_transmit_req);
781   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
782     GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
783   GNUNET_CLIENT_disconnect (handle->client);
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 #if DEBUG_CORE
817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818               "Preparing for P2P transmission to `%4s'.\n",
819               GNUNET_i2s(&th->peer));
820 #endif
821   GNUNET_assert (th->timeout_task != GNUNET_SCHEDULER_NO_TASK);
822   sm = (struct SendMessage *) buf;
823   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
824   sm->priority = htonl (th->priority);
825   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
826   sm->peer = th->peer;
827   notify = th->notify;
828   notify_cls = th->notify_cls;
829   GNUNET_CORE_notify_transmit_ready_cancel (th);
830   trigger_next_request (h);
831   GNUNET_assert (size >= sizeof (struct SendMessage));
832   dt = notify (notify_cls, size - sizeof (struct SendMessage), &sm[1]);
833   if (0 == dt)
834     {
835       /* client decided to send nothing! */
836       return 0;
837     }
838   GNUNET_assert (dt >= sizeof (struct GNUNET_MessageHeader));
839   sm->header.size = htons (dt + sizeof (struct SendMessage));
840   GNUNET_assert (dt + sizeof (struct SendMessage) < size);
841   return dt + sizeof (struct SendMessage);
842 }
843
844
845 /**
846  * Ask the core to call "notify" once it is ready to transmit the
847  * given number of bytes to the specified "target".  If we are not yet
848  * connected to the specified peer, a call to this function will cause
849  * us to try to establish a connection.
850  *
851  * @param handle connection to core service
852  * @param priority how important is the message?
853  * @param maxdelay how long can the message wait?
854  * @param target who should receive the message,
855  *        use NULL for this peer (loopback)
856  * @param notify_size how many bytes of buffer space does notify want?
857  * @param notify function to call when buffer space is available
858  * @param notify_cls closure for notify
859  * @return non-NULL if the notify callback was queued,
860  *         NULL if we can not even queue the request (insufficient
861  *         memory); if NULL is returned, "notify" will NOT be called.
862  */
863 struct GNUNET_CORE_TransmitHandle *
864 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
865                                    unsigned int priority,
866                                    struct GNUNET_TIME_Relative maxdelay,
867                                    const struct GNUNET_PeerIdentity *target,
868                                    size_t notify_size,
869                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
870                                    void *notify_cls)
871 {
872   struct GNUNET_CORE_TransmitHandle *th;
873
874   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
875                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
876   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
877   th->ch = handle;
878   /* append to list */
879   th->prev = handle->pending_tail;
880   if (handle->pending_tail == NULL)
881     handle->pending_head = th;
882   else
883     handle->pending_tail->next = th;
884   th->get_message = &produce_send;
885   th->get_message_cls = th;
886   th->notify = notify;
887   th->notify_cls = notify_cls;
888   th->peer = *target;
889   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
890   th->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->sched,
891                                                    maxdelay,
892                                                    &timeout_request, th);
893   th->priority = priority;
894   th->msize = sizeof (struct SendMessage) + notify_size;
895   /* was the request queue previously empty? */
896   if ( (handle->pending_head == th) &&
897        (handle->th == NULL) )
898     trigger_next_request (handle);
899   return th;
900 }
901
902
903 /**
904  * Cancel the specified transmission-ready notification.
905  *
906  * @param h handle that was returned by "notify_transmit_ready".
907  */
908 void
909 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
910                                           *h)
911 {
912   struct GNUNET_CORE_Handle *handle = h->ch;
913
914   if (handle->submitted == h)
915     {
916       handle->submitted = NULL;
917     }
918   else
919     {
920       if (h->prev == NULL)
921         handle->pending_head = h->next;
922       else
923         h->prev->next = h->next;
924       if (h->next == NULL)
925         handle->pending_tail = h->prev;
926       else
927         h->next->prev = h->prev;
928     }
929   if (h->timeout_task != GNUNET_SCHEDULER_NO_TASK)
930     GNUNET_SCHEDULER_cancel (handle->sched, h->timeout_task);
931   GNUNET_free (h);
932 }
933
934
935 /* end of core_api.c */