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