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