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