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