-do not store/keep HELLOs with expired addresses on disk (#1932)
[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, 2010, 2012 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/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/).
27  *
28  * @author Christian Grothoff
29  *
30  * TODO:
31  * - notify clients when addresses in HELLO expire (#1933)
32  */
33
34 #include "platform.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_hello_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_statistics_service.h"
39 #include "peerinfo.h"
40
41 /**
42  * How often do we scan the HOST_DIR for new entries?
43  */
44 #define DATA_HOST_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
45
46 /**
47  * How often do we discard old entries in data/hosts/?
48  */
49 #define DATA_HOST_CLEAN_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 60)
50
51
52 /**
53  * In-memory cache of known hosts.
54  */
55 struct HostEntry
56 {
57
58   /**
59    * Identity of the peer.
60    */
61   struct GNUNET_PeerIdentity identity;
62
63   /**
64    * Hello for the peer (can be NULL)
65    */
66   struct GNUNET_HELLO_Message *hello;
67
68 };
69
70
71 /**
72  * The in-memory list of known hosts, mapping of
73  * host IDs to 'struct HostEntry*' values.
74  */
75 static struct GNUNET_CONTAINER_MultiHashMap *hostmap;
76
77 /**
78  * Clients to immediately notify about all changes.
79  */
80 static struct GNUNET_SERVER_NotificationContext *notify_list;
81
82 /**
83  * Directory where the hellos are stored in (data/hosts)
84  */
85 static char *networkIdDirectory;
86
87 /**
88  * Handle for reporting statistics.
89  */
90 static struct GNUNET_STATISTICS_Handle *stats;
91
92
93 /**
94  * Notify all clients in the notify list about the
95  * given host entry changing.
96  *
97  * @param he entry of the host for which we generate a notification
98  * @return generated notification message
99  */
100 static struct InfoMessage *
101 make_info_message (const struct HostEntry *he)
102 {
103   struct InfoMessage *im;
104   size_t hs;
105
106   hs = (NULL == he->hello) ? 0 : GNUNET_HELLO_size (he->hello);
107   im = GNUNET_malloc (sizeof (struct InfoMessage) + hs);
108   im->header.size = htons (hs + sizeof (struct InfoMessage));
109   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
110   im->peer = he->identity;
111   if (he->hello != NULL)
112     memcpy (&im[1], he->hello, hs);
113   return im;
114 }
115
116
117 /**
118  * Address iterator that causes expired entries to be discarded.
119  *
120  * @param cls pointer to the current time
121  * @param address the address
122  * @param expiration expiration time for the address
123  * @return GNUNET_NO if expiration smaller than the current time
124  */
125 static int
126 discard_expired (void *cls, const struct GNUNET_HELLO_Address *address,
127                  struct GNUNET_TIME_Absolute expiration)
128 {
129   const struct GNUNET_TIME_Absolute *now = cls;
130
131   if (now->abs_value > expiration.abs_value)
132   {
133     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
134                 _("Removing expired address of transport `%s'\n"),
135                 address->transport_name);
136     return GNUNET_NO;
137   }
138   return GNUNET_OK;
139 }
140
141
142 /**
143  * Address iterator that counts the remaining addresses.
144  *
145  * @param cls pointer to the counter
146  * @param address the address
147  * @param expiration expiration time for the address
148  * @return GNUNET_OK (always)
149  */
150 static int
151 count_addresses (void *cls, const struct GNUNET_HELLO_Address *address,
152                  struct GNUNET_TIME_Absolute expiration)
153 {
154   unsigned int *cnt = cls;
155
156   (*cnt)++;
157   return GNUNET_OK;
158 }
159
160
161 /**
162  * Get the filename under which we would store the GNUNET_HELLO_Message
163  * for the given host and protocol.
164  *
165  * @param id peer for which we need the filename for the HELLO
166  * @return filename of the form DIRECTORY/HOSTID
167  */
168 static char *
169 get_host_filename (const struct GNUNET_PeerIdentity *id)
170 {
171   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
172   char *fn;
173
174   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
175   GNUNET_asprintf (&fn, "%s%s%s", networkIdDirectory, DIR_SEPARATOR_STR, &fil);
176   return fn;
177 }
178
179
180 /**
181  * Broadcast information about the given entry to all
182  * clients that care.
183  *
184  * @param entry entry to broadcast about
185  */
186 static void
187 notify_all (struct HostEntry *entry)
188 {
189   struct InfoMessage *msg;
190
191   msg = make_info_message (entry);
192   GNUNET_SERVER_notification_context_broadcast (notify_list, &msg->header,
193                                                 GNUNET_NO);
194   GNUNET_free (msg);
195 }
196
197
198 /**
199  * Try to read the HELLO in the given filename and discard expired
200  * addresses.  Removes the file if the HELLO is mal-formed.  If all
201  * addresses are expired, the HELLO is also removed (but the HELLO
202  * with the public key is still returned if it was found and valid).
203  * 
204  * @param fn name of the file
205  * @param unlink_garbage if GNUNET_YES, try to remove useless files
206  * @return HELLO of the file, NULL on error
207  */
208 static struct GNUNET_HELLO_Message *
209 read_host_file (const char *fn,
210                 int unlink_garbage)
211 {
212   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
213   const struct GNUNET_HELLO_Message *hello;
214   struct GNUNET_HELLO_Message *hello_clean;
215   int size;
216   struct GNUNET_TIME_Absolute now;
217   unsigned int left;
218
219   if (GNUNET_YES != GNUNET_DISK_file_test (fn))
220     return NULL;
221   size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
222   hello = (const struct GNUNET_HELLO_Message *) buffer;
223   if ((size < sizeof (struct GNUNET_MessageHeader)) ||
224       (size != ntohs ((((const struct GNUNET_MessageHeader *) hello)->size)))
225       || (size != GNUNET_HELLO_size (hello)))
226   {
227     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
228                 _("Failed to parse HELLO in file `%s'\n"),
229                 fn);
230     if ( (GNUNET_YES == unlink_garbage) &&
231          (0 != UNLINK (fn)) )
232       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
233     return NULL;
234   }
235   now = GNUNET_TIME_absolute_get ();
236   hello_clean =
237     GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired,
238                                     &now);
239   left = 0;
240   (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses,
241                                          &left);
242   if (0 == left)
243   {
244     /* no addresses left, remove from disk */
245     if ( (GNUNET_YES == unlink_garbage) &&
246          (0 != UNLINK (fn)) )
247       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
248   }
249   return hello_clean; 
250 }
251
252
253 /**
254  * Add a host to the list.
255  *
256  * @param identity the identity of the host
257  */
258 static void
259 add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity)
260 {
261   struct HostEntry *entry;
262   char *fn;
263
264   entry = GNUNET_CONTAINER_multihashmap_get (hostmap, &identity->hashPubKey);
265   if (NULL != entry)
266     return;
267   GNUNET_STATISTICS_update (stats, gettext_noop ("# peers known"), 1,
268                             GNUNET_NO);
269   entry = GNUNET_malloc (sizeof (struct HostEntry));
270   entry->identity = *identity;
271   GNUNET_CONTAINER_multihashmap_put (hostmap, &identity->hashPubKey, entry,
272                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
273   fn = get_host_filename (identity);
274   entry->hello = read_host_file (fn, GNUNET_YES);
275   GNUNET_free (fn);
276   notify_all (entry);
277 }
278
279
280 /**
281  * Remove a file that should not be there.  LOG
282  * success or failure.
283  *
284  * @param fullname name of the file to remove
285  */
286 static void
287 remove_garbage (const char *fullname)
288 {
289   if (0 == UNLINK (fullname))
290     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
291                 _
292                 ("File `%s' in directory `%s' does not match naming convention. "
293                  "Removed.\n"), fullname, networkIdDirectory);
294   else
295     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
296                               "unlink", fullname);
297 }
298
299
300 /**
301  * Closure for 'hosts_directory_scan_callback'.
302  */
303 struct DirScanContext
304 {
305   /**
306    * GNUNET_YES if we should remove files that are broken,
307    * GNUNET_NO if the directory we are iterating over should
308    * be treated as read-only by us.
309    */ 
310   int remove_files;
311
312   /**
313    * Counter for the number of (valid) entries found, incremented
314    * by one for each match.
315    */
316   unsigned int matched;
317 };
318
319
320 /**
321  * Function that is called on each HELLO file in a particular directory.
322  * Try to parse the file and add the HELLO to our list.
323  *
324  * @param cls pointer to 'unsigned int' to increment for each file, or NULL
325  *            if the file is from a read-only, read-once resource directory
326  * @param fullname name of the file to parse
327  * @return GNUNET_OK (continue iteration)
328  */
329 static int
330 hosts_directory_scan_callback (void *cls, const char *fullname)
331 {
332   struct DirScanContext *dsc = cls;
333   struct GNUNET_PeerIdentity identity;
334   const char *filename;
335   struct HostEntry *entry;
336   struct GNUNET_HELLO_Message *hello;
337   struct GNUNET_PeerIdentity id;
338
339   if (GNUNET_YES != GNUNET_DISK_file_test (fullname))
340     return GNUNET_OK;           /* ignore non-files */
341   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
342   {
343     if (GNUNET_YES == dsc->remove_files)
344       remove_garbage (fullname);
345     return GNUNET_OK;
346   }
347   filename =
348       &fullname[strlen (fullname) -
349                 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1];
350   if (DIR_SEPARATOR != filename[-1])
351   {
352     if (GNUNET_YES == dsc->remove_files)
353       remove_garbage (fullname);
354     return GNUNET_OK;
355   }
356   if (GNUNET_OK !=
357       GNUNET_CRYPTO_hash_from_string (filename, &identity.hashPubKey))
358   {
359     /* odd filename, but might still be valid, try getting identity from HELLO */
360     if ( (NULL != (hello = read_host_file (filename, 
361                                            dsc->remove_files))) &&
362          (GNUNET_OK ==
363           GNUNET_HELLO_get_id (hello,
364                                &id)) )
365     {
366       /* ok, found something valid, remember HELLO */
367       entry = GNUNET_malloc (sizeof (struct HostEntry));
368       entry->identity = id;
369       GNUNET_CONTAINER_multihashmap_put (hostmap, &entry->identity.hashPubKey, entry,
370                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
371       entry->hello = hello;
372       notify_all (entry);
373       dsc->matched++;
374       return GNUNET_OK;   
375     }
376     if (GNUNET_YES == dsc->remove_files)
377       remove_garbage (fullname);
378     return GNUNET_OK;
379   }
380   dsc->matched++;
381   add_host_to_known_hosts (&identity);
382   return GNUNET_OK;
383 }
384
385
386 /**
387  * Call this method periodically to scan data/hosts for new hosts.
388  *
389  * @param cls unused
390  * @param tc scheduler context, aborted if reason is shutdown
391  */
392 static void
393 cron_scan_directory_data_hosts (void *cls,
394                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
395 {
396   static unsigned int retries;
397   struct DirScanContext dsc;
398
399   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
400     return;
401   if (GNUNET_SYSERR == GNUNET_DISK_directory_create (networkIdDirectory))
402   {
403     GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
404                                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
405                                                 &cron_scan_directory_data_hosts, NULL);
406     return;
407   }
408   dsc.matched = 0;
409   dsc.remove_files = GNUNET_YES;
410   GNUNET_DISK_directory_scan (networkIdDirectory,
411                               &hosts_directory_scan_callback, &dsc);
412   if ((0 == dsc.matched) && (0 == (++retries & 31)))
413     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
414                 _("Still no peers found in `%s'!\n"), networkIdDirectory);
415   GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ, 
416                                               GNUNET_SCHEDULER_PRIORITY_IDLE,
417                                               &cron_scan_directory_data_hosts,
418                                               NULL);
419 }
420
421
422 /**
423  * Bind a host address (hello) to a hostId.
424  *
425  * @param peer the peer for which this is a hello
426  * @param hello the verified (!) hello message
427  */
428 static void
429 bind_address (const struct GNUNET_PeerIdentity *peer,
430               const struct GNUNET_HELLO_Message *hello)
431 {
432   char *fn;
433   struct HostEntry *host;
434   struct GNUNET_HELLO_Message *mrg;
435   struct GNUNET_TIME_Absolute delta;
436   unsigned int cnt;
437
438   add_host_to_known_hosts (peer);
439   host = GNUNET_CONTAINER_multihashmap_get (hostmap, &peer->hashPubKey);
440   GNUNET_assert (NULL != host);
441   if (NULL == host->hello)
442   {
443     host->hello = GNUNET_malloc (GNUNET_HELLO_size (hello));
444     memcpy (host->hello, hello, GNUNET_HELLO_size (hello));
445   }
446   else
447   {
448     mrg = GNUNET_HELLO_merge (host->hello, hello);
449     delta = GNUNET_HELLO_equals (mrg, host->hello, GNUNET_TIME_absolute_get ());
450     if (delta.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
451     {
452       GNUNET_free (mrg);
453       return;
454     }
455     GNUNET_free (host->hello);
456     host->hello = mrg;
457   }
458   fn = get_host_filename (peer);
459   if (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn))
460   {
461     cnt = 0;
462     (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses,
463                                            &cnt);
464     if (0 == cnt)
465     {      
466       /* no valid addresses, don't put HELLO on disk */
467       (void) UNLINK (fn); 
468     }
469     else
470     {
471       if (GNUNET_SYSERR ==
472           GNUNET_DISK_fn_write (fn, host->hello, GNUNET_HELLO_size (host->hello),
473                                 GNUNET_DISK_PERM_USER_READ |
474                                 GNUNET_DISK_PERM_USER_WRITE |
475                                 GNUNET_DISK_PERM_GROUP_READ |
476                                 GNUNET_DISK_PERM_OTHER_READ))
477         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
478     }
479   }
480   GNUNET_free (fn);
481   notify_all (host);
482 }
483
484
485 /**
486  * Do transmit info about peer to given host.
487  *
488  * @param cls NULL to hit all hosts, otherwise specifies a particular target
489  * @param key hostID
490  * @param value information to transmit
491  * @return GNUNET_YES (continue to iterate)
492  */
493 static int
494 add_to_tc (void *cls, const struct GNUNET_HashCode * key, void *value)
495 {
496   struct GNUNET_SERVER_TransmitContext *tc = cls;
497   struct HostEntry *pos = value;
498   struct InfoMessage *im;
499   uint16_t hs;
500   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
501
502   hs = 0;
503   im = (struct InfoMessage *) buf;
504   if (pos->hello != NULL)
505   {
506     hs = GNUNET_HELLO_size (pos->hello);
507     GNUNET_assert (hs <
508                    GNUNET_SERVER_MAX_MESSAGE_SIZE -
509                    sizeof (struct InfoMessage));
510     memcpy (&im[1], pos->hello, hs);
511   }
512   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
513   im->header.size = htons (sizeof (struct InfoMessage) + hs);
514   im->reserved = htonl (0);
515   im->peer = pos->identity;
516   GNUNET_SERVER_transmit_context_append_message (tc, &im->header);
517   return GNUNET_YES;
518 }
519
520
521 /**
522  * @brief delete expired HELLO entries in data/hosts/
523  *
524  * @param cls pointer to current time (struct GNUNET_TIME_Absolute)
525  * @param fn filename to test to see if the HELLO expired
526  * @return GNUNET_OK (continue iteration)
527  */
528 static int
529 discard_hosts_helper (void *cls, const char *fn)
530 {
531   struct GNUNET_TIME_Absolute *now = cls;
532   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
533   const struct GNUNET_HELLO_Message *hello;
534   struct GNUNET_HELLO_Message *new_hello;
535   int size;
536   unsigned int cnt;
537
538   size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
539   if (size < sizeof (struct GNUNET_MessageHeader))
540   {
541     if (0 != UNLINK (fn))
542       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
543                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
544     return GNUNET_OK;
545   }
546   hello = (const struct GNUNET_HELLO_Message *) buffer;
547   new_hello =
548     GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now);
549   cnt = 0;
550   if (NULL != new_hello)
551     (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses, &cnt);
552   if ( (NULL != new_hello) && (0 < cnt) )
553   {
554     GNUNET_DISK_fn_write (fn, new_hello, GNUNET_HELLO_size (new_hello),
555                           GNUNET_DISK_PERM_USER_READ |
556                           GNUNET_DISK_PERM_USER_WRITE |
557                           GNUNET_DISK_PERM_GROUP_READ |
558                           GNUNET_DISK_PERM_OTHER_READ);
559   }
560   else
561   {
562     if (0 != UNLINK (fn))
563       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
564                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
565   }
566   GNUNET_free_non_null (new_hello);
567   return GNUNET_OK;
568 }
569
570
571 /**
572  * Call this method periodically to scan data/hosts for ancient
573  * HELLOs to expire.
574  *
575  * @param cls unused
576  * @param tc scheduler context, aborted if reason is shutdown
577  */
578 static void
579 cron_clean_data_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
580 {
581   struct GNUNET_TIME_Absolute now;
582
583   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
584     return;
585   now = GNUNET_TIME_absolute_get ();
586   GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now);
587   GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, &cron_clean_data_hosts,
588                                 NULL);
589 }
590
591
592 /**
593  * Handle HELLO-message.
594  *
595  * @param cls closure
596  * @param client identification of the client
597  * @param message the actual message
598  */
599 static void
600 handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
601               const struct GNUNET_MessageHeader *message)
602 {
603   const struct GNUNET_HELLO_Message *hello;
604   struct GNUNET_PeerIdentity pid;
605
606   hello = (const struct GNUNET_HELLO_Message *) message;
607   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
608   {
609     GNUNET_break (0);
610     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
611     return;
612   }
613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
614               "HELLO", GNUNET_i2s (&pid));
615   bind_address (&pid, hello);
616   GNUNET_SERVER_receive_done (client, GNUNET_OK);
617 }
618
619
620 /**
621  * Handle GET-message.
622  *
623  * @param cls closure
624  * @param client identification of the client
625  * @param message the actual message
626  */
627 static void
628 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
629             const struct GNUNET_MessageHeader *message)
630 {
631   const struct ListPeerMessage *lpm;
632   struct GNUNET_SERVER_TransmitContext *tc;
633
634   lpm = (const struct ListPeerMessage *) message;
635   GNUNET_break (0 == ntohl (lpm->reserved));
636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
637               "GET", GNUNET_i2s (&lpm->peer));
638   tc = GNUNET_SERVER_transmit_context_create (client);
639   GNUNET_CONTAINER_multihashmap_get_multiple (hostmap, &lpm->peer.hashPubKey,
640                                               &add_to_tc, tc);
641   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
642                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
643   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
644 }
645
646
647 /**
648  * Handle GET-ALL-message.
649  *
650  * @param cls closure
651  * @param client identification of the client
652  * @param message the actual message
653  */
654 static void
655 handle_get_all (void *cls, struct GNUNET_SERVER_Client *client,
656                 const struct GNUNET_MessageHeader *message)
657 {
658   struct GNUNET_SERVER_TransmitContext *tc;
659
660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "GET_ALL");
661   tc = GNUNET_SERVER_transmit_context_create (client);
662   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &add_to_tc, tc);
663   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
664                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
665   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
666 }
667
668
669 /**
670  * Pass the given client the information we have in the respective
671  * host entry; the client is already in the notification context.
672  *
673  * @param cls the 'struct GNUNET_SERVER_Client' to notify
674  * @param key key for the value (unused)
675  * @param value the 'struct HostEntry' to notify the client about
676  * @return GNUNET_YES (always, continue to iterate)
677  */
678 static int
679 do_notify_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
680 {
681   struct GNUNET_SERVER_Client *client = cls;
682   struct HostEntry *he = value;
683   struct InfoMessage *msg;
684
685   msg = make_info_message (he);
686   GNUNET_SERVER_notification_context_unicast (notify_list, client, &msg->header,
687                                               GNUNET_NO);
688   GNUNET_free (msg);
689   return GNUNET_YES;
690 }
691
692
693 /**
694  * Handle NOTIFY-message.
695  *
696  * @param cls closure
697  * @param client identification of the client
698  * @param message the actual message
699  */
700 static void
701 handle_notify (void *cls, struct GNUNET_SERVER_Client *client,
702                const struct GNUNET_MessageHeader *message)
703 {
704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "NOTIFY");
705   GNUNET_SERVER_client_mark_monitor (client);
706   GNUNET_SERVER_notification_context_add (notify_list, client);
707   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &do_notify_entry, client);
708   GNUNET_SERVER_receive_done (client, GNUNET_OK);
709 }
710
711
712 /**
713  * Release memory taken by a host entry.
714  *
715  * @param cls NULL
716  * @param key key of the host entry
717  * @param value the 'struct HostEntry' to free
718  * @return GNUNET_YES (continue to iterate)
719  */
720 static int
721 free_host_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
722 {
723   struct HostEntry *he = value;
724
725   GNUNET_free_non_null (he->hello);
726   GNUNET_free (he);
727   return GNUNET_YES;
728 }
729
730
731 /**
732  * Clean up our state.  Called during shutdown.
733  *
734  * @param cls unused
735  * @param tc scheduler task context, unused
736  */
737 static void
738 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
739 {
740   GNUNET_SERVER_notification_context_destroy (notify_list);
741   notify_list = NULL;
742   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &free_host_entry, NULL);
743   GNUNET_CONTAINER_multihashmap_destroy (hostmap);
744   if (NULL != stats)
745   {
746     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
747     stats = NULL;
748   }
749 }
750
751
752 /**
753  * Start up peerinfo service.
754  *
755  * @param cls closure
756  * @param server the initialized server
757  * @param cfg configuration to use
758  */
759 static void
760 run (void *cls, struct GNUNET_SERVER_Handle *server,
761      const struct GNUNET_CONFIGURATION_Handle *cfg)
762 {
763   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
764     {&handle_hello, NULL, GNUNET_MESSAGE_TYPE_HELLO, 0},
765     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
766      sizeof (struct ListPeerMessage)},
767     {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
768      sizeof (struct GNUNET_MessageHeader)},
769     {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
770      sizeof (struct GNUNET_MessageHeader)},
771     {NULL, NULL, 0, 0}
772   };
773   char *peerdir;
774   char *ip;
775   struct DirScanContext dsc;
776
777   hostmap = GNUNET_CONTAINER_multihashmap_create (1024);
778   stats = GNUNET_STATISTICS_create ("peerinfo", cfg);
779   notify_list = GNUNET_SERVER_notification_context_create (server, 0);
780   GNUNET_assert (GNUNET_OK ==
781                  GNUNET_CONFIGURATION_get_value_filename (cfg, "peerinfo",
782                                                           "HOSTS",
783                                                           &networkIdDirectory));
784   GNUNET_DISK_directory_create (networkIdDirectory);
785   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
786                                       &cron_scan_directory_data_hosts, NULL);
787   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
788                                       &cron_clean_data_hosts, NULL);
789   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
790                                 NULL);
791   GNUNET_SERVER_add_handlers (server, handlers);
792   ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
793   GNUNET_asprintf (&peerdir,
794                    "%shellos",
795                    ip);
796   GNUNET_free (ip);
797   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
798               _("Importing HELLOs from `%s'\n"),
799               peerdir);
800   dsc.matched = 0;
801   dsc.remove_files = GNUNET_NO;
802   GNUNET_DISK_directory_scan (peerdir,
803                               &hosts_directory_scan_callback, &dsc);
804   GNUNET_free (peerdir);
805 }
806
807
808 /**
809  * The main function for the peerinfo service.
810  *
811  * @param argc number of arguments from the command line
812  * @param argv command line arguments
813  * @return 0 ok, 1 on error
814  */
815 int
816 main (int argc, char *const *argv)
817 {
818   int ret;
819
820   ret =
821       (GNUNET_OK ==
822        GNUNET_SERVICE_run (argc, argv, "peerinfo", GNUNET_SERVICE_OPTION_NONE,
823                            &run, NULL)) ? 0 : 1;
824   GNUNET_free_non_null (networkIdDirectory);
825   return ret;
826 }
827
828
829 /* end of gnunet-service-peerinfo.c */