444ae98e26b7c341374a8b8b50413aac8257d030
[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 trigger_transmit (struct GNUNET_PEERINFO_Handle *h);
192
193
194 /**
195  * Close the existing connection to PEERINFO and reconnect.
196  *
197  * @param h handle to the service
198  */
199 static void reconnect (struct GNUNET_PEERINFO_Handle *h);
200
201 /**
202  * Task scheduled to re-try connecting to the peerinfo service.
203  *
204  * @param cls the 'struct GNUNET_PEERINFO_Handle'
205  * @param ts scheduler context
206  */
207 static void
208 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
209 {
210   struct GNUNET_PEERINFO_Handle *h = cls;
211
212   h->r_task = GNUNET_SCHEDULER_NO_TASK;
213   reconnect (h);
214 }
215
216
217 /**
218  * Close the existing connection to PEERINFO and reconnect.
219  *
220  * @param h handle to the service
221  */
222 static void
223 reconnect (struct GNUNET_PEERINFO_Handle *h)
224 {
225   if (h->r_task != GNUNET_SCHEDULER_NO_TASK)
226   {
227     GNUNET_SCHEDULER_cancel (h->r_task);
228     h->r_task = GNUNET_SCHEDULER_NO_TASK;
229   }
230   if (NULL != h->th)
231   {
232     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
233     h->th = NULL;
234   }
235   if (NULL != h->client)
236   {
237     GNUNET_CLIENT_disconnect (h->client, GNUNET_SYSERR);
238     h->client = NULL;
239   }
240   h->client = GNUNET_CLIENT_connect ("peerinfo", h->cfg);
241   if (NULL == h->client)
242   {
243     h->r_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
244                                               &reconnect_task, h);
245     return;
246   }
247   trigger_transmit (h);
248 }
249
250
251 /**
252  * Transmit the request at the head of the transmission queue
253  * and trigger continuation (if any).
254  *
255  * @param cls the 'struct GNUNET_PEERINFO_Handle' (with the queue)
256  * @param size size of the buffer (0 on error)
257  * @param buf where to copy the message
258  * @return number of bytes copied to buf
259  */
260 static size_t
261 do_transmit (void *cls, size_t size, void *buf)
262 {
263   struct GNUNET_PEERINFO_Handle *h = cls;
264   struct TransmissionQueueEntry *tqe = h->tq_head;
265   size_t ret;
266
267   h->th = NULL;
268   if (tqe == NULL)
269     return 0;
270   if (buf == NULL)
271   {
272     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
273                 _("Failed to transmit message to `%s' service.\n"), "PEERINFO");
274     GNUNET_CONTAINER_DLL_remove (h->tq_head, h->tq_tail, tqe);
275     reconnect (h);
276     if (tqe->cont != NULL)
277       tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
278     GNUNET_free (tqe);
279     return 0;
280   }
281   ret = tqe->size;
282   GNUNET_assert (size >= ret);
283   memcpy (buf, &tqe[1], ret);
284 #if DEBUG_PEERINFO
285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
286               "Transmitting request of size %u to `%s' service.\n",
287               ret, "PEERINFO");
288 #endif
289   GNUNET_CONTAINER_DLL_remove (h->tq_head, h->tq_tail, tqe);
290   if (tqe->cont != NULL)
291     tqe->cont (tqe->cont_cls, GNUNET_OK);
292   else
293     trigger_transmit (h);
294   GNUNET_free (tqe);
295   return ret;
296 }
297
298
299 /**
300  * Check if we have a request pending in the transmission queue and are
301  * able to transmit it right now.  If so, schedule transmission.
302  *
303  * @param h handle to the service
304  */
305 static void
306 trigger_transmit (struct GNUNET_PEERINFO_Handle *h)
307 {
308   struct TransmissionQueueEntry *tqe;
309
310   if (NULL == (tqe = h->tq_head))
311     return;
312   if (h->th != NULL)
313     return;
314   if (h->in_receive == GNUNET_YES)
315     return;
316   if (NULL == h->client)
317   {
318     reconnect (h);
319     return;
320   }
321   h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
322                                                tqe->size,
323                                                GNUNET_TIME_absolute_get_remaining
324                                                (tqe->timeout), GNUNET_YES,
325                                                &do_transmit, h);
326 }
327
328
329 /**
330  * Add a host to the persistent list.  This method operates in 
331  * semi-reliable mode: if the transmission is not completed by
332  * the time 'GNUNET_PEERINFO_disconnect' is called, it will be
333  * aborted.  Furthermore, if a second HELLO is added for the
334  * same peer before the first one was transmitted, PEERINFO may
335  * merge the two HELLOs prior to transmission to the service.
336  *
337  * @param h handle to the peerinfo service
338  * @param hello the verified (!) HELLO message
339  */
340 void
341 GNUNET_PEERINFO_add_peer (struct GNUNET_PEERINFO_Handle *h,
342                           const struct GNUNET_HELLO_Message *hello)
343 {
344   uint16_t hs = GNUNET_HELLO_size (hello);
345   struct TransmissionQueueEntry *tqe;
346
347 #if DEBUG_PEERINFO
348   struct GNUNET_PeerIdentity peer;
349
350   GNUNET_assert (GNUNET_OK == GNUNET_HELLO_get_id (hello, &peer));
351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
352               "Adding peer `%s' to PEERINFO database (%u bytes of `%s')\n",
353               GNUNET_i2s (&peer), hs, "HELLO");
354 #endif
355   tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) + hs);
356   tqe->size = hs;
357   tqe->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
358   memcpy (&tqe[1], hello, hs);
359   GNUNET_CONTAINER_DLL_insert_after (h->tq_head, h->tq_tail, h->tq_tail, tqe);
360   trigger_transmit (h);
361 }
362
363
364 /**
365  * Context for an iteration request.
366  */
367 struct GNUNET_PEERINFO_IteratorContext
368 {
369   /**
370    * Handle to the PEERINFO service.
371    */
372   struct GNUNET_PEERINFO_Handle *h;
373
374   /**
375    * Function to call with the results.
376    */
377   GNUNET_PEERINFO_Processor callback;
378
379   /**
380    * Closure for 'callback'.
381    */
382   void *callback_cls;
383
384   /**
385    * Our entry in the transmission queue.
386    */
387   struct TransmissionQueueEntry *tqe;
388
389   /**
390    * Task responsible for timeout.
391    */
392   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
393
394   /**
395    * Timeout for the operation.
396    */
397   struct GNUNET_TIME_Absolute timeout;
398
399   /**
400    * Are we now receiving?
401    */
402   int in_receive;
403 };
404
405
406 /**
407  * Type of a function to call when we receive a message
408  * from the service.
409  *
410  * @param cls closure
411  * @param msg message received, NULL on timeout or fatal error
412  */
413 static void
414 peerinfo_handler (void *cls, const struct GNUNET_MessageHeader *msg)
415 {
416   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
417   const struct InfoMessage *im;
418   const struct GNUNET_HELLO_Message *hello;
419   uint16_t ms;
420
421   ic->h->in_receive = GNUNET_NO;
422   if (msg == NULL)
423   {
424     reconnect (ic->h);
425     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
426       GNUNET_SCHEDULER_cancel (ic->timeout_task);
427     if (ic->callback != NULL)
428       ic->callback (ic->callback_cls, NULL, NULL,
429                     _("Failed to receive response from `PEERINFO' service."));
430     GNUNET_free (ic);
431     return;
432   }
433   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END)
434   {
435 #if DEBUG_PEERINFO
436     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
437                 "Received end of list of peers from `%s' service\n",
438                 "PEERINFO");
439 #endif
440     trigger_transmit (ic->h);
441     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
442       GNUNET_SCHEDULER_cancel (ic->timeout_task);
443     if (ic->callback != NULL)
444       ic->callback (ic->callback_cls, NULL, NULL, NULL);
445     GNUNET_free (ic);
446     return;
447   }
448   ms = ntohs (msg->size);
449   if ((ms < sizeof (struct InfoMessage)) ||
450       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_PEERINFO_INFO))
451   {
452     GNUNET_break (0);
453     reconnect (ic->h);
454     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
455       GNUNET_SCHEDULER_cancel (ic->timeout_task);
456     if (ic->callback != NULL)
457       ic->callback (ic->callback_cls, NULL, NULL,
458                     _("Received invalid message from `PEERINFO' service.\n"));
459     GNUNET_free (ic);
460     return;
461   }
462   im = (const struct InfoMessage *) msg;
463   GNUNET_break (0 == ntohl (im->reserved));
464   hello = NULL;
465   if (ms > sizeof (struct InfoMessage) + sizeof (struct GNUNET_MessageHeader))
466   {
467     hello = (const struct GNUNET_HELLO_Message *) &im[1];
468     if (ms != sizeof (struct InfoMessage) + GNUNET_HELLO_size (hello))
469     {
470       GNUNET_break (0);
471       reconnect (ic->h);
472       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
473         GNUNET_SCHEDULER_cancel (ic->timeout_task);
474       if (ic->callback != NULL)
475         ic->callback (ic->callback_cls, NULL, NULL,
476                       _("Received invalid message from `PEERINFO' service.\n"));
477       GNUNET_free (ic);
478       return;
479     }
480   }
481 #if DEBUG_PEERINFO
482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
483               "Received %u bytes of `%s' information about peer `%s' from `%s' service\n",
484               (hello == NULL) ? 0 : (unsigned int) GNUNET_HELLO_size (hello),
485               "HELLO", GNUNET_i2s (&im->peer), "PEERINFO");
486 #endif
487   ic->h->in_receive = GNUNET_YES;
488   if (ic->callback != NULL)
489     ic->callback (ic->callback_cls, &im->peer, hello, NULL);
490   GNUNET_CLIENT_receive (ic->h->client,
491                          &peerinfo_handler,
492                          ic, GNUNET_TIME_absolute_get_remaining (ic->timeout));
493 }
494
495
496 /**
497  * We've transmitted the iteration request.  Now get ready to process
498  * the results (or handle transmission error).
499  *
500  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext'
501  * @param transmit_success GNUNET_OK if transmission worked
502  */
503 static void
504 iterator_start_receive (void *cls, int transmit_success)
505 {
506   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
507
508   if (GNUNET_OK != transmit_success)
509   {
510     if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
511     {
512       GNUNET_SCHEDULER_cancel (ic->timeout_task);
513       ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
514     }
515     reconnect (ic->h);
516     if (ic->callback != NULL)
517       ic->callback (ic->callback_cls, NULL, NULL,
518                     _
519                     ("Failed to transmit iteration request to `PEERINFO' service\n"));
520     GNUNET_free (ic);
521     return;
522   }
523 #if DEBUG_PEERINFO
524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
525               "Waiting for response from `%s' service.\n", "PEERINFO");
526 #endif
527   ic->h->in_receive = GNUNET_YES;
528   ic->in_receive = GNUNET_YES;
529   ic->tqe = NULL;
530   GNUNET_CLIENT_receive (ic->h->client,
531                          &peerinfo_handler,
532                          ic, GNUNET_TIME_absolute_get_remaining (ic->timeout));
533 }
534
535
536 /**
537  * Peerinfo iteration request has timed out.  
538  *
539  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext*'
540  * @param tc scheduler context
541  */
542 static void
543 signal_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
544 {
545   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
546
547   ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
548   if (!ic->in_receive)
549     GNUNET_CONTAINER_DLL_remove (ic->h->tq_head, ic->h->tq_tail, ic->tqe);
550   else
551     reconnect (ic->h);
552   ic->callback (ic->callback_cls,
553                 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 = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
596                          sizeof (struct GNUNET_MessageHeader));
597     tqe->size = sizeof (struct GNUNET_MessageHeader);
598     lapm = (struct GNUNET_MessageHeader *) &tqe[1];
599     lapm->size = htons (sizeof (struct GNUNET_MessageHeader));
600     lapm->type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL);
601   }
602   else
603   {
604 #if DEBUG_PEERINFO
605     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
606                 "Requesting information on peer `%4s' from PEERINFO service\n",
607                 GNUNET_i2s (peer));
608 #endif
609     tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
610                          sizeof (struct ListPeerMessage));
611     tqe->size = sizeof (struct ListPeerMessage);
612     lpm = (struct ListPeerMessage *) &tqe[1];
613     lpm->header.size = htons (sizeof (struct ListPeerMessage));
614     lpm->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET);
615     memcpy (&lpm->peer, peer, sizeof (struct GNUNET_PeerIdentity));
616   }
617   ic = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_IteratorContext));
618   ic->h = h;
619   ic->tqe = tqe;
620   ic->callback = callback;
621   ic->callback_cls = callback_cls;
622   ic->timeout = GNUNET_TIME_relative_to_absolute (timeout);
623   ic->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
624                                                    &signal_timeout, ic);
625   tqe->timeout = ic->timeout;
626   tqe->cont = &iterator_start_receive;
627   tqe->cont_cls = ic;
628   tqe->timeout = ic->timeout;
629   GNUNET_CONTAINER_DLL_insert_after (h->tq_head, h->tq_tail, h->tq_tail, tqe);
630   trigger_transmit (h);
631   return ic;
632 }
633
634
635 /**
636  * Cancel an iteration over peer information.
637  *
638  * @param ic context of the iterator to cancel
639  */
640 void
641 GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic)
642 {
643   if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
644   {
645     GNUNET_SCHEDULER_cancel (ic->timeout_task);
646     ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
647   }
648   ic->callback = NULL;
649   if (GNUNET_YES == ic->in_receive)
650     return;                     /* need to finish processing */
651   GNUNET_CONTAINER_DLL_remove (ic->h->tq_head, ic->h->tq_tail, ic->tqe);
652   GNUNET_free (ic->tqe);
653   GNUNET_free (ic);
654 }
655
656
657 /* end of peerinfo_api.c */