4323be478f267fffe89fbf574db12f1fdb02f33f
[oweals/gnunet.git] / src / peerinfo / gnunet-service-peerinfo.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/gnunet-service-peerinfo.c
23  * @brief maintains list of known peers
24  *
25  * Code to maintain the list of currently known hosts (in memory
26  * structure of data/hosts/ and data/credit/).
27  *
28  * @author Christian Grothoff
29  *
30  * TODO:
31  * - HostEntries are never 'free'd (add expiration, upper bound?)
32  */
33
34 #include "platform.h"
35 #include "gnunet_crypto_lib.h"
36 #include "gnunet_disk_lib.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_service_lib.h"
40 #include "peerinfo.h"
41
42 /**
43  * How often do we scan the HOST_DIR for new entries?
44  */
45 #define DATA_HOST_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
46
47 /**
48  * How often do we flush trust values to disk?
49  */
50 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
51
52 /**
53  * How often do we discard old entries in data/hosts/?
54  */
55 #define DATA_HOST_CLEAN_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 60)
56
57 /**
58  * In-memory cache of known hosts.
59  */
60 struct HostEntry
61 {
62
63   /**
64    * This is a linked list.
65    */
66   struct HostEntry *next;
67
68   /**
69    * Identity of the peer.
70    */
71   struct GNUNET_PeerIdentity identity;
72
73   /**
74    * Hello for the peer (can be NULL)
75    */
76   struct GNUNET_HELLO_Message *hello;
77
78   /**
79    * Trust rating for this peer
80    */
81   uint32_t trust;
82
83   /**
84    * Trust rating for this peer on disk.
85    */
86   uint32_t disk_trust;
87
88 };
89
90
91 /**
92  * Entries that we still need to tell the client about.
93  */
94 struct PendingEntry
95 {
96
97   /**
98    * This is a linked list.
99    */
100   struct PendingEntry *next;
101
102   /**
103    * Entry to tell the client about.
104    */
105   struct HostEntry *he;
106 };
107
108
109 /**
110  * Clients to notify of changes to the peer information.
111  */
112 struct NotifyList
113 {
114
115   /**
116    * This is a linked list.
117    */
118   struct NotifyList *next;
119
120   /**
121    * Client to notify.
122    */ 
123   struct GNUNET_SERVER_Client *client;
124
125   /**
126    * Notifications pending for this entry.
127    */
128   struct PendingEntry *pending;
129
130   /**
131    * Handle for a transmit ready request.
132    */
133   struct GNUNET_CONNECTION_TransmitHandle *transmit_ctx;
134 };
135
136
137 /**
138  * The in-memory list of known hosts.
139  */
140 static struct HostEntry *hosts;
141
142 /**
143  * Clients to immediately notify about all changes.
144  */
145 static struct NotifyList *notify_list;
146
147 /**
148  * Directory where the hellos are stored in (data/hosts)
149  */
150 static char *networkIdDirectory;
151
152 /**
153  * Where do we store trust information?
154  */
155 static char *trustDirectory;
156
157
158 /**
159  * Transmit peer information messages from the pending queue
160  * to the client.
161  *
162  * @param cls the 'struct NotifyList' that we are processing
163  * @param size number of bytes we can transmit
164  * @param vbuf where to write the messages
165  * @return number of bytes written to vbuf
166  */
167 static size_t
168 transmit_pending_notification (void *cls,
169                                size_t size,
170                                void *vbuf)
171 {
172   struct NotifyList *nl = cls;
173   char *buf = vbuf;
174   struct PendingEntry *pos;
175   struct PendingEntry *next;
176   struct InfoMessage im;
177   uint16_t hs;
178   size_t left;
179
180   nl->transmit_ctx = NULL;
181   next = nl->pending;
182   pos = nl->pending;
183   left = size;
184   while ( (pos != NULL) &&
185           (left >= sizeof (struct InfoMessage) + (hs = GNUNET_HELLO_size (pos->he->hello))) )
186     {
187       next = pos->next;
188       im.header.size = htons (hs + sizeof (struct InfoMessage));
189       im.header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
190       im.trust = htonl (pos->he->trust);
191       im.peer = pos->he->identity;
192       memcpy (&buf[size - left], &im, sizeof (struct InfoMessage));      
193       memcpy (&buf[size - left + sizeof (struct InfoMessage)], pos->he->hello, hs);
194       left -= hs + sizeof (struct InfoMessage);
195       GNUNET_free (pos);
196       pos = next;      
197     }
198   nl->pending = next;
199   if (nl->pending != NULL)
200     {
201       nl->transmit_ctx 
202         = GNUNET_SERVER_notify_transmit_ready (nl->client,
203                                                sizeof (struct InfoMessage) + hs,
204                                                GNUNET_TIME_UNIT_FOREVER_REL,
205                                                &transmit_pending_notification,
206                                                nl);
207     }
208   return size - left;
209 }
210
211
212
213 /**
214  * Notify client about host change.  Checks if the
215  * respective host entry is already in the list of things
216  * to send to the client, and if not, adds it.  Also
217  * triggers a new request for transmission if the pending
218  * list was previously empty.
219  *
220  * @param nl client to notify
221  * @param hc entry to notify about
222  */
223 static void
224 do_notify (struct NotifyList *nl,
225            struct HostEntry *he)
226 {
227   struct PendingEntry *pe;
228
229   pe = nl->pending;
230   while (NULL != pe)
231     {
232       if (pe->he == he)
233         return; /* already in list */
234       pe = pe->next;
235     }
236   pe = GNUNET_malloc (sizeof (struct PendingEntry));
237   pe->next = nl->pending;
238   pe->he = he;
239   nl->pending = pe;
240   if (nl->transmit_ctx != NULL)
241     return; /* already trying to transmit */
242   nl->transmit_ctx = GNUNET_SERVER_notify_transmit_ready (nl->client,
243                                                           sizeof (struct InfoMessage) + GNUNET_HELLO_size (he->hello),
244                                                           GNUNET_TIME_UNIT_FOREVER_REL,
245                                                           &transmit_pending_notification,
246                                                           nl);
247 }
248
249
250 /**
251  * Notify all clients in the notify list about the
252  * given host entry changing.
253  */
254 static void
255 notify_all (struct HostEntry *he)
256 {
257   struct NotifyList *nl;
258
259   nl = notify_list;
260   while (NULL != nl)
261     {
262       do_notify (nl, he);
263       nl = nl->next;
264     }
265 }
266
267
268 /**
269  * Address iterator that causes expired entries to be discarded.
270  *
271  * @param cls pointer to the current time
272  * @param tname name of the transport
273  * @param expiration expiration time for the address
274  * @param addr the address
275  * @param addrlen length of addr in bytes
276  * @return GNUNET_NO if expiration smaller than the current time
277  */
278 static int
279 discard_expired (void *cls,
280                  const char *tname,
281                  struct GNUNET_TIME_Absolute expiration,
282                  const void *addr, size_t addrlen)
283 {
284   const struct GNUNET_TIME_Absolute *now = cls;
285   if (now->value > expiration.value)
286     return GNUNET_NO;
287   return GNUNET_OK;
288 }
289
290
291 /**
292  * Get the filename under which we would store the GNUNET_HELLO_Message
293  * for the given host and protocol.
294  * @return filename of the form DIRECTORY/HOSTID
295  */
296 static char *
297 get_host_filename (const struct GNUNET_PeerIdentity *id)
298 {
299   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
300   char *fn;
301
302   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
303   GNUNET_asprintf (&fn,
304                    "%s%s%s", networkIdDirectory, DIR_SEPARATOR_STR, &fil);
305   return fn;
306 }
307
308
309 /**
310  * Get the filename under which we would store the GNUNET_HELLO_Message
311  * for the given host and protocol.
312  * @return filename of the form DIRECTORY/HOSTID
313  */
314 static char *
315 get_trust_filename (const struct GNUNET_PeerIdentity *id)
316 {
317   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
318   char *fn;
319
320   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
321   GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
322   return fn;
323 }
324
325 /**
326  * Find the host entry for the given peer.  Call
327  * only when synchronized!
328  * @return NULL if not found
329  */
330 static struct HostEntry *
331 lookup_host_entry (const struct GNUNET_PeerIdentity *id)
332 {
333   struct HostEntry *pos;
334
335   pos = hosts;
336   while ((pos != NULL) &&
337          (0 !=
338           memcmp (id, &pos->identity, sizeof (struct GNUNET_PeerIdentity))))
339     pos = pos->next;
340   return pos;
341 }
342
343
344 /**
345  * Add a host to the list.
346  *
347  * @param identity the identity of the host
348  */
349 static void
350 add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity)
351 {
352   struct HostEntry *entry;
353   char *fn;
354   uint32_t trust;
355   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE];
356   const struct GNUNET_HELLO_Message *hello;
357   struct GNUNET_HELLO_Message *hello_clean;
358   int size;
359   struct GNUNET_TIME_Absolute now;
360
361   entry = lookup_host_entry (identity);
362   if (entry != NULL)
363     return;
364   entry = GNUNET_malloc (sizeof (struct HostEntry));
365   entry->identity = *identity;
366   fn = get_trust_filename (identity);
367   if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
368       (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
369     entry->disk_trust = entry->trust = ntohl (trust);
370   GNUNET_free (fn);
371
372   fn = get_host_filename (identity);
373   if (GNUNET_DISK_file_test (fn) == GNUNET_YES)
374     {
375       size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
376       hello = (const struct GNUNET_HELLO_Message *) buffer;
377       if ( (size < sizeof (struct GNUNET_MessageHeader)) ||
378            (size != ntohs((((const struct GNUNET_MessageHeader*) hello)->size))) ||
379            (size != GNUNET_HELLO_size (hello)) )
380         {
381           GNUNET_break (0);
382           if (0 != UNLINK (fn))
383             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
384                                       "unlink",
385                                       fn);
386         }
387       else
388         {
389           now = GNUNET_TIME_absolute_get ();
390           hello_clean = GNUNET_HELLO_iterate_addresses (hello,
391                                                         GNUNET_YES,
392                                                         &discard_expired, &now);
393           entry->hello = hello_clean;
394         }
395     }
396   GNUNET_free (fn);
397   entry->next = hosts;
398   hosts = entry;
399   notify_all (entry);
400 }
401
402
403 /**
404  * Increase the host credit by a value.
405  *
406  * @param hostId is the identity of the host
407  * @param value is the int value by which the
408  *  host credit is to be increased or decreased
409  * @returns the actual change in trust (positive or negative)
410  */
411 static int
412 change_host_trust (const struct GNUNET_PeerIdentity *hostId, int value)
413 {
414   struct HostEntry *host;
415   unsigned int old_trust;
416
417   if (value == 0)
418     return 0;
419   host = lookup_host_entry (hostId);
420   if (host == NULL)
421     {
422       add_host_to_known_hosts (hostId);
423       host = lookup_host_entry (hostId);
424     }
425   GNUNET_assert (host != NULL);
426   old_trust = host->trust;
427   if (value > 0)
428     {
429       if (host->trust + value < host->trust)
430         {
431           value = ((uint32_t) - 1) - host->trust;
432           host->trust = (uint32_t) - 1; /* maximized */
433         }
434       else
435         host->trust += value;
436     }
437   else
438     {
439       if (host->trust < -value)
440         {
441           value = -host->trust;
442           host->trust = 0;
443         }
444       else
445         host->trust += value;
446     }
447   if (host->trust != old_trust)
448     notify_all (host);
449   return value;
450 }
451
452
453 /**
454  * Remove a file that should not be there.  LOG
455  * success or failure.
456  */
457 static void
458 remove_garbage (const char *fullname)
459 {
460   if (0 == UNLINK (fullname))
461     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
462                 _
463                 ("File `%s' in directory `%s' does not match naming convention. "
464                  "Removed.\n"), fullname, networkIdDirectory);
465   else
466     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR |
467                               GNUNET_ERROR_TYPE_BULK, "unlink", fullname);
468 }
469
470
471 static int
472 hosts_directory_scan_callback (void *cls, const char *fullname)
473 {
474   unsigned int *matched = cls;
475   struct GNUNET_PeerIdentity identity;
476   const char *filename;
477
478   if (GNUNET_DISK_file_test (fullname) != GNUNET_YES)
479     return GNUNET_OK;           /* ignore non-files */
480   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
481     {
482       remove_garbage (fullname);
483       return GNUNET_OK;
484     }
485   filename =
486     &fullname[strlen (fullname) -
487               sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1];
488   if (filename[-1] != DIR_SEPARATOR)
489     {
490       remove_garbage (fullname);
491       return GNUNET_OK;
492     }
493   if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (filename,
494                                                    &identity.hashPubKey))
495     {
496       remove_garbage (fullname);
497       return GNUNET_OK;
498     }
499   (*matched)++;
500   add_host_to_known_hosts (&identity);
501   return GNUNET_OK;
502 }
503
504
505 /**
506  * Call this method periodically to scan data/hosts for new hosts.
507  */
508 static void
509 cron_scan_directory_data_hosts (void *cls,
510                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
511 {
512   static unsigned int retries;
513   unsigned int count;
514
515   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
516     return;
517   count = 0;
518   GNUNET_DISK_directory_create (networkIdDirectory);
519   GNUNET_DISK_directory_scan (networkIdDirectory,
520                               &hosts_directory_scan_callback, &count);
521   if ((0 == count) && (0 == (++retries & 31)))
522     GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
523                 GNUNET_ERROR_TYPE_BULK,
524                 _("Still no peers found in `%s'!\n"), networkIdDirectory);
525   GNUNET_SCHEDULER_add_delayed (tc->sched,
526                                 DATA_HOST_FREQ,
527                                 &cron_scan_directory_data_hosts, NULL);
528 }
529
530
531 /**
532  * Bind a host address (hello) to a hostId.
533  *
534  * @param peer the peer for which this is a hello
535  * @param hello the verified (!) hello message
536  */
537 static void
538 bind_address (const struct GNUNET_PeerIdentity *peer,
539               const struct GNUNET_HELLO_Message *hello)
540 {
541   char *fn;
542   struct HostEntry *host;
543   struct GNUNET_HELLO_Message *mrg;
544
545   add_host_to_known_hosts (peer);
546   host = lookup_host_entry (peer);
547   GNUNET_assert (host != NULL);
548   if (host->hello == NULL)
549     {
550       host->hello = GNUNET_malloc (GNUNET_HELLO_size (hello));
551       memcpy (host->hello, hello, GNUNET_HELLO_size (hello));
552     }
553   else
554     {
555       mrg = GNUNET_HELLO_merge (host->hello, hello);
556       /* FIXME: check if old and merged hello are equal,
557          and if so, bail out early... */
558       GNUNET_free (host->hello);
559       host->hello = mrg;
560     }
561   fn = get_host_filename (peer);
562   GNUNET_DISK_fn_write (fn, 
563                         host->hello, 
564                         GNUNET_HELLO_size (host->hello),
565                         GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
566                         | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ);
567   GNUNET_free (fn);
568   notify_all (host);
569 }
570
571
572 /**
573  * Do transmit info either for only the host matching the given
574  * argument or for all known hosts and change their trust values by
575  * the given delta.
576  *
577  * @param only NULL to hit all hosts, otherwise specifies a particular target
578  * @param trust_change how much should the trust be changed
579  * @param client who is making the request (and will thus receive our confirmation)
580  */
581 static void
582 send_to_each_host (const struct GNUNET_PeerIdentity *only,
583                    int trust_change, struct GNUNET_SERVER_Client *client)
584 {
585   struct HostEntry *pos;
586   struct InfoMessage *im;
587   const struct GNUNET_MessageHeader *end;
588   uint16_t hs;
589   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
590   struct GNUNET_SERVER_TransmitContext *tc;
591
592   tc = GNUNET_SERVER_transmit_context_create (client);
593   pos = hosts;
594   while (pos != NULL)
595     {
596       if ((only == NULL) ||
597           (0 ==
598            memcmp (only, &pos->identity,
599                    sizeof (struct GNUNET_PeerIdentity))))
600         {
601           change_host_trust (&pos->identity, trust_change);
602           hs = 0;
603           im = (struct InfoMessage *) buf;
604           if (pos->hello != NULL)
605             {
606               hs = GNUNET_HELLO_size (pos->hello);
607               GNUNET_assert (hs <
608                              GNUNET_SERVER_MAX_MESSAGE_SIZE -
609                              sizeof (struct InfoMessage));
610               memcpy (&im[1], pos->hello, hs);
611             }
612           im->trust = htonl (pos->trust);
613           im->peer = pos->identity;
614           end = &im->header;
615           GNUNET_SERVER_transmit_context_append (tc,
616                                                  &end[1],
617                                                  hs +
618                                                  sizeof (struct InfoMessage) -
619                                                  sizeof (struct
620                                                          GNUNET_MessageHeader),
621                                                  GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
622         }
623       pos = pos->next;
624     }
625   GNUNET_SERVER_transmit_context_append (tc, NULL, 0,
626                                          GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
627   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
628 }
629
630
631 /**
632  * Write host-trust information to a file - flush the buffer entry!
633  * Assumes synchronized access.
634  */
635 static void
636 flush_trust (struct HostEntry *host)
637 {
638   char *fn;
639   uint32_t trust;
640
641   if (host->trust == host->disk_trust)
642     return;                     /* unchanged */
643   fn = get_trust_filename (&host->identity);
644   if (host->trust == 0)
645     {
646       if ((0 != UNLINK (fn)) && (errno != ENOENT))
647         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
648                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
649     }
650   else
651     {
652       trust = htonl (host->trust);
653       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
654                                                     sizeof(uint32_t),
655                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
656                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
657         host->disk_trust = host->trust;
658     }
659   GNUNET_free (fn);
660 }
661
662 /**
663  * Call this method periodically to scan data/hosts for new hosts.
664  */
665 static void
666 cron_flush_trust (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
667 {
668   struct HostEntry *pos;
669
670   pos = hosts;
671   while (pos != NULL)
672     {
673       flush_trust (pos);
674       pos = pos->next;
675     }
676   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
677     return;
678   GNUNET_SCHEDULER_add_delayed (tc->sched,
679                                 TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
680 }
681
682
683 /**
684  * @brief delete expired HELLO entries in data/hosts/
685  */
686 static int
687 discard_hosts_helper (void *cls, const char *fn)
688 {
689   struct GNUNET_TIME_Absolute *now = cls;
690   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE];
691   const struct GNUNET_HELLO_Message *hello;
692   struct GNUNET_HELLO_Message *new_hello;
693   int size;
694
695   size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
696   if ((size < sizeof (struct GNUNET_MessageHeader)) && (0 != UNLINK (fn)))
697     {
698       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
699                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
700       return GNUNET_OK;
701     }
702   hello = (const struct GNUNET_HELLO_Message *) buffer;
703   new_hello = GNUNET_HELLO_iterate_addresses (hello,
704                                               GNUNET_YES,
705                                               &discard_expired, now);
706   if ((new_hello == NULL) && (0 != UNLINK (fn)))
707     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
708                               GNUNET_ERROR_TYPE_BULK, "unlink", fn);
709   if (new_hello != NULL)
710     {
711       GNUNET_DISK_fn_write (fn, 
712                             new_hello,
713                             GNUNET_HELLO_size (new_hello),
714                             GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
715                             | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ);
716       GNUNET_free (new_hello);
717     }
718   return GNUNET_OK;
719 }
720
721
722 /**
723  * Call this method periodically to scan data/hosts for new hosts.
724  */
725 static void
726 cron_clean_data_hosts (void *cls,
727                        const struct GNUNET_SCHEDULER_TaskContext *tc)
728 {
729   struct GNUNET_TIME_Absolute now;
730
731   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
732     return;
733   now = GNUNET_TIME_absolute_get ();
734   GNUNET_DISK_directory_scan (networkIdDirectory,
735                               &discard_hosts_helper, &now);
736
737   GNUNET_SCHEDULER_add_delayed (tc->sched,
738                                 DATA_HOST_CLEAN_FREQ,
739                                 &cron_clean_data_hosts, NULL);
740 }
741
742
743 /**
744  * Handle ADD-message.
745  *
746  * @param cls closure
747  * @param client identification of the client
748  * @param message the actual message
749  */
750 static void
751 handle_add (void *cls,
752             struct GNUNET_SERVER_Client *client,
753             const struct GNUNET_MessageHeader *message)
754 {
755   const struct PeerAddMessage *pam;
756   const struct GNUNET_MessageHeader *hello;
757   uint16_t size;
758
759   size = ntohs (message->size);
760   if (size <
761       sizeof (struct PeerAddMessage) + sizeof (struct GNUNET_MessageHeader))
762     {
763       GNUNET_break (0);
764       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
765       return;
766     }
767   pam = (const struct PeerAddMessage *) message;
768   hello = (const struct GNUNET_MessageHeader *) &pam[1];
769   if (size != sizeof (struct PeerAddMessage) + ntohs (hello->size))
770     {
771       GNUNET_break (0);
772       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
773       return;
774     }
775   bind_address (&pam->peer, (const struct GNUNET_HELLO_Message *) hello);
776   GNUNET_SERVER_receive_done (client, GNUNET_OK);
777 }
778
779
780 /**
781  * Handle GET-message.
782  *
783  * @param cls closure
784  * @param client identification of the client
785  * @param message the actual message
786  */
787 static void
788 handle_get (void *cls,
789             struct GNUNET_SERVER_Client *client,
790             const struct GNUNET_MessageHeader *message)
791 {
792   const struct ListPeerMessage *lpm;
793
794   lpm = (const struct ListPeerMessage *) message;
795   send_to_each_host (&lpm->peer, ntohl (lpm->trust_change), client);
796 }
797
798
799 /**
800  * Handle GET-ALL-message.
801  *
802  * @param cls closure
803  * @param client identification of the client
804  * @param message the actual message
805  */
806 static void
807 handle_get_all (void *cls,
808                 struct GNUNET_SERVER_Client *client,
809                 const struct GNUNET_MessageHeader *message)
810 {
811   const struct ListAllPeersMessage *lpm;
812
813   lpm = (const struct ListAllPeersMessage *) message;
814   send_to_each_host (NULL, ntohl (lpm->trust_change), client);
815 }
816
817
818 /**
819  * Handle NOTIFY-message.
820  *
821  * @param cls closure
822  * @param client identification of the client
823  * @param message the actual message
824  */
825 static void
826 handle_notify (void *cls,
827             struct GNUNET_SERVER_Client *client,
828             const struct GNUNET_MessageHeader *message)
829 {
830   struct NotifyList *nl;
831   struct HostEntry *pos;
832
833   nl = GNUNET_malloc (sizeof (struct NotifyList));
834   nl->next = notify_list;
835   nl->client = client;
836   GNUNET_SERVER_client_keep (client);  
837   notify_list = nl;
838   pos = hosts;
839   while (NULL != pos)
840     {
841       do_notify (nl, pos);
842       pos = pos->next;
843     }
844 }
845
846
847 /**
848  * List of handlers for the messages understood by this
849  * service.
850  */
851 static struct GNUNET_SERVER_MessageHandler handlers[] = {
852   {&handle_add, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_ADD, 0},
853   {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
854    sizeof (struct ListPeerMessage)},
855   {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
856    sizeof (struct ListAllPeersMessage)},
857   {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
858    sizeof (struct GNUNET_MessageHeader)},
859   {NULL, NULL, 0, 0}
860 };
861
862
863 /**
864  * Function that is called when a client disconnects.
865  */
866 static void
867 notify_disconnect (void *cls,
868                    struct GNUNET_SERVER_Client *client)
869 {
870   struct NotifyList *pos;
871   struct NotifyList *prev;
872   struct NotifyList *next;
873   struct PendingEntry *p;
874
875   pos = notify_list;
876   prev = NULL;
877   while (pos != NULL)
878     {
879       next = pos->next;
880       if (pos->client == client)
881         {
882           while (NULL != (p = pos->pending))
883             {
884               pos->pending = p->next;
885               GNUNET_free (p);
886             }
887           if (pos->transmit_ctx != NULL)
888             {
889               GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->transmit_ctx);
890               pos->transmit_ctx = NULL;
891             }
892           if (prev == NULL)
893             notify_list = next;
894           else
895             prev->next = next;
896           GNUNET_SERVER_client_drop (client);
897           GNUNET_free (pos);
898         }
899       else
900         {
901           prev = pos;
902         }
903       pos = next;
904     }
905
906 }
907
908
909 /**
910  * Process statistics requests.
911  *
912  * @param cls closure
913  * @param sched scheduler to use
914  * @param server the initialized server
915  * @param cfg configuration to use
916  */
917 static void
918 run (void *cls,
919      struct GNUNET_SCHEDULER_Handle *sched,
920      struct GNUNET_SERVER_Handle *server,
921      const struct GNUNET_CONFIGURATION_Handle *cfg)
922 {
923   GNUNET_assert (GNUNET_OK ==
924                  GNUNET_CONFIGURATION_get_value_filename (cfg,
925                                                           "peerinfo",
926                                                           "HOSTS",
927                                                           &networkIdDirectory));
928   GNUNET_assert (GNUNET_OK ==
929                  GNUNET_CONFIGURATION_get_value_filename (cfg,
930                                                           "peerinfo",
931                                                           "TRUST",
932                                                           &trustDirectory));
933   GNUNET_DISK_directory_create (networkIdDirectory);
934   GNUNET_DISK_directory_create (trustDirectory);
935   GNUNET_SCHEDULER_add_with_priority (sched,
936                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
937                                       &cron_scan_directory_data_hosts, NULL);
938   GNUNET_SCHEDULER_add_with_priority (sched,
939                                       GNUNET_SCHEDULER_PRIORITY_HIGH,
940                                       &cron_flush_trust, NULL);
941   GNUNET_SCHEDULER_add_with_priority (sched,
942                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
943                                       &cron_clean_data_hosts, NULL);
944   GNUNET_SERVER_disconnect_notify (server, &notify_disconnect, NULL);
945   GNUNET_SERVER_add_handlers (server, handlers);
946 }
947
948
949 /**
950  * The main function for the statistics service.
951  *
952  * @param argc number of arguments from the command line
953  * @param argv command line arguments
954  * @return 0 ok, 1 on error
955  */
956 int
957 main (int argc, char *const *argv)
958 {
959   int ret;
960
961   ret = (GNUNET_OK ==
962          GNUNET_SERVICE_run (argc,
963                              argv,
964                               "peerinfo",
965                              GNUNET_SERVICE_OPTION_NONE,
966                              &run, NULL)) ? 0 : 1;
967   GNUNET_free_non_null (networkIdDirectory);
968   GNUNET_free_non_null (trustDirectory);
969   return ret;
970 }
971
972
973 /* end of gnunet-service-peerinfo.c */