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