e7f095eac8aba9e32cc744b8a610c87846202ee7
[oweals/gnunet.git] / src / peerinfo / peerinfo_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2004, 2005, 2007, 2009, 2010 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 3, 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    * Connection to the service.
95    */
96   struct GNUNET_CLIENT_Connection *client;
97
98   /**
99    * Head of transmission queue.
100    */
101   struct TransmissionQueueEntry *tq_head;
102
103   /**
104    * Tail of transmission queue.
105    */
106   struct TransmissionQueueEntry *tq_tail;
107
108   /**
109    * Handle for the current transmission request, or NULL if none is pending.
110    */
111   struct GNUNET_CLIENT_TransmitHandle *th;
112
113   /**
114    * Set to GNUNET_YES if we are currently receiving replies from the
115    * service.
116    */
117   int in_receive;
118
119 };
120
121
122 /**
123  * Connect to the peerinfo service.
124  *
125  * @param cfg configuration to use
126  * @return NULL on error (configuration related, actual connection
127  *         establishment may happen asynchronously).
128  */
129 struct GNUNET_PEERINFO_Handle *
130 GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
131 {
132   struct GNUNET_CLIENT_Connection *client;
133   struct GNUNET_PEERINFO_Handle *ret;
134
135   client = GNUNET_CLIENT_connect ("peerinfo", cfg);
136   if (client == NULL)
137     return NULL;
138   ret = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_Handle));
139   ret->client = client;
140   ret->cfg = cfg;
141   return ret;
142 }
143
144
145 /**
146  * Disconnect from the peerinfo service.  Note that all iterators must
147  * have completed or have been cancelled by the time this function is
148  * called (otherwise, calling this function is a serious error).
149  * Furthermore, if 'GNUNET_PEERINFO_add_peer' operations are still
150  * pending, they will be cancelled silently on disconnect.
151  *
152  * @param h handle to disconnect
153  */
154 void
155 GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h)
156 {
157   struct TransmissionQueueEntry *tqe;
158
159   while (NULL != (tqe = h->tq_head))
160     {     
161       GNUNET_CONTAINER_DLL_remove (h->tq_head,
162                                    h->tq_tail,
163                                    tqe);
164       if (tqe->cont != NULL)
165         tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
166       GNUNET_free (tqe);
167     }
168   if (h->th != NULL)
169     {
170       GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
171       h->th = NULL;
172     }
173   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
174   GNUNET_free (h);
175 }
176
177
178 /**
179  * Check if we have a request pending in the transmission queue and are
180  * able to transmit it right now.  If so, schedule transmission.
181  *
182  * @param h handle to the service
183  */
184 static void
185 trigger_transmit (struct GNUNET_PEERINFO_Handle *h);
186
187
188 /**
189  * Close the existing connection to PEERINFO and reconnect.
190  *
191  * @param h handle to the service
192  */
193 static void
194 reconnect (struct GNUNET_PEERINFO_Handle *h)
195 {
196   GNUNET_CLIENT_disconnect (h->client, GNUNET_SYSERR);
197   h->th = NULL;
198   h->client = GNUNET_CLIENT_connect ("peerinfo", h->cfg);
199   GNUNET_assert (h->client != NULL);
200 }
201
202
203 /**
204  * Transmit the request at the head of the transmission queue
205  * and trigger continuation (if any).
206  *
207  * @param cls the 'struct GNUNET_PEERINFO_Handle' (with the queue)
208  * @param size size of the buffer (0 on error)
209  * @param buf where to copy the message
210  * @return number of bytes copied to buf
211  */
212 static size_t
213 do_transmit (void *cls, size_t size, void *buf)
214 {
215   struct GNUNET_PEERINFO_Handle *h = cls;
216   struct TransmissionQueueEntry *tqe = h->tq_head;
217   size_t ret;
218
219   h->th = NULL;
220   if (buf == NULL)
221     {
222       GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
223                   _("Failed to transmit message to `%s' service.\n"),
224                   "PEERINFO");
225       if (tqe != NULL)
226         GNUNET_CONTAINER_DLL_remove (h->tq_head,
227                                      h->tq_tail,
228                                      tqe);
229       reconnect (h);
230       trigger_transmit (h);
231       if (tqe != NULL)
232         {
233           if (tqe->cont != NULL)
234             tqe->cont (tqe->cont_cls, GNUNET_SYSERR);
235           GNUNET_free (tqe);
236         }
237       return 0;
238     }
239   ret = tqe->size;
240   GNUNET_assert (size >= ret);
241   memcpy (buf, &tqe[1], ret);
242 #if DEBUG_PEERINFO
243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
244               "Transmitting request of size %u to `%s' service.\n",
245               ret, 
246               "PEERINFO");
247 #endif
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_DEBUG,
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->timeout_task);
391       if (ic->callback != NULL)
392         ic->callback (ic->callback_cls, NULL, NULL);
393       GNUNET_free (ic);
394       return;
395     }
396   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END)
397     {
398 #if DEBUG_PEERINFO
399       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
400                   "Received end of list of peers from `%s' service\n",
401                   "PEERINFO");
402 #endif
403       trigger_transmit (ic->h);
404       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
405         GNUNET_SCHEDULER_cancel (ic->timeout_task);
406       if (ic->callback != NULL)
407         ic->callback (ic->callback_cls, NULL, NULL);
408       GNUNET_free (ic);
409       return;
410     }
411   ms = ntohs (msg->size);
412   if ((ms < sizeof (struct InfoMessage)) ||
413       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_PEERINFO_INFO))
414     {
415       GNUNET_break (0);
416       reconnect (ic->h);
417       trigger_transmit (ic->h);
418       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
419         GNUNET_SCHEDULER_cancel (ic->timeout_task);
420       if (ic->callback != NULL)
421         ic->callback (ic->callback_cls, NULL, NULL);
422       GNUNET_free (ic);
423       return;
424     }
425   im = (const struct InfoMessage *) msg;
426   GNUNET_break (0 == ntohl (im->reserved));
427   hello = NULL;
428   if (ms > sizeof (struct InfoMessage) + sizeof (struct GNUNET_MessageHeader))
429     {
430       hello = (const struct GNUNET_HELLO_Message *) &im[1];
431       if (ms != sizeof (struct InfoMessage) + GNUNET_HELLO_size (hello))
432         {
433           GNUNET_break (0);
434           reconnect (ic->h);
435           trigger_transmit (ic->h);
436           if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
437             GNUNET_SCHEDULER_cancel (ic->timeout_task);
438           if (ic->callback != NULL)
439             ic->callback (ic->callback_cls, NULL, NULL);
440           GNUNET_free (ic);
441           return;
442         }
443     }
444 #if DEBUG_PEERINFO
445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
446               "Received %u bytes of `%s' information about peer `%s' from `%s' service\n",
447               (hello == NULL) ? 0 : (unsigned int) GNUNET_HELLO_size (hello),
448               "HELLO",
449               GNUNET_i2s (&im->peer),
450               "PEERINFO");
451 #endif
452   ic->h->in_receive = GNUNET_YES;
453   if (ic->callback != NULL)
454     ic->callback (ic->callback_cls, &im->peer, hello);
455   GNUNET_CLIENT_receive (ic->h->client,
456                          &peerinfo_handler,
457                          ic,
458                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
459 }
460
461
462 /**
463  * We've transmitted the iteration request.  Now get ready to process
464  * the results (or handle transmission error).
465  *
466  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext'
467  * @param transmit_success GNUNET_OK if transmission worked
468  */
469 static void
470 iterator_start_receive (void *cls,
471                         int transmit_success)
472 {
473   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
474
475   if (GNUNET_OK != transmit_success)
476     {
477       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
478                   _("Failed to transmit iteration request to `%s' service (%d).\n"),
479                   "PEERINFO",
480                   transmit_success);
481       if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
482         {
483           GNUNET_SCHEDULER_cancel (ic->timeout_task);
484           ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
485         }
486       reconnect (ic->h);
487       trigger_transmit (ic->h);
488       if (ic->callback != NULL)
489         ic->callback (ic->callback_cls, NULL, NULL);
490       GNUNET_free (ic);
491       return;
492     }  
493 #if DEBUG_PEERINFO
494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495               "Waiting for response from `%s' service.\n",
496               "PEERINFO");
497 #endif
498   ic->h->in_receive = GNUNET_YES;
499   ic->in_receive = GNUNET_YES;
500   ic->tqe = NULL;
501   GNUNET_CLIENT_receive (ic->h->client,
502                          &peerinfo_handler,
503                          ic,
504                          GNUNET_TIME_absolute_get_remaining (ic->timeout));
505 }
506
507
508 /**
509  * Peerinfo iteration request has timed out.  
510  *
511  * @param cls the 'struct GNUNET_PEERINFO_IteratorContext*'
512  * @param tc scheduler context
513  */
514 static void
515 signal_timeout (void *cls,
516                 const struct GNUNET_SCHEDULER_TaskContext *tc)
517 {
518   struct GNUNET_PEERINFO_IteratorContext *ic = cls;
519
520   GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
521               _("Timeout transmitting iteration request to `%s' service.\n"),
522               "PEERINFO");
523   ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
524   if (! ic->in_receive)
525     GNUNET_CONTAINER_DLL_remove (ic->h->tq_head,
526                                  ic->h->tq_tail,
527                                  ic->tqe);
528   reconnect (ic->h);
529   ic->callback (ic->callback_cls, NULL, NULL);
530   ic->callback = NULL;
531   GNUNET_free_non_null (ic->tqe);
532   GNUNET_free (ic);
533 }
534
535
536 /**
537  * Call a method for each known matching host and change its trust
538  * value.  The callback method will be invoked once for each matching
539  * host and then finally once with a NULL pointer.  After that final
540  * invocation, the iterator context must no longer be used.
541  *
542  * Instead of calling this function with 'peer == NULL' it is often
543  * better to use 'GNUNET_PEERINFO_notify'.
544  * 
545  * @param h handle to the peerinfo service
546  * @param peer restrict iteration to this peer only (can be NULL)
547  * @param timeout how long to wait until timing out
548  * @param callback the method to call for each peer
549  * @param callback_cls closure for callback
550  * @return NULL on error (in this case, 'callback' is never called!), 
551  *         otherwise an iterator context
552  */
553 struct GNUNET_PEERINFO_IteratorContext *
554 GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h,
555                          const struct GNUNET_PeerIdentity *peer,
556                          struct GNUNET_TIME_Relative timeout,
557                          GNUNET_PEERINFO_Processor callback,
558                          void *callback_cls)
559 {
560   struct GNUNET_MessageHeader *lapm;
561   struct ListPeerMessage *lpm;
562   struct GNUNET_PEERINFO_IteratorContext *ic;
563   struct TransmissionQueueEntry *tqe;
564
565   if (peer == NULL)
566     {
567 #if DEBUG_PEERINFO
568       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
569                   "Requesting list of peers from PEERINFO service\n");
570 #endif
571       tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
572                            sizeof (struct GNUNET_MessageHeader));
573       tqe->size = sizeof (struct GNUNET_MessageHeader);
574       lapm = (struct GNUNET_MessageHeader *) &tqe[1];
575       lapm->size = htons (sizeof (struct GNUNET_MessageHeader));
576       lapm->type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL);
577     }
578   else
579     {
580 #if DEBUG_PEERINFO
581       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582                   "Requesting information on peer `%4s' from PEERINFO service\n",
583                   GNUNET_i2s (peer));
584 #endif
585       tqe = GNUNET_malloc (sizeof (struct TransmissionQueueEntry) +
586                            sizeof (struct ListPeerMessage));
587       tqe->size = sizeof (struct ListPeerMessage);
588       lpm = (struct ListPeerMessage *) &tqe[1];
589       lpm->header.size = htons (sizeof (struct ListPeerMessage));
590       lpm->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_GET);
591       memcpy (&lpm->peer, peer, sizeof (struct GNUNET_PeerIdentity));
592     }
593   ic = GNUNET_malloc (sizeof (struct GNUNET_PEERINFO_IteratorContext));
594   ic->h = h;
595   ic->tqe = tqe;
596   ic->callback = callback;
597   ic->callback_cls = callback_cls;
598   ic->timeout = GNUNET_TIME_relative_to_absolute (timeout);
599   ic->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
600                                                    &signal_timeout,
601                                                    ic);
602   tqe->timeout = ic->timeout;
603   tqe->cont = &iterator_start_receive;
604   tqe->cont_cls = ic;
605   tqe->timeout = ic->timeout;
606   GNUNET_CONTAINER_DLL_insert_after (h->tq_head,
607                                      h->tq_tail,
608                                      h->tq_tail,
609                                      tqe);
610   trigger_transmit (h);
611   return ic;
612 }
613
614
615
616 /**
617  * Cancel an iteration over peer information.
618  *
619  * @param ic context of the iterator to cancel
620  */
621 void
622 GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic)
623 {
624   if (ic->timeout_task != GNUNET_SCHEDULER_NO_TASK)
625     {
626       GNUNET_SCHEDULER_cancel (ic->timeout_task);
627       ic->timeout_task = GNUNET_SCHEDULER_NO_TASK;
628     }
629   ic->callback = NULL;
630   if (ic->in_receive)
631     return; /* need to finish processing */
632   GNUNET_CONTAINER_DLL_remove (ic->h->tq_head,
633                                ic->h->tq_tail,
634                                ic->tqe);
635   GNUNET_free (ic->tqe);
636   GNUNET_free (ic);
637 }
638
639
640 /* end of peerinfo_api.c */