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