77c13db86cb2155f5c30bff894f9e86cb8b92b97
[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    * (pre-connects, no session key exchange yet).
61    */
62   GNUNET_CORE_ConnectEventHandler pre_connects;
63
64   /**
65    * Function to call whenever we're notified about a peer connecting.
66    */
67   GNUNET_CORE_ConnectEventHandler connects;
68
69   /**
70    * Function to call whenever we're notified about a peer disconnecting.
71    */
72   GNUNET_CORE_DisconnectEventHandler disconnects;
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 for notifications.
91    */
92   struct GNUNET_CLIENT_Connection *client_notifications;
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_notifications);
267   h->currently_down = GNUNET_YES;
268   h->client_notifications = GNUNET_CLIENT_connect (h->sched, "core", h->cfg);
269   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
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 }
295
296
297 /**
298  * Function called when we are ready to transmit a request from our
299  * request list (or when this operation timed out).
300  *
301  * @param cls closure
302  * @param size number of bytes available in buf
303  * @param buf where the callee should write the message
304  * @return number of bytes written to buf
305  */
306 static size_t
307 request_start (void *cls, size_t size, void *buf)
308 {
309   struct GNUNET_CORE_Handle *h = cls;
310   struct GNUNET_CORE_TransmitHandle *th;
311   size_t ret;
312
313   h->th = NULL;
314   th = h->pending_head;
315   if (buf == NULL)
316     {
317       timeout_request (th, NULL);
318       return 0;
319     }
320   /* create new timeout task (in case core takes too long to respond!) */
321   th->timeout_task = GNUNET_SCHEDULER_add_delayed (h->sched,
322                                                    GNUNET_TIME_absolute_get_remaining
323                                                    (th->timeout),
324                                                    &timeout_request, th);
325   /* remove th from doubly-linked pending list, move to submitted */
326   GNUNET_assert (th->prev == NULL);
327   h->pending_head = th->next;
328   if (th->next == NULL)
329     h->pending_tail = NULL;
330   else
331     th->next->prev = NULL;
332   GNUNET_assert (h->submitted == NULL);
333   h->submitted = th;
334   GNUNET_assert (size >= th->msize);
335   ret = th->get_message (th->get_message_cls, size, buf);
336   GNUNET_assert (ret <= size);
337   return ret;
338 }
339
340
341 /**
342  * Check the list of pending requests, send the next
343  * one to the core.
344  */
345 static void
346 trigger_next_request (struct GNUNET_CORE_Handle *h)
347 {
348   struct GNUNET_CORE_TransmitHandle *th;
349
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   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
356     {
357       GNUNET_SCHEDULER_cancel (h->sched, th->timeout_task);
358       th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
359     }
360   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
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  * Handler for notification messages received from the core.
372  *
373  * @param cls our "struct GNUNET_CORE_Handle"
374  * @param msg the message received from the core service
375  */
376 static void
377 main_notify_handler (void *cls, const struct GNUNET_MessageHeader *msg)
378 {
379   struct GNUNET_CORE_Handle *h = cls;
380   unsigned int hpos;
381   const struct ConnectNotifyMessage *cnm;
382   const struct DisconnectNotifyMessage *dnm;
383   const struct NotifyTrafficMessage *ntm;
384   const struct GNUNET_MessageHeader *em;
385   uint16_t msize;
386   uint16_t et;
387   const struct GNUNET_CORE_MessageHandler *mh;
388
389   if (msg == NULL)
390     {
391       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
392                   _
393                   ("Client was disconnected from core service, trying to reconnect.\n"));
394       reconnect (h);
395       return;
396     }
397   msize = ntohs (msg->size);
398 #if DEBUG_CORE
399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
400               "Processing message of type %u and size %u from core service\n",
401               ntohs (msg->type), msize);
402 #endif
403   switch (ntohs (msg->type))
404     {
405     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_PRE_CONNECT:
406       if (NULL == h->pre_connects)
407         {
408           GNUNET_break (0);
409           break;
410         }
411       if (msize != sizeof (struct ConnectNotifyMessage))
412         {
413           GNUNET_break (0);
414           break;
415         }
416       cnm = (const struct ConnectNotifyMessage *) msg;
417       h->pre_connects (h->cls,
418                        &cnm->peer,
419                        GNUNET_TIME_relative_ntoh (cnm->latency),
420                        ntohl (cnm->distance));
421       break;
422     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT:
423       if (NULL == h->connects)
424         {
425           GNUNET_break (0);
426           break;
427         }
428       if (msize != sizeof (struct ConnectNotifyMessage))
429         {
430           GNUNET_break (0);
431           break;
432         }
433       cnm = (const struct ConnectNotifyMessage *) msg;
434       h->connects (h->cls,
435                    &cnm->peer,
436                    GNUNET_TIME_relative_ntoh (cnm->latency),
437                    ntohl (cnm->distance));
438       break;
439     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT:
440       if (NULL == h->disconnects)
441         {
442           GNUNET_break (0);
443           break;
444         }
445       if (msize != sizeof (struct DisconnectNotifyMessage))
446         {
447           GNUNET_break (0);
448           break;
449         }
450       dnm = (const struct DisconnectNotifyMessage *) msg;
451       h->disconnects (h->cls,
452                       &dnm->peer);
453       break;
454     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND:
455       if (msize <
456           sizeof (struct NotifyTrafficMessage) +
457           sizeof (struct GNUNET_MessageHeader))
458         {
459           GNUNET_break (0);
460           break;
461         }
462       ntm = (const struct NotifyTrafficMessage *) msg;
463       em = (const struct GNUNET_MessageHeader *) &ntm[1];
464 #if DEBUG_CORE
465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466                   "Received message of type %u from peer `%4s'\n",
467                   ntohs (em->type), GNUNET_i2s (&ntm->peer));
468 #endif
469       if ((GNUNET_NO == h->inbound_hdr_only) &&
470           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
471         {
472           GNUNET_break (0);
473           break;
474         }
475       et = ntohs (em->type);
476       for (hpos = 0; hpos < h->hcnt; hpos++)
477         {
478           mh = &h->handlers[hpos];
479           if (mh->type != et)
480             continue;
481           if ((mh->expected_size != ntohs (em->size)) &&
482               (mh->expected_size != 0))
483             {
484               GNUNET_break (0);
485               continue;
486             }
487           if (GNUNET_OK !=
488               h->handlers[hpos].callback (h->cls, &ntm->peer, em,
489                                           GNUNET_TIME_relative_ntoh (ntm->latency),
490                                           ntohl (ntm->distance)))
491             {
492               /* error in processing, disconnect ! */
493               reconnect (h);
494               return;
495             }
496         }
497       if (NULL != h->inbound_notify)
498         h->inbound_notify (h->cls, &ntm->peer, em,
499                            GNUNET_TIME_relative_ntoh (ntm->latency),
500                            ntohl (ntm->distance));
501       break;
502     case GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND:
503       if (msize <
504           sizeof (struct NotifyTrafficMessage) +
505           sizeof (struct GNUNET_MessageHeader))
506         {
507           GNUNET_break (0);
508           break;
509         }
510       ntm = (const struct NotifyTrafficMessage *) msg;
511       em = (const struct GNUNET_MessageHeader *) &ntm[1];
512       if ((GNUNET_NO == h->outbound_hdr_only) &&
513           (msize != ntohs (em->size) + sizeof (struct NotifyTrafficMessage)))
514         {
515           GNUNET_break (0);
516           break;
517         }
518       if (NULL == h->outbound_notify)
519         {
520           GNUNET_break (0);
521           break;
522         }
523       h->outbound_notify (h->cls, &ntm->peer, em,
524                           GNUNET_TIME_relative_ntoh (ntm->latency),
525                           ntohl (ntm->distance));
526       break;
527     default:
528       GNUNET_break (0);
529       break;
530     }
531   GNUNET_CLIENT_receive (h->client_notifications,
532                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
533 }
534
535
536 /**
537  * Function called when we are ready to transmit our
538  * "START" message (or when this operation timed out).
539  *
540  * @param cls closure
541  * @param size number of bytes available in buf
542  * @param buf where the callee should write the message
543  * @return number of bytes written to buf
544  */
545 static size_t transmit_start (void *cls, size_t size, void *buf);
546
547
548 /**
549  * Function called on the first message received from
550  * the service (contains our public key, etc.).
551  * Should trigger calling the init callback
552  * and then start our regular message processing.
553  *
554  * @param cls closure
555  * @param msg message received, NULL on timeout or fatal error
556  */
557 static void
558 init_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg)
559 {
560   struct GNUNET_CORE_Handle *h = cls;
561   const struct InitReplyMessage *m;
562   GNUNET_CORE_StartupCallback init;
563   struct GNUNET_PeerIdentity my_identity;
564
565   if ((msg == NULL) ||
566       (ntohs (msg->size) != sizeof (struct InitReplyMessage)) ||
567       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY))
568     {
569       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
570                   _
571                   ("Error connecting to core service (failed to receive `%s' message).\n"),
572                   "INIT_REPLY");
573       GNUNET_break (msg == NULL);
574       transmit_start (h, 0, NULL);
575       return;
576     }
577   m = (const struct InitReplyMessage *) msg;
578   /* start our message processing loop */
579 #if DEBUG_CORE
580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
581               _
582               ("Successfully connected to core service, starting processing loop.\n"));
583 #endif
584   h->currently_down = GNUNET_NO;
585   trigger_next_request (h);
586   GNUNET_CLIENT_receive (h->client_notifications,
587                          &main_notify_handler, h, GNUNET_TIME_UNIT_FOREVER_REL);
588   if (NULL != (init = h->init))
589     {
590       /* mark so we don't call init on reconnect */
591       h->init = NULL;
592 #if DEBUG_CORE
593       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
594                   _("Successfully connected to core service.\n"));
595 #endif
596       GNUNET_CRYPTO_hash (&m->publicKey,
597                           sizeof (struct
598                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
599                           &my_identity.hashPubKey);
600       init (h->cls, h, &my_identity, &m->publicKey);
601     }
602 }
603
604
605 static void
606 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
607 {
608   struct GNUNET_CORE_Handle *h = cls;
609   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
610   reconnect (h);
611 }
612
613
614 /**
615  * Function called when we are ready to transmit our
616  * "START" message (or when this operation timed out).
617  *
618  * @param cls closure
619  * @param size number of bytes available in buf
620  * @param buf where the callee should write the message
621  * @return number of bytes written to buf
622  */
623 static size_t
624 transmit_start (void *cls, size_t size, void *buf)
625 {
626   struct GNUNET_CORE_Handle *h = cls;
627   struct InitMessage *init;
628   uint16_t *ts;
629   uint16_t msize;
630   uint32_t opt;
631   unsigned int hpos;
632   struct GNUNET_TIME_Relative delay;
633
634   h->th = NULL;
635   if (size == 0)
636     {
637       if ((h->init == NULL) ||
638           (GNUNET_TIME_absolute_get ().value < h->startup_timeout.value))
639         {
640           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
641                       _("Failed to connect to core service, retrying.\n"));
642           delay = GNUNET_TIME_absolute_get_remaining (h->startup_timeout);
643           if ((h->init == NULL) || (delay.value > 1000))
644             delay = GNUNET_TIME_UNIT_SECONDS;
645           if (h->init == NULL)
646             h->startup_timeout =
647               GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
648           h->reconnect_task =
649             GNUNET_SCHEDULER_add_delayed (h->sched, 
650                                           delay, &reconnect_task, h);
651           return 0;
652         }
653       /* timeout on initial connect */
654       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
655                   _("Failed to connect to core service, giving up.\n"));
656       h->init (h->cls, NULL, NULL, NULL);
657       GNUNET_CORE_disconnect (h);
658       return 0;
659     }
660   msize = h->hcnt * sizeof (uint16_t) + sizeof (struct InitMessage);
661   GNUNET_assert (size >= msize);
662   init = buf;
663   init->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT);
664   init->header.size = htons (msize);
665   opt = GNUNET_CORE_OPTION_NOTHING;
666   if (h->pre_connects != NULL)
667     opt |= GNUNET_CORE_OPTION_SEND_PRE_CONNECT;
668   if (h->connects != NULL)
669     opt |= GNUNET_CORE_OPTION_SEND_CONNECT;
670   if (h->disconnects != NULL)
671     opt |= GNUNET_CORE_OPTION_SEND_DISCONNECT;
672   if (h->inbound_notify != NULL)
673     {
674       if (h->inbound_hdr_only)
675         opt |= GNUNET_CORE_OPTION_SEND_HDR_INBOUND;
676       else
677         opt |= GNUNET_CORE_OPTION_SEND_FULL_INBOUND;
678     }
679   if (h->outbound_notify != NULL)
680     {
681       if (h->outbound_hdr_only)
682         opt |= GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND;
683       else
684         opt |= GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND;
685     }
686   init->options = htonl (opt);
687   ts = (uint16_t *) & init[1];
688   for (hpos = 0; hpos < h->hcnt; hpos++)
689     ts[hpos] = htons (h->handlers[hpos].type);
690   GNUNET_CLIENT_receive (h->client_notifications,
691                          &init_reply_handler,
692                          h,
693                          GNUNET_TIME_absolute_get_remaining
694                          (h->startup_timeout));
695   return sizeof (struct InitMessage) + h->hcnt * sizeof (uint16_t);
696 }
697
698
699 /**
700  * Connect to the core service.  Note that the connection may
701  * complete (or fail) asynchronously.
702  *
703  * @param sched scheduler to use
704  * @param cfg configuration to use
705  * @param timeout after how long should we give up trying to connect to the core service?
706  * @param cls closure for the various callbacks that follow (including handlers in the handlers array)
707  * @param init callback to call on timeout or once we have successfully
708  *        connected to the core service; note that timeout is only meaningful if init is not NULL
709  * @param pre_connects function to call on peer pre-connect (no session key yet), can be NULL
710  * @param connects function to call on peer connect, can be NULL
711  * @param disconnects function to call on peer disconnect / timeout, can be NULL
712  * @param inbound_notify function to call for all inbound messages, can be NULL
713  * @param inbound_hdr_only set to GNUNET_YES if inbound_notify will only read the
714  *                GNUNET_MessageHeader and hence we do not need to give it the full message;
715  *                can be used to improve efficiency, ignored if inbound_notify is NULLL
716  * @param outbound_notify function to call for all outbound messages, can be NULL
717  * @param outbound_hdr_only set to GNUNET_YES if outbound_notify will only read the
718  *                GNUNET_MessageHeader and hence we do not need to give it the full message
719  *                can be used to improve efficiency, ignored if outbound_notify is NULLL
720  * @param handlers callbacks for messages we care about, NULL-terminated
721  * @return handle to the core service (only useful for disconnect until 'init' is called);
722  *                NULL on error (in this case, init is never called)
723  */
724 struct GNUNET_CORE_Handle *
725 GNUNET_CORE_connect (struct GNUNET_SCHEDULER_Handle *sched,
726                      const struct GNUNET_CONFIGURATION_Handle *cfg,
727                      struct GNUNET_TIME_Relative timeout,
728                      void *cls,
729                      GNUNET_CORE_StartupCallback init,
730                      GNUNET_CORE_ConnectEventHandler pre_connects,
731                      GNUNET_CORE_ConnectEventHandler connects,
732                      GNUNET_CORE_DisconnectEventHandler disconnects,
733                      GNUNET_CORE_MessageCallback inbound_notify,
734                      int inbound_hdr_only,
735                      GNUNET_CORE_MessageCallback outbound_notify,
736                      int outbound_hdr_only,
737                      const struct GNUNET_CORE_MessageHandler *handlers)
738 {
739   struct GNUNET_CORE_Handle *h;
740
741   h = GNUNET_malloc (sizeof (struct GNUNET_CORE_Handle));
742   h->sched = sched;
743   h->cfg = cfg;
744   h->cls = cls;
745   h->init = init;
746   h->pre_connects = pre_connects;
747   h->connects = connects;
748   h->disconnects = disconnects;
749   h->inbound_notify = inbound_notify;
750   h->outbound_notify = outbound_notify;
751   h->inbound_hdr_only = inbound_hdr_only;
752   h->outbound_hdr_only = outbound_hdr_only;
753   h->handlers = handlers;
754   h->client_notifications = GNUNET_CLIENT_connect (sched, "core", cfg);
755   if (h->client_notifications == NULL)
756     {
757       GNUNET_free (h);
758       return NULL;
759     }
760   h->startup_timeout = GNUNET_TIME_relative_to_absolute (timeout);
761   h->hcnt = 0;
762   while (handlers[h->hcnt].callback != NULL)
763     h->hcnt++;
764   GNUNET_assert (h->hcnt <
765                  (GNUNET_SERVER_MAX_MESSAGE_SIZE -
766                   sizeof (struct InitMessage)) / sizeof (uint16_t));
767 #if DEBUG_CORE
768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
769               "Trying to connect to core service in next %llu ms.\n",
770               timeout.value);
771 #endif
772   h->th =
773     GNUNET_CLIENT_notify_transmit_ready (h->client_notifications,
774                                          sizeof (struct InitMessage) +
775                                          sizeof (uint16_t) * h->hcnt, timeout,
776                                          GNUNET_YES,
777                                          &transmit_start, h);
778   return h;
779 }
780
781
782 /**
783  * Disconnect from the core service.
784  *
785  * @param handle connection to core to disconnect
786  */
787 void
788 GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle)
789 {
790   if (handle->th != NULL)
791     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
792   if (handle->solicit_transmit_req != NULL)
793     GNUNET_CORE_notify_transmit_ready_cancel (handle->solicit_transmit_req);
794   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
795     GNUNET_SCHEDULER_cancel (handle->sched, handle->reconnect_task);
796   GNUNET_CLIENT_disconnect (handle->client_notifications);
797   GNUNET_free_non_null (handle->solicit_buffer);
798   GNUNET_free (handle);
799 }
800
801
802 /**
803  * Build the message requesting data transmission.
804  */
805 static size_t
806 produce_send (void *cls, size_t size, void *buf)
807 {
808   struct GNUNET_CORE_TransmitHandle *th = cls;
809   struct GNUNET_CORE_Handle *h;
810   struct SendMessage *sm;
811   size_t dt;
812   GNUNET_CONNECTION_TransmitReadyNotify notify;
813   void *notify_cls;
814
815   h = th->ch;
816   if (buf == NULL)
817     {
818       /* timeout or error */
819 #if DEBUG_CORE
820       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821                   "P2P transmission request for `%4s' timed out.\n",
822                   GNUNET_i2s(&th->peer));
823 #endif
824       GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
825       GNUNET_CORE_notify_transmit_ready_cancel (th);
826       trigger_next_request (h);
827       return 0;
828     }
829 #if DEBUG_CORE
830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831               "Preparing for P2P transmission to `%4s'.\n",
832               GNUNET_i2s(&th->peer));
833 #endif
834   GNUNET_assert (th->timeout_task != GNUNET_SCHEDULER_NO_TASK);
835   sm = (struct SendMessage *) buf;
836   sm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND);
837   sm->priority = htonl (th->priority);
838   sm->deadline = GNUNET_TIME_absolute_hton (th->timeout);
839   sm->peer = th->peer;
840   notify = th->notify;
841   notify_cls = th->notify_cls;
842   GNUNET_CORE_notify_transmit_ready_cancel (th);
843   trigger_next_request (h);
844   GNUNET_assert (size >= sizeof (struct SendMessage));
845   dt = notify (notify_cls, size - sizeof (struct SendMessage), &sm[1]);
846   if (0 == dt)
847     {
848       /* client decided to send nothing! */
849       return 0;
850     }
851   GNUNET_assert (dt >= sizeof (struct GNUNET_MessageHeader));
852   sm->header.size = htons (dt + sizeof (struct SendMessage));
853   GNUNET_assert (dt + sizeof (struct SendMessage) < size);
854   return dt + sizeof (struct SendMessage);
855 }
856
857
858 /**
859  * Ask the core to call "notify" once it is ready to transmit the
860  * given number of bytes to the specified "target".  If we are not yet
861  * connected to the specified peer, a call to this function will cause
862  * us to try to establish a connection.
863  *
864  * @param handle connection to core service
865  * @param priority how important is the message?
866  * @param maxdelay how long can the message wait?
867  * @param target who should receive the message,
868  *        use NULL for this peer (loopback)
869  * @param notify_size how many bytes of buffer space does notify want?
870  * @param notify function to call when buffer space is available
871  * @param notify_cls closure for notify
872  * @return non-NULL if the notify callback was queued,
873  *         NULL if we can not even queue the request (insufficient
874  *         memory); if NULL is returned, "notify" will NOT be called.
875  */
876 struct GNUNET_CORE_TransmitHandle *
877 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
878                                    unsigned int priority,
879                                    struct GNUNET_TIME_Relative maxdelay,
880                                    const struct GNUNET_PeerIdentity *target,
881                                    size_t notify_size,
882                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
883                                    void *notify_cls)
884 {
885   struct GNUNET_CORE_TransmitHandle *th;
886
887   GNUNET_assert (notify_size + sizeof (struct SendMessage) <
888                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
889   th = GNUNET_malloc (sizeof (struct GNUNET_CORE_TransmitHandle));
890   th->ch = handle;
891   /* append to list */
892   th->prev = handle->pending_tail;
893   if (handle->pending_tail == NULL)
894     handle->pending_head = th;
895   else
896     handle->pending_tail->next = th;
897   th->get_message = &produce_send;
898   th->get_message_cls = th;
899   th->notify = notify;
900   th->notify_cls = notify_cls;
901   th->peer = *target;
902   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
903   th->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->sched,
904                                                    maxdelay,
905                                                    &timeout_request, th);
906   th->priority = priority;
907   th->msize = sizeof (struct SendMessage) + notify_size;
908   /* was the request queue previously empty? */
909   if ( (handle->pending_head == th) &&
910        (handle->th == NULL) )
911     trigger_next_request (handle);
912   return th;
913 }
914
915
916 /**
917  * Cancel the specified transmission-ready notification.
918  *
919  * @param h handle that was returned by "notify_transmit_ready".
920  */
921 void
922 GNUNET_CORE_notify_transmit_ready_cancel (struct GNUNET_CORE_TransmitHandle
923                                           *h)
924 {
925   struct GNUNET_CORE_Handle *handle = h->ch;
926
927   if (handle->submitted == h)
928     {
929       handle->submitted = NULL;
930     }
931   else
932     {
933       if (h->prev == NULL)
934         handle->pending_head = h->next;
935       else
936         h->prev->next = h->next;
937       if (h->next == NULL)
938         handle->pending_tail = h->prev;
939       else
940         h->next->prev = h->prev;
941     }
942   if (h->timeout_task != GNUNET_SCHEDULER_NO_TASK)
943     GNUNET_SCHEDULER_cancel (handle->sched, h->timeout_task);
944   GNUNET_free (h);
945 }
946
947
948 /* end of core_api.c */