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