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