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