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