fix more leaks
[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_malloc (sizeof (struct HostEntry));
450     entry->identity = *identity;
451     GNUNET_CONTAINER_multipeermap_put (hostmap, &entry->identity, entry,
452                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
453     notify_all (entry);
454     fn = get_host_filename (identity);
455     if (NULL != fn)
456     {
457       read_host_file (fn, GNUNET_YES, &r);
458       if (NULL != r.hello)
459         update_hello (identity, r.hello);
460       if (NULL != r.friend_only_hello)
461         update_hello (identity, r.friend_only_hello);
462       GNUNET_free_non_null (r.hello);
463       GNUNET_free_non_null (r.friend_only_hello);
464       GNUNET_free (fn);
465     }
466   }
467   return entry;
468 }
469
470
471 /**
472  * Remove a file that should not be there.  LOG
473  * success or failure.
474  *
475  * @param fullname name of the file to remove
476  */
477 static void
478 remove_garbage (const char *fullname)
479 {
480   if (0 == UNLINK (fullname))
481     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
482                 _
483                 ("File `%s' in directory `%s' does not match naming convention. "
484                  "Removed.\n"), fullname, networkIdDirectory);
485   else
486     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
487                               "unlink", fullname);
488 }
489
490
491 /**
492  * Closure for 'hosts_directory_scan_callback'.
493  */
494 struct DirScanContext
495 {
496   /**
497    * GNUNET_YES if we should remove files that are broken,
498    * GNUNET_NO if the directory we are iterating over should
499    * be treated as read-only by us.
500    */
501   int remove_files;
502
503   /**
504    * Counter for the number of (valid) entries found, incremented
505    * by one for each match.
506    */
507   unsigned int matched;
508 };
509
510
511 /**
512  * Function that is called on each HELLO file in a particular directory.
513  * Try to parse the file and add the HELLO to our list.
514  *
515  * @param cls pointer to 'unsigned int' to increment for each file, or NULL
516  *            if the file is from a read-only, read-once resource directory
517  * @param fullname name of the file to parse
518  * @return #GNUNET_OK (continue iteration)
519  */
520 static int
521 hosts_directory_scan_callback (void *cls, const char *fullname)
522 {
523   struct DirScanContext *dsc = cls;
524   struct GNUNET_PeerIdentity identity;
525   struct ReadHostFileContext r;
526   const char *filename;
527   struct GNUNET_PeerIdentity id_public;
528   struct GNUNET_PeerIdentity id_friend;
529   struct GNUNET_PeerIdentity id;
530
531   if (GNUNET_YES != GNUNET_DISK_file_test (fullname))
532     return GNUNET_OK;           /* ignore non-files */
533
534   filename = strrchr (fullname, DIR_SEPARATOR);
535   if ((NULL == filename) || (1 > strlen (filename)))
536         filename = fullname;
537   else
538     filename ++;
539
540   read_host_file (fullname, dsc->remove_files, &r);
541   if ( (NULL == r.hello) && (NULL == r.friend_only_hello))
542   {
543     if (GNUNET_YES == dsc->remove_files)
544       remove_garbage (fullname);
545     return GNUNET_OK;
546   }
547
548   if (NULL != r.friend_only_hello)
549   {
550     if (GNUNET_OK != GNUNET_HELLO_get_id (r.friend_only_hello, &id_friend))
551       if (GNUNET_YES == dsc->remove_files)
552       {
553         remove_garbage (fullname);
554         return GNUNET_OK;
555       }
556     id = id_friend;
557   }
558   if (NULL != r.hello)
559   {
560     if (GNUNET_OK != GNUNET_HELLO_get_id (r.hello, &id_public))
561       if (GNUNET_YES == dsc->remove_files)
562       {
563         remove_garbage (fullname);
564         return GNUNET_OK;
565       }
566     id = id_public;
567   }
568
569   if ( (NULL != r.hello) && (NULL != r.friend_only_hello) &&
570        (0 != memcmp (&id_friend, &id_public, sizeof (id_friend))) )
571   {
572     /* HELLOs are not for the same peer */
573     GNUNET_break (0);
574     if (GNUNET_YES == dsc->remove_files)
575       remove_garbage (fullname);
576     return GNUNET_OK;
577   }
578   if (GNUNET_OK == GNUNET_CRYPTO_ecc_public_sign_key_from_string (filename,
579                                                                   strlen (filename),
580                                                                   &identity.public_key))
581   {
582     if (0 != memcmp (&id, &identity, sizeof (id_friend)))
583     {
584       /* HELLOs are not for the same peer */
585       GNUNET_break (0);
586       if (GNUNET_YES == dsc->remove_files)
587         remove_garbage (fullname);
588       return GNUNET_OK;
589     }
590   }
591
592   /* ok, found something valid, remember HELLO */
593   add_host_to_known_hosts (&id);
594   if (NULL != r.hello)
595   {
596     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s' public HELLO \n",
597                 GNUNET_i2s (&id));
598     update_hello (&id, r.hello);
599     GNUNET_free (r.hello);
600   }
601   if (NULL != r.friend_only_hello)
602   {
603     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s' friend only HELLO \n",
604                 GNUNET_i2s (&id));
605     update_hello (&id, r.friend_only_hello);
606     GNUNET_free (r.friend_only_hello);
607   }
608   dsc->matched++;
609   return GNUNET_OK;
610 }
611
612
613 /**
614  * Call this method periodically to scan data/hosts for new hosts.
615  *
616  * @param cls unused
617  * @param tc scheduler context, aborted if reason is shutdown
618  */
619 static void
620 cron_scan_directory_data_hosts (void *cls,
621                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
622 {
623   static unsigned int retries;
624   struct DirScanContext dsc;
625
626   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
627     return;
628   if (GNUNET_SYSERR == GNUNET_DISK_directory_create (networkIdDirectory))
629   {
630     GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
631                                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
632                                                 &cron_scan_directory_data_hosts, NULL);
633     return;
634   }
635   dsc.matched = 0;
636   dsc.remove_files = GNUNET_YES;
637   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
638               _("Scanning directory `%s'\n"), networkIdDirectory);
639   GNUNET_DISK_directory_scan (networkIdDirectory,
640                               &hosts_directory_scan_callback, &dsc);
641   if ((0 == dsc.matched) && (0 == (++retries & 31)))
642     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
643                 _("Still no peers found in `%s'!\n"), networkIdDirectory);
644   GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
645                                               GNUNET_SCHEDULER_PRIORITY_IDLE,
646                                               &cron_scan_directory_data_hosts,
647                                               NULL);
648 }
649
650
651 static struct GNUNET_HELLO_Message *
652 update_friend_hello (const struct GNUNET_HELLO_Message *hello,
653                      const struct GNUNET_HELLO_Message *friend_hello)
654 {
655   struct GNUNET_HELLO_Message * res;
656   struct GNUNET_HELLO_Message * tmp;
657   struct GNUNET_CRYPTO_EccPublicSignKey pk;
658
659   if (NULL != friend_hello)
660   {
661     res = GNUNET_HELLO_merge (hello, friend_hello);
662     GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
663     return res;
664   }
665
666   if (GNUNET_OK !=
667       GNUNET_HELLO_get_key (hello, &pk))
668   {
669     GNUNET_break (0);
670     return NULL;
671   }
672   tmp = GNUNET_HELLO_create (&pk, NULL, NULL, GNUNET_YES);
673   res = GNUNET_HELLO_merge (hello, tmp);
674   GNUNET_free (tmp);
675   GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
676   return res;
677 }
678
679
680 /**
681  * Bind a host address (hello) to a hostId.
682  *
683  * @param peer the peer for which this is a hello
684  * @param hello the verified (!) hello message
685  */
686 static void
687 update_hello (const struct GNUNET_PeerIdentity *peer,
688               const struct GNUNET_HELLO_Message *hello)
689 {
690   char *fn;
691   struct HostEntry *host;
692   struct GNUNET_HELLO_Message *mrg;
693   struct GNUNET_HELLO_Message **dest;
694   struct GNUNET_TIME_Absolute delta;
695   unsigned int cnt;
696   unsigned int size;
697   int friend_hello_type;
698   int store_hello;
699   int store_friend_hello;
700   int pos;
701   char *buffer;
702
703   host = GNUNET_CONTAINER_multipeermap_get (hostmap, peer);
704   GNUNET_assert (NULL != host);
705
706   friend_hello_type = GNUNET_HELLO_is_friend_only (hello);
707         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating %s HELLO for `%s'\n",
708                         (GNUNET_YES == friend_hello_type) ? "friend-only" : "public",
709                         GNUNET_i2s (peer));
710
711   dest = NULL;
712   if (GNUNET_YES == friend_hello_type)
713   {
714     dest = &host->friend_only_hello;
715   }
716   else
717   {
718     dest = &host->hello;
719   }
720
721   if (NULL == (*dest))
722   {
723     (*dest) = GNUNET_malloc (GNUNET_HELLO_size (hello));
724     memcpy ((*dest), hello, GNUNET_HELLO_size (hello));
725   }
726   else
727   {
728     mrg = GNUNET_HELLO_merge ((*dest), hello);
729     delta = GNUNET_HELLO_equals (mrg, (*dest), GNUNET_TIME_absolute_get ());
730     if (delta.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
731     {
732       /* no differences, just ignore the update */
733         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No change in %s HELLO for `%s'\n",
734                         (GNUNET_YES == friend_hello_type) ? "friend-only" : "public",
735                         GNUNET_i2s (peer));
736       GNUNET_free (mrg);
737       return;
738     }
739     GNUNET_free ((*dest));
740     (*dest) = mrg;
741   }
742
743   if ((NULL != (host->hello)) && (GNUNET_NO == friend_hello_type))
744   {
745     /* Update friend only hello */
746     mrg = update_friend_hello (host->hello, host->friend_only_hello);
747     if (NULL != host->friend_only_hello)
748       GNUNET_free (host->friend_only_hello);
749     host->friend_only_hello = mrg;
750   }
751
752   if (NULL != host->hello)
753     GNUNET_assert ((GNUNET_NO == GNUNET_HELLO_is_friend_only (host->hello)));
754   if (NULL != host->friend_only_hello)
755     GNUNET_assert ((GNUNET_YES == GNUNET_HELLO_is_friend_only(host->friend_only_hello)));
756
757   fn = get_host_filename (peer);
758   if ( (NULL != fn) &&
759        (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn)) )
760   {
761     store_hello = GNUNET_NO;
762     size = 0;
763     cnt = 0;
764     if (NULL != host->hello)
765       (void) GNUNET_HELLO_iterate_addresses (host->hello,
766                                              GNUNET_NO, &count_addresses, &cnt);
767     if (cnt > 0)
768     {
769       store_hello = GNUNET_YES;
770       size += GNUNET_HELLO_size (host->hello);
771     }
772     cnt = 0;
773     if (NULL != host->friend_only_hello)
774       (void) GNUNET_HELLO_iterate_addresses (host->friend_only_hello, GNUNET_NO,
775                                              &count_addresses, &cnt);
776     store_friend_hello = GNUNET_NO;
777     if (0 < cnt)
778     {
779       store_friend_hello = GNUNET_YES;
780       size += GNUNET_HELLO_size (host->friend_only_hello);
781     }
782
783     if ((GNUNET_NO == store_hello) && (GNUNET_NO == store_friend_hello))
784     {
785       /* no valid addresses, don't put HELLO on disk; in fact,
786          if one exists on disk, remove it */
787       (void) UNLINK (fn);
788     }
789     else
790     {
791       buffer = GNUNET_malloc (size);
792       pos = 0;
793
794       if (GNUNET_YES == store_hello)
795       {
796         memcpy (buffer, host->hello, GNUNET_HELLO_size (host->hello));
797         pos += GNUNET_HELLO_size (host->hello);
798       }
799       if (GNUNET_YES == store_friend_hello)
800       {
801         memcpy (&buffer[pos], host->friend_only_hello, GNUNET_HELLO_size (host->friend_only_hello));
802         pos += GNUNET_HELLO_size (host->friend_only_hello);
803       }
804       GNUNET_assert (pos == size);
805
806       if (GNUNET_SYSERR == GNUNET_DISK_fn_write (fn, buffer, size,
807                                                  GNUNET_DISK_PERM_USER_READ |
808                                                  GNUNET_DISK_PERM_USER_WRITE |
809                                                  GNUNET_DISK_PERM_GROUP_READ |
810                                                  GNUNET_DISK_PERM_OTHER_READ))
811         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
812       else
813         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stored %s %s HELLO in %s  with total size %u\n",
814                     (GNUNET_YES == store_friend_hello) ? "friend-only": "",
815                     (GNUNET_YES == store_hello) ? "public": "",
816                     fn, size);
817       GNUNET_free (buffer);
818     }
819   }
820   GNUNET_free_non_null (fn);
821   notify_all (host);
822 }
823
824
825 /**
826  * Do transmit info about peer to given host.
827  *
828  * @param cls NULL to hit all hosts, otherwise specifies a particular target
829  * @param key hostID
830  * @param value information to transmit
831  * @return GNUNET_YES (continue to iterate)
832  */
833 static int
834 add_to_tc (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
835 {
836   struct TransmitContext *tc = cls;
837   struct HostEntry *pos = value;
838   struct InfoMessage *im;
839   uint16_t hs;
840   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
841
842   hs = 0;
843   im = (struct InfoMessage *) buf;
844
845   if ((pos->hello != NULL) && (GNUNET_NO == tc->friend_only))
846   {
847         /* Copy public HELLO */
848     hs = GNUNET_HELLO_size (pos->hello);
849     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
850                    sizeof (struct InfoMessage));
851     memcpy (&im[1], pos->hello, hs);
852     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                 "Sending public HELLO with size %u for peer `%4s'\n",
854                 hs, GNUNET_i2s (key));
855   }
856   else if ((pos->friend_only_hello != NULL) && (GNUNET_YES == tc->friend_only))
857   {
858         /* Copy friend only HELLO */
859     hs = GNUNET_HELLO_size (pos->friend_only_hello);
860     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
861                    sizeof (struct InfoMessage));
862     memcpy (&im[1], pos->friend_only_hello, hs);
863     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864                 "Sending friend-only HELLO with size %u for peer `%4s'\n",
865                 hs, GNUNET_i2s (key));
866   }
867   else
868   {
869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870                   "Adding no HELLO for peer `%s'\n",
871                  GNUNET_i2s (key));
872   }
873
874   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
875   im->header.size = htons (sizeof (struct InfoMessage) + hs);
876   im->reserved = htonl (0);
877   im->peer = pos->identity;
878   GNUNET_SERVER_transmit_context_append_message (tc->tc, &im->header);
879   return GNUNET_YES;
880 }
881
882
883 /**
884  * @brief delete expired HELLO entries in directory
885  *
886  * @param cls pointer to current time (struct GNUNET_TIME_Absolute)
887  * @param fn filename to test to see if the HELLO expired
888  * @return GNUNET_OK (continue iteration)
889  */
890 static int
891 discard_hosts_helper (void *cls, const char *fn)
892 {
893   struct GNUNET_TIME_Absolute *now = cls;
894   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
895   const struct GNUNET_HELLO_Message *hello;
896   struct GNUNET_HELLO_Message *new_hello;
897   int read_size;
898   unsigned int cur_hello_size;
899   unsigned int new_hello_size;
900   int read_pos;
901   int write_pos;
902   unsigned int cnt;
903   char *writebuffer;
904
905
906   read_size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
907   if (read_size < sizeof (struct GNUNET_MessageHeader))
908   {
909     if (0 != UNLINK (fn))
910       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
911                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
912     return GNUNET_OK;
913   }
914
915   writebuffer = GNUNET_malloc (read_size);
916   read_pos = 0;
917   write_pos = 0;
918   while (read_pos < read_size)
919   {
920     /* Check each HELLO */
921     hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos];
922     cur_hello_size = GNUNET_HELLO_size (hello);
923     if (0 == cur_hello_size)
924     {
925       /* Invalid data, discard */
926       if (0 != UNLINK (fn))
927         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
928                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
929       return GNUNET_OK;
930     }
931     new_hello = GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now);
932     cnt = 0;
933     if (NULL != new_hello)
934       (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses, &cnt);
935     if ( (NULL != new_hello) && (0 < cnt) )
936     {
937       /* Store new HELLO to write it when done */
938       new_hello_size = GNUNET_HELLO_size (new_hello);
939       memcpy (&writebuffer[write_pos], new_hello, new_hello_size);
940       write_pos += new_hello_size;
941     }
942     read_pos += cur_hello_size;
943     GNUNET_free_non_null (new_hello);
944   }
945
946   if (0 < write_pos)
947   {
948       GNUNET_DISK_fn_write (fn, writebuffer,write_pos,
949                             GNUNET_DISK_PERM_USER_READ |
950                             GNUNET_DISK_PERM_USER_WRITE |
951                             GNUNET_DISK_PERM_GROUP_READ |
952                             GNUNET_DISK_PERM_OTHER_READ);
953   }
954   else if (0 != UNLINK (fn))
955     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
956                               GNUNET_ERROR_TYPE_BULK, "unlink", fn);
957
958   GNUNET_free (writebuffer);
959   return GNUNET_OK;
960 }
961
962
963 /**
964  * Call this method periodically to scan peerinfo/ for ancient
965  * HELLOs to expire.
966  *
967  * @param cls unused
968  * @param tc scheduler context, aborted if reason is shutdown
969  */
970 static void
971 cron_clean_data_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
972 {
973   struct GNUNET_TIME_Absolute now;
974
975   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
976     return;
977   now = GNUNET_TIME_absolute_get ();
978   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
979               _("Cleaning up directory `%s'\n"), networkIdDirectory);
980   GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now);
981   GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, &cron_clean_data_hosts,
982                                 NULL);
983 }
984
985
986 /**
987  * Handle HELLO-message.
988  *
989  * @param cls closure
990  * @param client identification of the client
991  * @param message the actual message
992  */
993 static void
994 handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
995               const struct GNUNET_MessageHeader *message)
996 {
997   const struct GNUNET_HELLO_Message *hello;
998   struct GNUNET_PeerIdentity pid;
999
1000   hello = (const struct GNUNET_HELLO_Message *) message;
1001   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
1002   {
1003     GNUNET_break (0);
1004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1005     return;
1006   }
1007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
1008               "HELLO", GNUNET_i2s (&pid));
1009   add_host_to_known_hosts (&pid);
1010   update_hello (&pid, hello);
1011   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1012 }
1013
1014
1015 /**
1016  * Handle GET-message.
1017  *
1018  * @param cls closure
1019  * @param client identification of the client
1020  * @param message the actual message
1021  */
1022 static void
1023 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
1024             const struct GNUNET_MessageHeader *message)
1025 {
1026   const struct ListPeerMessage *lpm;
1027   struct TransmitContext tcx;
1028
1029   lpm = (const struct ListPeerMessage *) message;
1030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
1031               "GET", GNUNET_i2s (&lpm->peer));
1032   tcx.friend_only = ntohl (lpm->include_friend_only);
1033   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
1034   GNUNET_CONTAINER_multipeermap_get_multiple (hostmap, &lpm->peer,
1035                                               &add_to_tc, &tcx);
1036   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
1037                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
1038   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
1039 }
1040
1041
1042 /**
1043  * Handle GET-ALL-message.
1044  *
1045  * @param cls closure
1046  * @param client identification of the client
1047  * @param message the actual message
1048  */
1049 static void
1050 handle_get_all (void *cls, struct GNUNET_SERVER_Client *client,
1051                 const struct GNUNET_MessageHeader *message)
1052 {
1053   const struct ListAllPeersMessage *lapm;
1054   struct TransmitContext tcx;
1055
1056   lapm = (const struct ListAllPeersMessage *) message;
1057   tcx.friend_only = ntohl (lapm->include_friend_only);
1058   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "GET_ALL");
1059   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
1060   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &add_to_tc, &tcx);
1061   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
1062                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
1063   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
1064 }
1065
1066
1067
1068 /**
1069  * Pass the given client the information we have in the respective
1070  * host entry; the client is already in the notification context.
1071  *
1072  * @param cls the 'struct GNUNET_SERVER_Client' to notify
1073  * @param key key for the value (unused)
1074  * @param value the 'struct HostEntry' to notify the client about
1075  * @return GNUNET_YES (always, continue to iterate)
1076  */
1077 static int
1078 do_notify_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1079 {
1080   struct NotificationContext *nc = cls;
1081   struct HostEntry *he = value;
1082   struct InfoMessage *msg;
1083
1084   if ((NULL == he->hello) && (GNUNET_NO == nc->include_friend_only))
1085   {
1086     /* We have no public hello  */
1087     return GNUNET_YES;
1088   }
1089
1090   if ( (NULL == he->friend_only_hello) &&
1091        (GNUNET_YES == nc->include_friend_only) )
1092   {
1093     /* We have no friend hello */
1094     return GNUNET_YES;
1095   }
1096
1097   msg = make_info_message (he, nc->include_friend_only);
1098   GNUNET_SERVER_notification_context_unicast (notify_list,
1099                                               nc->client,
1100                                               &msg->header,
1101                                               GNUNET_NO);
1102   GNUNET_free (msg);
1103   return GNUNET_YES;
1104 }
1105
1106
1107 /**
1108  * Handle NOTIFY-message.
1109  *
1110  * @param cls closure
1111  * @param client identification of the client
1112  * @param message the actual message
1113  */
1114 static void
1115 handle_notify (void *cls, struct GNUNET_SERVER_Client *client,
1116                const struct GNUNET_MessageHeader *message)
1117 {
1118   struct NotifyMessage *nm = (struct NotifyMessage *) message;
1119   struct NotificationContext *nc;
1120
1121   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1122               "`%s' message received\n",
1123               "NOTIFY");
1124   nc = GNUNET_malloc (sizeof (struct NotificationContext));
1125   nc->client = client;
1126   nc->include_friend_only = ntohl (nm->include_friend_only);
1127
1128   GNUNET_CONTAINER_DLL_insert (nc_head, nc_tail, nc);
1129   GNUNET_SERVER_client_mark_monitor (client);
1130         GNUNET_SERVER_notification_context_add (notify_list, client);
1131   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &do_notify_entry, nc);
1132   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1133 }
1134
1135
1136 /**
1137  * Client disconnect callback
1138  *
1139  * @param cls unused
1140  * @param client server client
1141  */
1142 static void
1143 disconnect_cb (void *cls,struct GNUNET_SERVER_Client *client)
1144 {
1145   struct NotificationContext *cur;
1146
1147   for (cur = nc_head; NULL != cur; cur = cur->next)
1148     if (cur->client == client)
1149       break;
1150   if (NULL == cur)
1151     return;
1152   GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1153   GNUNET_free (cur);
1154 }
1155
1156
1157 /**
1158  * Release memory taken by a host entry.
1159  *
1160  * @param cls NULL
1161  * @param key key of the host entry
1162  * @param value the 'struct HostEntry' to free
1163  * @return GNUNET_YES (continue to iterate)
1164  */
1165 static int
1166 free_host_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1167 {
1168   struct HostEntry *he = value;
1169
1170   GNUNET_free_non_null (he->hello);
1171   GNUNET_free_non_null (he->friend_only_hello);
1172   GNUNET_free (he);
1173   return GNUNET_YES;
1174 }
1175
1176
1177 /**
1178  * Clean up our state.  Called during shutdown.
1179  *
1180  * @param cls unused
1181  * @param tc scheduler task context, unused
1182  */
1183 static void
1184 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1185 {
1186   struct NotificationContext *cur;
1187   struct NotificationContext *next;
1188
1189   GNUNET_SERVER_notification_context_destroy (notify_list);
1190   notify_list = NULL;
1191
1192   for (cur = nc_head; NULL != cur; cur = next)
1193   {
1194     next = cur->next;
1195     GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1196     GNUNET_free (cur);
1197   }
1198   GNUNET_CONTAINER_multipeermap_iterate (hostmap, &free_host_entry, NULL);
1199   GNUNET_CONTAINER_multipeermap_destroy (hostmap);
1200   if (NULL != stats)
1201   {
1202     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1203     stats = NULL;
1204   }
1205 }
1206
1207
1208 /**
1209  * Start up peerinfo service.
1210  *
1211  * @param cls closure
1212  * @param server the initialized server
1213  * @param cfg configuration to use
1214  */
1215 static void
1216 run (void *cls, struct GNUNET_SERVER_Handle *server,
1217      const struct GNUNET_CONFIGURATION_Handle *cfg)
1218 {
1219   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1220     {&handle_hello, NULL, GNUNET_MESSAGE_TYPE_HELLO, 0},
1221     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
1222      sizeof (struct ListPeerMessage)},
1223     {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
1224      sizeof (struct ListAllPeersMessage)},
1225     {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
1226      sizeof (struct NotifyMessage)},
1227     {NULL, NULL, 0, 0}
1228   };
1229   char *peerdir;
1230   char *ip;
1231   struct DirScanContext dsc;
1232   int noio;
1233   int use_included;
1234
1235   hostmap = GNUNET_CONTAINER_multipeermap_create (1024, GNUNET_YES);
1236   stats = GNUNET_STATISTICS_create ("peerinfo", cfg);
1237   notify_list = GNUNET_SERVER_notification_context_create (server, 0);
1238   noio = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "NO_IO");
1239   use_included = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "USE_INCLUDED_HELLOS");
1240   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1241                                 NULL);
1242   if (GNUNET_YES != noio)
1243   {
1244     GNUNET_assert (GNUNET_OK ==
1245                    GNUNET_CONFIGURATION_get_value_filename (cfg, "peerinfo",
1246                                                             "HOSTS",
1247                                                             &networkIdDirectory));
1248     if (GNUNET_OK !=
1249         GNUNET_DISK_directory_create (networkIdDirectory))
1250     {
1251       GNUNET_SCHEDULER_shutdown ();
1252       return;
1253     }
1254
1255     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1256                                         &cron_scan_directory_data_hosts, NULL);
1257
1258     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1259                                         &cron_clean_data_hosts, NULL);
1260     if (GNUNET_YES == use_included)
1261     {
1262         ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
1263         GNUNET_asprintf (&peerdir,
1264                      "%shellos",
1265                      ip);
1266         GNUNET_free (ip);
1267
1268                         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1269                         _("Importing HELLOs from `%s'\n"),
1270                         peerdir);
1271                         dsc.matched = 0;
1272                         dsc.remove_files = GNUNET_NO;
1273
1274                         GNUNET_DISK_directory_scan (peerdir,
1275                                         &hosts_directory_scan_callback, &dsc);
1276
1277                         GNUNET_free (peerdir);
1278     }
1279   }
1280   GNUNET_SERVER_add_handlers (server, handlers);
1281   GNUNET_SERVER_disconnect_notify (server, &disconnect_cb, NULL) ;
1282 }
1283
1284
1285 /**
1286  * The main function for the peerinfo service.
1287  *
1288  * @param argc number of arguments from the command line
1289  * @param argv command line arguments
1290  * @return 0 ok, 1 on error
1291  */
1292 int
1293 main (int argc, char *const *argv)
1294 {
1295   int ret;
1296
1297   ret =
1298       (GNUNET_OK ==
1299        GNUNET_SERVICE_run (argc, argv, "peerinfo", GNUNET_SERVICE_OPTION_NONE,
1300                            &run, NULL)) ? 0 : 1;
1301   GNUNET_free_non_null (networkIdDirectory);
1302   return ret;
1303 }
1304
1305
1306 /* end of gnunet-service-peerinfo.c */