run indent twice, it alternates between two 'canonical' forms, also run whitespace...
[oweals/gnunet.git] / src / peerinfo / peerinfo_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2004, 2005, 2007, 2009, 2010 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 3, 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 peerinfo/peerinfo_api.c
23  * @brief API to access peerinfo service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_client_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_peerinfo_service.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_time_lib.h"
32 #include "peerinfo.h"
33
34 /**
35  * Function to call after transmission has succeeded.
36  *
37  * @param cls closure
38  * @param success GNUNET_OK if transmission worked, GNUNET_SYSERR on error
39  */
40 typedef void (*TransmissionContinuation) (void *cls, int success);
41
42
43 /**
44  * Entry in the transmission queue to PEERINFO service.
45  */
46 struct TransmissionQueueEntry
47 {
48   /**
49    * This is a linked list.
50    */
51   struct TransmissionQueueEntry *next;
52
53   /**
54    * This is a linked list.
55    */
56   struct TransmissionQueueEntry *prev;
57
58   /**
59    * Function to call after request has been transmitted, or NULL (in which
60    * case we must consider sending the next entry immediately).
61    */
62   TransmissionContinuation cont;
63
64   /**
65    * Closure for 'cont'.
66    */
67   void *cont_cls;
68
69   /**
70    * Timeout for the operation.
71    */
72   struct GNUNET_TIME_Absolute timeout;
73
74   /**
75    * Number of bytes of the request message (follows after this struct).
76    */
77   size_t size;
78
79 };
80
81
82 /**
83  * Handle to the peerinfo service.
84  */
85 struct GNUNET_PEERINFO_Handle
86 {
87   /**
88    * Our configuration.
89    */
90   const struct GNUNET_CONFIGURATION_Handle *cfg;
91
92   /**
93    * Connection to the service.
94    */
95   struct GNUNET_CLIENT_Connection *client;
96
97   /**
98    * Head of transmission queue.
99    */
100   struct TransmissionQueueEntry *tq_head;
101
102   /**
103    * Tail of transmission queue.
104    */
105   struct TransmissionQueueEntry *tq_tail;
106
107   /**
108    * Handle for the current transmission request, or NULL if none is pending.
109    */
110   struct GNUNET_CLIENT_TransmitHandle *th;
111
112   /**
113    * ID for a reconnect task.
114    */
115   GNUNET_SCHEDULER_TaskIdentifier r_task;
116
117   /**
118    * Set to GNUNET_YES if we are currently receiving replies from the
119    * service.
120    */
121   int in_receive;
122
123 };
124
125
126 /**
127  * Connect to the peerinfo service.
128  *
129  * @param cfg configuration to use
130  * @return NULL on error (configuration related, actual connection
131  *         establishment may happen asynchronously).
132  */
133 struct GNUNET_PEERINFO_Handle *
134 GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
135 {
136   struct GNUNET_PEERINFO_Handle *ret;
137
138   ret = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_Handle));
139   ret->client = GNUNET_CLIENT_connect ("peerinfo", cfg);
140   ret->cfg = cfg;
141   return ret;
142 }
143
144
145 /**
146  * Disconnect from the peerinfo service.  Note that all iterators must
147  * have completed or have been cancelled by the time this function is
148  * called (otherwise, calling this function is a serious error).
149  * Furthermore, if 'GNUNET_PEERINFO_add_peer' operations are still
150  * pending, they will be cancelled silently on disconnect.
151  *
152  * @param h handle to disconnect
153  */
154 void
155 GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h)
156 {
157   struct TransmissionQueueEntry *tqe;
158
159   while (NULL != (tqe = h->tq_head))
160   {
161     GNUNET_CONTAINER_DLL_remove (h->tq_head, h->tq_tail, tqe);
162     if (tqe->cont != NULL)
163       tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
164     GNUNET_free (tqe);
165   }
166   if (h->th != NULL)
167   {
168     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
169     h->th = NULL;
170   }
171   if (NULL != h->client)
172   {
173     GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
174     h->client = NULL;
175   }
176   if (GNUNET_SCHEDULER_NO_TASK != h->r_task)
177   {
178     GNUNET_SCHEDULER_cancel (h->r_task);
179     h->r_task = GNUNET_SCHEDULER_NO_TASK;
180   }
181   GNUNET_free (h);
182 }
183
184
185 /**
186  * Check if we have a request pending in the transmission queue and are
187  * able to transmit it right now.  If so, schedule transmission.
188  *
189  * @param h handle to the service
190  */
191 static void
192 trigger_transmit (struct GNUNET_PEERINFO_Handle *h);
193
194
195 /**
196  * Close the existing connection to PEERINFO and reconnect.
197  *
198  * @param h handle to the service
199  */
200 static void
201 reconnect (struct GNUNET_PEERINFO_Handle *h);
202
203 /**
204  * Task scheduled to re-try connecting to the peerinfo service.
205  *
206  * @param cls the 'struct GNUNET_PEERINFO_Handle'
207  * @param ts scheduler context
208  */
209 static void
210 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
211 {
212   struct GNUNET_PEERINFO_Handle *h = cls;
213
214   h->r_task = GNUNET_SCHEDULER_NO_TASK;
215   reconnect (h);
216 }
217
218
219 /**
220  * Close the existing connection to PEERINFO and reconnect.
221  *
222  * @param h handle to the service
223  */
224 static void
225 reconnect (struct GNUNET_PEERINFO_Handle *h)
226 {
227   if (h->r_task != GNUNET_SCHEDULER_NO_TASK)
228   {
229     GNUNET_SCHEDULER_cancel (h->r_task);
230     h->r_task = GNUNET_SCHEDULER_NO_TASK;
231   }
232   if (NULL != h->th)
233   {
234     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
235     h->th = NULL;
236   }
237   if (NULL != h->client)
238   {
239     GNUNET_CLIENT_disconnect (h->client, GNUNET_SYSERR);
240     h->client = NULL;
241   }
242   h->client = GNUNET_CLIENT_connect ("peerinfo", h->cfg);
243   if (NULL == h->client)
244   {
245     h->r_task =
246         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &reconnect_task,
247                                       h);
248     return;
249   }
250   trigger_transmit (h);
251 }
252
253
254 /**
255  * Transmit the request at the head of the transmission queue
256  * and trigger continuation (if any).
257  *
258  * @param cls the 'struct GNUNET_PEERINFO_Handle' (with the queue)
259  * @param size size of the buffer (0 on error)
260  * @param buf where to copy the message
261  * @return number of bytes copied to buf
262  */
263 static size_t
264 do_transmit (void *cls, size_t size, void *buf)
265 {
266   struct GNUNET_PEERINFO_Handle *h = cls;
267   struct TransmissionQueueEntry *tqe = h->tq_head;
268   size_t ret;
269
270   h->th = NULL;
271   if (tqe == NULL)
272     return 0;
273   if (buf == NULL)
274   {
275     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
276                 _("Failed to transmit message to `%s' service.\n"), "PEERINFO");
277     GNUNET_CONTAINER_DLL_remove (h->tq_head, h->tq_tail, tqe);
278     reconnect (h);
279     if (tqe->cont != NULL)
280       tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
281     GNUNET_free (tqe);
282     return 0;
283   }
284   ret = tqe->size;
285   GNUNET_assert (size >= ret);
286   memcpy (buf, &tqe[1], ret);
287 #if DEBUG_PEERINFO
288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
289               "Transmitting request of size %u to `%s' service.\n", ret,
290               "PEERINFO");
291 #endif
292   GNUNET_CONTAINER_DLL_remove (h->tq_head, h->tq_tail, tqe);
293   if (tqe->cont != NULL)
294     tqe->cont (tqe->cont_cls, GNUNET_OK);
295   else
296     trigger_transmit (h);
297   GNUNET_free (tqe);
298   return ret;
299 }
300
301
302 /**
303  * Check if we have a request pending in the transmission queue and are
304  * able to transmit it right now.  If so, schedule transmission.
305  *
306  * @param h handle to the service
307  */
308 static void
309 trigger_transmit (struct GNUNET_PEERINFO_Handle *h)
310 {
311   struct TransmissionQueueEntry *tqe;
312
313   if (NULL == (tqe = h->tq_head))
314     return;
315   if (h->th != NULL)
316     return;
317   if (h->in_receive == GNUNET_YES)
318     return;
319   if (NULL == h->client)
320   {
321     reconnect (h);
322     return;
323   }
324   h->th =
325       GNUNET_CLIENT_notify_transmit_ready (h->client, tqe->size,
326                                            GNUNET_TIME_absolute_get_remaining
327                                            (tqe->timeout), GNUNET_YES,
328                                            &do_transmit, h);
329 }
330
331
332 /**
333  * Add a host to the persistent list.  This method operates in
334  * semi-reliable mode: if the transmission is not completed by
335  * the time 'GNUNET_PEERINFO_disconnect' is called, it will be
336  * aborted.  Furthermore, if a second HELLO is added for the
337  * same peer before the first one was transmitted, PEERINFO may
338  * merge the two HELLOs prior to transmission to the service.
339  *
340  * @param h handle to the peerinfo service
341  * @param hello the verified (!) HELLO message
342  */
343 void
344 GNUNET_PEERINFO_add_peer (struct GNUNET_PEERINFO_Handle *h,
345                           const struct GNUNET_HELLO_Message *hello)
346 {
347   uint16_t hs = GNUNET_HELLO_size (hello);
348   struct TransmissionQueueEntry *tqe;
349
350 #if DEBUG_PEERINFO
351   struct GNUNET_PeerIdentity peer;
352
353   GNUNET_assert (GNUNET_OK == GNUNET_HELLO_get_id (hello, &peer));
354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
355               "Adding peer `%s' to PEERINFO database (%u bytes of `%s')\n",
356               GNUNET_i2s (&peer), hs, "HELLO");
357 #endif
358   tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) + hs);
359   tqe->size = hs;
360   tqe->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
361   memcpy (&tqe[1], hello, hs);
362   GNUNET_CONTAINER_DLL_insert_after (h->tq_head, h->tq_tail, h->tq_tail, tqe);
363   trigger_transmit (h);
364 }
365
366
367 /**
368  * Context for an iteration request.
369  */
370 struct GNUNET_PEERINFO_IteratorContext
371 {
372   /**
373    * Handle to the PEERINFO service.
374    */
375   struct GNUNET_PEERINFO_Handle *h;
376
377   /**
378    * Function to call with the results.
379    */
380   GNUNET_PEERINFO_Processor callback;
381
382   /**
383    * Closure for 'callback'.
384    */
385   void *callback_cls;
386
387   /**
388    * Our entry in the transmission queue.
389    */
390   struct TransmissionQueueEntry *tqe;
391
392   /**
393    * Task responsible for timeout.
394    */
395   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
396
397   /**
398    * Timeout for the operation.
399    */
400   struct GNUNET_TIME_Absolute timeout;
401
402   /**
403    * Are we now receiving?
404    */
405   int in_receive;
406 };
407
408
409 /**
410  * Type of a function to call when we receive a message
411  * from the service.
412  *
413  * @param cls closure
414  * @param msg message received, NULL on timeout or fatal error
415  */
416 static void
417 peerinfo_handler (void *cls, const struct GNUNET_MessageHeader *msg)
418 {
419   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
420   const struct InfoMessage *im;
421   const struct GNUNET_HELLO_Message *hello;
422   uint16_t ms;
423
424   ic->h->in_receive = GNUNET_NO;
425   if (msg == NULL)
426   {
427     reconnect (ic->h);
428     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
429       GNUNET_SCHEDULER_cancel (ic->timeout_task);
430     if (ic->callback != NULL)
431       ic->callback (ic->callback_cls, NULL, NULL,
432                     _("Failed to receive response from `PEERINFO' service."));
433     GNUNET_free (ic);
434     return;
435   }
436   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END)
437   {
438 #if DEBUG_PEERINFO
439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
440                 "Received end of list of peers from `%s' service\n",
441                 "PEERINFO");
442 #endif
443     trigger_transmit (ic->h);
444     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
445       GNUNET_SCHEDULER_cancel (ic->timeout_task);
446     if (ic->callback != NULL)
447       ic->callback (ic->callback_cls, NULL, NULL, NULL);
448     GNUNET_free (ic);
449     return;
450   }
451   ms = ntohs (msg->size);
452   if ((ms < sizeof (struct InfoMessage)) ||
453       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_PEERINFO_INFO))
454   {
455     GNUNET_break (0);
456     reconnect (ic->h);
457     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
458       GNUNET_SCHEDULER_cancel (ic->timeout_task);
459     if (ic->callback != NULL)
460       ic->callback (ic->callback_cls, NULL, NULL,
461                     _("Received invalid message from `PEERINFO' service.\n"));
462     GNUNET_free (ic);
463     return;
464   }
465   im = (const struct InfoMessage *) msg;
466   GNUNET_break (0 == ntohl (im->reserved));
467   hello = NULL;
468   if (ms > sizeof (struct InfoMessage) + sizeof (struct GNUNET_MessageHeader))
469   {
470     hello = (const struct GNUNET_HELLO_Message *) &im[1];
471     if (ms != sizeof (struct InfoMessage) + GNUNET_HELLO_size (hello))
472     {
473       GNUNET_break (0);
474       reconnect (ic->h);
475       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
476         GNUNET_SCHEDULER_cancel (ic->timeout_task);
477       if (ic->callback != NULL)
478         ic->callback (ic->callback_cls, NULL, NULL,
479                       _("Received invalid message from `PEERINFO' service.\n"));
480       GNUNET_free (ic);
481       return;
482     }
483   }
484 #if DEBUG_PEERINFO
485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
486               "Received %u bytes of `%s' information about peer `%s' from `%s' service\n",
487               (hello == NULL) ? 0 : (unsigned int) GNUNET_HELLO_size (hello),
488               "HELLO", GNUNET_i2s (&im->peer), "PEERINFO");
489 #endif
490   ic->h->in_receive = GNUNET_YES;
491   if (ic->callback != NULL)
492     ic->callback (ic->callback_cls, &im->peer, hello, NULL);
493   GNUNET_CLIENT_receive (ic->h->client, &peerinfo_handler, ic,
494                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
495 }
496
497
498 /**
499  * We've transmitted the iteration request.  Now get ready to process
500  * the results (or handle transmission error).
501  *
502  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext'
503  * @param transmit_success GNUNET_OK if transmission worked
504  */
505 static void
506 iterator_start_receive (void *cls, int transmit_success)
507 {
508   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
509
510   if (GNUNET_OK != transmit_success)
511   {
512     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
513     {
514       GNUNET_SCHEDULER_cancel (ic->timeout_task);
515       ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
516     }
517     reconnect (ic->h);
518     if (ic->callback != NULL)
519       ic->callback (ic->callback_cls, NULL, NULL,
520                     _
521                     ("Failed to transmit iteration request to `PEERINFO' service\n"));
522     GNUNET_free (ic);
523     return;
524   }
525 #if DEBUG_PEERINFO
526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
527               "Waiting for response from `%s' service.\n", "PEERINFO");
528 #endif
529   ic->h->in_receive = GNUNET_YES;
530   ic->in_receive = GNUNET_YES;
531   ic->tqe = NULL;
532   GNUNET_CLIENT_receive (ic->h->client, &peerinfo_handler, ic,
533                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
534 }
535
536
537 /**
538  * Peerinfo iteration request has timed out.
539  *
540  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext*'
541  * @param tc scheduler context
542  */
543 static void
544 signal_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
545 {
546   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
547
548   ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
549   if (!ic->in_receive)
550     GNUNET_CONTAINER_DLL_remove (ic->h->tq_head, ic->h->tq_tail, ic->tqe);
551   else
552     reconnect (ic->h);
553   ic->callback (ic->callback_cls, NULL, NULL,
554                 _
555                 ("Timeout transmitting iteration request to `PEERINFO' service.\n"));
556   ic->callback = NULL;
557   GNUNET_free_non_null (ic->tqe);
558   GNUNET_free (ic);
559 }
560
561
562 /**
563  * Call a method for each known matching host and change its trust
564  * value.  The callback method will be invoked once for each matching
565  * host and then finally once with a NULL pointer.  After that final
566  * invocation, the iterator context must no longer be used.
567  *
568  * Instead of calling this function with 'peer == NULL' it is often
569  * better to use 'GNUNET_PEERINFO_notify'.
570  *
571  * @param h handle to the peerinfo service
572  * @param peer restrict iteration to this peer only (can be NULL)
573  * @param timeout how long to wait until timing out
574  * @param callback the method to call for each peer
575  * @param callback_cls closure for callback
576  * @return iterator context
577  */
578 struct GNUNET_PEERINFO_IteratorContext *
579 GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h,
580                          const struct GNUNET_PeerIdentity *peer,
581                          struct GNUNET_TIME_Relative timeout,
582                          GNUNET_PEERINFO_Processor callback, void *callback_cls)
583 {
584   struct GNUNET_MessageHeader *lapm;
585   struct ListPeerMessage *lpm;
586   struct GNUNET_PEERINFO_IteratorContext *ic;
587   struct TransmissionQueueEntry *tqe;
588
589   if (peer == NULL)
590   {
591 #if DEBUG_PEERINFO
592     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
593                 "Requesting list of peers from PEERINFO service\n");
594 #endif
595     tqe =
596         GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
597                        sizeof (struct GNUNET_MessageHeader));
598     tqe->size = sizeof (struct GNUNET_MessageHeader);
599     lapm = (struct GNUNET_MessageHeader *) &tqe[1];
600     lapm->size = htons (sizeof (struct GNUNET_MessageHeader));
601     lapm->type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL);
602   }
603   else
604   {
605 #if DEBUG_PEERINFO
606     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
607                 "Requesting information on peer `%4s' from PEERINFO service\n",
608                 GNUNET_i2s (peer));
609 #endif
610     tqe =
611         GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
612                        sizeof (struct ListPeerMessage));
613     tqe->size = sizeof (struct ListPeerMessage);
614     lpm = (struct ListPeerMessage *) &tqe[1];
615     lpm->header.size = htons (sizeof (struct ListPeerMessage));
616     lpm->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET);
617     memcpy (&lpm->peer, peer, sizeof (struct GNUNET_PeerIdentity));
618   }
619   ic = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_IteratorContext));
620   ic->h = h;
621   ic->tqe = tqe;
622   ic->callback = callback;
623   ic->callback_cls = callback_cls;
624   ic->timeout = GNUNET_TIME_relative_to_absolute (timeout);
625   ic->timeout_task =
626       GNUNET_SCHEDULER_add_delayed (timeout, &signal_timeout, ic);
627   tqe->timeout = ic->timeout;
628   tqe->cont = &iterator_start_receive;
629   tqe->cont_cls = ic;
630   tqe->timeout = ic->timeout;
631   GNUNET_CONTAINER_DLL_insert_after (h->tq_head, h->tq_tail, h->tq_tail, tqe);
632   trigger_transmit (h);
633   return ic;
634 }
635
636
637 /**
638  * Cancel an iteration over peer information.
639  *
640  * @param ic context of the iterator to cancel
641  */
642 void
643 GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic)
644 {
645   if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
646   {
647     GNUNET_SCHEDULER_cancel (ic->timeout_task);
648     ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
649   }
650   ic->callback = NULL;
651   if (GNUNET_YES == ic->in_receive)
652     return;                     /* need to finish processing */
653   GNUNET_CONTAINER_DLL_remove (ic->h->tq_head, ic->h->tq_tail, ic->tqe);
654   GNUNET_free (ic->tqe);
655   GNUNET_free (ic);
656 }
657
658
659 /* end of peerinfo_api.c */