initial changes to support 2 hellos
[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_MultiHashMap *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 (data/hosts)
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  * @return generated notification message
173  */
174 static struct InfoMessage *
175 make_info_message (const struct HostEntry *he, int include_friend_only)
176 {
177   struct InfoMessage *im;
178   struct GNUNET_HELLO_Message *src;
179   size_t hs;
180
181   if (GNUNET_YES == include_friend_only)
182         src = he->friend_only_hello;
183   else
184         src = he->hello;
185
186   hs = (NULL == src) ? 0 : GNUNET_HELLO_size (src);
187   im = GNUNET_malloc (sizeof (struct InfoMessage) + hs);
188   im->header.size = htons (hs + sizeof (struct InfoMessage));
189   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
190   im->peer = he->identity;
191   if (NULL != src)
192     memcpy (&im[1], src, hs);
193   return im;
194 }
195
196
197 /**
198  * Address iterator that causes expired entries to be discarded.
199  *
200  * @param cls pointer to the current time
201  * @param address the address
202  * @param expiration expiration time for the address
203  * @return GNUNET_NO if expiration smaller than the current time
204  */
205 static int
206 discard_expired (void *cls, const struct GNUNET_HELLO_Address *address,
207                  struct GNUNET_TIME_Absolute expiration)
208 {
209   const struct GNUNET_TIME_Absolute *now = cls;
210
211   if (now->abs_value > expiration.abs_value)
212   {
213     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
214                 _("Removing expired address of transport `%s'\n"),
215                 address->transport_name);
216     return GNUNET_NO;
217   }
218   return GNUNET_OK;
219 }
220
221
222 /**
223  * Address iterator that counts the remaining addresses.
224  *
225  * @param cls pointer to the counter
226  * @param address the address
227  * @param expiration expiration time for the address
228  * @return GNUNET_OK (always)
229  */
230 static int
231 count_addresses (void *cls, const struct GNUNET_HELLO_Address *address,
232                  struct GNUNET_TIME_Absolute expiration)
233 {
234   unsigned int *cnt = cls;
235
236   (*cnt)++;
237   return GNUNET_OK;
238 }
239
240
241 /**
242  * Get the filename under which we would store the GNUNET_HELLO_Message
243  * for the given host and protocol.
244  *
245  * @param id peer for which we need the filename for the HELLO
246  * @return filename of the form DIRECTORY/HOSTID
247  */
248 static char *
249 get_host_filename (const struct GNUNET_PeerIdentity *id)
250 {
251   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
252   char *fn;
253
254   if (NULL == networkIdDirectory)
255     return NULL;
256   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
257   GNUNET_asprintf (&fn, "%s%s%s", networkIdDirectory, DIR_SEPARATOR_STR, &fil);
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
278         for (cur = nc_head; NULL != cur; cur = cur->next)
279         {
280                 if (GNUNET_NO == cur->include_friend_only)
281                         GNUNET_SERVER_notification_context_unicast (notify_list,
282                                                                                                                                                                                                         cur->client,
283                                                                                                                                                                                                         &msg_pub->header,
284                                                                                                                                                                                                         GNUNET_NO);
285                 if (GNUNET_YES == cur->include_friend_only)
286                         GNUNET_SERVER_notification_context_unicast (notify_list,
287                                                                                                                                                                                                         cur->client,
288                                                                                                                                                                                                         &msg_friend->header,
289                                                                                                                                                                                                         GNUNET_NO);
290         }
291   GNUNET_free (msg_pub);
292   GNUNET_free (msg_friend);
293 }
294
295
296 /**
297  * Try to read the HELLOs in the given filename and discard expired
298  * addresses.  Removes the file if one the HELLO is mal-formed.  If all
299  * addresses are expired, the HELLO is also removed (but the HELLO
300  * with the public key is still returned if it was found and valid).
301  * 
302  * @param fn name of the file
303  * @param unlink_garbage if GNUNET_YES, try to remove useless files
304  */
305 static void
306 read_host_file (const char *fn, int unlink_garbage, struct ReadHostFileContext *r)
307 {
308   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
309   const struct GNUNET_HELLO_Message *hello_1st;
310   const struct GNUNET_HELLO_Message *hello_2nd;
311   struct GNUNET_HELLO_Message *hello_clean_1st;
312   struct GNUNET_HELLO_Message *hello_clean_2nd;
313   int size_1st;
314   int size_2nd;
315   int size_total;
316   struct GNUNET_TIME_Absolute now;
317   unsigned int left;
318
319   hello_1st = NULL;
320   hello_2nd = NULL;
321   hello_clean_1st = NULL;
322   hello_clean_2nd = NULL;
323   size_1st = 0;
324   size_2nd = 0;
325   size_total = 0;
326   r->friend_only_hello = NULL;
327   r->hello = NULL;
328
329   if (GNUNET_YES != GNUNET_DISK_file_test (fn))
330     return;
331
332   size_total = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
333   if (size_total < sizeof (struct GNUNET_MessageHeader))
334   {
335             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
336                                                                         _("Failed to parse HELLO in file `%s': %s\n"),
337                                                                         fn, "Fail has invalid size");
338     if ( (GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)) )
339       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
340     return;
341   }
342
343   hello_1st = (const struct GNUNET_HELLO_Message *) buffer;
344   size_1st = ntohs (((const struct GNUNET_MessageHeader *) hello_1st)->size);
345   if ((size_1st < sizeof (struct GNUNET_MessageHeader)) ||
346                 (size_1st != GNUNET_HELLO_size (hello_1st)))
347   {
348             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
349                                                                         _("Failed to parse HELLO in file `%s': %s\n"),
350                                                                         fn, "1nd HELLO has wrong size");
351     if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
352       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
353     return;
354   }
355
356   if (size_total > size_1st)
357   {
358                 hello_2nd = (const struct GNUNET_HELLO_Message *) &buffer[size_1st];
359                 size_2nd = ntohs (((const struct GNUNET_MessageHeader *) hello_2nd)->size);
360           if ((size_2nd < sizeof (struct GNUNET_MessageHeader)) ||
361                         (size_2nd != GNUNET_HELLO_size (hello_2nd)))
362           {
363             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
364                                                                                 _("Failed to parse HELLO in file `%s': %s\n"),
365                                                                                 fn, "2nd HELLO has wrong size");
366             if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
367               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
368             return;
369           }
370   }
371
372   if (size_total != (size_1st + size_2nd))
373   {
374             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
375                                                         _("Failed to parse HELLO in file `%s': %s\n"),
376                                                         fn, "Multiple HELLOs but total size is wrong");
377             if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
378               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
379             return;
380   }
381
382   now = GNUNET_TIME_absolute_get ();
383
384   hello_clean_1st = GNUNET_HELLO_iterate_addresses (hello_1st, GNUNET_YES,
385                                                                                                                                                                                                   &discard_expired, &now);
386   left = 0;
387   (void) GNUNET_HELLO_iterate_addresses (hello_1st, GNUNET_NO,
388                                                                                                                                                          &count_addresses, &left);
389   if (0 == left)
390   {
391     /* no addresses left, remove from disk */
392     if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
393       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
394   }
395
396   if (GNUNET_NO == GNUNET_HELLO_is_friend_only(hello_clean_1st))
397         r->hello = hello_clean_1st;
398   else
399         r->friend_only_hello = hello_clean_1st;
400
401   if (NULL != hello_2nd)
402   {
403           hello_clean_2nd = GNUNET_HELLO_iterate_addresses (hello_2nd, GNUNET_YES,
404                                                                                                                                                                                                           &discard_expired, &now);
405           left = 0;
406           (void) GNUNET_HELLO_iterate_addresses (hello_2nd, GNUNET_NO,
407                                                                                                                                                                  &count_addresses, &left);
408           if (0 == left)
409           {
410             /* no addresses left, remove from disk */
411             if ((GNUNET_YES == unlink_garbage) && (0 != UNLINK (fn)))
412               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
413           }
414
415           if (GNUNET_NO == GNUNET_HELLO_is_friend_only(hello_clean_2nd))
416                 r->hello = hello_clean_2nd;
417           else
418                 r->friend_only_hello = hello_clean_2nd;
419   }
420 }
421
422
423 /**
424  * Add a host to the list.
425  *
426  * @param identity the identity of the host
427  */
428 static void
429 add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity)
430 {
431   struct HostEntry *entry;
432   struct ReadHostFileContext r;
433   char *fn;
434
435   entry = GNUNET_CONTAINER_multihashmap_get (hostmap, &identity->hashPubKey);
436   if (NULL != entry)
437     return;
438   GNUNET_STATISTICS_update (stats, gettext_noop ("# peers known"), 1,
439                             GNUNET_NO);
440   entry = GNUNET_malloc (sizeof (struct HostEntry));
441   entry->identity = *identity;
442   GNUNET_CONTAINER_multihashmap_put (hostmap, &entry->identity.hashPubKey, entry,
443                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
444   fn = get_host_filename (identity);
445   if (NULL != fn)
446   {
447     read_host_file (fn, GNUNET_YES, &r);
448     entry->hello = r.hello;
449     entry->hello = r.friend_only_hello;
450     GNUNET_free (fn);
451   }
452   notify_all (entry);
453 }
454
455
456 /**
457  * Remove a file that should not be there.  LOG
458  * success or failure.
459  *
460  * @param fullname name of the file to remove
461  */
462 static void
463 remove_garbage (const char *fullname)
464 {
465   if (0 == UNLINK (fullname))
466     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
467                 _
468                 ("File `%s' in directory `%s' does not match naming convention. "
469                  "Removed.\n"), fullname, networkIdDirectory);
470   else
471     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
472                               "unlink", fullname);
473 }
474
475
476 /**
477  * Closure for 'hosts_directory_scan_callback'.
478  */
479 struct DirScanContext
480 {
481   /**
482    * GNUNET_YES if we should remove files that are broken,
483    * GNUNET_NO if the directory we are iterating over should
484    * be treated as read-only by us.
485    */ 
486   int remove_files;
487
488   /**
489    * Counter for the number of (valid) entries found, incremented
490    * by one for each match.
491    */
492   unsigned int matched;
493 };
494
495
496 /**
497  * Function that is called on each HELLO file in a particular directory.
498  * Try to parse the file and add the HELLO to our list.
499  *
500  * @param cls pointer to 'unsigned int' to increment for each file, or NULL
501  *            if the file is from a read-only, read-once resource directory
502  * @param fullname name of the file to parse
503  * @return GNUNET_OK (continue iteration)
504  */
505 static int
506 hosts_directory_scan_callback (void *cls, const char *fullname)
507 {
508   struct DirScanContext *dsc = cls;
509   struct GNUNET_PeerIdentity identity;
510   struct ReadHostFileContext r;
511   const char *filename;
512   struct HostEntry *entry;
513   struct GNUNET_PeerIdentity id_public;
514   struct GNUNET_PeerIdentity id_friend;
515
516   if (GNUNET_YES != GNUNET_DISK_file_test (fullname))
517     return GNUNET_OK;           /* ignore non-files */
518   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
519   {
520     if (GNUNET_YES == dsc->remove_files)
521       remove_garbage (fullname);
522     return GNUNET_OK;
523   }
524   filename =
525       &fullname[strlen (fullname) -
526                 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1];
527   if (DIR_SEPARATOR != filename[-1])
528   {
529     if (GNUNET_YES == dsc->remove_files)
530       remove_garbage (fullname);
531     return GNUNET_OK;
532   }
533   if (GNUNET_OK !=
534       GNUNET_CRYPTO_hash_from_string (filename, &identity.hashPubKey))
535   {
536     /* odd filename, but might still be valid, try getting identity from HELLO */
537         read_host_file (filename, dsc->remove_files, &r);
538         if ( ((NULL != r.hello) &&
539                                 (GNUNET_OK == GNUNET_HELLO_get_id (r.hello, &id_public))) ||
540                          ((NULL != r.friend_only_hello) &&
541                                 (GNUNET_OK == GNUNET_HELLO_get_id (r.friend_only_hello, &id_friend))) )
542         {
543                         if ( (NULL != r.hello) && (NULL != r.friend_only_hello) &&
544                                         (0 != memcmp (&id_friend, &id_public, sizeof (id_friend))) )
545                         {
546                                 /* HELLOs are not for the same peer */
547                                 GNUNET_break (0);
548                                 if (GNUNET_YES == dsc->remove_files)
549                                         remove_garbage (fullname);
550                                 return GNUNET_OK;
551                         }
552
553                         /* ok, found something valid, remember HELLO */
554       entry = GNUNET_malloc (sizeof (struct HostEntry));
555       entry->identity = id_friend;
556       GNUNET_CONTAINER_multihashmap_put (hostmap, &entry->identity.hashPubKey, entry,
557                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
558       entry->hello = r.hello;
559                         entry->hello = r.friend_only_hello;
560                         notify_all (entry);
561                         dsc->matched++;
562
563       return GNUNET_OK;   
564     }
565     if (GNUNET_YES == dsc->remove_files)
566       remove_garbage (fullname);
567     return GNUNET_OK;
568   }
569   dsc->matched++;
570   add_host_to_known_hosts (&identity);
571   return GNUNET_OK;
572 }
573
574
575 /**
576  * Call this method periodically to scan data/hosts for new hosts.
577  *
578  * @param cls unused
579  * @param tc scheduler context, aborted if reason is shutdown
580  */
581 static void
582 cron_scan_directory_data_hosts (void *cls,
583                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
584 {
585   static unsigned int retries;
586   struct DirScanContext dsc;
587
588   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
589     return;
590   if (GNUNET_SYSERR == GNUNET_DISK_directory_create (networkIdDirectory))
591   {
592     GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ,
593                                                 GNUNET_SCHEDULER_PRIORITY_IDLE,
594                                                 &cron_scan_directory_data_hosts, NULL);
595     return;
596   }
597   dsc.matched = 0;
598   dsc.remove_files = GNUNET_YES;
599   GNUNET_DISK_directory_scan (networkIdDirectory,
600                               &hosts_directory_scan_callback, &dsc);
601   if ((0 == dsc.matched) && (0 == (++retries & 31)))
602     GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
603                 _("Still no peers found in `%s'!\n"), networkIdDirectory);
604   GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ, 
605                                               GNUNET_SCHEDULER_PRIORITY_IDLE,
606                                               &cron_scan_directory_data_hosts,
607                                               NULL);
608 }
609
610
611 static struct GNUNET_HELLO_Message *
612 update_friend_hello (const struct GNUNET_HELLO_Message *hello,
613                                                                                  const struct GNUNET_HELLO_Message *friend_hello)
614 {
615         struct GNUNET_HELLO_Message * res;
616         struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pk;
617
618         if (NULL != friend_hello)
619         {
620                 res = GNUNET_HELLO_merge (hello, friend_hello);
621                 GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
622                 return res;
623         }
624
625         GNUNET_HELLO_get_key (hello, &pk);
626         res = GNUNET_HELLO_create (&pk, NULL, NULL, GNUNET_YES);
627         res = GNUNET_HELLO_merge (hello, res);
628         GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res));
629         return res;
630 }
631
632
633
634 /**
635  * Bind a host address (hello) to a hostId.
636  *
637  * @param peer the peer for which this is a hello
638  * @param hello the verified (!) hello message
639  */
640 static void
641 bind_address (const struct GNUNET_PeerIdentity *peer,
642               const struct GNUNET_HELLO_Message *hello)
643 {
644   char *fn;
645   struct HostEntry *host;
646   struct GNUNET_HELLO_Message *mrg;
647   struct GNUNET_HELLO_Message **dest;
648   struct GNUNET_TIME_Absolute delta;
649   unsigned int cnt;
650   int friend_hello_type;
651
652   add_host_to_known_hosts (peer);
653   host = GNUNET_CONTAINER_multihashmap_get (hostmap, &peer->hashPubKey);
654   GNUNET_assert (NULL != host);
655   friend_hello_type = GNUNET_HELLO_is_friend_only (hello);
656
657   dest = NULL;
658   if (GNUNET_YES == friend_hello_type)
659   {
660         dest = &host->friend_only_hello;
661   }
662   else
663   {
664         dest = &host->hello;
665   }
666
667   if (NULL == (*dest))
668   {
669         (*dest) = GNUNET_malloc (GNUNET_HELLO_size (hello));
670     memcpy ((*dest), hello, GNUNET_HELLO_size (hello));
671   }
672   else
673   {
674     mrg = GNUNET_HELLO_merge ((*dest), hello);
675     delta = GNUNET_HELLO_equals (mrg, (*dest), GNUNET_TIME_absolute_get ());
676     if (delta.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
677     {
678       /* no differences, just ignore the update */
679       GNUNET_free (mrg);
680       return;
681     }
682     GNUNET_free ((*dest));
683     (*dest) = mrg;
684   }
685
686   if ((NULL != (host->hello)) && (GNUNET_NO == friend_hello_type))
687                 host->friend_only_hello = update_friend_hello (host->hello,  host->friend_only_hello);
688
689         fn = get_host_filename (peer);
690         if ( (NULL != fn) &&
691                          (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn)) )
692                 {
693 #if 0
694                         cnt = 0;
695                         (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses,
696                                                          &cnt);
697                         if (0 == cnt)
698                         {
699                                 /* no valid addresses, don't put HELLO on disk; in fact,
700                  if one exists on disk, remove it */
701                                 (void) UNLINK (fn);
702                         }
703                         else
704                         {
705                                 if (GNUNET_SYSERR ==
706                         GNUNET_DISK_fn_write (fn, host->hello, GNUNET_HELLO_size (host->hello),
707                                         GNUNET_DISK_PERM_USER_READ |
708                                         GNUNET_DISK_PERM_USER_WRITE |
709                                         GNUNET_DISK_PERM_GROUP_READ |
710                                         GNUNET_DISK_PERM_OTHER_READ))
711                 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
712                         }
713                 }
714 #endif
715                 GNUNET_free_non_null (fn);
716   }
717
718   notify_all (host);
719 }
720
721
722 /**
723  * Do transmit info about peer to given host.
724  *
725  * @param cls NULL to hit all hosts, otherwise specifies a particular target
726  * @param key hostID
727  * @param value information to transmit
728  * @return GNUNET_YES (continue to iterate)
729  */
730 static int
731 add_to_tc (void *cls, const struct GNUNET_HashCode * key, void *value)
732 {
733   struct TransmitContext *tc = cls;
734   struct HostEntry *pos = value;
735   struct InfoMessage *im;
736   uint16_t hs;
737   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
738
739   hs = 0;
740   im = (struct InfoMessage *) buf;
741
742   if ((pos->hello != NULL) && (GNUNET_NO == tc->friend_only))
743   {
744         /* Copy public HELLO */
745     hs = GNUNET_HELLO_size (pos->hello);
746     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
747                    sizeof (struct InfoMessage));
748     memcpy (&im[1], pos->hello, hs);
749
750   }
751
752   if ((pos->friend_only_hello != NULL) && (GNUNET_YES == tc->friend_only))
753   {
754         /* Copy friend only HELLO */
755     hs = GNUNET_HELLO_size (pos->friend_only_hello);
756     GNUNET_assert (hs < GNUNET_SERVER_MAX_MESSAGE_SIZE -
757                    sizeof (struct InfoMessage));
758     memcpy (&im[1], pos->friend_only_hello, hs);
759
760   }
761   im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO);
762   im->header.size = htons (sizeof (struct InfoMessage) + hs);
763   im->reserved = htonl (0);
764   im->peer = pos->identity;
765   GNUNET_SERVER_transmit_context_append_message (tc->tc, &im->header);
766   return GNUNET_YES;
767 }
768
769
770 /**
771  * @brief delete expired HELLO entries in directory
772  *
773  * @param cls pointer to current time (struct GNUNET_TIME_Absolute)
774  * @param fn filename to test to see if the HELLO expired
775  * @return GNUNET_OK (continue iteration)
776  */
777 static int
778 discard_hosts_helper (void *cls, const char *fn)
779 {
780   struct GNUNET_TIME_Absolute *now = cls;
781   char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
782   const struct GNUNET_HELLO_Message *hello;
783   struct GNUNET_HELLO_Message *new_hello;
784   int size;
785   unsigned int cnt;
786
787   size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
788   if (size < sizeof (struct GNUNET_MessageHeader))
789   {
790     if (0 != UNLINK (fn))
791       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
792                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
793     return GNUNET_OK;
794   }
795   hello = (const struct GNUNET_HELLO_Message *) buffer;
796   new_hello =
797     GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now);
798   cnt = 0;
799   if (NULL != new_hello)
800     (void) GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_addresses, &cnt);
801   if ( (NULL != new_hello) && (0 < cnt) )
802   {
803     GNUNET_DISK_fn_write (fn, new_hello, GNUNET_HELLO_size (new_hello),
804                           GNUNET_DISK_PERM_USER_READ |
805                           GNUNET_DISK_PERM_USER_WRITE |
806                           GNUNET_DISK_PERM_GROUP_READ |
807                           GNUNET_DISK_PERM_OTHER_READ);
808   }
809   else
810   {
811     if (0 != UNLINK (fn))
812       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
813                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
814   }
815   GNUNET_free_non_null (new_hello);
816   return GNUNET_OK;
817 }
818
819
820 /**
821  * Call this method periodically to scan data/hosts for ancient
822  * HELLOs to expire.
823  *
824  * @param cls unused
825  * @param tc scheduler context, aborted if reason is shutdown
826  */
827 static void
828 cron_clean_data_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
829 {
830   struct GNUNET_TIME_Absolute now;
831
832   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
833     return;
834   now = GNUNET_TIME_absolute_get ();
835   GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now);
836   GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, &cron_clean_data_hosts,
837                                 NULL);
838 }
839
840
841 /**
842  * Handle HELLO-message.
843  *
844  * @param cls closure
845  * @param client identification of the client
846  * @param message the actual message
847  */
848 static void
849 handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
850               const struct GNUNET_MessageHeader *message)
851 {
852   const struct GNUNET_HELLO_Message *hello;
853   struct GNUNET_PeerIdentity pid;
854
855   hello = (const struct GNUNET_HELLO_Message *) message;
856   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
857   {
858     GNUNET_break (0);
859     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
860     return;
861   }
862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
863               "HELLO", GNUNET_i2s (&pid));
864   bind_address (&pid, hello);
865   GNUNET_SERVER_receive_done (client, GNUNET_OK);
866 }
867
868
869 /**
870  * Handle GET-message.
871  *
872  * @param cls closure
873  * @param client identification of the client
874  * @param message the actual message
875  */
876 static void
877 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
878             const struct GNUNET_MessageHeader *message)
879 {
880   const struct ListPeerMessage *lpm;
881   struct TransmitContext tcx;
882
883   lpm = (const struct ListPeerMessage *) message;
884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received for peer `%4s'\n",
885               "GET", GNUNET_i2s (&lpm->peer));
886   tcx.friend_only = ntohl (lpm->include_friend_only);
887   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
888   GNUNET_CONTAINER_multihashmap_get_multiple (hostmap, &lpm->peer.hashPubKey,
889                                               &add_to_tc, &tcx);
890   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
891                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
892   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
893 }
894
895
896 /**
897  * Handle GET-ALL-message.
898  *
899  * @param cls closure
900  * @param client identification of the client
901  * @param message the actual message
902  */
903 static void
904 handle_get_all (void *cls, struct GNUNET_SERVER_Client *client,
905                 const struct GNUNET_MessageHeader *message)
906 {
907   const struct ListAllPeersMessage *lapm;
908   struct TransmitContext tcx;
909
910   lapm = (const struct ListAllPeersMessage *) message;
911   tcx.friend_only = ntohl (lapm->include_friend_only);
912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "GET_ALL");
913   tcx.tc = GNUNET_SERVER_transmit_context_create (client);
914   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &add_to_tc, &tcx);
915   GNUNET_SERVER_transmit_context_append_data (tcx.tc, NULL, 0,
916                                               GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END);
917   GNUNET_SERVER_transmit_context_run (tcx.tc, GNUNET_TIME_UNIT_FOREVER_REL);
918 }
919
920
921
922 /**
923  * Pass the given client the information we have in the respective
924  * host entry; the client is already in the notification context.
925  *
926  * @param cls the 'struct GNUNET_SERVER_Client' to notify
927  * @param key key for the value (unused)
928  * @param value the 'struct HostEntry' to notify the client about
929  * @return GNUNET_YES (always, continue to iterate)
930  */
931 static int
932 do_notify_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
933 {
934         struct NotificationContext *nc = cls;
935   struct HostEntry *he = value;
936   struct InfoMessage *msg;
937
938
939         if ((NULL == he->hello) && (GNUNET_NO == nc->include_friend_only))
940         {
941                 /* We have no public hello  */
942           return GNUNET_YES;
943         }
944
945
946         if ((NULL == he->friend_only_hello) && GNUNET_YES == nc->include_friend_only)
947         {
948                 /* We have no friend hello */
949           return GNUNET_YES;
950         }
951
952         msg = make_info_message (he, nc->include_friend_only);
953         GNUNET_SERVER_notification_context_unicast (notify_list,
954                         nc->client,
955                         &msg->header,
956                         GNUNET_NO);
957   GNUNET_free (msg);
958   return GNUNET_YES;
959 }
960
961
962 /**
963  * Handle NOTIFY-message.
964  *
965  * @param cls closure
966  * @param client identification of the client
967  * @param message the actual message
968  */
969 static void
970 handle_notify (void *cls, struct GNUNET_SERVER_Client *client,
971                const struct GNUNET_MessageHeader *message)
972 {
973   struct NotifyMessage *nm = (struct NotifyMessage *) message;
974   struct NotificationContext *nc;
975
976         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' message received\n", "NOTIFY");
977
978         nc = GNUNET_malloc (sizeof (struct NotificationContext));
979         nc->client = client;
980         nc->include_friend_only = ntohl (nm->include_friend_only);
981
982         GNUNET_CONTAINER_DLL_insert (nc_head, nc_tail, nc);
983   GNUNET_SERVER_client_mark_monitor (client);
984         GNUNET_SERVER_notification_context_add (notify_list, client);
985   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &do_notify_entry, nc);
986   GNUNET_SERVER_receive_done (client, GNUNET_OK);
987 }
988
989
990 /**
991  * Client disconnect callback
992  *
993  * @param cls unused
994  * @param client server client
995  */
996 static void disconnect_cb (void *cls,struct GNUNET_SERVER_Client *client)
997 {
998         struct NotificationContext *cur;
999
1000         for (cur = nc_head; NULL != cur; cur = cur->next)
1001                 if (cur->client == client)
1002                         break;
1003
1004         if (NULL == cur)
1005                 return;
1006
1007         GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1008         GNUNET_free (cur);
1009 }
1010
1011
1012 /**
1013  * Release memory taken by a host entry.
1014  *
1015  * @param cls NULL
1016  * @param key key of the host entry
1017  * @param value the 'struct HostEntry' to free
1018  * @return GNUNET_YES (continue to iterate)
1019  */
1020 static int
1021 free_host_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
1022 {
1023   struct HostEntry *he = value;
1024
1025   GNUNET_free_non_null (he->hello);
1026   GNUNET_free_non_null (he->friend_only_hello);
1027   GNUNET_free (he);
1028   return GNUNET_YES;
1029 }
1030
1031
1032 /**
1033  * Clean up our state.  Called during shutdown.
1034  *
1035  * @param cls unused
1036  * @param tc scheduler task context, unused
1037  */
1038 static void
1039 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1040 {
1041         struct NotificationContext *cur;
1042         struct NotificationContext *next;
1043         GNUNET_SERVER_notification_context_destroy (notify_list);
1044   notify_list = NULL;
1045
1046         for (cur = nc_head; NULL != cur; cur = next)
1047         {
1048                         next = cur->next;
1049                         GNUNET_CONTAINER_DLL_remove (nc_head, nc_tail, cur);
1050                         GNUNET_free (cur);
1051         }
1052
1053   GNUNET_CONTAINER_multihashmap_iterate (hostmap, &free_host_entry, NULL);
1054   GNUNET_CONTAINER_multihashmap_destroy (hostmap);
1055   if (NULL != stats)
1056   {
1057     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1058     stats = NULL;
1059   }
1060 }
1061
1062
1063 /**
1064  * Start up peerinfo service.
1065  *
1066  * @param cls closure
1067  * @param server the initialized server
1068  * @param cfg configuration to use
1069  */
1070 static void
1071 run (void *cls, struct GNUNET_SERVER_Handle *server,
1072      const struct GNUNET_CONFIGURATION_Handle *cfg)
1073 {
1074   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1075     {&handle_hello, NULL, GNUNET_MESSAGE_TYPE_HELLO, 0},
1076     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET,
1077      sizeof (struct ListPeerMessage)},
1078     {&handle_get_all, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL,
1079      sizeof (struct ListAllPeersMessage)},
1080     {&handle_notify, NULL, GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY,
1081      sizeof (struct NotifyMessage)},
1082     {NULL, NULL, 0, 0}
1083   };
1084   char *peerdir;
1085   char *ip;
1086   struct DirScanContext dsc;
1087   int noio;
1088
1089   hostmap = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1090   stats = GNUNET_STATISTICS_create ("peerinfo", cfg);
1091   notify_list = GNUNET_SERVER_notification_context_create (server, 0);
1092   noio = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "NO_IO");
1093   if (GNUNET_YES != noio)
1094   {
1095     GNUNET_assert (GNUNET_OK ==
1096                    GNUNET_CONFIGURATION_get_value_filename (cfg, "peerinfo",
1097                                                             "HOSTS",
1098                                                             &networkIdDirectory));
1099     GNUNET_DISK_directory_create (networkIdDirectory);
1100     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1101                                         &cron_scan_directory_data_hosts, NULL);
1102     GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1103                                         &cron_clean_data_hosts, NULL);
1104     ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
1105     GNUNET_asprintf (&peerdir,
1106                      "%shellos",
1107                      ip);
1108     GNUNET_free (ip);
1109     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1110                 _("Importing HELLOs from `%s'\n"),
1111                 peerdir);
1112     dsc.matched = 0;
1113     dsc.remove_files = GNUNET_NO;
1114     GNUNET_DISK_directory_scan (peerdir,
1115                                 &hosts_directory_scan_callback, &dsc);
1116     GNUNET_free (peerdir);
1117   }
1118   GNUNET_SERVER_add_handlers (server, handlers);
1119   GNUNET_SERVER_disconnect_notify (server, &disconnect_cb, NULL) ;
1120   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1121                                 NULL);
1122
1123 }
1124
1125
1126 /**
1127  * The main function for the peerinfo service.
1128  *
1129  * @param argc number of arguments from the command line
1130  * @param argv command line arguments
1131  * @return 0 ok, 1 on error
1132  */
1133 int
1134 main (int argc, char *const *argv)
1135 {
1136   int ret;
1137
1138   ret =
1139       (GNUNET_OK ==
1140        GNUNET_SERVICE_run (argc, argv, "peerinfo", GNUNET_SERVICE_OPTION_NONE,
1141                            &run, NULL)) ? 0 : 1;
1142   GNUNET_free_non_null (networkIdDirectory);
1143   return ret;
1144 }
1145
1146
1147 /* end of gnunet-service-peerinfo.c */