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