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