02379e36e75910a0b5b4c25164979dfbd3cae3de
[oweals/gnunet.git] / src / core / core_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 2, 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_core_service.h"
29 #include "core.h"
30
31
32 /**
33  * Context for the core service connection.
34  */
35 struct GNUNET_CORE_Handle
36 {
37
38   /**
39    * Our scheduler.
40    */
41   struct GNUNET_SCHEDULER_Handle *sched;
42
43   /**
44    * Configuration we're using.
45    */
46   struct GNUNET_CONFIGURATION_Handle *cfg;
47
48   /**
49    * Closure for the various callbacks.
50    */
51   void *cls;
52
53   /**
54    * Function to call once we've handshaked with the core service.
55    */
56   GNUNET_CORE_StartupCallback init;
57
58   /**
59    * Function to call whenever we're notified about a peer connecting.
60    */
61   GNUNET_CORE_ClientEventHandler connects;
62
63   /**
64    * Function to call whenever we're notified about a peer disconnecting.
65    */
66   GNUNET_CORE_ClientEventHandler disconnects;
67
68   /**
69    * Function to call whenever we're asked to generate traffic
70    * (data provided to be transmitted back to the service).
71    */
72   GNUNET_CORE_BufferFillCallback bfc;
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.
91    */
92   struct GNUNET_CLIENT_Connection *client;
93
94   /**
95    * Handle for our current transmission request.
96    */
97   struct GNUNET_NETWORK_TransmitHandle *th;
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    * How long to wait until we time out the connection attempt?
116    */
117   struct GNUNET_TIME_Absolute startup_timeout;
118
119   /**
120    * ID of reconnect task (if any).
121    */
122   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
123
124   /**
125    * Number of entries in the handlers array.
126    */
127   unsigned int hcnt;
128
129   /**
130    * For inbound notifications without a specific handler, do
131    * we expect to only receive headers?
132    */
133   int inbound_hdr_only;
134
135   /**
136    * For outbound notifications without a specific handler, do
137    * we expect to only receive headers?
138    */
139   int outbound_hdr_only;
140
141   /**
142    * Are we currently disconnected and hence unable to forward
143    * requests?
144    */
145   int currently_down;
146 };
147
148
149 /**
150  * Handle for a transmission request.
151  */
152 struct GNUNET_CORE_TransmitHandle
153 {
154
155   /**
156    * We keep active transmit handles in a doubly-linked list.
157    */
158   struct GNUNET_CORE_TransmitHandle *next;
159
160   /**
161    * We keep active transmit handles in a doubly-linked list.
162    */
163   struct GNUNET_CORE_TransmitHandle *prev;
164
165   /**
166    * Corresponding core handle.
167    */
168   struct GNUNET_CORE_Handle *ch;
169
170   /**
171    * Function that will be called to get the actual request
172    * (once we are ready to transmit this request to the core).
173    * The function will be called with a NULL buffer to signal
174    * timeout.
175    */
176   GNUNET_NETWORK_TransmitReadyNotify get_message;
177
178   /**
179    * Closure for get_message.
180    */
181   void *get_message_cls;
182
183   /**
184    * If this entry is for a configuration request, pointer
185    * to the information callback; otherwise NULL.
186    */
187   GNUNET_CORE_PeerConfigurationInfoCallback info;
188
189   /**
190    * Closure for info.
191    */
192   void *info_cls;
193
194   /**
195    * If this entry is for a transmission request, pointer
196    * to the notify callback; otherwise NULL.
197    */
198   GNUNET_NETWORK_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 /**
235  * Function called when we are ready to transmit our
236  * "START" message (or when this operation timed out).
237  *
238  * @param cls closure
239  * @param size number of bytes available in buf
240  * @param buf where the callee should write the message
241  * @return number of bytes written to buf
242  */
243 static size_t transmit_start (void *cls, size_t size, void *buf);
244
245
246 /**
247  * Our current client connection went down.  Clean it up
248  * and try to reconnect!
249  */
250 static void
251 reconnect (struct GNUNET_CORE_Handle *h)
252 {
253   GNUNET_CLIENT_disconnect (h->client);
254   h->currently_down = GNUNET_YES;
255   h->client = GNUNET_CLIENT_connect (h->sched, "core", h->cfg);
256   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
257                                                sizeof (struct InitMessage) +
258                                                sizeof (uint16_t) * h->hcnt,
259                                                GNUNET_TIME_UNIT_SECONDS,
260                                                &transmit_start, h);
261 }
262
263
264 /**
265  * The given request hit its timeout.  Remove from the
266  * doubly-linked list and call the respective continuation.
267  *
268  * @param cls the transmit handle of the request that timed out
269  * @param tc context, can be NULL (!)
270  */
271 static void
272 timeout_request (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
273 {
274   struct GNUNET_CORE_TransmitHandle *th = cls;
275   struct GNUNET_CORE_Handle *h;
276
277   h = th->ch;
278   th->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
279   GNUNET_assert (0 == th->get_message (th->get_message_cls, 0, NULL));
280   GNUNET_CORE_notify_transmit_ready_cancel (th);
281 }
282
283
284 /**
285  * Function called when we are ready to transmit a request from our
286  * request list (or when this operation timed out).
287  *
288  * @param cls closure
289  * @param size number of bytes available in buf
290  * @param buf where the callee should write the message
291  * @return number of bytes written to buf
292  */
293 static size_t
294 request_start (void *cls, size_t size, void *buf)
295 {
296   struct GNUNET_CORE_Handle *h = cls;
297   struct GNUNET_CORE_TransmitHandle *th;
298   size_t ret;
299
300   h->th = NULL;
301   th = h->pending_head;
302   if (buf == NULL)
303     {
304       timeout_request (th, NULL);
305       return 0;
306     }
307   /* create new timeout task (in case core takes too long to respond!) */
308   th->timeout_task = GNUNET_SCHEDULER_add_delayed (h->sched,
309                                                    GNUNET_NO,
310                                                    GNUNET_SCHEDULER_PRIORITY_KEEP,
311                                                    GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
312                                                    GNUNET_TIME_absolute_get_remaining
313                                                    (th->timeout),
314                                                    &timeout_request, th);
315   /* remove th from doubly-linked pending list, move to submitted */
316   GNUNET_assert (th->prev == NULL);
317   h->pending_head = th->next;
318   if (th->next == NULL)
319     h->pending_tail = NULL;
320   else
321     th->next->prev = NULL;
322   GNUNET_assert (h->submitted == NULL);
323   h->submitted = th;
324   GNUNET_assert (size >= th->msize);
325   ret = th->get_message (th->get_message_cls, size, buf);
326   GNUNET_assert (ret <= size);
327   return ret;
328 }
329
330
331 /**
332  * Check the list of pending requests, send the next
333  * one to the core.
334  */
335 static void
336 trigger_next_request (struct GNUNET_CORE_Handle *h)
337 {
338   struct GNUNET_CORE_TransmitHandle *th;
339   if (h->currently_down)
340     return;                     /* connection temporarily down */
341   if (NULL == (th = h->pending_head))
342     return;                     /* no requests pending */
343   GNUNET_assert (NULL == h->th);
344   GNUNET_SCHEDULER_cancel (h->sched, th->timeout_task);
345   th->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
346   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
347                                                th->msize,
348                                                GNUNET_TIME_absolute_get_remaining
349                                                (th->timeout), &request_start,
350                                                h);
351 }
352
353
354 /**
355  * cls is a pointer to a 32 bit number followed by that
356  * amount of data.  If possible, copy to buf and return
357  * number of bytes copied.  Always free the buffer.
358  */
359 static size_t
360 copy_and_free (void *cls, size_t size, void *buf)
361 {
362   char *cbuf = cls;
363   uint32_t have;
364
365   memcpy (&have, cbuf, sizeof (uint32_t));
366   if (have > size)
367     {
368       /* timeout / error case */
369       GNUNET_free (cbuf);
370       return 0;
371     }
372   memcpy (buf, cbuf + sizeof (uint32_t), have);
373   GNUNET_free (cbuf);
374   return have;
375 }
376
377
378 /**
379  * Call bfc callback to solicit traffic for the given peer.
380  */
381 static void
382 solicit_traffic (struct GNUNET_CORE_Handle *h,
383                  const struct GNUNET_PeerIdentity *peer, uint32_t amount)
384 {
385   char buf[amount];
386   size_t have;
387   char *cbuf;
388
389   have = h->bfc (h->cls, peer, buf, amount);
390   if (have == 0)
391     return;
392   GNUNET_assert (have >= sizeof (struct GNUNET_MessageHeader));
393   cbuf = GNUNET_malloc (have + sizeof (uint32_t));
394   memcpy (cbuf, &have, sizeof (uint32_t));
395   memcpy (cbuf + sizeof (uint32_t), buf, have);
396   GNUNET_CORE_notify_transmit_ready (h,
397                                      0,
398                                      GNUNET_TIME_UNIT_SECONDS,
399                                      peer, have, &copy_and_free, cbuf);
400 }
401
402
403 /**
404  * Handler for most messages received from the core.
405  */
406 static void
407 main_handler (void *cls, const struct GNUNET_MessageHeader *msg)
408 {
409   struct GNUNET_CORE_Handle *h = cls;
410   unsigned int hpos;
411   const struct ConnectNotifyMessage *cnm;
412   const struct NotifyTrafficMessage *ntm;
413   const struct ConfigurationInfoMessage *cim;
414   const struct SolicitTrafficMessage *stm;
415   const struct GNUNET_MessageHeader *em;
416   uint16_t msize;
417   uint16_t et;
418   uint32_t ss;
419   const struct GNUNET_CORE_MessageHandler *mh;
420
421   if (msg == NULL)
422     {
423       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
424                   _
425                   ("Client was disconnected from core service, trying to reconnect.\n"));
426       reconnect (h);
427       return;
428     }
429   msize = ntohs (msg->size);
430 #if DEBUG_CORE
431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
432               "Processing message of type %u and size %u from core service\n",
433               ntohs (msg->type), msize);
434 #endif
435   switch (ntohs (msg->type))
436     {
437     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
438       if (NULL == h->connects)
439         {
440           GNUNET_break (0);
441           break;
442         }
443       if (msize != sizeof (struct ConnectNotifyMessage))
444         {
445           GNUNET_break (0);
446           break;
447         }
448       cnm = (const struct ConnectNotifyMessage *) msg;
449       break;
450     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
451       if (NULL == h->disconnects)
452         {
453           GNUNET_break (0);
454           break;
455         }
456       if (msize != sizeof (struct ConnectNotifyMessage))
457         {
458           GNUNET_break (0);
459           break;
460         }
461       cnm = (const struct ConnectNotifyMessage *) msg;
462       break;
463     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
464       if (msize <
465           sizeof (struct NotifyTrafficMessage) +
466           sizeof (struct GNUNET_MessageHeader))
467         {
468           GNUNET_break (0);
469           break;
470         }
471       ntm = (const struct NotifyTrafficMessage *) msg;
472       em = (const struct GNUNET_MessageHeader *) &ntm[1];
473 #if DEBUG_CORE
474       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
475                   "Received message of type %u from peer `%4s'\n",
476                   ntohs (em->type), GNUNET_i2s (&ntm->peer));
477 #endif
478       if ((GNUNET_NO == h->inbound_hdr_only) &&
479           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
480         {
481           GNUNET_break (0);
482           break;
483         }
484       et = ntohs (em->type);
485       for (hpos = 0; hpos < h->hcnt; hpos++)
486         {
487           mh = &h->handlers[hpos];
488           if (mh->type != et)
489             continue;
490           if ((mh->expected_size != ntohs (em->size)) &&
491               (mh->expected_size != 0))
492             {
493               GNUNET_break (0);
494               continue;
495             }
496           if (GNUNET_OK !=
497               h->handlers[hpos].callback (h->cls, &ntm->peer, em))
498             {
499               /* error in processing, disconnect ! */
500               reconnect (h);
501               return;
502             }
503         }
504       if (NULL != h->inbound_notify)
505         h->inbound_notify (h->cls, &ntm->peer, em);
506       break;
507     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
508       if (msize <
509           sizeof (struct NotifyTrafficMessage) +
510           sizeof (struct GNUNET_MessageHeader))
511         {
512           GNUNET_break (0);
513           break;
514         }
515       ntm = (const struct NotifyTrafficMessage *) msg;
516       em = (const struct GNUNET_MessageHeader *) &ntm[1];
517       if ((GNUNET_NO == h->outbound_hdr_only) &&
518           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
519         {
520           GNUNET_break (0);
521           break;
522         }
523       if (NULL == h->outbound_notify)
524         {
525           GNUNET_break (0);
526           break;
527         }
528       h->outbound_notify (h->cls, &ntm->peer, em);
529       break;
530     case GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO:
531       if (msize != sizeof (struct ConfigurationInfoMessage))
532         {
533           GNUNET_break (0);
534           break;
535         }
536       if (NULL == h->submitted)
537         break;
538       cim = (const struct ConfigurationInfoMessage *) msg;
539
540       /* process configuration data */
541       if (h->submitted->info != NULL)
542         h->submitted->info (h->submitted->info_cls,
543                             &h->submitted->peer,
544                             ntohl (cim->bpm_in),
545                             ntohl (cim->bpm_out),
546                             GNUNET_TIME_relative_ntoh (cim->latency),
547                             (int) ntohl (cim->reserved_amount),
548                             cim->preference);
549       /* done, clean up! */
550       GNUNET_CORE_notify_transmit_ready_cancel (h->submitted);
551       trigger_next_request (h);
552       break;
553     case GNUNET_MESSAGE_TYPE_CORE_SOLICIT_TRAFFIC:
554       if (msize != sizeof (struct SolicitTrafficMessage))
555         {
556           GNUNET_break (0);
557           break;
558         }
559       stm = (const struct SolicitTrafficMessage *) msg;
560       if (NULL == h->bfc)
561         {
562           GNUNET_break (0);
563           break;
564         }
565       ss = ntohl (stm->solicit_size);
566       if ((ss > GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
567           (ss + sizeof (struct SendMessage) > GNUNET_SERVER_MAX_MESSAGE_SIZE))
568         {
569           GNUNET_break (0);
570           break;
571         }
572       solicit_traffic (h, &stm->peer, ss);
573       break;
574     default:
575       GNUNET_break (0);
576       break;
577     }
578   GNUNET_CLIENT_receive (h->client,
579                          &main_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
580 }
581
582
583
584 /**
585  * Function called when we are ready to transmit our
586  * "START" message (or when this operation timed out).
587  *
588  * @param cls closure
589  * @param size number of bytes available in buf
590  * @param buf where the callee should write the message
591  * @return number of bytes written to buf
592  */
593 static size_t transmit_start (void *cls, size_t size, void *buf);
594
595
596 /**
597  * Function called on the first message received from
598  * the service (contains our public key, etc.).
599  * Should trigger calling the init callback
600  * and then start our regular message processing.
601  *
602  * @param cls closure
603  * @param msg message received, NULL on timeout or fatal error
604  */
605 static void
606 init_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg)
607 {
608   struct GNUNET_CORE_Handle *h = cls;
609   const struct InitReplyMessage *m;
610   GNUNET_CORE_StartupCallback init;
611   struct GNUNET_PeerIdentity my_identity;
612
613   if ((msg == NULL) ||
614       (ntohs (msg->size) != sizeof (struct InitReplyMessage)) ||
615       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY))
616     {
617       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
618                   _
619                   ("Error connecting to core service (failed to receive `%s' message).\n"),
620                   "INIT_REPLY");
621       GNUNET_break (msg == NULL);
622       transmit_start (h, 0, NULL);
623       return;
624     }
625   m = (const struct InitReplyMessage *) msg;
626   /* start our message processing loop */
627 #if DEBUG_CORE
628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
629               _
630               ("Successfully connected to core service, starting processing loop.\n"));
631 #endif
632   h->currently_down = GNUNET_NO;
633   trigger_next_request (h);
634   GNUNET_CLIENT_receive (h->client,
635                          &main_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
636   if (NULL != (init = h->init))
637     {
638       /* mark so we don't call init on reconnect */
639       h->init = NULL;
640 #if DEBUG_CORE
641       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
642                   _("Successfully connected to core service.\n"));
643 #endif
644       GNUNET_CRYPTO_hash (&m->publicKey,
645                           sizeof (struct
646                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
647                           &my_identity.hashPubKey);
648       init (h->cls, h, &my_identity, &m->publicKey);
649     }
650 }
651
652
653 static void
654 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
655 {
656   struct GNUNET_CORE_Handle *h = cls;
657   h->reconnect_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
658   reconnect (h);
659 }
660
661
662 /**
663  * Function called when we are ready to transmit our
664  * "START" message (or when this operation timed out).
665  *
666  * @param cls closure
667  * @param size number of bytes available in buf
668  * @param buf where the callee should write the message
669  * @return number of bytes written to buf
670  */
671 static size_t
672 transmit_start (void *cls, size_t size, void *buf)
673 {
674   struct GNUNET_CORE_Handle *h = cls;
675   struct InitMessage *init;
676   uint16_t *ts;
677   uint16_t msize;
678   uint32_t opt;
679   unsigned int hpos;
680   struct GNUNET_TIME_Relative delay;
681
682   h->th = NULL;
683   if (size == 0)
684     {
685       if ((h->init == NULL) ||
686           (GNUNET_TIME_absolute_get ().value < h->startup_timeout.value))
687         {
688           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
689                       _("Failed to connect to core service, retrying.\n"));
690           delay = GNUNET_TIME_absolute_get_remaining (h->startup_timeout);
691           if ((h->init == NULL) || (delay.value > 1000))
692             delay = GNUNET_TIME_UNIT_SECONDS;
693           if (h->init == NULL)
694             h->startup_timeout =
695               GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
696           h->reconnect_task =
697             GNUNET_SCHEDULER_add_delayed (h->sched, GNUNET_NO,
698                                           GNUNET_SCHEDULER_PRIORITY_IDLE,
699                                           GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
700                                           delay, &reconnect_task, h);
701           return 0;
702         }
703       /* timeout on initial connect */
704       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
705                   _("Failed to connect to core service, giving up.\n"));
706       h->init (h->cls, NULL, NULL, NULL);
707       GNUNET_CORE_disconnect (h);
708       return 0;
709     }
710   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
711   GNUNET_assert (size >= msize);
712   init = buf;
713   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
714   init->header.size = htons (msize);
715   opt = GNUNET_CORE_OPTION_NOTHING;
716   if (h->connects != NULL)
717     opt |= GNUNET_CORE_OPTION_SEND_CONNECT;
718   if (h->disconnects != NULL)
719     opt |= GNUNET_CORE_OPTION_SEND_DISCONNECT;
720   if (h->bfc != NULL)
721     opt |= GNUNET_CORE_OPTION_SEND_BFC;
722   if (h->inbound_notify != NULL)
723     {
724       if (h->inbound_hdr_only)
725         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
726       else
727         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
728     }
729   if (h->outbound_notify != NULL)
730     {
731       if (h->outbound_hdr_only)
732         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
733       else
734         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
735     }
736   init->options = htonl (opt);
737   ts = (uint16_t *) & init[1];
738   for (hpos = 0; hpos < h->hcnt; hpos++)
739     ts[hpos] = htons (h->handlers[hpos].type);
740   GNUNET_CLIENT_receive (h->client,
741                          &init_reply_handler,
742                          h,
743                          GNUNET_TIME_absolute_get_remaining
744                          (h->startup_timeout));
745   return sizeof (struct InitMessage) + h->hcnt * sizeof (uint16_t);
746 }
747
748
749 /**
750  * Connect to the core service.  Note that the connection may
751  * complete (or fail) asynchronously.
752  *
753  * @param sched scheduler to use
754  * @param cfg configuration to use
755  * @param timeout after how long should we give up trying to connect to the core service?
756  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
757  * @param init callback to call on timeout or once we have successfully
758  *        connected to the core service
759  * @param connects function to call on peer connect, can be NULL
760  * @param disconnects function to call on peer disconnect / timeout, can be NULL
761  * @param bfc function to call to fill up spare bandwidth, can be NULL
762  * @param inbound_notify function to call for all inbound messages, can be NULL
763  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
764  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
765  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
766  * @param outbound_notify function to call for all outbound messages, can be NULL
767  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
768  *                GNUNET_MessageHeader and hence we do not need to give it the full message
769  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
770  * @param handlers callbacks for messages we care about, NULL-terminated
771  */
772 void
773 GNUNET_CORE_connect (struct GNUNET_SCHEDULER_Handle *sched,
774                      struct GNUNET_CONFIGURATION_Handle *cfg,
775                      struct GNUNET_TIME_Relative timeout,
776                      void *cls,
777                      GNUNET_CORE_StartupCallback init,
778                      GNUNET_CORE_ClientEventHandler connects,
779                      GNUNET_CORE_ClientEventHandler disconnects,
780                      GNUNET_CORE_BufferFillCallback bfc,
781                      GNUNET_CORE_MessageCallback inbound_notify,
782                      int inbound_hdr_only,
783                      GNUNET_CORE_MessageCallback outbound_notify,
784                      int outbound_hdr_only,
785                      const struct GNUNET_CORE_MessageHandler *handlers)
786 {
787   struct GNUNET_CORE_Handle *h;
788
789   GNUNET_assert (init != NULL);
790   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
791   h->sched = sched;
792   h->cfg = cfg;
793   h->cls = cls;
794   h->init = init;
795   h->connects = connects;
796   h->disconnects = disconnects;
797   h->bfc = bfc;
798   h->inbound_notify = inbound_notify;
799   h->outbound_notify = outbound_notify;
800   h->inbound_hdr_only = inbound_hdr_only;
801   h->outbound_hdr_only = outbound_hdr_only;
802   h->handlers = handlers;
803   h->client = GNUNET_CLIENT_connect (sched, "core", cfg);
804   h->startup_timeout = GNUNET_TIME_relative_to_absolute (timeout);
805   h->hcnt = 0;
806   while (handlers[h->hcnt].callback != NULL)
807     h->hcnt++;
808   GNUNET_assert (h->hcnt <
809                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
810                   sizeof (struct InitMessage)) / sizeof (uint16_t));
811 #if DEBUG_CORE
812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813               "Trying to connect to core service in next %llu ms.\n",
814               timeout.value);
815 #endif
816   h->th =
817     GNUNET_CLIENT_notify_transmit_ready (h->client,
818                                          sizeof (struct InitMessage) +
819                                          sizeof (uint16_t) * h->hcnt, timeout,
820                                          &transmit_start, h);
821 }
822
823
824 /**
825  * Disconnect from the core service.
826  *
827  * @param handle connection to core to disconnect
828  */
829 void
830 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
831 {
832   if (handle->th != NULL)
833     GNUNET_NETWORK_notify_transmit_ready_cancel (handle->th);
834   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
835     GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
836   GNUNET_CLIENT_disconnect (handle->client);
837   GNUNET_free (handle);
838 }
839
840
841 /**
842  * Build the configure message.
843  */
844 static size_t
845 produce_configure_message (void *cls, size_t size, void *buf)
846 {
847   struct GNUNET_CORE_TransmitHandle *th = cls;
848   struct GNUNET_CORE_Handle *ch = th->ch;
849
850   if (buf == NULL)
851     {
852       /* communicate handle timeout/error! */
853       if (th->info != NULL)
854         th->info (th->info_cls, NULL, 0, 0, GNUNET_TIME_UNIT_ZERO, 0, 0.0);
855       if (th->timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
856         GNUNET_CORE_notify_transmit_ready_cancel (th);
857       if (ch->submitted == th)
858         ch->submitted = NULL;
859       trigger_next_request (ch);
860       return 0;
861     }
862   GNUNET_assert (size >= sizeof (struct RequestConfigureMessage));
863   memcpy (buf, &th[1], sizeof (struct RequestConfigureMessage));
864   if (th->prev == NULL)
865     ch->pending_head = th->next;
866   else
867     th->prev->next = th->next;
868   if (th->next == NULL)
869     ch->pending_tail = th->prev;
870   else
871     th->next->prev = th->prev;
872   GNUNET_assert (ch->submitted == NULL);
873   ch->submitted = th;
874   return sizeof (struct RequestConfigureMessage);
875 }
876
877
878 /**
879  * Obtain statistics and/or change preferences for the given peer.
880  *
881  * @param handle connection to core to use
882  * @param peer identifies the peer
883  * @param timeout after how long should we give up (and call "info" with NULL
884  *                for "peer" to signal an error)?
885  * @param bpm_out set to the current bandwidth limit (sending) for this peer,
886  *                caller should set "bpm_out" to "-1" to avoid changing
887  *                the current value; otherwise "bpm_out" will be lowered to
888  *                the specified value; passing a pointer to "0" can be used to force
889  *                us to disconnect from the peer; "bpm_out" might not increase
890  *                as specified since the upper bound is generally
891  *                determined by the other peer!
892  * @param amount reserve N bytes for receiving, negative
893  *                amounts can be used to undo a (recent) reservation;
894  * @param preference increase incoming traffic share preference by this amount;
895  *                in the absence of "amount" reservations, we use this
896  *                preference value to assign proportional bandwidth shares
897  *                to all connected peers
898  * @param info function to call with the resulting configuration information
899  * @param info_cls closure for info
900  */
901 void
902 GNUNET_CORE_peer_configure (struct GNUNET_CORE_Handle *handle,
903                             const struct GNUNET_PeerIdentity *peer,
904                             struct GNUNET_TIME_Relative timeout,
905                             unsigned int bpm_out,
906                             int amount,
907                             double preference,
908                             GNUNET_CORE_PeerConfigurationInfoCallback info,
909                             void *info_cls)
910 {
911   struct RequestConfigureMessage *rcm;
912   struct GNUNET_CORE_TransmitHandle *th;
913
914   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle) +
915                       sizeof (struct RequestConfigureMessage));
916   /* append to list */
917   th->prev = handle->pending_tail;
918   if (handle->pending_tail == NULL)
919     handle->pending_head = th;
920   else
921     handle->pending_tail->next = th;
922   th->ch = handle;
923   th->get_message = &produce_configure_message;
924   th->get_message_cls = th;
925   th->info = info;
926   th->info_cls = info_cls;
927   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
928   th->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->sched,
929                                                    GNUNET_NO,
930                                                    GNUNET_SCHEDULER_PRIORITY_KEEP,
931                                                    GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
932                                                    timeout,
933                                                    &timeout_request, th);
934   th->msize = sizeof (struct RequestConfigureMessage);
935   rcm = (struct RequestConfigureMessage *) &th[1];
936   rcm->header.size = htons (sizeof (struct RequestConfigureMessage));
937   rcm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_REQUEST_CONFIGURE);
938   rcm->reserved = htonl (0);
939   rcm->limit_outbound_bpm = htonl (bpm_out);
940   rcm->reserve_inbound = htonl (amount);
941   rcm->preference_change = preference;
942   rcm->peer = *peer;
943   if (handle->pending_head == th)
944     trigger_next_request (handle);
945 }
946
947
948 /**
949  * Build the message requesting data transmission.
950  */
951 static size_t
952 produce_send (void *cls, size_t size, void *buf)
953 {
954   struct GNUNET_CORE_TransmitHandle *th = cls;
955   struct GNUNET_CORE_Handle *h;
956   struct SendMessage *sm;
957   size_t dt;
958   GNUNET_NETWORK_TransmitReadyNotify notify;
959   void *notify_cls;
960
961   h = th->ch;
962   if (buf == NULL)
963     {
964       /* timeout or error */
965       GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
966       if (th->timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
967         GNUNET_CORE_notify_transmit_ready_cancel (th);
968       trigger_next_request (h);
969       return 0;
970     }
971   GNUNET_assert (th->timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
972   sm = (struct SendMessage *) buf;
973   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
974   sm->priority = htonl (th->priority);
975   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
976   sm->peer = th->peer;
977   notify = th->notify;
978   notify_cls = th->notify_cls;
979   GNUNET_CORE_notify_transmit_ready_cancel (th);
980   trigger_next_request (h);
981   GNUNET_assert (size >= sizeof (struct SendMessage));
982   dt = notify (notify_cls, size - sizeof (struct SendMessage), &sm[1]);
983   sm->header.size = htons (dt + sizeof (struct SendMessage));
984   GNUNET_assert (dt + sizeof (struct SendMessage) < size);
985   return dt + sizeof (struct SendMessage);
986 }
987
988
989 /**
990  * Ask the core to call "notify" once it is ready to transmit the
991  * given number of bytes to the specified "target".  If we are not yet
992  * connected to the specified peer, a call to this function will cause
993  * us to try to establish a connection.
994  *
995  * @param handle connection to core service
996  * @param priority how important is the message?
997  * @param maxdelay how long can the message wait?
998  * @param target who should receive the message,
999  *        use NULL for this peer (loopback)
1000  * @param notify_size how many bytes of buffer space does notify want?
1001  * @param notify function to call when buffer space is available
1002  * @param notify_cls closure for notify
1003  * @return non-NULL if the notify callback was queued,
1004  *         NULL if we can not even queue the request (insufficient
1005  *         memory); if NULL is returned, "notify" will NOT be called.
1006  */
1007 struct GNUNET_CORE_TransmitHandle *
1008 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1009                                    unsigned int priority,
1010                                    struct GNUNET_TIME_Relative maxdelay,
1011                                    const struct GNUNET_PeerIdentity *target,
1012                                    size_t notify_size,
1013                                    GNUNET_NETWORK_TransmitReadyNotify notify,
1014                                    void *notify_cls)
1015 {
1016   struct GNUNET_CORE_TransmitHandle *th;
1017
1018   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
1019                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1020   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
1021   th->ch = handle;
1022   /* append to list */
1023   th->prev = handle->pending_tail;
1024   if (handle->pending_tail == NULL)
1025     handle->pending_head = th;
1026   else
1027     handle->pending_tail->next = th;
1028   th->get_message = &produce_send;
1029   th->get_message_cls = th;
1030   th->notify = notify;
1031   th->notify_cls = notify_cls;
1032   th->peer = *target;
1033   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1034   th->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->sched,
1035                                                    GNUNET_NO,
1036                                                    GNUNET_SCHEDULER_PRIORITY_KEEP,
1037                                                    GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1038                                                    maxdelay,
1039                                                    &timeout_request, th);
1040   th->priority = priority;
1041   th->msize = sizeof (struct SendMessage) + notify_size;
1042   /* was the request queue previously empty? */
1043   if (handle->pending_head == th)
1044     trigger_next_request (handle);
1045   return NULL;
1046 }
1047
1048
1049 /**
1050  * Cancel the specified transmission-ready notification.
1051  *
1052  * @param h handle that was returned by "notify_transmit_ready".
1053  */
1054 void
1055 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
1056                                           *h)
1057 {
1058   struct GNUNET_CORE_Handle *handle = h->ch;
1059
1060   if (handle->submitted == h)
1061     {
1062       handle->submitted = NULL;
1063     }
1064   else
1065     {
1066       if (h->prev == NULL)
1067         handle->pending_head = h->next;
1068       else
1069         h->prev->next = h->next;
1070       if (h->next == NULL)
1071         handle->pending_tail = h->prev;
1072       else
1073         h->next->prev = h->prev;
1074     }
1075   if (h->timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1076     GNUNET_SCHEDULER_cancel (handle->sched, h->timeout_task);
1077   GNUNET_free (h);
1078 }
1079
1080
1081 /* end of core_api.c */