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