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