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