Verify that GCD(m,n) != 1 when n is an RSA modulus
[oweals/gnunet.git] / src / statistics / statistics_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2011 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file statistics/statistics_api.c
23  * @brief API of the statistics service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_statistics_service.h"
31 #include "statistics.h"
32
33 /**
34  * How long do we wait until a statistics request for setting
35  * a value times out?  (The update will be lost if the
36  * service does not react within this timeframe).
37  */
38 #define SET_TRANSMIT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "statistics-api",__VA_ARGS__)
41
42 /**
43  * Types of actions.
44  */
45 enum ActionType
46 {
47   /**
48    * Get a value.
49    */
50   ACTION_GET,
51
52   /**
53    * Set a value.
54    */
55   ACTION_SET,
56
57   /**
58    * Update a value.
59    */
60   ACTION_UPDATE,
61
62   /**
63    * Watch a value.
64    */
65   ACTION_WATCH
66 };
67
68
69 /**
70  * Entry kept for each value we are watching.
71  */
72 struct GNUNET_STATISTICS_WatchEntry
73 {
74
75   /**
76    * What subsystem is this action about? (never NULL)
77    */
78   char *subsystem;
79
80   /**
81    * What value is this action about? (never NULL)
82    */
83   char *name;
84
85   /**
86    * Function to call
87    */
88   GNUNET_STATISTICS_Iterator proc;
89
90   /**
91    * Closure for proc
92    */
93   void *proc_cls;
94
95 };
96
97
98 /**
99  * Linked list of things we still need to do.
100  */
101 struct GNUNET_STATISTICS_GetHandle
102 {
103
104   /**
105    * This is a doubly linked list.
106    */
107   struct GNUNET_STATISTICS_GetHandle *next;
108
109   /**
110    * This is a doubly linked list.
111    */
112   struct GNUNET_STATISTICS_GetHandle *prev;
113
114   /**
115    * Main statistics handle.
116    */
117   struct GNUNET_STATISTICS_Handle *sh;
118
119   /**
120    * What subsystem is this action about? (can be NULL)
121    */
122   char *subsystem;
123
124   /**
125    * What value is this action about? (can be NULL)
126    */
127   char *name;
128
129   /**
130    * Continuation to call once action is complete.
131    */
132   GNUNET_STATISTICS_Callback cont;
133
134   /**
135    * Function to call (for GET actions only).
136    */
137   GNUNET_STATISTICS_Iterator proc;
138
139   /**
140    * Closure for proc and cont.
141    */
142   void *cls;
143
144   /**
145    * Timeout for this action.
146    */
147   struct GNUNET_TIME_Absolute timeout;
148
149   /**
150    * Task run on timeout.
151    */
152   struct GNUNET_SCHEDULER_Task * timeout_task;
153
154   /**
155    * Associated value.
156    */
157   uint64_t value;
158
159   /**
160    * Flag for SET/UPDATE actions.
161    */
162   int make_persistent;
163
164   /**
165    * Has the current iteration been aborted; for GET actions.
166    */
167   int aborted;
168
169   /**
170    * Is this a GET, SET, UPDATE or WATCH?
171    */
172   enum ActionType type;
173
174   /**
175    * Size of the message that we will be transmitting.
176    */
177   uint16_t msize;
178
179 };
180
181
182 /**
183  * Handle for the service.
184  */
185 struct GNUNET_STATISTICS_Handle
186 {
187   /**
188    * Name of our subsystem.
189    */
190   char *subsystem;
191
192   /**
193    * Configuration to use.
194    */
195   const struct GNUNET_CONFIGURATION_Handle *cfg;
196
197   /**
198    * Socket (if available).
199    */
200   struct GNUNET_CLIENT_Connection *client;
201
202   /**
203    * Currently pending transmission request.
204    */
205   struct GNUNET_CLIENT_TransmitHandle *th;
206
207   /**
208    * Head of the linked list of pending actions (first action
209    * to be performed).
210    */
211   struct GNUNET_STATISTICS_GetHandle *action_head;
212
213   /**
214    * Tail of the linked list of actions (for fast append).
215    */
216   struct GNUNET_STATISTICS_GetHandle *action_tail;
217
218   /**
219    * Action we are currently busy with (action request has been
220    * transmitted, we're now receiving the response from the
221    * service).
222    */
223   struct GNUNET_STATISTICS_GetHandle *current;
224
225   /**
226    * Array of watch entries.
227    */
228   struct GNUNET_STATISTICS_WatchEntry **watches;
229
230   /**
231    * Task doing exponential back-off trying to reconnect.
232    */
233   struct GNUNET_SCHEDULER_Task * backoff_task;
234
235   /**
236    * Time for next connect retry.
237    */
238   struct GNUNET_TIME_Relative backoff;
239
240   /**
241    * Maximum heap size observed so far (if available).
242    */
243   uint64_t peak_heap_size;
244
245   /**
246    * Maximum resident set side observed so far (if available).
247    */
248   uint64_t peak_rss;
249
250   /**
251    * Size of the 'watches' array.
252    */
253   unsigned int watches_size;
254
255   /**
256    * Should this handle auto-destruct once all actions have
257    * been processed?
258    */
259   int do_destroy;
260
261   /**
262    * Are we currently receiving from the service?
263    */
264   int receiving;
265
266 };
267
268
269 /**
270  * Obtain statistics about this process's memory consumption and
271  * report those as well (if they changed).
272  */
273 static void
274 update_memory_statistics (struct GNUNET_STATISTICS_Handle *h)
275 {
276 #if ENABLE_HEAP_STATISTICS
277   uint64_t current_heap_size = 0;
278   uint64_t current_rss = 0;
279
280   if (GNUNET_NO != h->do_destroy)
281     return;
282 #if HAVE_MALLINFO
283   {
284     struct mallinfo mi;
285
286     mi = mallinfo();
287     current_heap_size = mi.uordblks + mi.fordblks;
288   }
289 #endif
290 #if HAVE_GETRUSAGE
291   {
292     struct rusage ru;
293
294     if (0 == getrusage (RUSAGE_SELF, &ru))
295     {
296       current_rss = 1024LL * ru.ru_maxrss;
297     }
298   }
299 #endif
300   if (current_heap_size > h->peak_heap_size)
301   {
302     h->peak_heap_size = current_heap_size;
303     GNUNET_STATISTICS_set (h, "# peak heap size", current_heap_size, GNUNET_NO);
304   }
305   if (current_rss > h->peak_rss)
306   {
307     h->peak_rss = current_rss;
308     GNUNET_STATISTICS_set (h, "# peak resident set size", current_rss, GNUNET_NO);
309   }
310 #endif
311 }
312
313
314 /**
315  * Schedule the next action to be performed.
316  *
317  * @param h statistics handle to reconnect
318  */
319 static void
320 schedule_action (struct GNUNET_STATISTICS_Handle *h);
321
322
323 /**
324  * Transmit request to service that we want to watch
325  * the development of a particular value.
326  *
327  * @param h statistics handle
328  * @param watch watch entry of the value to watch
329  */
330 static void
331 schedule_watch_request (struct GNUNET_STATISTICS_Handle *h,
332                         struct GNUNET_STATISTICS_WatchEntry *watch)
333 {
334   struct GNUNET_STATISTICS_GetHandle *ai;
335   size_t slen;
336   size_t nlen;
337   size_t nsize;
338
339   slen = strlen (watch->subsystem) + 1;
340   nlen = strlen (watch->name) + 1;
341   nsize = sizeof (struct GNUNET_MessageHeader) + slen + nlen;
342   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
343   {
344     GNUNET_break (0);
345     return;
346   }
347   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
348   ai->sh = h;
349   ai->subsystem = GNUNET_strdup (watch->subsystem);
350   ai->name = GNUNET_strdup (watch->name);
351   ai->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
352   ai->msize = nsize;
353   ai->type = ACTION_WATCH;
354   ai->proc = watch->proc;
355   ai->cls = watch->proc_cls;
356   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
357                                     ai);
358   schedule_action (h);
359 }
360
361
362 /**
363  * Free memory associated with the given action item.
364  *
365  * @param gh action item to free
366  */
367 static void
368 free_action_item (struct GNUNET_STATISTICS_GetHandle *gh)
369 {
370   if (NULL != gh->timeout_task)
371   {
372     GNUNET_SCHEDULER_cancel (gh->timeout_task);
373     gh->timeout_task = NULL;
374   }
375   GNUNET_free_non_null (gh->subsystem);
376   GNUNET_free_non_null (gh->name);
377   GNUNET_free (gh);
378 }
379
380
381 /**
382  * Disconnect from the statistics service.
383  *
384  * @param h statistics handle to disconnect from
385  */
386 static void
387 do_disconnect (struct GNUNET_STATISTICS_Handle *h)
388 {
389   struct GNUNET_STATISTICS_GetHandle *c;
390
391   if (NULL != h->th)
392   {
393     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
394     h->th = NULL;
395   }
396   h->receiving = GNUNET_NO;
397   if (NULL != (c = h->current))
398   {
399     h->current = NULL;
400     if ( (NULL != c->cont) &&
401          (GNUNET_YES != c->aborted) )
402     {
403       c->cont (c->cls, GNUNET_SYSERR);
404       c->cont = NULL;
405     }
406     free_action_item (c);
407   }
408   if (NULL != h->client)
409   {
410     GNUNET_CLIENT_disconnect (h->client);
411     h->client = NULL;
412   }
413 }
414
415
416 /**
417  * Try to (re)connect to the statistics service.
418  *
419  * @param h statistics handle to reconnect
420  * @return #GNUNET_YES on success, #GNUNET_NO on failure.
421  */
422 static int
423 try_connect (struct GNUNET_STATISTICS_Handle *h)
424 {
425   struct GNUNET_STATISTICS_GetHandle *gh;
426   struct GNUNET_STATISTICS_GetHandle *gn;
427   unsigned int i;
428
429   if (NULL != h->backoff_task)
430     return GNUNET_NO;
431   if (NULL != h->client)
432     return GNUNET_YES;
433   h->client = GNUNET_CLIENT_connect ("statistics", h->cfg);
434   if (NULL != h->client)
435   {
436     gn = h->action_head;
437     while (NULL != (gh = gn))
438     {
439       gn = gh->next;
440       if (gh->type == ACTION_WATCH)
441       {
442         GNUNET_CONTAINER_DLL_remove (h->action_head,
443                                      h->action_tail,
444                                      gh);
445         free_action_item (gh);
446       }
447     }
448     for (i = 0; i < h->watches_size; i++)
449     {
450       if (NULL != h->watches[i])
451         schedule_watch_request (h, h->watches[i]);
452     }
453     return GNUNET_YES;
454   }
455   LOG (GNUNET_ERROR_TYPE_DEBUG,
456        "Failed to connect to statistics service!\n");
457   return GNUNET_NO;
458 }
459
460
461 /**
462  * We've waited long enough, reconnect now.
463  *
464  * @param cls the `struct GNUNET_STATISTICS_Handle` to reconnect
465  */
466 static void
467 reconnect_task (void *cls)
468 {
469   struct GNUNET_STATISTICS_Handle *h = cls;
470
471   h->backoff_task = NULL;
472   schedule_action (h);
473 }
474
475
476 /**
477  * Task used by 'reconnect_later' to shutdown the handle
478  *
479  * @param cls the statistics handle
480  */
481 static void
482 do_destroy (void *cls)
483 {
484   struct GNUNET_STATISTICS_Handle *h = cls;
485
486   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
487 }
488
489
490 /**
491  * Reconnect at a later time, respecting back-off.
492  *
493  * @param h statistics handle
494  */
495 static void
496 reconnect_later (struct GNUNET_STATISTICS_Handle *h)
497 {
498   int loss;
499   struct GNUNET_STATISTICS_GetHandle *gh;
500
501   GNUNET_assert (NULL == h->backoff_task);
502   if (GNUNET_YES == h->do_destroy)
503   {
504     /* So we are shutting down and the service is not reachable.
505      * Chances are that it's down for good and we are not going to connect to
506      * it anymore.
507      * Give up and don't sync the rest of the data.
508      */
509     loss = GNUNET_NO;
510     for (gh = h->action_head; NULL != gh; gh = gh->next)
511       if ( (gh->make_persistent) && (ACTION_SET == gh->type) )
512         loss = GNUNET_YES;
513     if (GNUNET_YES == loss)
514       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
515                   _("Could not save some persistent statistics\n"));
516     h->do_destroy = GNUNET_NO;
517     GNUNET_SCHEDULER_add_now (&do_destroy, h);
518     return;
519   }
520   h->backoff_task =
521     GNUNET_SCHEDULER_add_delayed (h->backoff, &reconnect_task, h);
522   h->backoff = GNUNET_TIME_STD_BACKOFF (h->backoff);
523 }
524
525
526 /**
527  * Process a #GNUNET_MESSAGE_TYPE_STATISTICS_VALUE message.
528  *
529  * @param h statistics handle
530  * @param msg message received from the service, never NULL
531  * @return #GNUNET_OK if the message was well-formed
532  */
533 static int
534 process_statistics_value_message (struct GNUNET_STATISTICS_Handle *h,
535                                   const struct GNUNET_MessageHeader *msg)
536 {
537   char *service;
538   char *name;
539   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
540   uint16_t size;
541
542   if (h->current->aborted)
543   {
544     LOG (GNUNET_ERROR_TYPE_DEBUG,
545          "Iteration was aborted, ignoring VALUE\n");
546     return GNUNET_OK;           /* don't bother */
547   }
548   size = ntohs (msg->size);
549   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
550   {
551     GNUNET_break (0);
552     return GNUNET_SYSERR;
553   }
554   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
555   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
556   if (size !=
557       GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1], size, 2,
558                                       &service, &name))
559   {
560     GNUNET_break (0);
561     return GNUNET_SYSERR;
562   }
563   LOG (GNUNET_ERROR_TYPE_DEBUG,
564        "Received valid statistic on `%s:%s': %llu\n",
565        service, name,
566        GNUNET_ntohll (smsg->value));
567   if (GNUNET_OK !=
568       h->current->proc (h->current->cls, service, name,
569                         GNUNET_ntohll (smsg->value),
570                         0 !=
571                         (ntohl (smsg->uid) & GNUNET_STATISTICS_PERSIST_BIT)))
572   {
573     LOG (GNUNET_ERROR_TYPE_DEBUG,
574          "Processing of remaining statistics aborted by client.\n");
575     h->current->aborted = GNUNET_YES;
576   }
577   LOG (GNUNET_ERROR_TYPE_DEBUG,
578        "VALUE processed successfully\n");
579   return GNUNET_OK;
580 }
581
582
583 /**
584  * We have received a watch value from the service.  Process it.
585  *
586  * @param h statistics handle
587  * @param msg the watch value message
588  * @return #GNUNET_OK if the message was well-formed, #GNUNET_SYSERR if not,
589  *         #GNUNET_NO if this watch has been cancelled
590  */
591 static int
592 process_watch_value (struct GNUNET_STATISTICS_Handle *h,
593                      const struct GNUNET_MessageHeader *msg)
594 {
595   const struct GNUNET_STATISTICS_WatchValueMessage *wvm;
596   struct GNUNET_STATISTICS_WatchEntry *w;
597   uint32_t wid;
598
599   if (sizeof (struct GNUNET_STATISTICS_WatchValueMessage) != ntohs (msg->size))
600   {
601     GNUNET_break (0);
602     return GNUNET_SYSERR;
603   }
604   wvm = (const struct GNUNET_STATISTICS_WatchValueMessage *) msg;
605   GNUNET_break (0 == ntohl (wvm->reserved));
606   wid = ntohl (wvm->wid);
607   if (wid >= h->watches_size)
608   {
609     GNUNET_break (0);
610     return GNUNET_SYSERR;
611   }
612   w = h->watches[wid];
613   if (NULL == w)
614     return GNUNET_NO;
615   (void) w->proc (w->proc_cls, w->subsystem, w->name,
616                   GNUNET_ntohll (wvm->value),
617                   0 != (ntohl (wvm->flags) & GNUNET_STATISTICS_PERSIST_BIT));
618   return GNUNET_OK;
619 }
620
621
622 /**
623  * Task used to destroy the statistics handle.
624  *
625  * @param cls the `struct GNUNET_STATISTICS_Handle`
626  */
627 static void
628 destroy_task (void *cls)
629 {
630   struct GNUNET_STATISTICS_Handle *h = cls;
631
632   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
633 }
634
635
636 /**
637  * Function called with messages from stats service.
638  *
639  * @param cls closure
640  * @param msg message received, NULL on timeout or fatal error
641  */
642 static void
643 receive_stats (void *cls,
644                const struct GNUNET_MessageHeader *msg)
645 {
646   struct GNUNET_STATISTICS_Handle *h = cls;
647   struct GNUNET_STATISTICS_GetHandle *c;
648   int ret;
649
650   if (NULL == msg)
651   {
652     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
653          "Error receiving statistics from service, is the service running?\n");
654     do_disconnect (h);
655     reconnect_later (h);
656     return;
657   }
658   switch (ntohs (msg->type))
659   {
660   case GNUNET_MESSAGE_TYPE_TEST:
661     if (GNUNET_SYSERR != h->do_destroy)
662     {
663       /* not in shutdown, why do we get 'TEST'? */
664       GNUNET_break (0);
665       do_disconnect (h);
666       reconnect_later (h);
667       return;
668     }
669     h->do_destroy = GNUNET_NO;
670     GNUNET_SCHEDULER_add_now (&destroy_task, h);
671     break;
672   case GNUNET_MESSAGE_TYPE_STATISTICS_END:
673     LOG (GNUNET_ERROR_TYPE_DEBUG,
674          "Received end of statistics marker\n");
675     if (NULL == (c = h->current))
676     {
677       GNUNET_break (0);
678       do_disconnect (h);
679       reconnect_later (h);
680       return;
681     }
682     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
683     if (h->watches_size > 0)
684     {
685       GNUNET_CLIENT_receive (h->client, &receive_stats, h,
686                              GNUNET_TIME_UNIT_FOREVER_REL);
687     }
688     else
689     {
690       h->receiving = GNUNET_NO;
691     }
692     h->current = NULL;
693     schedule_action (h);
694     if (NULL != c->cont)
695     {
696       c->cont (c->cls, GNUNET_OK);
697       c->cont = NULL;
698     }
699     free_action_item (c);
700     return;
701   case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
702     if (GNUNET_OK != process_statistics_value_message (h, msg))
703     {
704       do_disconnect (h);
705       reconnect_later (h);
706       return;
707     }
708     /* finally, look for more! */
709     LOG (GNUNET_ERROR_TYPE_DEBUG,
710          "Processing VALUE done, now reading more\n");
711     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
712                            GNUNET_TIME_absolute_get_remaining (h->
713                                                                current->timeout));
714     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
715     return;
716   case GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE:
717     if (GNUNET_OK !=
718         (ret = process_watch_value (h, msg)))
719     {
720       do_disconnect (h);
721       if (GNUNET_NO == ret)
722         h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
723       reconnect_later (h);
724       return;
725     }
726     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
727     GNUNET_assert (h->watches_size > 0);
728     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
729                            GNUNET_TIME_UNIT_FOREVER_REL);
730     return;
731   default:
732     GNUNET_break (0);
733     do_disconnect (h);
734     reconnect_later (h);
735     return;
736   }
737 }
738
739
740 /**
741  * Transmit a GET request (and if successful, start to receive
742  * the response).
743  *
744  * @param handle statistics handle
745  * @param size how many bytes can we write to @a buf
746  * @param buf where to write requests to the service
747  * @return number of bytes written to @a buf
748  */
749 static size_t
750 transmit_get (struct GNUNET_STATISTICS_Handle *handle,
751               size_t size,
752               void *buf)
753 {
754   struct GNUNET_STATISTICS_GetHandle *c;
755   struct GNUNET_MessageHeader *hdr;
756   size_t slen1;
757   size_t slen2;
758   uint16_t msize;
759
760   GNUNET_assert (NULL != (c = handle->current));
761   if (NULL == buf)
762   {
763     /* timeout / error */
764     LOG (GNUNET_ERROR_TYPE_DEBUG,
765          "Transmission of request for statistics failed!\n");
766     do_disconnect (handle);
767     reconnect_later (handle);
768     return 0;
769   }
770   slen1 = strlen (c->subsystem) + 1;
771   slen2 = strlen (c->name) + 1;
772   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
773   GNUNET_assert (msize <= size);
774   hdr = (struct GNUNET_MessageHeader *) buf;
775   hdr->size = htons (msize);
776   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
777   GNUNET_assert (slen1 + slen2 ==
778                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
779                                              c->subsystem,
780                                              c->name));
781   if (GNUNET_YES != handle->receiving)
782   {
783     LOG (GNUNET_ERROR_TYPE_DEBUG,
784          "Transmission of GET done, now reading response\n");
785     handle->receiving = GNUNET_YES;
786     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
787                            GNUNET_TIME_absolute_get_remaining (c->timeout));
788   }
789   return msize;
790 }
791
792
793 /**
794  * Transmit a WATCH request (and if successful, start to receive
795  * the response).
796  *
797  * @param handle statistics handle
798  * @param size how many bytes can we write to @a buf
799  * @param buf where to write requests to the service
800  * @return number of bytes written to @a buf
801  */
802 static size_t
803 transmit_watch (struct GNUNET_STATISTICS_Handle *handle,
804                 size_t size,
805                 void *buf)
806 {
807   struct GNUNET_MessageHeader *hdr;
808   size_t slen1;
809   size_t slen2;
810   uint16_t msize;
811
812   if (NULL == buf)
813   {
814     /* timeout / error */
815     LOG (GNUNET_ERROR_TYPE_DEBUG,
816          "Transmission of request for statistics failed!\n");
817     do_disconnect (handle);
818     reconnect_later (handle);
819     return 0;
820   }
821   LOG (GNUNET_ERROR_TYPE_DEBUG,
822        "Transmitting watch request for `%s'\n",
823        handle->current->name);
824   slen1 = strlen (handle->current->subsystem) + 1;
825   slen2 = strlen (handle->current->name) + 1;
826   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
827   GNUNET_assert (msize <= size);
828   hdr = (struct GNUNET_MessageHeader *) buf;
829   hdr->size = htons (msize);
830   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_WATCH);
831   GNUNET_assert (slen1 + slen2 ==
832                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
833                                              handle->current->subsystem,
834                                              handle->current->name));
835   if (GNUNET_YES != handle->receiving)
836   {
837     handle->receiving = GNUNET_YES;
838     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
839                            GNUNET_TIME_UNIT_FOREVER_REL);
840   }
841   GNUNET_assert (NULL == handle->current->cont);
842   free_action_item (handle->current);
843   handle->current = NULL;
844   return msize;
845 }
846
847
848 /**
849  * Transmit a SET/UPDATE request.
850  *
851  * @param handle statistics handle
852  * @param size how many bytes can we write to @a buf
853  * @param buf where to write requests to the service
854  * @return number of bytes written to @a buf
855  */
856 static size_t
857 transmit_set (struct GNUNET_STATISTICS_Handle *handle,
858               size_t size,
859               void *buf)
860 {
861   struct GNUNET_STATISTICS_SetMessage *r;
862   size_t slen;
863   size_t nlen;
864   size_t nsize;
865
866   if (NULL == buf)
867   {
868     do_disconnect (handle);
869     reconnect_later (handle);
870     return 0;
871   }
872   slen = strlen (handle->current->subsystem) + 1;
873   nlen = strlen (handle->current->name) + 1;
874   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
875   if (size < nsize)
876   {
877     GNUNET_break (0);
878     do_disconnect (handle);
879     reconnect_later (handle);
880     return 0;
881   }
882   r = buf;
883   r->header.size = htons (nsize);
884   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
885   r->flags = 0;
886   r->value = GNUNET_htonll (handle->current->value);
887   if (handle->current->make_persistent)
888     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
889   if (handle->current->type == ACTION_UPDATE)
890     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
891   GNUNET_assert (slen + nlen ==
892                  GNUNET_STRINGS_buffer_fill ((char *) &r[1], slen + nlen, 2,
893                                              handle->current->subsystem,
894                                              handle->current->name));
895   GNUNET_assert (NULL == handle->current->cont);
896   free_action_item (handle->current);
897   handle->current = NULL;
898   update_memory_statistics (handle);
899   return nsize;
900 }
901
902
903 /**
904  * Function called when we are ready to transmit a request to the service.
905  *
906  * @param cls the `struct GNUNET_STATISTICS_Handle`
907  * @param size how many bytes can we write to @a buf
908  * @param buf where to write requests to the service
909  * @return number of bytes written to @a buf
910  */
911 static size_t
912 transmit_action (void *cls, size_t size, void *buf)
913 {
914   struct GNUNET_STATISTICS_Handle *h = cls;
915   size_t ret;
916
917   h->th = NULL;
918   ret = 0;
919   if (NULL != h->current)
920     switch (h->current->type)
921     {
922     case ACTION_GET:
923       ret = transmit_get (h, size, buf);
924       break;
925     case ACTION_SET:
926     case ACTION_UPDATE:
927       ret = transmit_set (h, size, buf);
928       break;
929     case ACTION_WATCH:
930       ret = transmit_watch (h, size, buf);
931       break;
932     default:
933       GNUNET_assert (0);
934       break;
935     }
936   schedule_action (h);
937   return ret;
938 }
939
940
941 /**
942  * Get handle for the statistics service.
943  *
944  * @param subsystem name of subsystem using the service
945  * @param cfg services configuration in use
946  * @return handle to use
947  */
948 struct GNUNET_STATISTICS_Handle *
949 GNUNET_STATISTICS_create (const char *subsystem,
950                           const struct GNUNET_CONFIGURATION_Handle *cfg)
951 {
952   struct GNUNET_STATISTICS_Handle *ret;
953
954   if (GNUNET_YES ==
955       GNUNET_CONFIGURATION_get_value_yesno (cfg, "statistics", "DISABLE"))
956     return NULL;
957   GNUNET_assert (NULL != subsystem);
958   GNUNET_assert (NULL != cfg);
959   ret = GNUNET_new (struct GNUNET_STATISTICS_Handle);
960   ret->cfg = cfg;
961   ret->subsystem = GNUNET_strdup (subsystem);
962   ret->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
963   return ret;
964 }
965
966
967 /**
968  * Destroy a handle (free all state associated with
969  * it).
970  *
971  * @param h statistics handle to destroy
972  * @param sync_first set to #GNUNET_YES if pending SET requests should
973  *        be completed
974  */
975 void
976 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h,
977                            int sync_first)
978 {
979   struct GNUNET_STATISTICS_GetHandle *pos;
980   struct GNUNET_STATISTICS_GetHandle *next;
981   struct GNUNET_TIME_Relative timeout;
982   int i;
983
984   if (NULL == h)
985     return;
986   GNUNET_assert (GNUNET_NO == h->do_destroy); // Don't call twice.
987   if (NULL != h->backoff_task)
988   {
989     GNUNET_SCHEDULER_cancel (h->backoff_task);
990     h->backoff_task = NULL;
991   }
992   if (sync_first)
993   {
994     if (NULL != h->current)
995     {
996       if (ACTION_GET == h->current->type)
997       {
998         if (NULL != h->th)
999         {
1000           GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
1001           h->th = NULL;
1002         }
1003         free_action_item (h->current);
1004         h->current = NULL;
1005       }
1006     }
1007     next = h->action_head;
1008     while (NULL != (pos = next))
1009     {
1010       next = pos->next;
1011       if (ACTION_GET == pos->type)
1012       {
1013         GNUNET_CONTAINER_DLL_remove (h->action_head,
1014                                      h->action_tail,
1015                                      pos);
1016         free_action_item (pos);
1017       }
1018     }
1019     if ( (NULL == h->current) &&
1020          (NULL != (h->current = h->action_head)) )
1021       GNUNET_CONTAINER_DLL_remove (h->action_head,
1022                                    h->action_tail,
1023                                    h->current);
1024     h->do_destroy = GNUNET_YES;
1025     if ((NULL != h->current) && (NULL == h->th) &&
1026         (NULL != h->client))
1027     {
1028       timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1029       h->th =
1030         GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1031                                              timeout, GNUNET_YES,
1032                                              &transmit_action, h);
1033       GNUNET_assert (NULL != h->th);
1034     }
1035     if (NULL != h->th)
1036       return; /* do not finish destruction just yet */
1037   }
1038   while (NULL != (pos = h->action_head))
1039   {
1040     GNUNET_CONTAINER_DLL_remove (h->action_head,
1041                                  h->action_tail,
1042                                  pos);
1043     free_action_item (pos);
1044   }
1045   do_disconnect (h);
1046   for (i = 0; i < h->watches_size; i++)
1047   {
1048     if (NULL == h->watches[i])
1049       continue;
1050     GNUNET_free (h->watches[i]->subsystem);
1051     GNUNET_free (h->watches[i]->name);
1052     GNUNET_free (h->watches[i]);
1053   }
1054   GNUNET_array_grow (h->watches, h->watches_size, 0);
1055   GNUNET_free (h->subsystem);
1056   GNUNET_free (h);
1057 }
1058
1059
1060 /**
1061  * Function called to transmit TEST message to service to
1062  * confirm that the service has received all of our 'SET'
1063  * messages (during statistics disconnect/shutdown).
1064  *
1065  * @param cls the `struct GNUNET_STATISTICS_Handle`
1066  * @param size how many bytes can we write to @a buf
1067  * @param buf where to write requests to the service
1068  * @return number of bytes written to @a buf
1069  */
1070 static size_t
1071 transmit_test_on_shutdown (void *cls,
1072                            size_t size,
1073                            void *buf)
1074 {
1075   struct GNUNET_STATISTICS_Handle *h = cls;
1076   struct GNUNET_MessageHeader hdr;
1077
1078   h->th = NULL;
1079   if (NULL == buf)
1080   {
1081     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1082                 _("Failed to receive acknowledgement from statistics service, some statistics might have been lost!\n"));
1083     h->do_destroy = GNUNET_NO;
1084     GNUNET_SCHEDULER_add_now (&destroy_task, h);
1085     return 0;
1086   }
1087   hdr.type = htons (GNUNET_MESSAGE_TYPE_TEST);
1088   hdr.size = htons (sizeof (struct GNUNET_MessageHeader));
1089   memcpy (buf, &hdr, sizeof (hdr));
1090   if (GNUNET_YES != h->receiving)
1091   {
1092     h->receiving = GNUNET_YES;
1093     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
1094                            GNUNET_TIME_UNIT_FOREVER_REL);
1095   }
1096   return sizeof (struct GNUNET_MessageHeader);
1097 }
1098
1099
1100 /**
1101  * Schedule the next action to be performed.
1102  *
1103  * @param h statistics handle
1104  */
1105 static void
1106 schedule_action (struct GNUNET_STATISTICS_Handle *h)
1107 {
1108   struct GNUNET_TIME_Relative timeout;
1109
1110   if ( (NULL != h->th) ||
1111        (NULL != h->backoff_task) )
1112     return;                     /* action already pending */
1113   if (GNUNET_YES != try_connect (h))
1114   {
1115     reconnect_later (h);
1116     return;
1117   }
1118   if (NULL != h->current)
1119     return; /* action already pending */
1120   /* schedule next action */
1121   h->current = h->action_head;
1122   if (NULL == h->current)
1123   {
1124     if (GNUNET_YES == h->do_destroy)
1125     {
1126       h->do_destroy = GNUNET_SYSERR; /* in 'TEST' mode */
1127       h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
1128                                                    sizeof (struct GNUNET_MessageHeader),
1129                                                    SET_TRANSMIT_TIMEOUT,
1130                                                    GNUNET_NO,
1131                                                    &transmit_test_on_shutdown, h);
1132     }
1133     return;
1134   }
1135   GNUNET_CONTAINER_DLL_remove (h->action_head, h->action_tail, h->current);
1136   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1137   if (NULL ==
1138       (h->th =
1139        GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1140                                             timeout, GNUNET_YES,
1141                                             &transmit_action, h)))
1142   {
1143     LOG (GNUNET_ERROR_TYPE_DEBUG,
1144          "Failed to transmit request to statistics service.\n");
1145     do_disconnect (h);
1146     reconnect_later (h);
1147   }
1148 }
1149
1150
1151 /**
1152  * We have run into a timeout on a #GNUNET_STATISTICS_get() operation,
1153  * call the continuation.
1154  *
1155  * @param cls the `struct GNUNET_STATISTICS_GetHandle`
1156  */
1157 static void
1158 run_get_timeout (void *cls)
1159 {
1160   struct GNUNET_STATISTICS_GetHandle *gh = cls;
1161   GNUNET_STATISTICS_Callback cont = gh->cont;
1162   void *cont_cls = gh->cls;
1163
1164   gh->timeout_task = NULL;
1165   GNUNET_STATISTICS_get_cancel (gh);
1166   cont (cont_cls, GNUNET_SYSERR);
1167 }
1168
1169
1170 /**
1171  * Get statistic from the peer.
1172  *
1173  * @param handle identification of the statistics service
1174  * @param subsystem limit to the specified subsystem, NULL for our subsystem
1175  * @param name name of the statistic value, NULL for all values
1176  * @param timeout after how long should we give up (and call
1177  *        cont with an error code)?
1178  * @param cont continuation to call when done (can be NULL)
1179  *        This callback CANNOT destroy the statistics handle in the same call.
1180  * @param proc function to call on each value
1181  * @param cls closure for @a cont and @a proc
1182  * @return NULL on error
1183  */
1184 struct GNUNET_STATISTICS_GetHandle *
1185 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
1186                        const char *subsystem, const char *name,
1187                        struct GNUNET_TIME_Relative timeout,
1188                        GNUNET_STATISTICS_Callback cont,
1189                        GNUNET_STATISTICS_Iterator proc, void *cls)
1190 {
1191   size_t slen1;
1192   size_t slen2;
1193   struct GNUNET_STATISTICS_GetHandle *ai;
1194
1195   if (NULL == handle)
1196     return NULL;
1197   GNUNET_assert (NULL != proc);
1198   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1199   if (NULL == subsystem)
1200     subsystem = "";
1201   if (NULL == name)
1202     name = "";
1203   slen1 = strlen (subsystem) + 1;
1204   slen2 = strlen (name) + 1;
1205   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
1206                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1207   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1208   ai->sh = handle;
1209   ai->subsystem = GNUNET_strdup (subsystem);
1210   ai->name = GNUNET_strdup (name);
1211   ai->cont = cont;
1212   ai->proc = proc;
1213   ai->cls = cls;
1214   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1215   ai->type = ACTION_GET;
1216   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
1217   ai->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
1218                                                    &run_get_timeout,
1219                                                    ai);
1220   GNUNET_CONTAINER_DLL_insert_tail (handle->action_head,
1221                                     handle->action_tail,
1222                                     ai);
1223   schedule_action (handle);
1224   return ai;
1225 }
1226
1227
1228 /**
1229  * Cancel a 'get' request.  Must be called before the 'cont'
1230  * function is called.
1231  *
1232  * @param gh handle of the request to cancel
1233  */
1234 void
1235 GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh)
1236 {
1237   if (NULL == gh)
1238     return;
1239   if (NULL != gh->timeout_task)
1240   {
1241     GNUNET_SCHEDULER_cancel (gh->timeout_task);
1242     gh->timeout_task = NULL;
1243   }
1244   gh->cont = NULL;
1245   if (gh->sh->current == gh)
1246   {
1247     gh->aborted = GNUNET_YES;
1248   }
1249   else
1250   {
1251     GNUNET_CONTAINER_DLL_remove (gh->sh->action_head, gh->sh->action_tail, gh);
1252     GNUNET_free (gh->name);
1253     GNUNET_free (gh->subsystem);
1254     GNUNET_free (gh);
1255   }
1256 }
1257
1258
1259 /**
1260  * Watch statistics from the peer (be notified whenever they change).
1261  *
1262  * @param handle identification of the statistics service
1263  * @param subsystem limit to the specified subsystem, never NULL
1264  * @param name name of the statistic value, never NULL
1265  * @param proc function to call on each value
1266  * @param proc_cls closure for @a proc
1267  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1268  */
1269 int
1270 GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle,
1271                          const char *subsystem, const char *name,
1272                          GNUNET_STATISTICS_Iterator proc, void *proc_cls)
1273 {
1274   struct GNUNET_STATISTICS_WatchEntry *w;
1275
1276   if (NULL == handle)
1277     return GNUNET_SYSERR;
1278   w = GNUNET_new (struct GNUNET_STATISTICS_WatchEntry);
1279   w->subsystem = GNUNET_strdup (subsystem);
1280   w->name = GNUNET_strdup (name);
1281   w->proc = proc;
1282   w->proc_cls = proc_cls;
1283   GNUNET_array_append (handle->watches, handle->watches_size, w);
1284   schedule_watch_request (handle, w);
1285   return GNUNET_OK;
1286 }
1287
1288
1289 /**
1290  * Stop watching statistics from the peer.
1291  *
1292  * @param handle identification of the statistics service
1293  * @param subsystem limit to the specified subsystem, never NULL
1294  * @param name name of the statistic value, never NULL
1295  * @param proc function to call on each value
1296  * @param proc_cls closure for @a proc
1297  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error (no such watch)
1298  */
1299 int
1300 GNUNET_STATISTICS_watch_cancel (struct GNUNET_STATISTICS_Handle *handle,
1301                                 const char *subsystem,
1302                                 const char *name,
1303                                 GNUNET_STATISTICS_Iterator proc,
1304                                 void *proc_cls)
1305 {
1306   struct GNUNET_STATISTICS_WatchEntry *w;
1307   unsigned int i;
1308
1309   if (NULL == handle)
1310     return GNUNET_SYSERR;
1311   for (i=0;i<handle->watches_size;i++)
1312   {
1313     w = handle->watches[i];
1314     if (NULL == w)
1315       continue;
1316     if ( (w->proc == proc) &&
1317          (w->proc_cls == proc_cls) &&
1318          (0 == strcmp (w->name, name)) &&
1319          (0 == strcmp (w->subsystem, subsystem)) )
1320     {
1321       GNUNET_free (w->name);
1322       GNUNET_free (w->subsystem);
1323       GNUNET_free (w);
1324       handle->watches[i] = NULL;
1325       return GNUNET_OK;
1326     }
1327   }
1328   return GNUNET_SYSERR;
1329 }
1330
1331
1332
1333 /**
1334  * Queue a request to change a statistic.
1335  *
1336  * @param h statistics handle
1337  * @param name name of the value
1338  * @param make_persistent  should the value be kept across restarts?
1339  * @param value new value or change
1340  * @param type type of the action (#ACTION_SET or #ACTION_UPDATE)
1341  */
1342 static void
1343 add_setter_action (struct GNUNET_STATISTICS_Handle *h,
1344                    const char *name,
1345                    int make_persistent,
1346                    uint64_t value,
1347                    enum ActionType type)
1348 {
1349   struct GNUNET_STATISTICS_GetHandle *ai;
1350   size_t slen;
1351   size_t nlen;
1352   size_t nsize;
1353   int64_t delta;
1354
1355   slen = strlen (h->subsystem) + 1;
1356   nlen = strlen (name) + 1;
1357   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
1358   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1359   {
1360     GNUNET_break (0);
1361     return;
1362   }
1363   for (ai = h->action_head; NULL != ai; ai = ai->next)
1364   {
1365     if (! ( (0 == strcmp (ai->subsystem, h->subsystem)) &&
1366             (0 == strcmp (ai->name, name)) &&
1367             ( (ACTION_UPDATE == ai->type) ||
1368               (ACTION_SET == ai->type) ) ) )
1369       continue;
1370     if (ACTION_SET == ai->type)
1371     {
1372       if (ACTION_UPDATE == type)
1373       {
1374         delta = (int64_t) value;
1375         if (delta > 0)
1376         {
1377           /* update old set by new delta */
1378           ai->value += delta;
1379         }
1380         else
1381         {
1382           /* update old set by new delta, but never go negative */
1383           if (ai->value < -delta)
1384             ai->value = 0;
1385           else
1386             ai->value += delta;
1387         }
1388       }
1389       else
1390       {
1391         /* new set overrides old set */
1392         ai->value = value;
1393       }
1394     }
1395     else
1396     {
1397       if (ACTION_UPDATE == type)
1398       {
1399         /* make delta cummulative */
1400         delta = (int64_t) value;
1401         ai->value += delta;
1402       }
1403       else
1404       {
1405         /* drop old 'update', use new 'set' instead */
1406         ai->value = value;
1407         ai->type = type;
1408       }
1409     }
1410     ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1411     ai->make_persistent = make_persistent;
1412     return;
1413   }
1414   /* no existing entry matches, create a fresh one */
1415   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1416   ai->sh = h;
1417   ai->subsystem = GNUNET_strdup (h->subsystem);
1418   ai->name = GNUNET_strdup (name);
1419   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1420   ai->make_persistent = make_persistent;
1421   ai->msize = nsize;
1422   ai->value = value;
1423   ai->type = type;
1424   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
1425                                     ai);
1426   schedule_action (h);
1427 }
1428
1429
1430 /**
1431  * Set statistic value for the peer.  Will always use our
1432  * subsystem (the argument used when "handle" was created).
1433  *
1434  * @param handle identification of the statistics service
1435  * @param name name of the statistic value
1436  * @param value new value to set
1437  * @param make_persistent should the value be kept across restarts?
1438  */
1439 void
1440 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
1441                        const char *name,
1442                        uint64_t value,
1443                        int make_persistent)
1444 {
1445   if (NULL == handle)
1446     return;
1447   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1448   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
1449 }
1450
1451
1452 /**
1453  * Set statistic value for the peer.  Will always use our
1454  * subsystem (the argument used when "handle" was created).
1455  *
1456  * @param handle identification of the statistics service
1457  * @param name name of the statistic value
1458  * @param delta change in value (added to existing value)
1459  * @param make_persistent should the value be kept across restarts?
1460  */
1461 void
1462 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
1463                           const char *name,
1464                           int64_t delta,
1465                           int make_persistent)
1466 {
1467   if (NULL == handle)
1468     return;
1469   if (0 == delta)
1470     return;
1471   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1472   add_setter_action (handle,
1473                      name,
1474                      make_persistent,
1475                      (uint64_t) delta,
1476                      ACTION_UPDATE);
1477 }
1478
1479
1480 /* end of statistics_api.c */