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