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