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