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