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