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