could theoretically be NULL, check
[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       if (tqe != NULL)
236         GNUNET_CONTAINER_DLL_remove (h->tq_head,
237                                      h->tq_tail,
238                                      tqe);
239       reconnect (h);
240       trigger_transmit (h);
241       if (tqe != NULL)
242         {
243           if (tqe->cont != NULL)
244             tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
245           GNUNET_free (tqe);
246         }
247       return 0;
248     }
249   ret = tqe->size;
250   GNUNET_assert (size >= ret);
251   memcpy (buf, &tqe[1], ret);
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;
277   if (h->th != NULL)
278     return;
279   if (h->in_receive == GNUNET_YES)
280     return;
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_WARNING,
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->h->sched, 
395                                  ic->timeout_task);
396       if (ic->callback != NULL)
397         ic->callback (ic->callback_cls, NULL, NULL, 1);
398       GNUNET_free (ic);
399       return;
400     }
401   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END)
402     {
403 #if DEBUG_PEERINFO
404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
405                   "Received end of list of peers from peerinfo database\n");
406 #endif
407       trigger_transmit (ic->h);
408       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
409         GNUNET_SCHEDULER_cancel (ic->h->sched, 
410                                  ic->timeout_task);
411       if (ic->callback != NULL)
412         ic->callback (ic->callback_cls, NULL, NULL, 0);
413       GNUNET_free (ic);
414       return;
415     }
416   ms = ntohs (msg->size);
417   if ((ms < sizeof (struct InfoMessage)) ||
418       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_PEERINFO_INFO))
419     {
420       GNUNET_break (0);
421       reconnect (ic->h);
422       trigger_transmit (ic->h);
423       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
424         GNUNET_SCHEDULER_cancel (ic->h->sched, 
425                                  ic->timeout_task);
426       if (ic->callback != NULL)
427         ic->callback (ic->callback_cls, NULL, NULL, 2);
428       GNUNET_free (ic);
429       return;
430     }
431   im = (const struct InfoMessage *) msg;
432   hello = NULL;
433   if (ms > sizeof (struct InfoMessage) + sizeof (struct GNUNET_MessageHeader))
434     {
435       hello = (const struct GNUNET_HELLO_Message *) &im[1];
436       if (ms != sizeof (struct InfoMessage) + GNUNET_HELLO_size (hello))
437         {
438           GNUNET_break (0);
439           reconnect (ic->h);
440           trigger_transmit (ic->h);
441           if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
442             GNUNET_SCHEDULER_cancel (ic->h->sched, 
443                                      ic->timeout_task);
444           if (ic->callback != NULL)
445             ic->callback (ic->callback_cls, NULL, NULL, 2);
446           GNUNET_free (ic);
447           return;
448         }
449     }
450 #if DEBUG_PEERINFO
451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
452               "Received %u bytes of `%s' information about peer `%s' from PEERINFO database\n",
453               (hello == NULL) ? 0 : (unsigned int) GNUNET_HELLO_size (hello),
454               "HELLO",
455               GNUNET_i2s (&im->peer));
456 #endif
457   ic->h->in_receive = GNUNET_YES;
458   if (ic->callback != NULL)
459     ic->callback (ic->callback_cls, &im->peer, hello, ntohl (im->trust));
460   GNUNET_CLIENT_receive (ic->h->client,
461                          &peerinfo_handler,
462                          ic,
463                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
464 }
465
466
467 /**
468  * We've transmitted the iteration request.  Now get ready to process
469  * the results (or handle transmission error).
470  *
471  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext'
472  * @param transmit_success GNUNET_OK if transmission worked
473  */
474 static void
475 iterator_start_receive (void *cls,
476                         int transmit_success)
477 {
478   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
479
480   if (GNUNET_OK != transmit_success)
481     {
482       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
483         {
484           GNUNET_SCHEDULER_cancel (ic->h->sched,
485                                    ic->timeout_task);
486           ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
487         }
488       reconnect (ic->h);
489       trigger_transmit (ic->h);
490       ic->callback (ic->callback_cls, NULL, NULL, 1);
491       GNUNET_free (ic);
492       return;
493     }  
494   ic->h->in_receive = GNUNET_YES;
495   ic->in_receive = GNUNET_YES;
496   ic->tqe = NULL;
497   GNUNET_CLIENT_receive (ic->h->client,
498                          &peerinfo_handler,
499                          ic,
500                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
501 }
502
503
504 /**
505  * Peerinfo iteration request has timed out.  
506  *
507  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext*'
508  * @param tc scheduler context
509  */
510 static void
511 signal_timeout (void *cls,
512                 const struct GNUNET_SCHEDULER_TaskContext *tc)
513 {
514   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
515
516   ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
517   if (! ic->in_receive)
518     GNUNET_CONTAINER_DLL_remove (ic->h->tq_head,
519                                  ic->h->tq_tail,
520                                  ic->tqe);
521   ic->callback (ic->callback_cls, NULL, NULL, 1);
522   ic->callback = NULL;
523   if (ic->in_receive)
524     return;
525   GNUNET_free (ic->tqe);
526   GNUNET_free (ic);
527 }
528
529
530 /**
531  * Call a method for each known matching host and change its trust
532  * value.  The callback method will be invoked once for each matching
533  * host and then finally once with a NULL pointer.  After that final
534  * invocation, the iterator context must no longer be used.
535  *
536  * Note that the last call can be triggered by timeout or by simply
537  * being done; however, the trust argument will be set to zero if we
538  * are done, 1 if we timed out and 2 for fatal error.
539  *
540  * Instead of calling this function with 'peer == NULL' and 'trust ==
541  * 0', it is often better to use 'GNUNET_PEERINFO_notify'.
542  * 
543  * @param h handle to the peerinfo service
544  * @param peer restrict iteration to this peer only (can be NULL)
545  * @param trust_delta how much to change the trust in all matching peers
546  * @param timeout how long to wait until timing out
547  * @param callback the method to call for each peer
548  * @param callback_cls closure for callback
549  * @return NULL on error (in this case, 'callback' is never called!), 
550  *         otherwise an iterator context
551  */
552 struct GNUNET_PEERINFO_IteratorContext *
553 GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h,
554                          const struct GNUNET_PeerIdentity *peer,
555                          int trust_delta,
556                          struct GNUNET_TIME_Relative timeout,
557                          GNUNET_PEERINFO_Processor callback,
558                          void *callback_cls)
559 {
560   struct ListAllPeersMessage *lapm;
561   struct ListPeerMessage *lpm;
562   struct GNUNET_PEERINFO_IteratorContext *ic;
563   struct TransmissionQueueEntry *tqe;
564
565 #if DEBUG_PEERINFO
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Requesting list of peers from peerinfo database\n");
568 #endif
569   if (peer == NULL)
570     {
571       tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
572                            sizeof (struct ListAllPeersMessage));
573       tqe->size = sizeof (struct ListAllPeersMessage);
574       lapm = (struct ListAllPeersMessage *) &tqe[1];
575       lapm->header.size = htons (sizeof (struct ListAllPeersMessage));
576       lapm->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL);
577       lapm->trust_change = htonl (trust_delta);
578     }
579   else
580     {
581       tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
582                            sizeof (struct ListPeerMessage));
583       tqe->size = sizeof (struct ListPeerMessage);
584       lpm = (struct ListPeerMessage *) &tqe[1];
585       lpm->header.size = htons (sizeof (struct ListPeerMessage));
586       lpm->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET);
587       lpm->trust_change = htonl (trust_delta);
588       memcpy (&lpm->peer, peer, sizeof (struct GNUNET_PeerIdentity));
589     }
590   ic = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_IteratorContext));
591   ic->h = h;
592   ic->tqe = tqe;
593   ic->callback = callback;
594   ic->callback_cls = callback_cls;
595   ic->timeout = GNUNET_TIME_relative_to_absolute (timeout);
596   ic->timeout_task = GNUNET_SCHEDULER_add_delayed (h->sched, 
597                                                    timeout,
598                                                    &signal_timeout,
599                                                    ic);
600   tqe->timeout = ic->timeout;
601   tqe->cont = &iterator_start_receive;
602   tqe->cont_cls = ic;
603   tqe->timeout = ic->timeout;
604   GNUNET_CONTAINER_DLL_insert_after (h->tq_head,
605                                      h->tq_tail,
606                                      h->tq_tail,
607                                      tqe);
608   trigger_transmit (h);
609   return ic;
610 }
611
612
613
614 /**
615  * Cancel an iteration over peer information.
616  *
617  * @param ic context of the iterator to cancel
618  */
619 void
620 GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic)
621 {
622   if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
623     {
624       GNUNET_SCHEDULER_cancel (ic->h->sched,
625                                ic->timeout_task);
626       ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
627     }
628   ic->callback = NULL;
629   if (ic->in_receive)
630     return; /* need to finish processing */
631   GNUNET_CONTAINER_DLL_remove (ic->h->tq_head,
632                                ic->h->tq_tail,
633                                ic->tqe);
634   GNUNET_free (ic->tqe);
635   GNUNET_free (ic);
636 }
637
638
639 /* end of peerinfo_api.c */