-minor fixes
[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    * Friend only hello for the peer (can be NULL)
70    */
71   struct GNUNET_HELLO_Message *friend_only_hello;
72
73 };
74
75 /**
76  * Transmit context for GET requests
77  */
78 struct TransmitContext
79 {
80   /**
81    * Server transmit context
82    */
83   struct GNUNET_SERVER_TransmitContext *tc;
84
85   /**
86    * Include friend only HELLOs GNUNET_YES or _NO
87    */
88   int friend_only;
89 };
90
91 /**
92  * Result of reading a file
93  */
94 struct ReadHostFileContext
95 {
96   /**
97    * Hello for the peer (can be NULL)
98    */
99   struct GNUNET_HELLO_Message *hello;
100
101   /**
102    * Friend only hello for the peer (can be NULL)
103    */
104   struct GNUNET_HELLO_Message *friend_only_hello;
105 };
106
107
108 /**
109  * Client notification context
110  */
111 struct NotificationContext
112 {
113         /**
114          * Next in DLL
115          */
116         struct NotificationContext *prev;
117
118         /**
119          * Previous in DLL
120          */
121         struct NotificationContext *next;
122
123         /**
124          * Server client
125          */
126         struct GNUNET_SERVER_Client *client;
127
128         /**
129          * Interested in friend only HELLO?
130          */
131         int include_friend_only;
132 };
133
134
135 /**
136  * The in-memory list of known hosts, mapping of
137  * host IDs to 'struct HostEntry*' values.
138  */
139 static struct GNUNET_CONTAINER_MultiPeerMap *hostmap;
140
141 /**
142  * Clients to immediately notify about all changes.
143  */
144 static struct GNUNET_SERVER_NotificationContext *notify_list;
145
146 /**
147  * Directory where the hellos are stored in (peerinfo/)
148  */
149 static char *networkIdDirectory;
150
151 /**
152  * Handle for reporting statistics.
153  */
154 static struct GNUNET_STATISTICS_Handle *stats;
155
156 /**
157  * DLL of notification contexts: head
158  */
159 static struct NotificationContext *nc_head;
160
161 /**
162  * DLL of notification contexts: tail
163  */
164 static struct NotificationContext *nc_tail;
165
166
167 /**
168  * Notify all clients in the notify list about the
169  * given host entry changing.
170  *
171  * @param he entry of the host for which we generate a notification
172  * @param include_friend_only create public of friend-only message
173  * @return generated notification message
174  */
175 static struct InfoMessage *
176 make_info_message (const struct HostEntry *he, int include_friend_only)
177 {
178   struct InfoMessage *im;
179   struct GNUNET_HELLO_Message *src;
180   size_t hs;
181
182   if (GNUNET_YES == include_friend_only)
183         src = he->friend_only_hello;
184   else
185         src = he->hello;
186
187   hs = (NULL == src) ? 0 : GNUNET_HELLO_size (src);
188   im = GNUNET_malloc (sizeof (struct InfoMessage) + hs);
189   im->header.size = htons (hs + sizeof (struct InfoMessage));
190   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
191   im->peer = he->identity;
192   if (NULL != src)
193     memcpy (&im[1], src, hs);
194   return im;
195 }
196
197
198 /**
199  * Address iterator that causes expired entries to be discarded.
200  *
201  * @param cls pointer to the current time
202  * @param address the address
203  * @param expiration expiration time for the address
204  * @return GNUNET_NO if expiration smaller than the current time
205  */
206 static int
207 discard_expired (void *cls, const struct GNUNET_HELLO_Address *address,
208                  struct GNUNET_TIME_Absolute expiration)
209 {
210   const struct GNUNET_TIME_Absolute *now = cls;
211
212   if (now->abs_value_us > expiration.abs_value_us)
213   {
214     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
215                 _("Removing expired address of transport `%s'\n"),
216                 address->transport_name);
217     return GNUNET_NO;
218   }
219   return GNUNET_OK;
220 }
221
222
223 /**
224  * Address iterator that counts the remaining addresses.
225  *
226  * @param cls pointer to the counter
227  * @param address the address
228  * @param expiration expiration time for the address
229  * @return GNUNET_OK (always)
230  */
231 static int
232 count_addresses (void *cls, const struct GNUNET_HELLO_Address *address,
233                  struct GNUNET_TIME_Absolute expiration)
234 {
235   unsigned int *cnt = cls;
236
237   (*cnt)++;
238   return GNUNET_OK;
239 }
240
241
242 /**
243  * Get the filename under which we would store the GNUNET_HELLO_Message
244  * for the given host and protocol.
245  *
246  * @param id peer for which we need the filename for the HELLO
247  * @return filename of the form DIRECTORY/HOSTID
248  */
249 static char *
250 get_host_filename (const struct GNUNET_PeerIdentity *id)
251 {
252   char *fn;
253
254   if (NULL == networkIdDirectory)
255     return NULL;
256   GNUNET_asprintf (&fn, "%s%s%s", networkIdDirectory, DIR_SEPARATOR_STR,
257                    GNUNET_i2s_full (id));
258   return fn;
259 }
260
261
262 /**
263  * Broadcast information about the given entry to all
264  * clients that care.
265  *
266  * @param entry entry to broadcast about
267  */
268 static void
269 notify_all (struct HostEntry *entry)
270 {
271   struct InfoMessage *msg_pub;
272   struct InfoMessage *msg_friend;
273   struct NotificationContext *cur;
274
275   msg_pub = make_info_message (entry, GNUNET_NO);
276   msg_friend = make_info_message (entry, GNUNET_YES);
277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
278               "Notifying all clients about peer `%s'\n",
279               GNUNET_i2s(&entry->identity));
280   for (cur = nc_head; NULL != cur; cur = cur->next)
281   {
282     if (GNUNET_NO == cur->include_friend_only)
283       {
284         GNUNET_SERVER_notification_context_unicast (notify_list,
285                                                     cur->client,
286                                                     &msg_pub->header,
287                                                     GNUNET_NO);
288       }
289     if (GNUNET_YES == cur->include_friend_only)
290     {
291       GNUNET_SERVER_notification_context_unicast (notify_list,
292                                                   cur->client,
293                                                   &msg_friend->header,
294                                                   GNUNET_NO);
295     }
296   }
297   GNUNET_free (msg_pub);
298   GNUNET_free (msg_friend);
299 }
300
301
302 /**
303  * Bind a host address (hello) to a hostId.
304  *
305  * @param peer the peer for which this is a hello
306  * @param hello the verified (!) hello message
307  */
308 static void
309 update_hello (const struct GNUNET_PeerIdentity *peer,
310               const struct GNUNET_HELLO_Message *hello);
311
312
313 /**
314  * Try to read the HELLOs in the given filename and discard expired
315  * addresses.  Removes the file if one the HELLO is mal-formed.  If all
316  * addresses are expired, the HELLO is also removed (but the HELLO
317  * with the public key is still returned if it was found and valid).
318  *
319  * The file can contain multiple HELLO messages, but onlu a public and a friend only
320  * HELLO should be included
321  *
322  * @param fn name of the file
323  * @param unlink_garbage if GNUNET_YES, try to remove useless files
324  * @param r ReadHostFileContext to store the resutl
325  */
326 static void
327 read_host_file (const char *fn, int unlink_garbage, struct ReadHostFileContext *r)
328 {
329   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
330   unsigned int size_total;
331   struct GNUNET_TIME_Absolute now;
332   unsigned int left;
333
334   const struct GNUNET_HELLO_Message *hello;
335   struct GNUNET_HELLO_Message *hello_clean;
336   unsigned read_pos;
337   int size_hello;
338
339   r->friend_only_hello = NULL;
340   r->hello = NULL;
341
342   if (GNUNET_YES != GNUNET_DISK_file_test (fn))
343   {
344     return;
345   }
346
347   size_total = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes from `%s'\n", size_total, fn);
349   if (size_total < sizeof (struct GNUNET_MessageHeader))
350   {
351     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
352                 _("Failed to parse HELLO in file `%s': %s\n"),
353                 fn, "Fail has invalid size");
354     if ( (GNUNET_YES == unlink_garbage) &&
355          (0 != UNLINK (fn)) &&
356          (ENOENT != errno) )
357       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
358     return;
359   }
360
361   read_pos = 0;
362   while (read_pos < size_total)
363   {
364     hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos];
365     size_hello = GNUNET_HELLO_size (hello);
366     if (0 == size_hello)
367       {
368         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
369                     _("Failed to parse HELLO in file `%s': %s %u \n"),
370                     fn, "HELLO is invalid and has size of ", size_hello);
371         if ((GNUNET_YES == unlink_garbage) &&
372             (0 != UNLINK (fn)) &&
373             (ENOENT != errno) )
374           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
375         return;
376       }
377
378     now = GNUNET_TIME_absolute_get ();
379     hello_clean = GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES,
380                                                   &discard_expired, &now);
381     left = 0;
382     (void) GNUNET_HELLO_iterate_addresses (hello_clean, GNUNET_NO,
383                                            &count_addresses, &left);
384
385     if (0 == left)
386     {
387       GNUNET_free (hello_clean);
388       break;
389     }
390
391     if (GNUNET_NO == GNUNET_HELLO_is_friend_only (hello_clean))
392     {
393       if (NULL == r->hello)
394         r->hello = hello_clean;
395       else
396       {
397         GNUNET_break (0);
398         GNUNET_free (r->hello);
399         r->hello = hello_clean;
400       }
401     }
402     else
403     {
404       if (NULL == r->friend_only_hello)
405         r->friend_only_hello = hello_clean;
406       else
407       {
408         GNUNET_break (0);
409         GNUNET_free (r->friend_only_hello);
410         r->friend_only_hello = hello_clean;
411       }
412     }
413     read_pos += size_hello;
414   }
415
416   if (0 == left)
417   {
418     /* no addresses left, remove from disk */
419     if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
420       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
421   }
422
423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
424               "Found `%s' and `%s' HELLO message in file\n",
425               (NULL != r->hello) ? "public" : "NO public",
426               (NULL != r->friend_only_hello) ? "friend only" : "NO friend only");
427 }
428
429
430 /**
431  * Add a host to the list and notify clients about this event
432  *
433  * @param identity the identity of the host
434  * @return the HostEntry
435  */
436 static struct HostEntry *
437 add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity)
438 {
439   struct HostEntry *entry;
440   struct ReadHostFileContext r;
441   char *fn;
442
443   entry = GNUNET_CONTAINER_multipeermap_get (hostmap, identity);
444   if (NULL == entry)
445   {
446     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding new peer `%s'\n", GNUNET_i2s (identity));
447     GNUNET_STATISTICS_update (stats, gettext_noop ("# peers known"), 1,
448                               GNUNET_NO);
449     entry = GNUNET_new (struct HostEntry);
450     entry->identity = *identity;
451     GNUNET_assert (GNUNET_OK ==
452                    GNUNET_CONTAINER_multipeermap_put (hostmap, &entry->identity, entry,
453                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
454     notify_all (entry);
455     fn = get_host_filename (identity);
456     if (NULL != fn)
457     {
458       read_host_file (fn, GNUNET_YES, &r);
459       if (NULL != r.hello)
460         update_hello (identity, r.hello);
461       if (NULL != r.friend_only_hello)
462         update_hello (identity, r.friend_only_hello);
463       GNUNET_free_non_null (r.hello);
464       GNUNET_free_non_null (r.friend_only_hello);
465       GNUNET_free (fn);
466     }
467   }
468   return entry;
469 }
470
471
472 /**
473  * Remove a file that should not be there.  LOG
474  * success or failure.
475  *
476  * @param fullname name of the file to remove
477  */
478 static void
479 remove_garbage (const char *fullname)
480 {
481   if (0 == UNLINK (fullname))
482     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
483                 _
484                 ("File `%s' in directory `%s' does not match naming convention. "
485                  "Removed.\n"), fullname, networkIdDirectory);
486   else
487     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
488                               "unlink", fullname);
489 }
490
491
492 /**
493  * Closure for 'hosts_directory_scan_callback'.
494  */
495 struct DirScanContext
496 {
497   /**
498    * GNUNET_YES if we should remove files that are broken,
499    * GNUNET_NO if the directory we are iterating over should
500    * be treated as read-only by us.
501    */
502   int remove_files;
503
504   /**
505    * Counter for the number of (valid) entries found, incremented
506    * by one for each match.
507    */
508   unsigned int matched;
509 };
510
511
512 /**
513  * Function that is called on each HELLO file in a particular directory.
514  * Try to parse the file and add the HELLO to our list.
515  *
516  * @param cls pointer to 'unsigned int' to increment for each file, or NULL
517  *            if the file is from a read-only, read-once resource directory
518  * @param fullname name of the file to parse
519  * @return #GNUNET_OK (continue iteration)
520  */
521 static int
522 hosts_directory_scan_callback (void *cls, const char *fullname)
523 {
524   struct DirScanContext *dsc = cls;
525   struct GNUNET_PeerIdentity identity;
526   struct ReadHostFileContext r;
527   const char *filename;
528   struct GNUNET_PeerIdentity id_public;
529   struct GNUNET_PeerIdentity id_friend;
530   struct GNUNET_PeerIdentity id;
531
532   if (GNUNET_YES != GNUNET_DISK_file_test (fullname))
533     return GNUNET_OK;           /* ignore non-files */
534
535   filename = strrchr (fullname, DIR_SEPARATOR);
536   if ((NULL == filename) || (1 > strlen (filename)))
537         filename = fullname;
538   else
539     filename ++;
540
541   read_host_file (fullname, dsc->remove_files, &r);
542   if ( (NULL == r.hello) && (NULL == r.friend_only_hello))
543   {
544     if (GNUNET_YES == dsc->remove_files)
545       remove_garbage (fullname);
546     return GNUNET_OK;
547   }
548
549   if (NULL != r.friend_only_hello)
550   {
551     if (GNUNET_OK != GNUNET_HELLO_get_id (r.friend_only_hello, &id_friend))
552       if (GNUNET_YES == dsc->remove_files)
553       {
554         remove_garbage (fullname);
555         return GNUNET_OK;
556       }
557     id = id_friend;
558   }
559   if (NULL != r.hello)
560   {
561     if (GNUNET_OK != GNUNET_HELLO_get_id (r.hello, &id_public))
562       if (GNUNET_YES == dsc->remove_files)
563       {
564         remove_garbage (fullname);
565         return GNUNET_OK;
566       }
567     id = id_public;
568   }
569
570   if ( (NULL != r.hello) && (NULL != r.friend_only_hello) &&
571        (0 != memcmp (&id_friend, &id_public, sizeof (id_friend))) )
572   {
573     /* HELLOs are not for the same peer */
574     GNUNET_break (0);
575     if (GNUNET_YES == dsc->remove_files)
576       remove_garbage (fullname);
577     return GNUNET_OK;
578   }
579   if (GNUNET_OK == GNUNET_CRYPTO_eddsa_public_key_from_string (filename,
580                                                                   strlen (filename),
581                                                                   &identity.public_key))
582   {
583     if (0 != memcmp (&id, &identity, sizeof (id_friend)))
584     {
585       /* HELLOs are not for the same peer */
586       GNUNET_break (0);
587       if (GNUNET_YES == dsc->remove_files)
588         remove_garbage (fullname);
589       return GNUNET_OK;
590     }
591   }
592
593   /* ok, found something valid, remember HELLO */
594   add_host_to_known_hosts (&id);
595   if (NULL != r.hello)
596   {
597     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s' public HELLO \n",
598                 GNUNET_i2s (&id));
599     update_hello (&id, r.hello);
600     GNUNET_free (r.hello);
601   }
602   if (NULL != r.friend_only_hello)
603   {
604     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s' friend only HELLO \n",
605                 GNUNET_i2s (&id));
606     update_hello (&id, r.friend_only_hello);
607     GNUNET_free (r.friend_only_hello);
608   }
609   dsc->matched++;
610   return GNUNET_OK;
611 }
612
613
614 /**
615  * Call this method periodically to scan data/hosts for new hosts.
616  *
617  * @param cls unused
618  * @param tc scheduler context, aborted if reason is shutdown
619  */
620 static void
621 cron_scan_directory_data_hosts (void *cls,
622                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
623 {
624   static unsigned int retries;
625   struct DirScanContext dsc;
626
627   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
628     return;
629   if (GNUNET_SYSERR == GNUNET_DISK_directory_create (networkIdDirectory))
630   {
631     GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
632                                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
633                                                 &cron_scan_directory_data_hosts, NULL);
634     return;
635   }
636   dsc.matched = 0;
637   dsc.remove_files = GNUNET_YES;
638   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
639               _("Scanning directory `%s'\n"), networkIdDirectory);
640   GNUNET_DISK_directory_scan (networkIdDirectory,
641                               &hosts_directory_scan_callback, &dsc);
642   if ((0 == dsc.matched) && (0 == (++retries & 31)))
643     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
644                 _("Still no peers found in `%s'!\n"), networkIdDirectory);
645   GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
646                                               GNUNET_SCHEDULER_PRIORITY_IDLE,
647                                               &cron_scan_directory_data_hosts,
648                                               NULL);
649 }
650
651
652 static struct GNUNET_HELLO_Message *
653 update_friend_hello (const struct GNUNET_HELLO_Message *hello,
654                      const struct GNUNET_HELLO_Message *friend_hello)
655 {
656   struct GNUNET_HELLO_Message * res;
657   struct GNUNET_HELLO_Message * tmp;
658   struct GNUNET_CRYPTO_EddsaPublicKey pk;
659
660   if (NULL != friend_hello)
661   {
662     res = GNUNET_HELLO_merge (hello, friend_hello);
663     GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
664     return res;
665   }
666
667   if (GNUNET_OK !=
668       GNUNET_HELLO_get_key (hello, &pk))
669   {
670     GNUNET_break (0);
671     return NULL;
672   }
673   tmp = GNUNET_HELLO_create (&pk, NULL, NULL, GNUNET_YES);
674   res = GNUNET_HELLO_merge (hello, tmp);
675   GNUNET_free (tmp);
676   GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
677   return res;
678 }
679
680
681 /**
682  * Bind a host address (hello) to a hostId.
683  *
684  * @param peer the peer for which this is a hello
685  * @param hello the verified (!) hello message
686  */
687 static void
688 update_hello (const struct GNUNET_PeerIdentity *peer,
689               const struct GNUNET_HELLO_Message *hello)
690 {
691   char *fn;
692   struct HostEntry *host;
693   struct GNUNET_HELLO_Message *mrg;
694   struct GNUNET_HELLO_Message **dest;
695   struct GNUNET_TIME_Absolute delta;
696   unsigned int cnt;
697   unsigned int size;
698   int friend_hello_type;
699   int store_hello;
700   int store_friend_hello;
701   int pos;
702   char *buffer;
703
704   host = GNUNET_CONTAINER_multipeermap_get (hostmap, peer);
705   GNUNET_assert (NULL != host);
706
707   friend_hello_type = GNUNET_HELLO_is_friend_only (hello);
708         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating %s HELLO for `%s'\n",
709                         (GNUNET_YES == friend_hello_type) ? "friend-only" : "public",
710                         GNUNET_i2s (peer));
711
712   dest = NULL;
713   if (GNUNET_YES == friend_hello_type)
714   {
715     dest = &host->friend_only_hello;
716   }
717   else
718   {
719     dest = &host->hello;
720   }
721
722   if (NULL == (*dest))
723   {
724     (*dest) = GNUNET_malloc (GNUNET_HELLO_size (hello));
725     memcpy ((*dest), hello, GNUNET_HELLO_size (hello));
726   }
727   else
728   {
729     mrg = GNUNET_HELLO_merge ((*dest), hello);
730     delta = GNUNET_HELLO_equals (mrg, (*dest), GNUNET_TIME_absolute_get ());
731     if (delta.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
732     {
733       /* no differences, just ignore the update */
734         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No change in %s HELLO for `%s'\n",
735                         (GNUNET_YES == friend_hello_type) ? "friend-only" : "public",
736                         GNUNET_i2s (peer));
737       GNUNET_free (mrg);
738       return;
739     }
740     GNUNET_free ((*dest));
741     (*dest) = mrg;
742   }
743
744   if ((NULL != (host->hello)) && (GNUNET_NO == friend_hello_type))
745   {
746     /* Update friend only hello */
747     mrg = update_friend_hello (host->hello, host->friend_only_hello);
748     if (NULL != host->friend_only_hello)
749       GNUNET_free (host->friend_only_hello);
750     host->friend_only_hello = mrg;
751   }
752
753   if (NULL != host->hello)
754     GNUNET_assert ((GNUNET_NO == GNUNET_HELLO_is_friend_only (host->hello)));
755   if (NULL != host->friend_only_hello)
756     GNUNET_assert ((GNUNET_YES == GNUNET_HELLO_is_friend_only(host->friend_only_hello)));
757
758   fn = get_host_filename (peer);
759   if ( (NULL != fn) &&
760        (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn)) )
761   {
762     store_hello = GNUNET_NO;
763     size = 0;
764     cnt = 0;
765     if (NULL != host->hello)
766       (void) GNUNET_HELLO_iterate_addresses (host->hello,
767                                              GNUNET_NO, &count_addresses, &cnt);
768     if (cnt > 0)
769     {
770       store_hello = GNUNET_YES;
771       size += GNUNET_HELLO_size (host->hello);
772     }
773     cnt = 0;
774     if (NULL != host->friend_only_hello)
775       (void) GNUNET_HELLO_iterate_addresses (host->friend_only_hello, GNUNET_NO,
776                                              &count_addresses, &cnt);
777     store_friend_hello = GNUNET_NO;
778     if (0 < cnt)
779     {
780       store_friend_hello = GNUNET_YES;
781       size += GNUNET_HELLO_size (host->friend_only_hello);
782     }
783
784     if ((GNUNET_NO == store_hello) && (GNUNET_NO == store_friend_hello))
785     {
786       /* no valid addresses, don't put HELLO on disk; in fact,
787          if one exists on disk, remove it */
788       (void) UNLINK (fn);
789     }
790     else
791     {
792       buffer = GNUNET_malloc (size);
793       pos = 0;
794
795       if (GNUNET_YES == store_hello)
796       {
797         memcpy (buffer, host->hello, GNUNET_HELLO_size (host->hello));
798         pos += GNUNET_HELLO_size (host->hello);
799       }
800       if (GNUNET_YES == store_friend_hello)
801       {
802         memcpy (&buffer[pos], host->friend_only_hello, GNUNET_HELLO_size (host->friend_only_hello));
803         pos += GNUNET_HELLO_size (host->friend_only_hello);
804       }
805       GNUNET_assert (pos == size);
806
807       if (GNUNET_SYSERR == GNUNET_DISK_fn_write (fn, buffer, size,
808                                                  GNUNET_DISK_PERM_USER_READ |
809                                                  GNUNET_DISK_PERM_USER_WRITE |
810                                                  GNUNET_DISK_PERM_GROUP_READ |
811                                                  GNUNET_DISK_PERM_OTHER_READ))
812         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
813       else
814         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stored %s %s HELLO in %s  with total size %u\n",
815                     (GNUNET_YES == store_friend_hello) ? "friend-only": "",
816                     (GNUNET_YES == store_hello) ? "public": "",
817                     fn, size);
818       GNUNET_free (buffer);
819     }
820   }
821   GNUNET_free_non_null (fn);
822   notify_all (host);
823 }
824
825
826 /**
827  * Do transmit info about peer to given host.
828  *
829  * @param cls NULL to hit all hosts, otherwise specifies a particular target
830  * @param key hostID
831  * @param value information to transmit
832  * @return GNUNET_YES (continue to iterate)
833  */
834 static int
835 add_to_tc (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
836 {
837   struct TransmitContext *tc = cls;
838   struct HostEntry *pos = value;
839   struct InfoMessage *im;
840   uint16_t hs;
841   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
842
843   hs = 0;
844   im = (struct InfoMessage *) buf;
845
846   if ((pos->hello != NULL) && (GNUNET_NO == tc->friend_only))
847   {
848         /* Copy public HELLO */
849     hs = GNUNET_HELLO_size (pos->hello);
850     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
851                    sizeof (struct InfoMessage));
852     memcpy (&im[1], pos->hello, hs);
853     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
854                 "Sending public HELLO with size %u for peer `%4s'\n",
855                 hs, GNUNET_i2s (key));
856   }
857   else if ((pos->friend_only_hello != NULL) && (GNUNET_YES == tc->friend_only))
858   {
859         /* Copy friend only HELLO */
860     hs = GNUNET_HELLO_size (pos->friend_only_hello);
861     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
862                    sizeof (struct InfoMessage));
863     memcpy (&im[1], pos->friend_only_hello, hs);
864     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
865                 "Sending friend-only HELLO with size %u for peer `%4s'\n",
866                 hs, GNUNET_i2s (key));
867   }
868   else
869   {
870       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
871                   "Adding no HELLO for peer `%s'\n",
872                  GNUNET_i2s (key));
873   }
874
875   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
876   im->header.size = htons (sizeof (struct InfoMessage) + hs);
877   im->reserved = htonl (0);
878   im->peer = pos->identity;
879   GNUNET_SERVER_transmit_context_append_message (tc->tc, &im->header);
880   return GNUNET_YES;
881 }
882
883
884 /**
885  * @brief delete expired HELLO entries in directory
886  *
887  * @param cls pointer to current time (struct GNUNET_TIME_Absolute)
888  * @param fn filename to test to see if the HELLO expired
889  * @return GNUNET_OK (continue iteration)
890  */
891 static int
892 discard_hosts_helper (void *cls, const char *fn)
893 {
894   struct GNUNET_TIME_Absolute *now = cls;
895   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
896   const struct GNUNET_HELLO_Message *hello;
897   struct GNUNET_HELLO_Message *new_hello;
898   int read_size;
899   unsigned int cur_hello_size;
900   unsigned int new_hello_size;
901   int read_pos;
902   int write_pos;
903   unsigned int cnt;
904   char *writebuffer;
905
906
907   read_size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
908   if (read_size < sizeof (struct GNUNET_MessageHeader))
909   {
910     if (0 != UNLINK (fn))
911       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
912                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
913     return GNUNET_OK;
914   }
915
916   writebuffer = GNUNET_malloc (read_size);
917   read_pos = 0;
918   write_pos = 0;
919   while (read_pos < read_size)
920   {
921     /* Check each HELLO */
922     hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos];
923     cur_hello_size = GNUNET_HELLO_size (hello);
924     if (0 == cur_hello_size)
925     {
926       /* Invalid data, discard */
927       if (0 != UNLINK (fn))
928         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
929                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
930       return GNUNET_OK;
931     }
932     new_hello = GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now);
933     cnt = 0;
934     if (NULL != new_hello)
935       (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses, &cnt);
936     if ( (NULL != new_hello) && (0 < cnt) )
937     {
938       /* Store new HELLO to write it when done */
939       new_hello_size = GNUNET_HELLO_size (new_hello);
940       memcpy (&writebuffer[write_pos], new_hello, new_hello_size);
941       write_pos += new_hello_size;
942     }
943     read_pos += cur_hello_size;
944     GNUNET_free_non_null (new_hello);
945   }
946
947   if (0 < write_pos)
948   {
949       GNUNET_DISK_fn_write (fn, writebuffer,write_pos,
950                             GNUNET_DISK_PERM_USER_READ |
951                             GNUNET_DISK_PERM_USER_WRITE |
952                             GNUNET_DISK_PERM_GROUP_READ |
953                             GNUNET_DISK_PERM_OTHER_READ);
954   }
955   else if (0 != UNLINK (fn))
956     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
957                               GNUNET_ERROR_TYPE_BULK, "unlink", fn);
958
959   GNUNET_free (writebuffer);
960   return GNUNET_OK;
961 }
962
963
964 /**
965  * Call this method periodically to scan peerinfo/ for ancient
966  * HELLOs to expire.
967  *
968  * @param cls unused
969  * @param tc scheduler context, aborted if reason is shutdown
970  */
971 static void
972 cron_clean_data_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
973 {
974   struct GNUNET_TIME_Absolute now;
975
976   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
977     return;
978   now = GNUNET_TIME_absolute_get ();
979   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
980               _("Cleaning up directory `%s'\n"), networkIdDirectory);
981   GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now);
982   GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, &cron_clean_data_hosts,
983                                 NULL);
984 }
985
986
987 /**
988  * Handle HELLO-message.
989  *
990  * @param cls closure
991  * @param client identification of the client
992  * @param message the actual message
993  */
994 static void
995 handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
996               const struct GNUNET_MessageHeader *message)
997 {
998   const struct GNUNET_HELLO_Message *hello;
999   struct GNUNET_PeerIdentity pid;
1000
1001   hello = (const struct GNUNET_HELLO_Message *) message;
1002   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
1003   {
1004     GNUNET_break (0);
1005     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1006     return;
1007   }
1008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
1009               "HELLO", GNUNET_i2s (&pid));
1010   add_host_to_known_hosts (&pid);
1011   update_hello (&pid, hello);
1012   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1013 }
1014
1015
1016 /**
1017  * Handle GET-message.
1018  *
1019  * @param cls closure
1020  * @param client identification of the client
1021  * @param message the actual message
1022  */
1023 static void
1024 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
1025             const struct GNUNET_MessageHeader *message)
1026 {
1027   const struct ListPeerMessage *lpm;
1028   struct TransmitContext tcx;
1029
1030   lpm = (const struct ListPeerMessage *) message;
1031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
1032               "GET", GNUNET_i2s (&lpm->peer));
1033   tcx.friend_only = ntohl (lpm->include_friend_only);
1034   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
1035   GNUNET_CONTAINER_multipeermap_get_multiple (hostmap, &lpm->peer,
1036                                               &add_to_tc, &tcx);
1037   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
1038                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
1039   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
1040 }
1041
1042
1043 /**
1044  * Handle GET-ALL-message.
1045  *
1046  * @param cls closure
1047  * @param client identification of the client
1048  * @param message the actual message
1049  */
1050 static void
1051 handle_get_all (void *cls, struct GNUNET_SERVER_Client *client,
1052                 const struct GNUNET_MessageHeader *message)
1053 {
1054   const struct ListAllPeersMessage *lapm;
1055   struct TransmitContext tcx;
1056
1057   lapm = (const struct ListAllPeersMessage *) message;
1058   tcx.friend_only = ntohl (lapm->include_friend_only);
1059   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "GET_ALL");
1060   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
1061   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &add_to_tc, &tcx);
1062   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
1063                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
1064   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
1065 }
1066
1067
1068
1069 /**
1070  * Pass the given client the information we have in the respective
1071  * host entry; the client is already in the notification context.
1072  *
1073  * @param cls the 'struct GNUNET_SERVER_Client' to notify
1074  * @param key key for the value (unused)
1075  * @param value the 'struct HostEntry' to notify the client about
1076  * @return GNUNET_YES (always, continue to iterate)
1077  */
1078 static int
1079 do_notify_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1080 {
1081   struct NotificationContext *nc = cls;
1082   struct HostEntry *he = value;
1083   struct InfoMessage *msg;
1084
1085   if ((NULL == he->hello) && (GNUNET_NO == nc->include_friend_only))
1086   {
1087     /* We have no public hello  */
1088     return GNUNET_YES;
1089   }
1090
1091   if ( (NULL == he->friend_only_hello) &&
1092        (GNUNET_YES == nc->include_friend_only) )
1093   {
1094     /* We have no friend hello */
1095     return GNUNET_YES;
1096   }
1097
1098   msg = make_info_message (he, nc->include_friend_only);
1099   GNUNET_SERVER_notification_context_unicast (notify_list,
1100                                               nc->client,
1101                                               &msg->header,
1102                                               GNUNET_NO);
1103   GNUNET_free (msg);
1104   return GNUNET_YES;
1105 }
1106
1107
1108 /**
1109  * Handle NOTIFY-message.
1110  *
1111  * @param cls closure
1112  * @param client identification of the client
1113  * @param message the actual message
1114  */
1115 static void
1116 handle_notify (void *cls, struct GNUNET_SERVER_Client *client,
1117                const struct GNUNET_MessageHeader *message)
1118 {
1119   struct NotifyMessage *nm = (struct NotifyMessage *) message;
1120   struct NotificationContext *nc;
1121
1122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123               "`%s' message received\n",
1124               "NOTIFY");
1125   nc = GNUNET_malloc (sizeof (struct NotificationContext));
1126   nc->client = client;
1127   nc->include_friend_only = ntohl (nm->include_friend_only);
1128
1129   GNUNET_CONTAINER_DLL_insert (nc_head, nc_tail, nc);
1130   GNUNET_SERVER_client_mark_monitor (client);
1131         GNUNET_SERVER_notification_context_add (notify_list, client);
1132   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &do_notify_entry, nc);
1133   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1134 }
1135
1136
1137 /**
1138  * Client disconnect callback
1139  *
1140  * @param cls unused
1141  * @param client server client
1142  */
1143 static void
1144 disconnect_cb (void *cls,struct GNUNET_SERVER_Client *client)
1145 {
1146   struct NotificationContext *cur;
1147
1148   for (cur = nc_head; NULL != cur; cur = cur->next)
1149     if (cur->client == client)
1150       break;
1151   if (NULL == cur)
1152     return;
1153   GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1154   GNUNET_free (cur);
1155 }
1156
1157
1158 /**
1159  * Release memory taken by a host entry.
1160  *
1161  * @param cls NULL
1162  * @param key key of the host entry
1163  * @param value the 'struct HostEntry' to free
1164  * @return GNUNET_YES (continue to iterate)
1165  */
1166 static int
1167 free_host_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1168 {
1169   struct HostEntry *he = value;
1170
1171   GNUNET_free_non_null (he->hello);
1172   GNUNET_free_non_null (he->friend_only_hello);
1173   GNUNET_free (he);
1174   return GNUNET_YES;
1175 }
1176
1177
1178 /**
1179  * Clean up our state.  Called during shutdown.
1180  *
1181  * @param cls unused
1182  * @param tc scheduler task context, unused
1183  */
1184 static void
1185 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1186 {
1187   struct NotificationContext *cur;
1188   struct NotificationContext *next;
1189
1190   GNUNET_SERVER_notification_context_destroy (notify_list);
1191   notify_list = NULL;
1192
1193   for (cur = nc_head; NULL != cur; cur = next)
1194   {
1195     next = cur->next;
1196     GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1197     GNUNET_free (cur);
1198   }
1199   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &free_host_entry, NULL);
1200   GNUNET_CONTAINER_multipeermap_destroy (hostmap);
1201   if (NULL != stats)
1202   {
1203     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1204     stats = NULL;
1205   }
1206 }
1207
1208
1209 /**
1210  * Start up peerinfo service.
1211  *
1212  * @param cls closure
1213  * @param server the initialized server
1214  * @param cfg configuration to use
1215  */
1216 static void
1217 run (void *cls, struct GNUNET_SERVER_Handle *server,
1218      const struct GNUNET_CONFIGURATION_Handle *cfg)
1219 {
1220   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1221     {&handle_hello, NULL, GNUNET_MESSAGE_TYPE_HELLO, 0},
1222     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
1223      sizeof (struct ListPeerMessage)},
1224     {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
1225      sizeof (struct ListAllPeersMessage)},
1226     {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
1227      sizeof (struct NotifyMessage)},
1228     {NULL, NULL, 0, 0}
1229   };
1230   char *peerdir;
1231   char *ip;
1232   struct DirScanContext dsc;
1233   int noio;
1234   int use_included;
1235
1236   hostmap = GNUNET_CONTAINER_multipeermap_create (1024, GNUNET_YES);
1237   stats = GNUNET_STATISTICS_create ("peerinfo", cfg);
1238   notify_list = GNUNET_SERVER_notification_context_create (server, 0);
1239   noio = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "NO_IO");
1240   use_included = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "USE_INCLUDED_HELLOS");
1241   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1242                                 NULL);
1243   if (GNUNET_YES != noio)
1244   {
1245     GNUNET_assert (GNUNET_OK ==
1246                    GNUNET_CONFIGURATION_get_value_filename (cfg, "peerinfo",
1247                                                             "HOSTS",
1248                                                             &networkIdDirectory));
1249     if (GNUNET_OK !=
1250         GNUNET_DISK_directory_create (networkIdDirectory))
1251     {
1252       GNUNET_SCHEDULER_shutdown ();
1253       return;
1254     }
1255
1256     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1257                                         &cron_scan_directory_data_hosts, NULL);
1258
1259     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1260                                         &cron_clean_data_hosts, NULL);
1261     if (GNUNET_YES == use_included)
1262     {
1263         ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
1264         GNUNET_asprintf (&peerdir,
1265                      "%shellos",
1266                      ip);
1267         GNUNET_free (ip);
1268
1269                         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1270                         _("Importing HELLOs from `%s'\n"),
1271                         peerdir);
1272                         dsc.matched = 0;
1273                         dsc.remove_files = GNUNET_NO;
1274
1275                         GNUNET_DISK_directory_scan (peerdir,
1276                                         &hosts_directory_scan_callback, &dsc);
1277
1278                         GNUNET_free (peerdir);
1279     }
1280   }
1281   GNUNET_SERVER_add_handlers (server, handlers);
1282   GNUNET_SERVER_disconnect_notify (server, &disconnect_cb, NULL) ;
1283 }
1284
1285
1286 /**
1287  * The main function for the peerinfo service.
1288  *
1289  * @param argc number of arguments from the command line
1290  * @param argv command line arguments
1291  * @return 0 ok, 1 on error
1292  */
1293 int
1294 main (int argc, char *const *argv)
1295 {
1296   int ret;
1297
1298   ret =
1299       (GNUNET_OK ==
1300        GNUNET_SERVICE_run (argc, argv, "peerinfo", GNUNET_SERVICE_OPTION_NONE,
1301                            &run, NULL)) ? 0 : 1;
1302   GNUNET_free_non_null (networkIdDirectory);
1303   return ret;
1304 }
1305
1306
1307 /* end of gnunet-service-peerinfo.c */