checkpoint save
[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, &entry->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       /* no differences, just ignore the update */
453       GNUNET_free (mrg);
454       return;
455     }
456     GNUNET_free (host->hello);
457     host->hello = mrg;
458   }
459   fn = get_host_filename (peer);
460   if (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn))
461   {
462     cnt = 0;
463     (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses,
464                                            &cnt);
465     if (0 == cnt)
466     {      
467       /* no valid addresses, don't put HELLO on disk; in fact,
468          if one exists on disk, remove it */
469       (void) UNLINK (fn); 
470     }
471     else
472     {
473       if (GNUNET_SYSERR ==
474           GNUNET_DISK_fn_write (fn, host->hello, GNUNET_HELLO_size (host->hello),
475                                 GNUNET_DISK_PERM_USER_READ |
476                                 GNUNET_DISK_PERM_USER_WRITE |
477                                 GNUNET_DISK_PERM_GROUP_READ |
478                                 GNUNET_DISK_PERM_OTHER_READ))
479         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
480     }
481   }
482   GNUNET_free (fn);
483   notify_all (host);
484 }
485
486
487 /**
488  * Do transmit info about peer to given host.
489  *
490  * @param cls NULL to hit all hosts, otherwise specifies a particular target
491  * @param key hostID
492  * @param value information to transmit
493  * @return GNUNET_YES (continue to iterate)
494  */
495 static int
496 add_to_tc (void *cls, const struct GNUNET_HashCode * key, void *value)
497 {
498   struct GNUNET_SERVER_TransmitContext *tc = cls;
499   struct HostEntry *pos = value;
500   struct InfoMessage *im;
501   uint16_t hs;
502   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
503
504   hs = 0;
505   im = (struct InfoMessage *) buf;
506   if (pos->hello != NULL)
507   {
508     hs = GNUNET_HELLO_size (pos->hello);
509     GNUNET_assert (hs <
510                    GNUNET_SERVER_MAX_MESSAGE_SIZE -
511                    sizeof (struct InfoMessage));
512     memcpy (&im[1], pos->hello, hs);
513   }
514   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
515   im->header.size = htons (sizeof (struct InfoMessage) + hs);
516   im->reserved = htonl (0);
517   im->peer = pos->identity;
518   GNUNET_SERVER_transmit_context_append_message (tc, &im->header);
519   return GNUNET_YES;
520 }
521
522
523 /**
524  * @brief delete expired HELLO entries in data/hosts/
525  *
526  * @param cls pointer to current time (struct GNUNET_TIME_Absolute)
527  * @param fn filename to test to see if the HELLO expired
528  * @return GNUNET_OK (continue iteration)
529  */
530 static int
531 discard_hosts_helper (void *cls, const char *fn)
532 {
533   struct GNUNET_TIME_Absolute *now = cls;
534   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
535   const struct GNUNET_HELLO_Message *hello;
536   struct GNUNET_HELLO_Message *new_hello;
537   int size;
538   unsigned int cnt;
539
540   size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
541   if (size < sizeof (struct GNUNET_MessageHeader))
542   {
543     if (0 != UNLINK (fn))
544       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
545                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
546     return GNUNET_OK;
547   }
548   hello = (const struct GNUNET_HELLO_Message *) buffer;
549   new_hello =
550     GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now);
551   cnt = 0;
552   if (NULL != new_hello)
553     (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses, &cnt);
554   if ( (NULL != new_hello) && (0 < cnt) )
555   {
556     GNUNET_DISK_fn_write (fn, new_hello, GNUNET_HELLO_size (new_hello),
557                           GNUNET_DISK_PERM_USER_READ |
558                           GNUNET_DISK_PERM_USER_WRITE |
559                           GNUNET_DISK_PERM_GROUP_READ |
560                           GNUNET_DISK_PERM_OTHER_READ);
561   }
562   else
563   {
564     if (0 != UNLINK (fn))
565       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
566                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
567   }
568   GNUNET_free_non_null (new_hello);
569   return GNUNET_OK;
570 }
571
572
573 /**
574  * Call this method periodically to scan data/hosts for ancient
575  * HELLOs to expire.
576  *
577  * @param cls unused
578  * @param tc scheduler context, aborted if reason is shutdown
579  */
580 static void
581 cron_clean_data_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
582 {
583   struct GNUNET_TIME_Absolute now;
584
585   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
586     return;
587   now = GNUNET_TIME_absolute_get ();
588   GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now);
589   GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, &cron_clean_data_hosts,
590                                 NULL);
591 }
592
593
594 /**
595  * Handle HELLO-message.
596  *
597  * @param cls closure
598  * @param client identification of the client
599  * @param message the actual message
600  */
601 static void
602 handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
603               const struct GNUNET_MessageHeader *message)
604 {
605   const struct GNUNET_HELLO_Message *hello;
606   struct GNUNET_PeerIdentity pid;
607
608   hello = (const struct GNUNET_HELLO_Message *) message;
609   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
610   {
611     GNUNET_break (0);
612     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
613     return;
614   }
615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
616               "HELLO", GNUNET_i2s (&pid));
617   bind_address (&pid, hello);
618   GNUNET_SERVER_receive_done (client, GNUNET_OK);
619 }
620
621
622 /**
623  * Handle GET-message.
624  *
625  * @param cls closure
626  * @param client identification of the client
627  * @param message the actual message
628  */
629 static void
630 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
631             const struct GNUNET_MessageHeader *message)
632 {
633   const struct ListPeerMessage *lpm;
634   struct GNUNET_SERVER_TransmitContext *tc;
635
636   lpm = (const struct ListPeerMessage *) message;
637   GNUNET_break (0 == ntohl (lpm->reserved));
638   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
639               "GET", GNUNET_i2s (&lpm->peer));
640   tc = GNUNET_SERVER_transmit_context_create (client);
641   GNUNET_CONTAINER_multihashmap_get_multiple (hostmap, &lpm->peer.hashPubKey,
642                                               &add_to_tc, tc);
643   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
644                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
645   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
646 }
647
648
649 /**
650  * Handle GET-ALL-message.
651  *
652  * @param cls closure
653  * @param client identification of the client
654  * @param message the actual message
655  */
656 static void
657 handle_get_all (void *cls, struct GNUNET_SERVER_Client *client,
658                 const struct GNUNET_MessageHeader *message)
659 {
660   struct GNUNET_SERVER_TransmitContext *tc;
661
662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "GET_ALL");
663   tc = GNUNET_SERVER_transmit_context_create (client);
664   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &add_to_tc, tc);
665   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
666                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
667   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
668 }
669
670
671 /**
672  * Pass the given client the information we have in the respective
673  * host entry; the client is already in the notification context.
674  *
675  * @param cls the 'struct GNUNET_SERVER_Client' to notify
676  * @param key key for the value (unused)
677  * @param value the 'struct HostEntry' to notify the client about
678  * @return GNUNET_YES (always, continue to iterate)
679  */
680 static int
681 do_notify_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
682 {
683   struct GNUNET_SERVER_Client *client = cls;
684   struct HostEntry *he = value;
685   struct InfoMessage *msg;
686
687   msg = make_info_message (he);
688   GNUNET_SERVER_notification_context_unicast (notify_list, client, &msg->header,
689                                               GNUNET_NO);
690   GNUNET_free (msg);
691   return GNUNET_YES;
692 }
693
694
695 /**
696  * Handle NOTIFY-message.
697  *
698  * @param cls closure
699  * @param client identification of the client
700  * @param message the actual message
701  */
702 static void
703 handle_notify (void *cls, struct GNUNET_SERVER_Client *client,
704                const struct GNUNET_MessageHeader *message)
705 {
706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "NOTIFY");
707   GNUNET_SERVER_client_mark_monitor (client);
708   GNUNET_SERVER_notification_context_add (notify_list, client);
709   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &do_notify_entry, client);
710   GNUNET_SERVER_receive_done (client, GNUNET_OK);
711 }
712
713
714 /**
715  * Release memory taken by a host entry.
716  *
717  * @param cls NULL
718  * @param key key of the host entry
719  * @param value the 'struct HostEntry' to free
720  * @return GNUNET_YES (continue to iterate)
721  */
722 static int
723 free_host_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
724 {
725   struct HostEntry *he = value;
726
727   GNUNET_free_non_null (he->hello);
728   GNUNET_free (he);
729   return GNUNET_YES;
730 }
731
732
733 /**
734  * Clean up our state.  Called during shutdown.
735  *
736  * @param cls unused
737  * @param tc scheduler task context, unused
738  */
739 static void
740 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
741 {
742   GNUNET_SERVER_notification_context_destroy (notify_list);
743   notify_list = NULL;
744   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &free_host_entry, NULL);
745   GNUNET_CONTAINER_multihashmap_destroy (hostmap);
746   if (NULL != stats)
747   {
748     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
749     stats = NULL;
750   }
751 }
752
753
754 /**
755  * Start up peerinfo service.
756  *
757  * @param cls closure
758  * @param server the initialized server
759  * @param cfg configuration to use
760  */
761 static void
762 run (void *cls, struct GNUNET_SERVER_Handle *server,
763      const struct GNUNET_CONFIGURATION_Handle *cfg)
764 {
765   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
766     {&handle_hello, NULL, GNUNET_MESSAGE_TYPE_HELLO, 0},
767     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
768      sizeof (struct ListPeerMessage)},
769     {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
770      sizeof (struct GNUNET_MessageHeader)},
771     {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
772      sizeof (struct GNUNET_MessageHeader)},
773     {NULL, NULL, 0, 0}
774   };
775   char *peerdir;
776   char *ip;
777   struct DirScanContext dsc;
778
779   hostmap = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
780   stats = GNUNET_STATISTICS_create ("peerinfo", cfg);
781   notify_list = GNUNET_SERVER_notification_context_create (server, 0);
782   GNUNET_assert (GNUNET_OK ==
783                  GNUNET_CONFIGURATION_get_value_filename (cfg, "peerinfo",
784                                                           "HOSTS",
785                                                           &networkIdDirectory));
786   GNUNET_DISK_directory_create (networkIdDirectory);
787   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
788                                       &cron_scan_directory_data_hosts, NULL);
789   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
790                                       &cron_clean_data_hosts, NULL);
791   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
792                                 NULL);
793   GNUNET_SERVER_add_handlers (server, handlers);
794   ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
795   GNUNET_asprintf (&peerdir,
796                    "%shellos",
797                    ip);
798   GNUNET_free (ip);
799   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
800               _("Importing HELLOs from `%s'\n"),
801               peerdir);
802   dsc.matched = 0;
803   dsc.remove_files = GNUNET_NO;
804   GNUNET_DISK_directory_scan (peerdir,
805                               &hosts_directory_scan_callback, &dsc);
806   GNUNET_free (peerdir);
807 }
808
809
810 /**
811  * The main function for the peerinfo service.
812  *
813  * @param argc number of arguments from the command line
814  * @param argv command line arguments
815  * @return 0 ok, 1 on error
816  */
817 int
818 main (int argc, char *const *argv)
819 {
820   int ret;
821
822   ret =
823       (GNUNET_OK ==
824        GNUNET_SERVICE_run (argc, argv, "peerinfo", GNUNET_SERVICE_OPTION_NONE,
825                            &run, NULL)) ? 0 : 1;
826   GNUNET_free_non_null (networkIdDirectory);
827   return ret;
828 }
829
830
831 /* end of gnunet-service-peerinfo.c */