adding argument to GNUNET_CORE_connect -- not yet implemented
[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 messages we should queue per target.
133    */
134   unsigned int queue_size;
135
136   /**
137    * Number of entries in the handlers array.
138    */
139   unsigned int hcnt;
140
141   /**
142    * For inbound notifications without a specific handler, do
143    * we expect to only receive headers?
144    */
145   int inbound_hdr_only;
146
147   /**
148    * For outbound notifications without a specific handler, do
149    * we expect to only receive headers?
150    */
151   int outbound_hdr_only;
152
153   /**
154    * Are we currently disconnected and hence unable to forward
155    * requests?
156    */
157   int currently_down;
158 };
159
160
161 /**
162  * Handle for a transmission request.
163  */
164 struct GNUNET_CORE_TransmitHandle
165 {
166
167   /**
168    * We keep active transmit handles in a doubly-linked list.
169    */
170   struct GNUNET_CORE_TransmitHandle *next;
171
172   /**
173    * We keep active transmit handles in a doubly-linked list.
174    */
175   struct GNUNET_CORE_TransmitHandle *prev;
176
177   /**
178    * Corresponding core handle.
179    */
180   struct GNUNET_CORE_Handle *ch;
181
182   /**
183    * Function that will be called to get the actual request
184    * (once we are ready to transmit this request to the core).
185    * The function will be called with a NULL buffer to signal
186    * timeout.
187    */
188   GNUNET_CONNECTION_TransmitReadyNotify get_message;
189
190   /**
191    * Closure for get_message.
192    */
193   void *get_message_cls;
194
195   /**
196    * If this entry is for a transmission request, pointer
197    * to the notify callback; otherwise NULL.
198    */
199   GNUNET_CONNECTION_TransmitReadyNotify notify;
200
201   /**
202    * Closure for notify.
203    */
204   void *notify_cls;
205
206   /**
207    * Peer the request is about.
208    */
209   struct GNUNET_PeerIdentity peer;
210
211   /**
212    * Timeout for this handle.
213    */
214   struct GNUNET_TIME_Absolute timeout;
215
216   /**
217    * ID of timeout task.
218    */
219   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
220
221   /**
222    * How important is this message?
223    */
224   uint32_t priority;
225
226   /**
227    * Size of this request.
228    */
229   uint16_t msize;
230
231
232 };
233
234
235 static void
236 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
237
238
239 /**
240  * Function called when we are ready to transmit our
241  * "START" message (or when this operation timed out).
242  *
243  * @param cls closure
244  * @param size number of bytes available in buf
245  * @param buf where the callee should write the message
246  * @return number of bytes written to buf
247  */
248 static size_t transmit_start (void *cls, size_t size, void *buf);
249
250
251 /**
252  * Our current client connection went down.  Clean it up
253  * and try to reconnect!
254  *
255  * @param h our handle to the core service
256  */
257 static void
258 reconnect (struct GNUNET_CORE_Handle *h)
259 {
260 #if DEBUG_CORE
261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
262               "Reconnecting to CORE service\n");
263 #endif
264   if (h->client_notifications != NULL)
265     GNUNET_CLIENT_disconnect (h->client_notifications, GNUNET_NO);
266   h->currently_down = GNUNET_YES;
267   h->client_notifications = GNUNET_CLIENT_connect ("core", h->cfg);
268   if (h->client_notifications == NULL)
269     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (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(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, do not process other messages! */
513               break;
514             }
515         }
516       if (NULL != h->inbound_notify)
517         h->inbound_notify (h->cls, &ntm->peer, em,
518                            GNUNET_TIME_relative_ntoh (ntm->latency),
519                            ntohl (ntm->distance));
520       break;
521     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
522       if (msize <
523           sizeof (struct NotifyTrafficMessage) +
524           sizeof (struct GNUNET_MessageHeader))
525         {
526           GNUNET_break (0);
527           break;
528         }
529       ntm = (const struct NotifyTrafficMessage *) msg;
530       em = (const struct GNUNET_MessageHeader *) &ntm[1];
531       if ((GNUNET_NO == h->outbound_hdr_only) &&
532           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
533         {
534           GNUNET_break (0);
535           break;
536         }
537       if (NULL == h->outbound_notify)
538         {
539           GNUNET_break (0);
540           break;
541         }
542       h->outbound_notify (h->cls, &ntm->peer, em,
543                           GNUNET_TIME_relative_ntoh (ntm->latency),
544                           ntohl (ntm->distance));
545       break;
546     default:
547       GNUNET_break (0);
548       break;
549     }
550   GNUNET_CLIENT_receive (h->client_notifications,
551                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
552 }
553
554
555 /**
556  * Function called when we are ready to transmit our
557  * "START" message (or when this operation timed out).
558  *
559  * @param cls closure
560  * @param size number of bytes available in buf
561  * @param buf where the callee should write the message
562  * @return number of bytes written to buf
563  */
564 static size_t transmit_start (void *cls, size_t size, void *buf);
565
566
567 /**
568  * Function called on the first message received from
569  * the service (contains our public key, etc.).
570  * Should trigger calling the init callback
571  * and then start our regular message processing.
572  *
573  * @param cls closure
574  * @param msg message received, NULL on timeout or fatal error
575  */
576 static void
577 init_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg)
578 {
579   struct GNUNET_CORE_Handle *h = cls;
580   const struct InitReplyMessage *m;
581   GNUNET_CORE_StartupCallback init;
582   struct GNUNET_PeerIdentity my_identity;
583
584   if ((msg == NULL) ||
585       (ntohs (msg->size) != sizeof (struct InitReplyMessage)) ||
586       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY))
587     {
588       if (msg != NULL)
589         {
590           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
591                       _
592                       ("Error connecting to core service (failed to receive `%s' message, got message of type %u and size %u).\n"),
593                       "INIT_REPLY",
594                       ntohs (msg->type),
595                       ntohs (msg->size));
596           GNUNET_break (0);
597         }
598       else
599         {
600 #if DEBUG_CORE
601           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
602                       _("Failed to connect to core service, will retry.\n"));
603 #endif
604         }
605       transmit_start (h, 0, NULL);
606       return;
607     }
608   m = (const struct InitReplyMessage *) msg;
609   GNUNET_break (0 == ntohl (m->reserved));
610   /* start our message processing loop */
611 #if DEBUG_CORE
612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
613               "Successfully connected to core service, starting processing loop.\n");
614 #endif
615   h->currently_down = GNUNET_NO;
616   trigger_next_request (h);
617   GNUNET_CLIENT_receive (h->client_notifications,
618                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
619   if (NULL != (init = h->init))
620     {
621       /* mark so we don't call init on reconnect */
622       h->init = NULL;
623       GNUNET_CRYPTO_hash (&m->publicKey,
624                           sizeof (struct
625                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
626                           &my_identity.hashPubKey);
627       init (h->cls, h, &my_identity, &m->publicKey);
628     }
629 }
630
631
632 static void
633 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
634 {
635   struct GNUNET_CORE_Handle *h = cls;
636   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
637   reconnect (h);
638 }
639
640
641 /**
642  * Function called when we are ready to transmit our
643  * "START" message (or when this operation timed out).
644  *
645  * @param cls closure
646  * @param size number of bytes available in buf
647  * @param buf where the callee should write the message
648  * @return number of bytes written to buf
649  */
650 static size_t
651 transmit_start (void *cls, size_t size, void *buf)
652 {
653   struct GNUNET_CORE_Handle *h = cls;
654   struct InitMessage *init;
655   uint16_t *ts;
656   uint16_t msize;
657   uint32_t opt;
658   unsigned int hpos;
659   struct GNUNET_TIME_Relative delay;
660
661   h->cth = NULL;
662   if (size == 0)
663     {
664       if ((h->init == NULL) ||
665           (GNUNET_TIME_absolute_get ().abs_value < h->startup_timeout.abs_value))
666         {
667           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
668                       _("Failed to connect to core service, retrying.\n"));
669           delay = GNUNET_TIME_absolute_get_remaining (h->startup_timeout);
670           if ((h->init == NULL) || (delay.rel_value > 1000))
671             delay = GNUNET_TIME_UNIT_SECONDS;
672           if (h->init == NULL)
673             h->startup_timeout =
674               GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
675           h->reconnect_task =
676             GNUNET_SCHEDULER_add_delayed (delay, &reconnect_task, h);
677           return 0;
678         }
679       /* timeout on initial connect */
680       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
681                   _("Failed to connect to core service, giving up.\n"));
682       h->init (h->cls, NULL, NULL, NULL);
683       GNUNET_CORE_disconnect (h);
684       return 0;
685     }
686   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
687   GNUNET_assert (size >= msize);
688   init = buf;
689   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
690   init->header.size = htons (msize);
691   opt = GNUNET_CORE_OPTION_NOTHING;
692   if (h->connects != NULL)
693     opt |= GNUNET_CORE_OPTION_SEND_CONNECT;
694   if (h->disconnects != NULL)
695     opt |= GNUNET_CORE_OPTION_SEND_DISCONNECT;
696   if (h->status_events != NULL)
697     opt |= GNUNET_CORE_OPTION_SEND_STATUS_CHANGE;
698   if (h->inbound_notify != NULL)
699     {
700       if (h->inbound_hdr_only)
701         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
702       else
703         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
704     }
705   if (h->outbound_notify != NULL)
706     {
707       if (h->outbound_hdr_only)
708         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
709       else
710         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
711     }
712   init->options = htonl (opt);
713   ts = (uint16_t *) & init[1];
714   for (hpos = 0; hpos < h->hcnt; hpos++)
715     ts[hpos] = htons (h->handlers[hpos].type);
716   GNUNET_CLIENT_receive (h->client_notifications,
717                          &init_reply_handler,
718                          h,
719                          GNUNET_TIME_absolute_get_remaining
720                          (h->startup_timeout));
721   return sizeof (struct InitMessage) + h->hcnt * sizeof (uint16_t);
722 }
723
724
725 /**
726  * Connect to the core service.  Note that the connection may
727  * complete (or fail) asynchronously.
728  *
729  * @param cfg configuration to use
730  * @param queue_size size of the per-peer message queue
731  * @param timeout after how long should we give up trying to connect to the core service?
732  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
733  * @param init callback to call on timeout or once we have successfully
734  *        connected to the core service; note that timeout is only meaningful if init is not NULL
735  * @param connects function to call on peer connect, can be NULL
736  * @param disconnects function to call on peer disconnect / timeout, can be NULL
737  * @param status_events function to call on changes to peer connection status, can be NULL
738  * @param inbound_notify function to call for all inbound messages, can be NULL
739  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
740  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
741  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
742  * @param outbound_notify function to call for all outbound messages, can be NULL
743  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
744  *                GNUNET_MessageHeader and hence we do not need to give it the full message
745  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
746  * @param handlers callbacks for messages we care about, NULL-terminated
747  * @return handle to the core service (only useful for disconnect until 'init' is called);
748  *                NULL on error (in this case, init is never called)
749  */
750 struct GNUNET_CORE_Handle *
751 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
752                      unsigned int queue_size,
753                      struct GNUNET_TIME_Relative timeout,
754                      void *cls,
755                      GNUNET_CORE_StartupCallback init,
756                      GNUNET_CORE_ConnectEventHandler connects,
757                      GNUNET_CORE_DisconnectEventHandler disconnects,
758                      GNUNET_CORE_PeerStatusEventHandler status_events,
759                      GNUNET_CORE_MessageCallback inbound_notify,
760                      int inbound_hdr_only,
761                      GNUNET_CORE_MessageCallback outbound_notify,
762                      int outbound_hdr_only,
763                      const struct GNUNET_CORE_MessageHandler *handlers)
764 {
765   struct GNUNET_CORE_Handle *h;
766
767   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
768   h->cfg = cfg;
769   h->cls = cls;
770   h->init = init;
771   h->connects = connects;
772   h->disconnects = disconnects;
773   h->status_events = status_events;
774   h->inbound_notify = inbound_notify;
775   h->outbound_notify = outbound_notify;
776   h->inbound_hdr_only = inbound_hdr_only;
777   h->outbound_hdr_only = outbound_hdr_only;
778   h->handlers = handlers;
779   h->queue_size = queue_size;
780   h->client_notifications = GNUNET_CLIENT_connect ("core", cfg);
781   if (h->client_notifications == NULL)
782     {
783       GNUNET_free (h);
784       return NULL;
785     }
786   h->startup_timeout = GNUNET_TIME_relative_to_absolute (timeout);
787   h->hcnt = 0;
788   while (handlers[h->hcnt].callback != NULL)
789     h->hcnt++;
790   GNUNET_assert (h->hcnt <
791                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
792                   sizeof (struct InitMessage)) / sizeof (uint16_t));
793 #if DEBUG_CORE
794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795               "Trying to connect to core service in next %llu ms.\n",
796               timeout.rel_value);
797 #endif
798   h->cth =
799     GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
800                                          sizeof (struct InitMessage) +
801                                          sizeof (uint16_t) * h->hcnt, timeout,
802                                          GNUNET_YES,
803                                          &transmit_start, h);
804   return h;
805 }
806
807
808 /**
809  * Disconnect from the core service.
810  *
811  * @param handle connection to core to disconnect
812  */
813 void
814 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
815 {
816   if (handle->cth != NULL)
817     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->cth);
818   if (handle->solicit_transmit_req != NULL)
819     GNUNET_CORE_notify_transmit_ready_cancel (handle->solicit_transmit_req);
820   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
821     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
822   if (handle->client_notifications != NULL)
823     GNUNET_CLIENT_disconnect (handle->client_notifications, GNUNET_NO);
824   GNUNET_break (handle->pending_head == NULL);
825   GNUNET_free_non_null (handle->solicit_buffer);
826   GNUNET_free (handle);
827 }
828
829
830 /**
831  * Build the message requesting data transmission.
832  */
833 static size_t
834 produce_send (void *cls, size_t size, void *buf)
835 {
836   struct GNUNET_CORE_TransmitHandle *th = cls;
837   struct GNUNET_CORE_Handle *h;
838   struct SendMessage *sm;
839   size_t dt;
840   GNUNET_CONNECTION_TransmitReadyNotify notify;
841   void *notify_cls;
842
843   h = th->ch;
844   if (buf == NULL)
845     {
846       /* timeout or error */
847 #if DEBUG_CORE
848       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849                   "P2P transmission request for `%4s' timed out.\n",
850                   GNUNET_i2s(&th->peer));
851 #endif
852       GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
853       GNUNET_CORE_notify_transmit_ready_cancel (th);
854       if ((h->pending_head == th) && (h->cth != NULL)) /* Request hasn't been canceled yet! */
855         {
856           GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
857           h->cth = NULL;
858           trigger_next_request (h);
859         }
860       /* Otherwise this request timed out, but another is actually queued for sending, so don't try to send another! */
861       return 0;
862     }
863   sm = (struct SendMessage *) buf;
864   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
865   sm->priority = htonl (th->priority);
866   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
867   sm->peer = th->peer;
868   notify = th->notify;
869   notify_cls = th->notify_cls;
870   GNUNET_CORE_notify_transmit_ready_cancel (th);
871   trigger_next_request (h);
872   size = GNUNET_MIN (size,
873                      GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
874   GNUNET_assert (size >= sizeof (struct SendMessage));
875   dt = notify (notify_cls, size - sizeof (struct SendMessage), &sm[1]);
876   if (0 == dt)
877     {
878 #if DEBUG_CORE
879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880               "Size of clients message to peer %s is 0!\n",
881               GNUNET_i2s(&sm->peer));
882 #endif
883       /* client decided to send nothing! */
884       return 0;
885     }
886 #if DEBUG_CORE
887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
888               "Produced SEND message to core with %u bytes payload\n",
889               dt);
890 #endif
891   GNUNET_assert (dt >= sizeof (struct GNUNET_MessageHeader));
892   if (dt + sizeof (struct SendMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
893     {
894       GNUNET_break (0);
895       return 0;
896     }
897 #if DEBUG_CORE
898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899               "Preparing for P2P transmission of %u bytes to `%4s'.\n",
900               dt,
901               GNUNET_i2s(&sm->peer));
902 #endif
903   sm->header.size = htons (dt + sizeof (struct SendMessage));
904   GNUNET_assert (dt + sizeof (struct SendMessage) <= size);
905   return dt + sizeof (struct SendMessage);
906 }
907
908
909 /**
910  * Ask the core to call "notify" once it is ready to transmit the
911  * given number of bytes to the specified "target".  If we are not yet
912  * connected to the specified peer, a call to this function will cause
913  * us to try to establish a connection.
914  *
915  * @param handle connection to core service
916  * @param priority how important is the message?
917  * @param maxdelay how long can the message wait?
918  * @param target who should receive the message,
919  *        use NULL for this peer (loopback)
920  * @param notify_size how many bytes of buffer space does notify want?
921  * @param notify function to call when buffer space is available
922  * @param notify_cls closure for notify
923  * @return non-NULL if the notify callback was queued,
924  *         NULL if we can not even queue the request (insufficient
925  *         memory); if NULL is returned, "notify" will NOT be called.
926  */
927 struct GNUNET_CORE_TransmitHandle *
928 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
929                                    unsigned int priority,
930                                    struct GNUNET_TIME_Relative maxdelay,
931                                    const struct GNUNET_PeerIdentity *target,
932                                    size_t notify_size,
933                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
934                                    void *notify_cls)
935 {
936   struct GNUNET_CORE_TransmitHandle *th;
937
938   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
939                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
940   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
941   th->ch = handle;
942   GNUNET_CONTAINER_DLL_insert_after (handle->pending_head,
943                                      handle->pending_tail,
944                                      handle->pending_tail,
945                                      th);
946   th->get_message = &produce_send;
947   th->get_message_cls = th;
948   th->notify = notify;
949   th->notify_cls = notify_cls;
950   th->peer = *target;
951   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
952   th->timeout_task = GNUNET_SCHEDULER_add_delayed (maxdelay,
953                                                    &timeout_request, th);
954   th->priority = priority;
955   th->msize = sizeof (struct SendMessage) + notify_size;
956   /* was the request queue previously empty? */
957   if ( (handle->pending_head == th) &&
958        (handle->cth == NULL) )
959     trigger_next_request (handle);
960   return th;
961 }
962
963
964 /**
965  * Cancel the specified transmission-ready notification.
966  *s
967  * @param th handle that was returned by "notify_transmit_ready".
968  */
969 void
970 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
971                                           *th)
972 {
973   struct GNUNET_CORE_Handle *h = th->ch;
974   
975   if (h->submitted == th)
976     h->submitted = NULL;
977   else    
978     GNUNET_CONTAINER_DLL_remove (h->pending_head,
979                                  h->pending_tail,
980                                  th);    
981   if (th->timeout_task != GNUNET_SCHEDULER_NO_TASK)
982     GNUNET_SCHEDULER_cancel (th->timeout_task);
983   GNUNET_free (th);
984 }
985
986
987 /* end of core_api.c */