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