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