make dist related fixes
[oweals/gnunet.git] / src / hostlist / hostlist-client.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2010 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 2, 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 hostlist/hostlist-client.c
23  * @brief hostlist support.  Downloads HELLOs via HTTP.
24  * @author Christian Grothoff
25  * @author Matthias Wachs
26  */
27
28 #include "platform.h"
29 #include "hostlist-client.h"
30 #include "gnunet_core_service.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet-daemon-hostlist.h"
35 #include <curl/curl.h>
36 #include "gnunet_common.h"
37 #include "gnunet_bio_lib.h"
38
39 #define DEBUG_HOSTLIST_CLIENT GNUNET_YES
40
41 #define MAX_URL_LEN 1000
42
43 /**
44  * Number of connections that we must have to NOT download
45  * hostlists anymore.
46  */
47 #define MIN_CONNECTIONS 4
48
49 /**
50  * A single hostlist obtained by hostlist advertisements
51  */
52 struct Hostlist
53 {
54   /**
55    * previous entry, used to manage entries in a double linked list
56    */
57   struct Hostlist * prev;
58
59   /**
60    * next entry, used to manage entries in a double linked list
61    */
62   struct Hostlist * next;
63
64   /**
65    * URI where hostlist can be obtained
66    */
67   const char *hostlist_uri;
68
69   /**
70    * Value describing the quality of the hostlist, the bigger the better but (should) never < 0
71    * used for deciding which hostlist is replaced if MAX_NUMBER_HOSTLISTS in data structure is reached
72    * intial value = HOSTLIST_INITIAL
73    * increased every successful download by HOSTLIST_SUCCESSFULL_DOWNLOAD
74    * increased every successful download by number of obtained HELLO messages
75    * decreased every failed download by HOSTLIST_SUCCESSFULL_DOWNLOAD
76    */
77   uint64_t quality;
78
79   /**
80    * Time the hostlist advertisement was recieved and the entry was created
81    */
82   struct GNUNET_TIME_Absolute time_creation;
83
84   /**
85    * Last time the hostlist was obtained
86    */
87   struct GNUNET_TIME_Absolute time_last_usage;
88
89   /**
90    * Number of HELLO messages obtained during last download
91    */
92   uint32_t hello_count;
93
94   /**
95    * Number of times the hostlist was obtained
96    */
97   uint32_t times_used;
98
99 };
100
101
102 /**
103  * Our configuration.
104  */
105 static const struct GNUNET_CONFIGURATION_Handle *cfg;
106
107 /**
108  * Our scheduler.
109  */
110 static struct GNUNET_SCHEDULER_Handle *sched;
111
112 /**
113  * Statistics handle.
114  */
115 struct GNUNET_STATISTICS_Handle *stats; 
116
117 /**
118  * Transport handle.
119  */
120 struct GNUNET_TRANSPORT_Handle *transport;
121                        
122 /**
123  * Proxy that we are using (can be NULL).
124  */
125 static char *proxy;
126
127 /**
128  * Buffer for data downloaded via HTTP.
129  */
130 static char download_buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE];
131
132 /**
133  * Number of bytes valid in 'download_buffer'.
134  */
135 static size_t download_pos;
136
137 /**
138  * Current URL that we are using.
139  */
140 static char *current_url;
141
142 /**
143  * Current CURL handle.
144  */
145 static CURL *curl;
146
147 /**
148  * Current multi-CURL handle.
149  */
150 static CURLM *multi;
151
152 /**
153  * ID of the current task scheduled.
154  */
155 static GNUNET_SCHEDULER_TaskIdentifier current_task;
156
157 /**
158  * ID of the current hostlist saving task scheduled.
159  */
160 static GNUNET_SCHEDULER_TaskIdentifier saving_task;
161
162 /**
163  * Amount of time we wait between hostlist downloads.
164  */
165 static struct GNUNET_TIME_Relative hostlist_delay;
166
167 /**
168  * Set to GNUNET_YES if the current URL had some problems.
169  */ 
170 static int bogus_url;
171
172 /**
173  * Number of active connections (according to core service).
174  */
175 static unsigned int connection_count;
176
177 /**
178  * At what time MUST the current hostlist request be done?
179  */
180 static struct GNUNET_TIME_Absolute end_time;
181
182 /**
183  * Head of the linked list used to store hostlists
184  */
185 static struct Hostlist * linked_list_head;
186
187 /**
188  *  Tail of the linked list used to store hostlists
189  */
190 static struct Hostlist * linked_list_tail;
191
192 /*
193  *  Size of the linke list  used to store hostlists
194  */
195 static unsigned int linked_list_size;
196
197 /**
198  * Value saying if preconfigured  is used
199  */
200 static unsigned int use_preconfigured_list;
201
202 /**
203  * Process downloaded bits by calling callback on each HELLO.
204  *
205  * @param ptr buffer with downloaded data
206  * @param size size of a record
207  * @param nmemb number of records downloaded
208  * @param ctx unused
209  * @return number of bytes that were processed (always size*nmemb)
210  */
211 static size_t
212 download_hostlist_processor (void *ptr, 
213                              size_t size, 
214                              size_t nmemb, 
215                              void *ctx)
216 {
217   const char * cbuf = ptr;
218   const struct GNUNET_MessageHeader *msg;
219   size_t total;
220   size_t cpy;
221   size_t left;
222   uint16_t msize;
223
224   total = size * nmemb;
225   if ( (total == 0) || (bogus_url) )
226     {
227       return total;  /* ok, no data or bogus data */
228     }
229   GNUNET_STATISTICS_update (stats, 
230                             gettext_noop ("# bytes downloaded from hostlist servers"), 
231                             (int64_t) total, 
232                             GNUNET_NO);  
233   left = total;
234   while ( (left > 0) ||
235           (download_pos > 0) )
236     {
237       cpy = GNUNET_MIN (left, GNUNET_SERVER_MAX_MESSAGE_SIZE - download_pos);
238       memcpy (&download_buffer[download_pos],
239               cbuf,
240               cpy);      
241       cbuf += cpy;
242       download_pos += cpy;
243       left -= cpy;
244       if (download_pos < sizeof(struct GNUNET_MessageHeader))
245         {
246           GNUNET_assert (left == 0);
247           break;
248         }
249       msg = (const struct GNUNET_MessageHeader *) download_buffer;
250       msize = ntohs(msg->size);
251       if (msize < sizeof(struct GNUNET_MessageHeader))
252         {        
253           GNUNET_STATISTICS_update (stats, 
254                                     gettext_noop ("# invalid HELLOs downloaded from hostlist servers"), 
255                                     1, 
256                                     GNUNET_NO);  
257           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
258                       _("Invalid `%s' message received from hostlist at `%s'\n"),
259                       "HELLO",
260                       current_url); 
261           bogus_url = 1;
262           return total;
263         }
264       if (download_pos < msize)
265         {
266           GNUNET_assert (left == 0);
267           break;
268         }
269       if (GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*)msg) == msize)
270         {
271 #if DEBUG_HOSTLIST_CLIENT
272           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
273                       "Received valid `%s' message from hostlist server.\n",
274                       "HELLO");
275 #endif
276           GNUNET_STATISTICS_update (stats, 
277                                     gettext_noop ("# valid HELLOs downloaded from hostlist servers"), 
278                                     1, 
279                                     GNUNET_NO);  
280           GNUNET_TRANSPORT_offer_hello (transport, msg);
281         }
282       else
283         {
284           GNUNET_STATISTICS_update (stats, 
285                                     gettext_noop ("# invalid HELLOs downloaded from hostlist servers"), 
286                                     1, 
287                                     GNUNET_NO);  
288           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
289                       _("Invalid `%s' message received from hostlist at `%s'\n"),
290                       "HELLO",
291                       current_url);
292           bogus_url = GNUNET_YES;
293           return total;
294         }
295       memmove (download_buffer,
296                &download_buffer[msize],
297                download_pos - msize);
298       download_pos -= msize;
299     }
300   return total;
301 }
302
303
304 /**
305  * Obtain a hostlist URL that we should use.
306  *
307  * @return NULL if there is no URL available
308  */
309 static char *
310 get_bootstrap_url ()
311 {
312   char *servers;
313   char *ret;
314   size_t urls;
315   size_t pos;
316
317   if (GNUNET_OK != 
318       GNUNET_CONFIGURATION_get_value_string (cfg,
319                                              "HOSTLIST",
320                                              "SERVERS",
321                                              &servers))
322     {
323       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
324                   _("No `%s' specified in `%s' configuration, will not bootstrap.\n"),
325                   "SERVERS", "HOSTLIST");
326       return NULL;
327     }
328
329   urls = 0;
330   if (strlen (servers) > 0)
331     {
332       urls++;
333       pos = strlen (servers) - 1;
334       while (pos > 0)
335         {
336           if (servers[pos] == ' ')
337             urls++;
338           pos--;
339         }
340     }
341   if (urls == 0)
342     {
343       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
344                   _("No `%s' specified in `%s' configuration, will not bootstrap.\n"),
345                   "SERVERS", "HOSTLIST");
346       GNUNET_free (servers);
347       return NULL;
348     }
349
350   urls = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, urls) + 1;
351   pos = strlen (servers) - 1;
352   while (pos > 0)
353     {
354       if (servers[pos] == ' ')
355         {
356           urls--;
357           servers[pos] = '\0';
358         }
359       if (urls == 0)
360         {
361           pos++;
362           break;
363         }
364       pos--;    
365     }
366   ret = GNUNET_strdup (&servers[pos]);
367   GNUNET_free (servers);
368   return ret;
369 }
370
371 /**
372  * Method deciding if a preconfigured or advertisied hostlist is used on a 50:50 ratio
373  * @return uri to use, NULL if there is no URL available
374  */
375 static char *
376 get_list_url ()
377 {
378   uint32_t index;
379   unsigned int counter;
380   struct Hostlist * pos;
381
382   if ( GNUNET_YES == use_preconfigured_list)
383   {
384     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
385                 "Using preconfigured bootstrap server\n");
386     use_preconfigured_list = GNUNET_NO;
387     return get_bootstrap_url();
388   }
389   index = GNUNET_CRYPTO_random_u32 ( GNUNET_CRYPTO_QUALITY_WEAK, linked_list_size);
390   counter = 0;
391   pos = linked_list_head;
392   while ( counter < index )
393     {
394       pos = pos->next;
395       counter ++;
396     }
397   use_preconfigured_list = GNUNET_YES;
398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
399               "Using learned hostlist `%s'\n", pos->hostlist_uri);
400   return strdup(pos->hostlist_uri);
401 }
402
403
404 #define CURL_EASY_SETOPT(c, a, b) do { ret = curl_easy_setopt(c, a, b); if (ret != CURLE_OK) GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("%s failed at %s:%d: `%s'\n"), "curl_easy_setopt", __FILE__, __LINE__, curl_easy_strerror(ret)); } while (0);
405
406
407 /**
408  * Schedule the background task that will (possibly)
409  * download a hostlist.
410  */
411 static void
412 schedule_hostlist_task (void);
413
414 /**
415  * Method to load persistent hostlist file during hostlist client shutdown
416  * @param shutdown set if called because of shutdown, entries in linked list will be destroyed
417  */
418 static void save_hostlist_file ( int shutdown );
419
420 /**
421  * Clean up the state from the task that downloaded the
422  * hostlist and schedule the next task.
423  */
424 static void 
425 clean_up ()
426 {
427   CURLMcode mret;
428
429   if (multi != NULL)
430     {
431       mret = curl_multi_remove_handle (multi, curl);
432       if (mret != CURLM_OK)
433         {
434           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
435                       _("%s failed at %s:%d: `%s'\n"),
436                       "curl_multi_remove_handle", __FILE__, __LINE__,
437                       curl_multi_strerror (mret));
438         }
439       mret = curl_multi_cleanup (multi);
440       if (mret != CURLM_OK)
441         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
442                     _("%s failed at %s:%d: `%s'\n"),
443                     "curl_multi_cleanup", __FILE__, __LINE__,
444                     curl_multi_strerror (mret));
445       multi = NULL;
446     }
447   if (curl != NULL)
448     {
449       curl_easy_cleanup (curl);
450       curl = NULL;
451     }  
452   GNUNET_free_non_null (current_url);
453   current_url = NULL;
454   schedule_hostlist_task ();
455 }
456
457
458 /**
459  * Ask CURL for the select set and then schedule the
460  * receiving task with the scheduler.
461  */
462 static void
463 run_multi (void);
464
465
466 /**
467  * Task that is run when we are ready to receive more data from the hostlist
468  * server. 
469  *
470  * @param cls closure, unused
471  * @param tc task context, unused
472  */
473 static void
474 multi_ready (void *cls,
475              const struct GNUNET_SCHEDULER_TaskContext *tc)
476 {
477   int running;
478   struct CURLMsg *msg;
479   CURLMcode mret;
480   
481   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
482     {
483 #if DEBUG_HOSTLIST_CLIENT
484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485                   "Shutdown requested while trying to download hostlist from `%s'\n",
486                   current_url);
487 #endif
488       clean_up ();
489       return;
490     }
491   if (GNUNET_TIME_absolute_get_remaining (end_time).value == 0)
492     {
493       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
494                   _("Timeout trying to download hostlist from `%s'\n"),
495                   current_url);
496       clean_up ();
497       return;
498     }
499 #if DEBUG_HOSTLIST_CLIENT
500   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
501               "Ready for processing hostlist client request\n");
502 #endif
503   do 
504     {
505       running = 0;
506       mret = curl_multi_perform (multi, &running);
507       if (running == 0)
508         {
509           do
510             {
511               msg = curl_multi_info_read (multi, &running);
512               GNUNET_break (msg != NULL);
513               if (msg == NULL)
514                 break;
515               switch (msg->msg)
516                 {
517                 case CURLMSG_DONE:
518                   if ( (msg->data.result != CURLE_OK) &&
519                        (msg->data.result != CURLE_GOT_NOTHING) )                       
520                     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
521                                _("%s failed for `%s' at %s:%d: `%s'\n"),
522                                "curl_multi_perform", 
523                                current_url,
524                                __FILE__,
525                                __LINE__,
526                                curl_easy_strerror (msg->data.result));            
527                   else
528                     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
529                                 _("Download of hostlist `%s' completed.\n"),
530                                 current_url);
531                   clean_up ();
532                   return;
533                 default:
534                   break;
535                 }
536             }
537           while (running > 0);
538         }
539     }
540   while (mret == CURLM_CALL_MULTI_PERFORM);
541   if (mret != CURLM_OK)
542     {
543       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
544                   _("%s failed at %s:%d: `%s'\n"),
545                   "curl_multi_perform", __FILE__, __LINE__,
546                   curl_multi_strerror (mret));
547       clean_up ();
548     }
549   run_multi ();
550 }
551
552
553 /**
554  * Ask CURL for the select set and then schedule the
555  * receiving task with the scheduler.
556  */
557 static void
558 run_multi () 
559 {
560   CURLMcode mret;
561   fd_set rs;
562   fd_set ws;
563   fd_set es;
564   int max;
565   struct GNUNET_NETWORK_FDSet *grs;
566   struct GNUNET_NETWORK_FDSet *gws;
567   long timeout;
568   struct GNUNET_TIME_Relative rtime;
569   
570   max = -1;
571   FD_ZERO (&rs);
572   FD_ZERO (&ws);
573   FD_ZERO (&es);
574   mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
575   if (mret != CURLM_OK)
576     {
577       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
578                   _("%s failed at %s:%d: `%s'\n"),
579                   "curl_multi_fdset", __FILE__, __LINE__,
580                   curl_multi_strerror (mret));
581       clean_up ();
582       return;
583     }
584   mret = curl_multi_timeout (multi, &timeout);
585   if (mret != CURLM_OK)
586     {
587       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
588                   _("%s failed at %s:%d: `%s'\n"),
589                   "curl_multi_timeout", __FILE__, __LINE__,
590                   curl_multi_strerror (mret));
591       clean_up ();
592       return;
593     }
594   rtime = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (end_time),
595                                     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
596                                                                    timeout));
597   grs = GNUNET_NETWORK_fdset_create ();
598   gws = GNUNET_NETWORK_fdset_create ();
599   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
600   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);  
601 #if DEBUG_HOSTLIST_CLIENT
602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
603               "Scheduling task for hostlist download using cURL\n");
604 #endif
605   current_task 
606     = GNUNET_SCHEDULER_add_select (sched,
607                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
608                                    GNUNET_SCHEDULER_NO_TASK,
609                                    rtime,
610                                    grs,
611                                    gws,
612                                    &multi_ready,
613                                    multi);
614   GNUNET_NETWORK_fdset_destroy (gws);
615   GNUNET_NETWORK_fdset_destroy (grs);
616 }
617
618
619 /**
620  * Main function that will download a hostlist and process its
621  * data.
622  */
623 static void
624 download_hostlist () 
625 {
626   CURLcode ret;
627   CURLMcode mret;
628
629   curl = curl_easy_init ();
630   multi = NULL;
631   if (curl == NULL)
632     {
633       GNUNET_break (0);
634       clean_up ();
635       return;
636     }
637   current_url = get_list_url ();
638   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
639               _("Bootstrapping using hostlist at `%s'.\n"), 
640               current_url);
641   GNUNET_STATISTICS_update (stats, 
642                             gettext_noop ("# hostlist downloads initiated"), 
643                             1, 
644                             GNUNET_NO);  
645   if (proxy != NULL)
646     CURL_EASY_SETOPT (curl, CURLOPT_PROXY, proxy);    
647   download_pos = 0;
648   bogus_url = 0;
649   CURL_EASY_SETOPT (curl,
650                     CURLOPT_WRITEFUNCTION, 
651                     &download_hostlist_processor);
652   if (ret != CURLE_OK)
653     {
654       clean_up ();
655       return;
656     }
657   CURL_EASY_SETOPT (curl,
658                     CURLOPT_WRITEDATA, 
659                     NULL);
660   if (ret != CURLE_OK)
661     {
662       clean_up ();
663       return;
664     }
665   CURL_EASY_SETOPT (curl, CURLOPT_FOLLOWLOCATION, 1);
666   CURL_EASY_SETOPT (curl, CURLOPT_MAXREDIRS, 4);
667   /* no need to abort if the above failed */
668   CURL_EASY_SETOPT (curl, 
669                     CURLOPT_URL, 
670                     current_url);
671   if (ret != CURLE_OK)
672     {
673       clean_up ();
674       return;
675     }
676   CURL_EASY_SETOPT (curl, 
677                     CURLOPT_FAILONERROR, 
678                     1);
679 #if 0
680   CURL_EASY_SETOPT (curl, 
681                     CURLOPT_VERBOSE, 
682                     1);
683 #endif
684   CURL_EASY_SETOPT (curl, 
685                     CURLOPT_BUFFERSIZE, 
686                     GNUNET_SERVER_MAX_MESSAGE_SIZE);
687   if (0 == strncmp (current_url, "http", 4))
688     CURL_EASY_SETOPT (curl, CURLOPT_USERAGENT, "GNUnet");
689   CURL_EASY_SETOPT (curl, 
690                     CURLOPT_CONNECTTIMEOUT, 
691                     60L);
692   CURL_EASY_SETOPT (curl, 
693                     CURLOPT_TIMEOUT, 
694                     60L);
695 #if 0
696   /* this should no longer be needed; we're now single-threaded! */
697   CURL_EASY_SETOPT (curl,
698                     CURLOPT_NOSIGNAL, 
699                     1);
700 #endif
701   multi = curl_multi_init ();
702   if (multi == NULL)
703     {
704       GNUNET_break (0);
705       clean_up ();
706       return;
707     }
708   mret = curl_multi_add_handle (multi, curl);
709   if (mret != CURLM_OK)
710     {
711       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
712                   _("%s failed at %s:%d: `%s'\n"),
713                   "curl_multi_add_handle", __FILE__, __LINE__,
714                   curl_multi_strerror (mret));
715       mret = curl_multi_cleanup (multi);
716       if (mret != CURLM_OK)
717         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
718                     _("%s failed at %s:%d: `%s'\n"),
719                     "curl_multi_cleanup", __FILE__, __LINE__,
720                     curl_multi_strerror (mret));
721       multi = NULL;
722       clean_up ();
723       return;
724     }
725   end_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES);
726   run_multi ();
727 }  
728
729
730 /**
731  * Task that checks if we should try to download a hostlist.
732  * If so, we initiate the download, otherwise we schedule
733  * this task again for a later time.
734  */
735 static void
736 check_task (void *cls,
737             const struct GNUNET_SCHEDULER_TaskContext *tc)
738 {
739   current_task = GNUNET_SCHEDULER_NO_TASK;
740   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
741     return;
742   if (connection_count < MIN_CONNECTIONS)
743     download_hostlist ();
744   else
745     schedule_hostlist_task ();
746 }
747
748
749 /**
750  * Compute when we should check the next time about downloading
751  * a hostlist; then schedule the task accordingly.
752  */
753 static void
754 schedule_hostlist_task ()
755 {
756   static int once;
757   struct GNUNET_TIME_Relative delay;
758
759   if (stats == NULL)
760     {
761       curl_global_cleanup ();
762       return; /* in shutdown */
763     }
764   delay = hostlist_delay;
765   if (hostlist_delay.value == 0)
766     hostlist_delay = GNUNET_TIME_UNIT_SECONDS;
767   else
768     hostlist_delay = GNUNET_TIME_relative_multiply (hostlist_delay, 2);
769   if (hostlist_delay.value > GNUNET_TIME_UNIT_HOURS.value * (1 + connection_count))
770     hostlist_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS,
771                                                     (1 + connection_count));
772   GNUNET_STATISTICS_set (stats,
773                          gettext_noop("# seconds between hostlist downloads"),
774                          hostlist_delay.value,
775                          GNUNET_YES);
776   if (0 == once)
777     {
778       delay = GNUNET_TIME_UNIT_ZERO;
779       once = 1;
780     }  
781   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
782               _("Have %u/%u connections.  Will consider downloading hostlist in %llums\n"),
783               connection_count,
784               MIN_CONNECTIONS,
785               (unsigned long long) delay.value);
786   current_task = GNUNET_SCHEDULER_add_delayed (sched,
787                                                delay,
788                                                &check_task,
789                                                NULL);
790 }
791
792 /**
793  * Task that writes hostlist entries to a file on a regular base
794  * cls closure
795  * tc TaskContext
796  */
797 static void
798 hostlist_saving_task (void *cls,
799             const struct GNUNET_SCHEDULER_TaskContext *tc)
800 {
801   saving_task = GNUNET_SCHEDULER_NO_TASK;
802   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
803     return;
804   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
805               _("Scheduled saving of hostlists\n"));
806   save_hostlist_file ( GNUNET_NO );
807
808   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
809               _("Hostlists will be saved to file again in %llums\n"),
810               (unsigned long long) SAVING_INTERVALL.value);
811   saving_task = GNUNET_SCHEDULER_add_delayed (sched,
812                                                SAVING_INTERVALL,
813                                                &hostlist_saving_task,
814                                                NULL);
815 }
816
817 /**
818  * Method called whenever a given peer connects.
819  *
820  * @param cls closure
821  * @param peer peer identity this notification is about
822  * @param latency reported latency of the connection with 'other'
823  * @param distance reported distance (DV) to 'other' 
824  */
825 static void
826 connect_handler (void *cls,
827                  const struct
828                  GNUNET_PeerIdentity * peer,
829                  struct GNUNET_TIME_Relative latency,
830                  uint32_t distance)
831 {
832   connection_count++;
833   GNUNET_STATISTICS_update (stats, 
834                             gettext_noop ("# active connections"), 
835                             1, 
836                             GNUNET_NO);  
837 }
838
839
840 /**
841  * Method called whenever a given peer disconnects.
842  *
843  * @param cls closure
844  * @param peer peer identity this notification is about
845  */
846 static void
847 disconnect_handler (void *cls,
848                     const struct
849                     GNUNET_PeerIdentity * peer)
850 {
851   connection_count--;
852   GNUNET_STATISTICS_update (stats, 
853                             gettext_noop ("# active connections"), 
854                             -1, 
855                             GNUNET_NO);  
856 }
857
858
859 /**
860  * Method to check if URI is in hostlist linked list
861  * @param uri uri to check
862  * @return GNUNET_YES if existing in linked list, GNUNET_NO if not
863  */
864 static int 
865 linked_list_contains (const char * uri)
866 {
867   struct Hostlist * pos;
868
869   pos = linked_list_head;
870   while (pos != NULL)
871     {
872       if (0 == strcmp(pos->hostlist_uri, uri) ) 
873         return GNUNET_YES;
874       pos = pos->next;
875     }
876   return GNUNET_NO;
877 }
878
879
880 /* linked_list_? */
881 static struct Hostlist *
882 linked_list_get_lowest_quality ( )
883 {
884   struct Hostlist * pos;
885   struct Hostlist * lowest;
886
887   if (linked_list_size == 0)
888     return NULL;
889   lowest = linked_list_head;
890   pos = linked_list_head->next;
891   while (pos != NULL)
892     {
893       if (pos->quality < lowest->quality) 
894         lowest = pos;
895       pos = pos->next;
896     }
897   return lowest;
898 }
899
900
901 /**
902  * Method called whenever an advertisement message arrives.
903  *
904  * @param cls closure (always NULL)
905  * @param client identification of the client
906  * @param message the actual message
907  * @return GNUNET_OK to keep the connection open,
908  *         GNUNET_SYSERR to close it (signal serious error)
909  */
910 static int
911 advertisement_handler (void *cls,
912     const struct GNUNET_PeerIdentity * peer,
913     const struct GNUNET_MessageHeader * message,
914     struct GNUNET_TIME_Relative latency,
915     uint32_t distance)
916 {
917   size_t size;
918   size_t uri_size;
919   const struct GNUNET_MessageHeader * incoming;
920   const char *uri;
921   struct Hostlist * hostlist;
922
923   GNUNET_assert (ntohs (message->type) == GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT);
924   size = ntohs (message->size);
925   if (size <= sizeof(struct GNUNET_MessageHeader))
926     {
927       GNUNET_break_op (0);
928       return GNUNET_SYSERR;
929     }
930   incoming = (const struct GNUNET_MessageHeader *) message;
931   uri = (const char*) &incoming[1];
932   uri_size = size - sizeof (struct GNUNET_MessageHeader);
933   if (uri [uri_size - 1] != '\0')
934     {
935       GNUNET_break_op (0);
936       return GNUNET_SYSERR;
937     }
938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939               "Hostlist client recieved advertisement from `%s' containing URI `%s'\n", 
940               GNUNET_i2s (peer), 
941               uri);
942   if (GNUNET_NO != linked_list_contains (uri))
943     {
944       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
945                 "URI `%s' is already known\n",
946                 uri);
947       return GNUNET_OK;
948     }
949   hostlist = GNUNET_malloc (sizeof (struct Hostlist) + uri_size);
950   hostlist->hostlist_uri = (const char*) &hostlist[1];
951   memcpy (&hostlist[1], uri, uri_size);
952   hostlist->time_creation = GNUNET_TIME_absolute_get();
953   hostlist->time_last_usage = GNUNET_TIME_absolute_get_zero();
954   hostlist->quality = HOSTLIST_INITIAL;  
955
956   GNUNET_CONTAINER_DLL_insert(linked_list_head, linked_list_tail, hostlist);
957   linked_list_size++;
958   
959   if (MAX_NUMBER_HOSTLISTS >= linked_list_size)
960     return GNUNET_OK;
961
962   /* No free entries available, replace existing entry  */
963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964               "Removing lowest quality entry\n" );  
965   struct Hostlist * lowest_quality = linked_list_get_lowest_quality();
966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967               "Hostlist with URI `%s' has the worst quality of all with value %llu\n", 
968               lowest_quality->hostlist_uri,
969               (unsigned long long) lowest_quality->quality);
970   GNUNET_CONTAINER_DLL_remove (linked_list_head, linked_list_tail, lowest_quality);
971   linked_list_size--;
972   GNUNET_free (lowest_quality);
973   return GNUNET_OK;
974 }
975
976
977 /**
978  * Continuation called by the statistics code once 
979  * we go the stat.  Initiates hostlist download scheduling.
980  *
981  * @param cls closure
982  * @param success GNUNET_OK if statistics were
983  *        successfully obtained, GNUNET_SYSERR if not.
984  */
985 static void
986 primary_task (void *cls, int success)
987 {
988   if (stats == NULL)
989     return; /* in shutdown */
990 #if DEBUG_HOSTLIST_CLIENT
991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
992               "Statistics request done, scheduling hostlist download\n");
993 #endif
994   schedule_hostlist_task ();
995 }
996
997
998 static int
999 process_stat (void *cls,
1000               const char *subsystem,
1001               const char *name,
1002               uint64_t value,
1003               int is_persistent)
1004 {
1005   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1006               _("Initial time between hostlist downloads is %llums\n"),
1007               (unsigned long long) value);
1008   hostlist_delay.value = value;
1009   return GNUNET_OK;
1010 }
1011
1012 /**
1013  * Method to load persistent hostlist file during hostlist client startup
1014  */
1015 static void 
1016 load_hostlist_file ()
1017 {
1018   char *filename;
1019   char *uri;
1020   char *emsg;
1021   struct Hostlist * hostlist;
1022   uri = NULL;
1023   uint32_t times_used;
1024   uint32_t hellos_returned;
1025   uint64_t quality;
1026   uint64_t last_used;
1027   uint64_t created;
1028   uint32_t counter;
1029
1030   if (GNUNET_OK !=
1031       GNUNET_CONFIGURATION_get_value_string (cfg,
1032                                              "HOSTLIST",
1033                                              "HOSTLISTFILE",
1034                                              &filename))
1035     {
1036       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1037                   _("No `%s' specified in `%s' configuration, cannot load hostlists from file.\n"),
1038                   "HOSTLISTFILE", "HOSTLIST");
1039       return;
1040     }
1041
1042   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1043               _("Loading saved hostlist entries from file `%s' \n"), filename);
1044
1045   struct GNUNET_BIO_ReadHandle * rh = GNUNET_BIO_read_open (filename);
1046   if (NULL == rh)
1047     {
1048       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1049                   _("Could not open file `%s' for reading to load hostlists: %s\n"), 
1050                   filename,
1051                   STRERROR (errno));
1052       GNUNET_free (filename);
1053       return;
1054     }
1055
1056
1057   while ( (GNUNET_OK == GNUNET_BIO_read_string (rh, "url" , &uri, MAX_URL_LEN)) &&
1058           (GNUNET_OK == GNUNET_BIO_read_int32 (rh, &times_used)) &&
1059           (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &quality)) &&
1060           (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &last_used)) &&
1061           (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &created)) &&
1062           (GNUNET_OK == GNUNET_BIO_read_int32 (rh, &hellos_returned)) )
1063     {
1064       hostlist = GNUNET_malloc (sizeof (struct Hostlist) + strlen (uri) + 1);
1065       hostlist->hello_count = hellos_returned;
1066       hostlist->hostlist_uri = (const char *) &hostlist[1];
1067       memcpy (&hostlist[1], uri, strlen(uri)+1);
1068       hostlist->quality = quality;
1069       hostlist->time_creation.value = created;
1070       hostlist->time_last_usage.value = last_used;
1071       GNUNET_CONTAINER_DLL_insert(linked_list_head, linked_list_tail, hostlist);
1072       linked_list_size++;
1073       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1074                   "Added hostlist entry eith URI `%s' \n", hostlist->hostlist_uri);
1075       uri = NULL;
1076       counter++;
1077       if ( counter >= MAX_NUMBER_HOSTLISTS ) break;
1078     }
1079
1080   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1081               _("%u hostlist URIs loaded from file\n"), counter);
1082   GNUNET_STATISTICS_set (stats,
1083                          gettext_noop("# hostlis URIs read from file"),
1084                          counter,
1085                          GNUNET_YES);
1086
1087   GNUNET_free_non_null (uri);
1088   emsg = NULL;
1089   GNUNET_BIO_read_close (rh, &emsg);
1090   if (emsg != NULL)
1091     GNUNET_free (emsg);
1092   GNUNET_free (filename);
1093 }
1094
1095
1096 /**
1097  * Method to load persistent hostlist file during hostlist client shutdown
1098  * @param shutdown set if called because of shutdown, entries in linked list will be destroyed
1099  */
1100 static void save_hostlist_file ( int shutdown )
1101 {
1102   char *filename;
1103   struct Hostlist *pos;
1104   struct GNUNET_BIO_WriteHandle * wh;
1105   int ok;
1106   uint32_t counter;
1107
1108   if (GNUNET_OK !=
1109       GNUNET_CONFIGURATION_get_value_string (cfg,
1110                                              "HOSTLIST",
1111                                              "HOSTLISTFILE",
1112                                              &filename))
1113     {
1114       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1115                   _("No `%s' specified in `%s' configuration, cannot save hostlists to file.\n"),
1116                   "HOSTLISTFILE", "HOSTLIST");
1117       return;
1118     }
1119   wh = GNUNET_BIO_write_open (filename);
1120   if ( NULL == wh)
1121     {
1122       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1123                   _("Could not open file `%s' for writing to save hostlists: %s\n"),
1124                   filename,
1125                   STRERROR (errno));
1126       return;
1127     }
1128   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1129               _("Writing %u hostlist URIs to `%s'\n" ),
1130               linked_list_size, filename);
1131
1132   /* add code to write hostlists to file using bio */
1133   ok = GNUNET_YES;
1134   counter = 0;
1135   while (NULL != (pos = linked_list_head))
1136     {
1137       if ( GNUNET_YES == shutdown)
1138       {
1139         GNUNET_CONTAINER_DLL_remove (linked_list_head, linked_list_tail, pos);
1140         linked_list_size--;
1141       }
1142       if (GNUNET_YES == ok)
1143         {
1144           if ( (GNUNET_OK !=
1145                 GNUNET_BIO_write_string (wh, pos->hostlist_uri)) ||
1146                (GNUNET_OK !=
1147                 GNUNET_BIO_write_int32 (wh, pos->times_used)) ||
1148                (GNUNET_OK !=
1149                 GNUNET_BIO_write_int64 (wh, pos->quality)) ||
1150                (GNUNET_OK !=
1151                 GNUNET_BIO_write_int64 (wh, pos->time_last_usage.value)) ||
1152                (GNUNET_OK !=
1153                 GNUNET_BIO_write_int64 (wh, pos->time_creation.value)) ||
1154                (GNUNET_OK !=
1155                 GNUNET_BIO_write_int32 (wh, pos->hello_count)))
1156             {
1157               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1158                           _("Error writing hostlist URIs to file `%s'\n"),
1159                           filename);
1160               ok = GNUNET_NO;
1161             }
1162         }
1163
1164       if ( GNUNET_YES == shutdown)
1165         GNUNET_free (pos);
1166       counter ++;
1167       if ( counter >= MAX_NUMBER_HOSTLISTS) break;
1168     }  
1169   GNUNET_STATISTICS_set (stats,
1170                          gettext_noop("# hostlist URIs written to file"),
1171                          counter,
1172                          GNUNET_YES);
1173
1174   if ( GNUNET_OK != GNUNET_BIO_write_close ( wh ) )
1175     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1176                 _("Error writing hostlist URIs to file `%s'\n"),
1177                 filename);
1178   GNUNET_free (filename);
1179 }
1180
1181 /**
1182  * Start downloading hostlists from hostlist servers as necessary.
1183  */
1184 int
1185 GNUNET_HOSTLIST_client_start (const struct GNUNET_CONFIGURATION_Handle *c,
1186                               struct GNUNET_SCHEDULER_Handle *s,
1187                               struct GNUNET_STATISTICS_Handle *st,
1188                               GNUNET_CORE_ConnectEventHandler *ch,
1189                               GNUNET_CORE_DisconnectEventHandler *dh,
1190                               GNUNET_CORE_MessageCallback *msgh,
1191                               int learn)
1192 {
1193   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
1194     {
1195       GNUNET_break (0);
1196       return GNUNET_SYSERR;
1197     }
1198   transport = GNUNET_TRANSPORT_connect (s, c, NULL, NULL, NULL, NULL);
1199   if (NULL == transport)
1200     {
1201       curl_global_cleanup ();
1202       return GNUNET_SYSERR;
1203     }
1204   cfg = c;
1205   sched = s;
1206   stats = st;
1207   if (GNUNET_OK !=
1208       GNUNET_CONFIGURATION_get_value_string (cfg,
1209                                              "HOSTLIST",
1210                                              "HTTP-PROXY", 
1211                                              &proxy))
1212     proxy = NULL;
1213   *ch = &connect_handler;
1214   *dh = &disconnect_handler;
1215   if (learn)
1216     *msgh = &advertisement_handler;
1217   else
1218     *msgh = NULL;
1219   linked_list_head = NULL;
1220   linked_list_tail = NULL;
1221   use_preconfigured_list = GNUNET_YES;
1222   load_hostlist_file ();
1223
1224   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1225               _("Hostlists will be saved to file again in  %llums\n"),
1226               (unsigned long long) SAVING_INTERVALL.value);
1227   saving_task = GNUNET_SCHEDULER_add_delayed (sched,
1228                                                SAVING_INTERVALL,
1229                                                &hostlist_saving_task,
1230                                                NULL);
1231
1232   GNUNET_STATISTICS_get (stats,
1233                          "hostlist",
1234                          gettext_noop("# seconds between hostlist downloads"),
1235                          GNUNET_TIME_UNIT_MINUTES,
1236                          &primary_task,
1237                          &process_stat,
1238                          NULL);
1239   return GNUNET_OK;
1240 }
1241
1242
1243 /**
1244  * Stop downloading hostlists from hostlist servers as necessary.
1245  */
1246 void
1247 GNUNET_HOSTLIST_client_stop ()
1248 {
1249 #if DEBUG_HOSTLIST_CLIENT
1250   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1251               "Hostlist client shutdown\n");
1252 #endif
1253   save_hostlist_file ( GNUNET_YES );
1254
1255   if (current_task != GNUNET_SCHEDULER_NO_TASK)
1256     {
1257       GNUNET_SCHEDULER_cancel (sched,
1258                                current_task);
1259       curl_global_cleanup ();
1260     }
1261   if (transport != NULL)
1262     {
1263       GNUNET_TRANSPORT_disconnect (transport);
1264       transport = NULL;
1265     }
1266   GNUNET_assert (NULL == transport);
1267   GNUNET_free_non_null (proxy);
1268   proxy = NULL;
1269   cfg = NULL;
1270   sched = NULL;
1271 }
1272
1273 /* end of hostlist-client.c */