371568ddfff4c92c7f96af166484e319e68f9cf6
[oweals/gnunet.git] / src / fs / fs.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2008, 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 fs/fs.c
23  * @brief main FS functions (master initialization, serialization, deserialization, shared code)
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_fs_service.h"
30 #include "fs.h"
31 #include "fs_tree.h"
32
33
34 /**
35  * Start the given job (send signal, remove from pending queue, update
36  * counters and state).
37  *
38  * @param qe job to start
39  */
40 static void
41 start_job (struct GNUNET_FS_QueueEntry *qe)
42 {
43   qe->client = GNUNET_CLIENT_connect (qe->h->sched, "fs", qe->h->cfg);
44   if (qe->client == NULL)
45     {
46       GNUNET_break (0);
47       return;
48     }
49   qe->start (qe->cls, qe->client);
50   qe->start_times++;
51   qe->h->active_blocks += qe->blocks;
52   qe->start_time = GNUNET_TIME_absolute_get ();
53   GNUNET_CONTAINER_DLL_remove (qe->h->pending_head,
54                                qe->h->pending_tail,
55                                qe);
56   GNUNET_CONTAINER_DLL_insert_after (qe->h->running_head,
57                                      qe->h->running_tail,
58                                      qe->h->running_tail,
59                                      qe);
60 }
61
62
63 /**
64  * Stop the given job (send signal, remove from active queue, update
65  * counters and state).
66  *
67  * @param qe job to stop
68  */
69 static void
70 stop_job (struct GNUNET_FS_QueueEntry *qe)
71 {
72   qe->client = NULL;
73   qe->stop (qe->cls);
74   qe->h->active_downloads--;
75   qe->h->active_blocks -= qe->blocks;
76   qe->run_time = GNUNET_TIME_relative_add (qe->run_time,
77                                            GNUNET_TIME_absolute_get_duration (qe->start_time));
78   GNUNET_CONTAINER_DLL_remove (qe->h->running_head,
79                                qe->h->running_tail,
80                                qe);
81   GNUNET_CONTAINER_DLL_insert_after (qe->h->pending_head,
82                                      qe->h->pending_tail,
83                                      qe->h->pending_tail,
84                                      qe);
85 }
86
87
88 /**
89  * Process the jobs in the job queue, possibly starting some
90  * and stopping others.
91  *
92  * @param cls the 'struct GNUNET_FS_Handle'
93  * @param tc scheduler context
94  */
95 static void
96 process_job_queue (void *cls,
97                    const struct GNUNET_SCHEDULER_TaskContext *tc)
98 {
99   struct GNUNET_FS_Handle *h = cls;
100   struct GNUNET_FS_QueueEntry *qe;
101   struct GNUNET_FS_QueueEntry *next;
102   struct GNUNET_TIME_Relative run_time;
103   struct GNUNET_TIME_Relative restart_at;
104   struct GNUNET_TIME_Relative rst;
105   struct GNUNET_TIME_Absolute end_time;
106
107   h->queue_job = GNUNET_SCHEDULER_NO_TASK;
108   next = h->pending_head;
109   while (NULL != (qe = next))
110     {
111       next = qe->next;
112       if (h->running_head == NULL)
113         {
114           start_job (qe);
115           continue;
116         }
117       if ( (qe->blocks + h->active_blocks <= h->max_parallel_requests) &&
118            (h->active_downloads + 1 <= h->max_parallel_downloads) )
119         {
120           start_job (qe);
121           continue;
122         }
123     }
124   if (h->pending_head == NULL)
125     return; /* no need to stop anything */
126   restart_at = GNUNET_TIME_UNIT_FOREVER_REL;
127   next = h->running_head;
128   while (NULL != (qe = next))
129     {
130       next = qe->next;
131       run_time = GNUNET_TIME_relative_multiply (h->avg_block_latency,
132                                                 qe->blocks * qe->start_times);
133       end_time = GNUNET_TIME_absolute_add (qe->start_time,
134                                            run_time);
135       rst = GNUNET_TIME_absolute_get_remaining (end_time);
136       restart_at = GNUNET_TIME_relative_min (rst, restart_at);
137       if (rst.value > 0)
138         continue;       
139       stop_job (qe);
140     }
141   h->queue_job = GNUNET_SCHEDULER_add_delayed (h->sched,
142                                                restart_at,
143                                                &process_job_queue,
144                                                h);
145 }
146
147
148 /**
149  * Add a job to the queue.
150  *
151  * @param h handle to the overall FS state
152  * @param start function to call to begin the job
153  * @param stop function to call to pause the job, or on dequeue (if the job was running)
154  * @param cls closure for start and stop
155  * @param blocks number of blocks this jobs uses
156  * @return queue handle
157  */
158 struct GNUNET_FS_QueueEntry *
159 GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h,
160                   GNUNET_FS_QueueStart start,
161                   GNUNET_FS_QueueStop stop,
162                   void *cls,
163                   unsigned int blocks)
164 {
165   struct GNUNET_FS_QueueEntry *qe;
166
167   qe = GNUNET_malloc (sizeof (struct GNUNET_FS_QueueEntry));
168   qe->h = h;
169   qe->start = start;
170   qe->stop = stop;
171   qe->cls = cls;
172   qe->queue_time = GNUNET_TIME_absolute_get ();
173   qe->blocks = blocks;
174   GNUNET_CONTAINER_DLL_insert_after (h->pending_head,
175                                      h->pending_tail,
176                                      h->pending_tail,
177                                      qe);
178   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
179     GNUNET_SCHEDULER_cancel (h->sched,
180                              h->queue_job);
181   h->queue_job 
182     = GNUNET_SCHEDULER_add_now (h->sched,
183                                 &process_job_queue,
184                                 h);
185   return qe;
186 }
187
188
189 /**
190  * Dequeue a job from the queue.
191  * @param qh handle for the job
192  */
193 void
194 GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qh)
195 {
196   struct GNUNET_FS_Handle *h;
197
198   h = qh->h;
199   if (qh->client != NULL)    
200     stop_job (qh);    
201   GNUNET_CONTAINER_DLL_remove (h->pending_head,
202                                h->pending_tail,
203                                qh);
204   GNUNET_free (qh);
205   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
206     GNUNET_SCHEDULER_cancel (h->sched,
207                              h->queue_job);
208   h->queue_job 
209     = GNUNET_SCHEDULER_add_now (h->sched,
210                                 &process_job_queue,
211                                 h);
212 }
213
214
215 /**
216  * Create a top-level activity entry.
217  *
218  * @param h global fs handle
219  * @param ssf suspend signal function to use
220  * @param ssf_cls closure for ssf
221  * @return fresh top-level activity handle
222  */
223 struct TopLevelActivity *
224 GNUNET_FS_make_top (struct GNUNET_FS_Handle *h,
225                     SuspendSignalFunction ssf,
226                     void *ssf_cls)
227 {
228   struct TopLevelActivity *ret;
229
230   ret = GNUNET_malloc (sizeof (struct TopLevelActivity));
231   ret->ssf = ssf;
232   ret->ssf_cls = ssf_cls;
233   GNUNET_CONTAINER_DLL_insert (h->top_head,
234                                h->top_tail,
235                                ret);
236   return ret;
237 }
238
239
240 /**
241  * Destroy a top-level activity entry.
242  * 
243  * @param h global fs handle
244  * @param top top level activity entry
245  */
246 void
247 GNUNET_FS_end_top (struct GNUNET_FS_Handle *h,
248                    struct TopLevelActivity *top)
249 {
250   GNUNET_CONTAINER_DLL_remove (h->top_head,
251                                h->top_tail,
252                                top);
253   GNUNET_free (top);
254 }
255
256
257
258 /**
259  * Closure for "data_reader_file".
260  */
261 struct FileInfo
262 {
263   /**
264    * Name of the file to read.
265    */
266   char *filename;
267
268   /**
269    * File descriptor, NULL if it has not yet been opened.
270    */
271   struct GNUNET_DISK_FileHandle *fd;
272 };
273
274
275 /**
276  * Function that provides data by reading from a file.
277  *
278  * @param cls closure (points to the file information)
279  * @param offset offset to read from; it is possible
280  *            that the caller might need to go backwards
281  *            a bit at times
282  * @param max maximum number of bytes that should be 
283  *            copied to buf; readers are not allowed
284  *            to provide less data unless there is an error;
285  *            a value of "0" will be used at the end to allow
286  *            the reader to clean up its internal state
287  * @param buf where the reader should write the data
288  * @param emsg location for the reader to store an error message
289  * @return number of bytes written, usually "max", 0 on error
290  */
291 size_t
292 GNUNET_FS_data_reader_file_(void *cls, 
293                             uint64_t offset,
294                             size_t max, 
295                             void *buf,
296                             char **emsg)
297 {
298   struct FileInfo *fi = cls;
299   ssize_t ret;
300
301   if (max == 0)
302     {
303       if (fi->fd != NULL)
304         GNUNET_DISK_file_close (fi->fd);
305       GNUNET_free (fi->filename);
306       GNUNET_free (fi);
307       return 0;
308     }  
309   if (fi->fd == NULL)
310     {
311       fi->fd = GNUNET_DISK_file_open (fi->filename,
312                                       GNUNET_DISK_OPEN_READ,
313                                       GNUNET_DISK_PERM_NONE);
314       if (fi->fd == NULL)
315         {
316           GNUNET_asprintf (emsg, 
317                            _("Could not open file `%s': %s"),
318                            fi->filename,
319                            STRERROR (errno));
320           return 0;
321         }
322     }
323   GNUNET_DISK_file_seek (fi->fd, offset, GNUNET_DISK_SEEK_SET);
324   ret = GNUNET_DISK_file_read (fi->fd, buf, max);
325   if (ret == -1)
326     {
327       GNUNET_asprintf (emsg, 
328                        _("Could not read file `%s': %s"),
329                        fi->filename,
330                        STRERROR (errno));
331       return 0;
332     }
333   if (ret != max)
334     {
335       GNUNET_asprintf (emsg, 
336                        _("Short read reading from file `%s'!"),
337                        fi->filename);
338       return 0;
339     }
340   return max;
341 }
342
343
344 /**
345  * Create the closure for the 'GNUNET_FS_data_reader_file_' callback.
346  *
347  * @param filename file to read
348  * @return closure to use, NULL on error
349  */
350 void *
351 GNUNET_FS_make_file_reader_context_ (const char *filename)
352 {
353   struct FileInfo *fi;
354
355   fi = GNUNET_malloc (sizeof(struct FileInfo));
356   fi->filename = GNUNET_STRINGS_filename_expand (filename);
357   if (fi->filename == NULL)
358     {
359       GNUNET_free (fi);
360       return NULL;
361     }
362   return fi;
363 }
364
365
366 /**
367  * Function that provides data by copying from a buffer.
368  *
369  * @param cls closure (points to the buffer)
370  * @param offset offset to read from; it is possible
371  *            that the caller might need to go backwards
372  *            a bit at times
373  * @param max maximum number of bytes that should be 
374  *            copied to buf; readers are not allowed
375  *            to provide less data unless there is an error;
376  *            a value of "0" will be used at the end to allow
377  *            the reader to clean up its internal state
378  * @param buf where the reader should write the data
379  * @param emsg location for the reader to store an error message
380  * @return number of bytes written, usually "max", 0 on error
381  */
382 size_t
383 GNUNET_FS_data_reader_copy_ (void *cls, 
384                              uint64_t offset,
385                              size_t max, 
386                              void *buf,
387                              char **emsg)
388 {
389   char *data = cls;
390
391   if (max == 0)
392     {
393       GNUNET_free_non_null (data);
394       return 0;
395     }  
396   memcpy (buf, &data[offset], max);
397   return max;
398 }
399
400
401
402 /**
403  * Return the full filename where we would store state information
404  * (for serialization/deserialization).
405  *
406  * @param h master context
407  * @param ext component of the path 
408  * @param ent entity identifier (or emtpy string for the directory)
409  * @return NULL on error
410  */
411 static char *
412 get_serialization_file_name (struct GNUNET_FS_Handle *h,
413                              const char *ext,
414                              const char *ent)
415 {
416   char *basename;
417   char *ret;
418   if (GNUNET_OK !=
419       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
420                                                "fs",
421                                                "STATE_DIR",
422                                                &basename))
423     return NULL;
424   GNUNET_asprintf (&ret,
425                    "%s%s%s-%s%s%s",
426                    basename,
427                    DIR_SEPARATOR_STR,
428                    h->client_name,
429                    ext,
430                    DIR_SEPARATOR_STR,
431                    ent);
432   GNUNET_free (basename);
433   return ret;
434 }
435
436
437 /**
438  * Return a read handle for deserialization.
439  *
440  * @param h master context
441  * @param ext component of the path 
442  * @param ent entity identifier (or emtpy string for the directory)
443  * @return NULL on error
444  */
445 static struct GNUNET_BIO_ReadHandle *
446 get_read_handle (struct GNUNET_FS_Handle *h,
447                  const char *ext,
448                  const char *ent)
449 {
450   char *fn;
451   struct GNUNET_BIO_ReadHandle *ret;
452
453   fn = get_serialization_file_name (h, ext, ent);
454   if (fn == NULL)
455     return NULL;
456   ret = GNUNET_BIO_read_open (fn);
457   GNUNET_free (fn);
458   return ret;
459 }
460
461
462 /**
463  * Return a write handle for serialization.
464  *
465  * @param h master context
466  * @param ext component of the path 
467  * @param ent entity identifier (or emtpy string for the directory)
468  * @return NULL on error
469  */
470 static struct GNUNET_BIO_WriteHandle *
471 get_write_handle (struct GNUNET_FS_Handle *h,
472                   const char *ext,
473                   const char *ent)
474 {
475   char *fn;
476   struct GNUNET_BIO_WriteHandle *ret;
477
478   fn = get_serialization_file_name (h, ext, ent);
479   if (fn == NULL)
480     return NULL;
481   ret = GNUNET_BIO_write_open (fn);
482   GNUNET_free (fn);
483   return ret;
484 }
485
486
487 /**
488  * Remove serialization/deserialization file from disk.
489  *
490  * @param h master context
491  * @param ext component of the path 
492  * @param ent entity identifier 
493  */
494 void
495 GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h,
496                              const char *ext,
497                              const char *ent)
498 {
499   char *filename;
500
501   if ( (NULL == ent) ||
502        (0 == strlen (ent)) )
503     {
504       GNUNET_break (0);
505       return;
506     }
507   filename = get_serialization_file_name (h, ext, ent);
508   if (0 != UNLINK (filename))
509     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
510                               "unlink", 
511                               filename);
512   GNUNET_free (filename);
513 }
514
515
516 /**
517  * Serialize a 'start_time'.  Since we use start-times to
518  * calculate the duration of some operation, we actually
519  * do not serialize the absolute time but the (relative)
520  * duration since the start time.  When we then
521  * deserialize the start time, we take the current time and
522  * subtract that duration so that we get again an absolute
523  * time stamp that will result in correct performance
524  * calculations.
525  *
526  * @param wh handle for writing
527  * @param timestamp time to serialize
528  * @return GNUNET_OK on success
529  */
530 static int
531 write_start_time (struct GNUNET_BIO_WriteHandle *wh,
532                   struct GNUNET_TIME_Absolute timestamp)
533 {
534   struct GNUNET_TIME_Relative dur;
535
536   dur = GNUNET_TIME_absolute_get_duration (timestamp);
537   return GNUNET_BIO_write_int64 (wh, dur.value);
538 }
539
540
541 /**
542  * Serialize a 'start_time'.  Since we use start-times to
543  * calculate the duration of some operation, we actually
544  * do not serialize the absolute time but the (relative)
545  * duration since the start time.  When we then
546  * deserialize the start time, we take the current time and
547  * subtract that duration so that we get again an absolute
548  * time stamp that will result in correct performance
549  * calculations.
550  *
551  * @param rh handle for reading
552  * @param timestamp where to write the deserialized timestamp
553  * @return GNUNET_OK on success
554  */
555 static int
556 read_start_time (struct GNUNET_BIO_ReadHandle *rh,
557                  struct GNUNET_TIME_Absolute *timestamp)
558 {
559   struct GNUNET_TIME_Relative dur;
560   if (GNUNET_OK !=
561       GNUNET_BIO_read_int64 (rh, &dur.value))
562     return GNUNET_SYSERR;
563   *timestamp = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (),
564                                               dur);
565   return GNUNET_OK;
566 }
567
568
569 /**
570  * Using the given serialization filename, try to deserialize
571  * the file-information tree associated with it.
572  *
573  * @param h master context
574  * @param filename name of the file (without directory) with
575  *        the infromation
576  * @return NULL on error
577  */
578 static struct GNUNET_FS_FileInformation *
579 deserialize_file_information (struct GNUNET_FS_Handle *h,
580                               const char *filename);
581
582
583 /**
584  * Using the given serialization filename, try to deserialize
585  * the file-information tree associated with it.
586  *
587  * @param h master context
588  * @param fn name of the file (without directory) with
589  *        the infromation
590  * @param rh handle for reading
591  * @return NULL on error
592  */
593 static struct GNUNET_FS_FileInformation *
594 deserialize_fi_node (struct GNUNET_FS_Handle *h,
595                      const char *fn,
596                      struct GNUNET_BIO_ReadHandle *rh)
597 {
598   struct GNUNET_FS_FileInformation *ret;
599   struct GNUNET_FS_FileInformation *nxt;
600   char b;
601   char *ksks;
602   char *chks;
603   char *filename;
604   uint32_t dsize;
605
606   if (GNUNET_OK !=
607       GNUNET_BIO_read (rh, "status flag", &b, sizeof(b)))
608     {
609       GNUNET_break (0);
610       return NULL;
611     }
612   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
613   ksks = NULL;
614   chks = NULL;
615   filename = NULL;
616   if ( (GNUNET_OK !=
617         GNUNET_BIO_read_meta_data (rh, "metadata", &ret->meta)) ||
618        (GNUNET_OK !=
619         GNUNET_BIO_read_string (rh, "ksk-uri", &ksks, 32*1024)) ||
620        ( (ksks != NULL) &&
621          (NULL == 
622           (ret->keywords = GNUNET_FS_uri_parse (ksks, NULL))) ) ||
623        (GNUNET_YES !=
624         GNUNET_FS_uri_test_ksk (ret->keywords)) ||
625        (GNUNET_OK !=
626         GNUNET_BIO_read_string (rh, "chk-uri", &chks, 1024)) ||
627        ( (chks != NULL) &&
628          ( (NULL == 
629             (ret->chk_uri = GNUNET_FS_uri_parse (chks, NULL))) ||
630            (GNUNET_YES !=
631             GNUNET_FS_uri_test_chk (ret->chk_uri)) ) ) ||
632        (GNUNET_OK !=
633         GNUNET_BIO_read_int64 (rh, &ret->expirationTime.value)) ||
634        (GNUNET_OK !=
635         read_start_time (rh, &ret->start_time)) ||
636        (GNUNET_OK !=
637         GNUNET_BIO_read_string (rh, "emsg", &ret->emsg, 16*1024)) ||
638        (GNUNET_OK !=
639         GNUNET_BIO_read_string (rh, "fn", &ret->filename, 16*1024)) ||
640        (GNUNET_OK !=
641         GNUNET_BIO_read_int32 (rh, &ret->anonymity)) ||
642        (GNUNET_OK !=
643         GNUNET_BIO_read_int32 (rh, &ret->priority)) )
644     goto cleanup;
645   switch (b)
646     {
647     case 0: /* file-insert */
648       if (GNUNET_OK !=
649           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
650         goto cleanup;
651       ret->is_directory = GNUNET_NO;
652       ret->data.file.do_index = GNUNET_NO;
653       ret->data.file.have_hash = GNUNET_NO;
654       ret->data.file.index_start_confirmed = GNUNET_NO;
655       if (GNUNET_NO == ret->is_published) 
656         {
657           if (NULL == ret->filename)
658             {
659               ret->data.file.reader = &GNUNET_FS_data_reader_copy_;
660               ret->data.file.reader_cls = GNUNET_malloc_large (ret->data.file.file_size);
661               if (ret->data.file.reader_cls == NULL)
662                 goto cleanup;
663               if (GNUNET_OK !=
664                   GNUNET_BIO_read (rh, "file-data", ret->data.file.reader_cls, ret->data.file.file_size))
665                 goto cleanup;
666             }      
667           else
668             {
669               ret->data.file.reader = &GNUNET_FS_data_reader_file_;
670               ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
671             }
672         }
673       break;
674     case 1: /* file-index, no hash */
675       if (NULL == ret->filename)
676         goto cleanup;
677       if (GNUNET_OK !=
678           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
679         goto cleanup;
680       ret->is_directory = GNUNET_NO;
681       ret->data.file.do_index = GNUNET_YES;
682       ret->data.file.have_hash = GNUNET_NO;
683       ret->data.file.index_start_confirmed = GNUNET_NO;
684       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
685       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
686       break;
687     case 2: /* file-index-with-hash */
688       if (NULL == ret->filename)
689         goto cleanup;
690       if ( (GNUNET_OK !=
691             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
692            (GNUNET_OK !=
693             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
694         goto cleanup;
695       ret->is_directory = GNUNET_NO;
696       ret->data.file.do_index = GNUNET_YES;
697       ret->data.file.have_hash = GNUNET_YES;
698       ret->data.file.index_start_confirmed = GNUNET_NO;
699       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
700       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
701       break;
702     case 3: /* file-index-with-hash-confirmed */
703       if (NULL == ret->filename)
704         goto cleanup;
705       if ( (GNUNET_OK !=
706             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
707            (GNUNET_OK !=
708             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
709         goto cleanup;
710
711       ret->is_directory = GNUNET_NO;
712       ret->data.file.do_index = GNUNET_YES;
713       ret->data.file.have_hash = GNUNET_YES;
714       ret->data.file.index_start_confirmed = GNUNET_YES;
715       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
716       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
717       break;
718     case 4: /* directory */
719       if ( (GNUNET_OK !=
720             GNUNET_BIO_read_int32 (rh, &dsize)) ||
721            (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large (dsize))) ||
722            (GNUNET_OK !=
723             GNUNET_BIO_read (rh, "dir-data", ret->data.dir.dir_data, dsize)) ||
724            (GNUNET_OK !=
725             GNUNET_BIO_read_string (rh, "ent-filename", &filename, 16*1024)) )
726         goto cleanup;
727       ret->data.dir.dir_size = (uint32_t) dsize;
728       ret->is_directory = GNUNET_YES;
729       if (filename != NULL)
730         {
731           ret->data.dir.entries = deserialize_file_information (h, filename);
732           GNUNET_free (filename);
733           filename = NULL;
734           nxt = ret->data.dir.entries;
735           while (nxt != NULL)
736             {
737               nxt->dir = ret;
738               nxt = nxt->next;
739             }  
740         }
741       break;
742     default:
743       GNUNET_break (0);
744       goto cleanup;
745     }
746   ret->serialization = GNUNET_strdup (fn);
747   if (GNUNET_OK !=
748       GNUNET_BIO_read_string (rh, "nxt-filename", &filename, 16*1024))
749     goto cleanup;  
750   if (filename != NULL)
751     {
752       ret->next = deserialize_file_information (h, filename);
753       GNUNET_free (filename);
754       filename = NULL;
755     }
756   GNUNET_free_non_null (ksks);
757   GNUNET_free_non_null (chks);
758   return ret;
759  cleanup:
760   GNUNET_free_non_null (ksks);
761   GNUNET_free_non_null (chks);
762   GNUNET_free_non_null (filename);
763   GNUNET_FS_file_information_destroy (ret, NULL, NULL);
764   return NULL;
765 }
766
767
768 /**
769  * Using the given serialization filename, try to deserialize
770  * the file-information tree associated with it.
771  *
772  * @param h master context
773  * @param filename name of the file (without directory) with
774  *        the infromation
775  * @return NULL on error
776  */
777 static struct GNUNET_FS_FileInformation *
778 deserialize_file_information (struct GNUNET_FS_Handle *h,
779                               const char *filename)
780 {
781   struct GNUNET_FS_FileInformation *ret;
782   struct GNUNET_BIO_ReadHandle *rh;
783   char *emsg;
784
785   rh = get_read_handle (h, "publish-fi", filename);
786   if (rh == NULL)
787     return NULL;
788   ret = deserialize_fi_node (h, filename, rh);
789   if (GNUNET_OK !=
790       GNUNET_BIO_read_close (rh, &emsg))
791     {
792       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
793                   _("Failed to resume publishing information `%s': %s\n"),
794                   filename,
795                   emsg);
796       GNUNET_free (emsg);
797     }
798   return ret;
799 }
800
801
802 /**
803  * Given a serialization name (full absolute path), return the
804  * basename of the file (without the path), which must only
805  * consist of the 6 random characters.
806  * 
807  * @param fullname name to extract the basename from
808  * @return copy of the basename, NULL on error
809  */
810 static char *
811 get_serialization_short_name (const char *fullname)
812 {
813   const char *end;
814   const char *nxt;
815
816   end = NULL;
817   nxt = fullname;
818   /* FIXME: we could do this faster since we know
819      the length of 'end'... */
820   while ('\0' != nxt)
821     {
822       if (DIR_SEPARATOR == *nxt)
823         end = nxt + 1;
824       nxt++;
825     }
826   if ( (end == NULL) ||
827        (strlen (end) == 0) )
828     {
829       GNUNET_break (0);
830       return NULL;
831     }
832   GNUNET_break (6 == strlen (end));
833   return GNUNET_strdup (end);  
834 }
835
836
837 /**
838  * Create a new random name for serialization.  Also checks if persistence
839  * is enabled and returns NULL if not.
840  *
841  * @param h master context
842  * @param ext component of the path 
843  * @return NULL on errror
844  */
845 static char *
846 make_serialization_file_name (struct GNUNET_FS_Handle *h,
847                               const char *ext)
848 {
849   char *fn;
850   char *dn;
851   char *ret;
852
853   if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE))
854     return NULL; /* persistence not requested */
855   dn = get_serialization_file_name (h, ext, "");
856   fn = GNUNET_DISK_mktemp (dn);
857   GNUNET_free (dn);
858   if (fn == NULL)
859     return NULL; /* epic fail */
860   ret = get_serialization_short_name (fn);
861   GNUNET_free (fn);
862   return ret;
863 }
864
865
866 /**
867  * Copy all of the data from the reader to the write handle.
868  *
869  * @param wh write handle
870  * @param fi file with reader
871  * @return GNUNET_OK on success
872  */
873 static int
874 copy_from_reader (struct GNUNET_BIO_WriteHandle *wh,
875                   struct GNUNET_FS_FileInformation * fi)
876 {
877   char buf[32 * 1024];
878   uint64_t off;
879   size_t ret;
880   char *emsg;
881
882   emsg = NULL;
883   off = 0;
884   while (off < fi->data.file.file_size)
885     {
886       ret = fi->data.file.reader (fi->data.file.reader_cls,
887                                   off, sizeof (buf),
888                                   buf,
889                                   &emsg);
890       if (ret == 0)
891         {
892           GNUNET_free (emsg);
893           return GNUNET_SYSERR;
894         }
895       if (GNUNET_OK != 
896           GNUNET_BIO_write (wh, buf, ret))
897         return GNUNET_SYSERR;
898       off += ret;
899     }
900   return GNUNET_OK;
901 }
902
903
904 /**
905  * Create a temporary file on disk to store the current
906  * state of "fi" in.
907  *
908  * @param fi file information to sync with disk
909  */
910 void
911 GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation * fi)
912 {
913   char *fn;
914   struct GNUNET_BIO_WriteHandle *wh;
915   char b;
916   char *ksks;
917   char *chks;
918
919   if (NULL == fi->serialization)    
920     fi->serialization = make_serialization_file_name (fi->h, "publish-fi");
921   if (NULL == fi->serialization)
922     return;
923   wh = get_write_handle (fi->h, "publish-fi", fi->serialization);
924   if (wh == NULL)
925     {
926       GNUNET_free (fi->serialization);
927       fi->serialization = NULL;
928       return;
929     }
930   if (GNUNET_YES == fi->is_directory)
931     b = 4;
932   else if (GNUNET_YES == fi->data.file.index_start_confirmed)
933     b = 3;
934   else if (GNUNET_YES == fi->data.file.have_hash)
935     b = 2;
936   else if (GNUNET_YES == fi->data.file.do_index)
937     b = 1;
938   else
939     b = 0;
940   if (fi->keywords != NULL)
941     ksks = GNUNET_FS_uri_to_string (fi->keywords);
942   else
943     ksks = NULL;
944   if (fi->chk_uri != NULL)
945     chks = GNUNET_FS_uri_to_string (fi->chk_uri);
946   else
947     chks = NULL;
948   if ( (GNUNET_OK !=
949         GNUNET_BIO_write (wh, &b, sizeof (b))) ||
950        (GNUNET_OK != 
951         GNUNET_BIO_write_meta_data (wh, fi->meta)) ||
952        (GNUNET_OK !=
953         GNUNET_BIO_write_string (wh, ksks)) ||
954        (GNUNET_OK !=
955         GNUNET_BIO_write_string (wh, chks)) ||
956        (GNUNET_OK != 
957         GNUNET_BIO_write_int64 (wh, fi->expirationTime.value)) ||
958        (GNUNET_OK != 
959         write_start_time (wh, fi->start_time)) ||
960        (GNUNET_OK !=
961         GNUNET_BIO_write_string (wh, fi->emsg)) ||
962        (GNUNET_OK !=
963         GNUNET_BIO_write_string (wh, fi->filename)) ||
964        (GNUNET_OK != 
965         GNUNET_BIO_write_int32 (wh, fi->anonymity)) ||
966        (GNUNET_OK != 
967         GNUNET_BIO_write_int32 (wh, fi->priority)) )
968     goto cleanup;
969   GNUNET_free_non_null (chks);
970   chks = NULL;
971   GNUNET_free_non_null (ksks);
972   ksks = NULL;
973   
974   switch (b)
975     {
976     case 0: /* file-insert */
977       if (GNUNET_OK !=
978           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
979         goto cleanup;
980       if ( (GNUNET_NO == fi->is_published) &&
981            (NULL == fi->filename) )     
982         if (GNUNET_OK != 
983             copy_from_reader (wh, fi))
984           goto cleanup;
985       break;
986     case 1: /* file-index, no hash */
987       if (NULL == fi->filename)
988         goto cleanup;
989       if (GNUNET_OK !=
990           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
991         goto cleanup;
992       break;
993     case 2: /* file-index-with-hash */
994     case 3: /* file-index-with-hash-confirmed */
995       if (NULL == fi->filename)
996         goto cleanup;
997       if ( (GNUNET_OK !=
998             GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) ||
999            (GNUNET_OK !=
1000             GNUNET_BIO_write (wh, &fi->data.file.file_id, sizeof (GNUNET_HashCode))) )
1001         goto cleanup;
1002       break;
1003     case 4: /* directory */
1004       if ( (GNUNET_OK !=
1005             GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) ||
1006            (GNUNET_OK !=
1007             GNUNET_BIO_write (wh, fi->data.dir.dir_data, (uint32_t) fi->data.dir.dir_size)) ||
1008            (GNUNET_OK !=
1009             GNUNET_BIO_write_string (wh, fi->data.dir.entries->serialization)) )
1010         goto cleanup;
1011       break;
1012     default:
1013       GNUNET_assert (0);
1014       goto cleanup;
1015     }
1016   if (GNUNET_OK !=
1017       GNUNET_BIO_write_string (wh, fi->next->serialization))
1018     goto cleanup;  
1019   if (GNUNET_OK ==
1020       GNUNET_BIO_write_close (wh))
1021     return; /* done! */
1022  cleanup:
1023   (void) GNUNET_BIO_write_close (wh);
1024   GNUNET_free_non_null (chks);
1025   GNUNET_free_non_null (ksks);
1026   fn = get_serialization_file_name (fi->h, "publish-fi", fi->serialization);
1027   if (0 != UNLINK (fn))
1028     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1029   GNUNET_free (fn);
1030   GNUNET_free (fi->serialization);
1031   fi->serialization = NULL;  
1032 }
1033
1034
1035
1036 /**
1037  * Find the entry in the file information struct where the
1038  * serialization filename matches the given name.
1039  *
1040  * @param pos file information to search
1041  * @param srch filename to search for
1042  * @return NULL if srch was not found in this subtree
1043  */
1044 static struct GNUNET_FS_FileInformation *
1045 find_file_position (struct GNUNET_FS_FileInformation *pos,
1046                     const char *srch)
1047 {
1048   struct GNUNET_FS_FileInformation *r;
1049
1050   while (pos != NULL)
1051     {
1052       if (0 == strcmp (srch,
1053                        pos->serialization))
1054         return pos;
1055       if (pos->is_directory)
1056         {
1057           r = find_file_position (pos->data.dir.entries,
1058                                   srch);
1059           if (r != NULL)
1060             return r;
1061         }
1062       pos = pos->next;
1063     }
1064   return NULL;
1065 }
1066
1067
1068 /**
1069  * Signal the FS's progress function that we are resuming
1070  * an upload.
1071  *
1072  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1073  * @param fi the entry in the publish-structure
1074  * @param length length of the file or directory
1075  * @param meta metadata for the file or directory (can be modified)
1076  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1077  * @param anonymity pointer to selected anonymity level (can be modified)
1078  * @param priority pointer to selected priority (can be modified)
1079  * @param expirationTime pointer to selected expiration time (can be modified)
1080  * @param client_info pointer to client context set upon creation (can be modified)
1081  * @return GNUNET_OK to continue (always)
1082  */
1083 static int
1084 fip_signal_resume(void *cls,
1085                   struct GNUNET_FS_FileInformation *fi,
1086                   uint64_t length,
1087                   struct GNUNET_CONTAINER_MetaData *meta,
1088                   struct GNUNET_FS_Uri **uri,
1089                   uint32_t *anonymity,
1090                   uint32_t *priority,
1091                   struct GNUNET_TIME_Absolute *expirationTime,
1092                   void **client_info)
1093 {
1094   struct GNUNET_FS_PublishContext *sc = cls;
1095   struct GNUNET_FS_ProgressInfo pi;
1096
1097   pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME;
1098   pi.value.publish.specifics.resume.message = sc->fi->emsg;
1099   pi.value.publish.specifics.resume.chk_uri = sc->fi->chk_uri;
1100   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1101   return GNUNET_OK;
1102 }
1103
1104
1105 /**
1106  * Function called with a filename of serialized publishing operation
1107  * to deserialize.
1108  *
1109  * @param cls the 'struct GNUNET_FS_Handle*'
1110  * @param filename complete filename (absolute path)
1111  * @return GNUNET_OK (continue to iterate)
1112  */
1113 static int
1114 deserialize_publish_file (void *cls,
1115                           const char *filename)
1116 {
1117   struct GNUNET_FS_Handle *h = cls;
1118   struct GNUNET_BIO_ReadHandle *rh;
1119   struct GNUNET_FS_PublishContext *pc;
1120   int32_t options;
1121   int32_t all_done;
1122   char *fi_root;
1123   char *ns;
1124   char *fi_pos;
1125   char *emsg;
1126
1127   pc = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
1128   pc->h = h;
1129   pc->serialization = get_serialization_short_name (filename);
1130   fi_root = NULL;
1131   fi_pos = NULL;
1132   ns = NULL;
1133   rh = GNUNET_BIO_read_open (filename);
1134   if (rh == NULL)
1135     goto cleanup;
1136   if ( (GNUNET_OK !=
1137         GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) ||
1138        (GNUNET_OK !=
1139         GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) ||
1140        (GNUNET_OK !=
1141         GNUNET_BIO_read_int32 (rh, &options)) ||
1142        (GNUNET_OK !=
1143         GNUNET_BIO_read_int32 (rh, &all_done)) ||
1144        (GNUNET_OK !=
1145         GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) ||
1146        (GNUNET_OK !=
1147         GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) ||
1148        (GNUNET_OK !=
1149         GNUNET_BIO_read_string (rh, "publish-ns", &ns, 1024)) )
1150     goto cleanup;          
1151   pc->options = options;
1152   pc->all_done = all_done;
1153   pc->fi = deserialize_file_information (h, fi_root);
1154   if (pc->fi == NULL)
1155     goto cleanup;    
1156   if (ns != NULL)
1157     {
1158       pc->namespace = GNUNET_FS_namespace_create (h, ns);
1159       if (pc->namespace == NULL)
1160         {
1161           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1162                       _("Failed to recover namespace `%s', cannot resume publishing operation.\n"),
1163                       ns);
1164           goto cleanup;
1165         }
1166     }
1167   if (fi_pos != NULL)
1168     {
1169       pc->fi_pos = find_file_position (pc->fi,
1170                                        fi_pos);
1171       GNUNET_free (fi_pos);
1172       fi_pos = NULL;
1173       if (pc->fi_pos == NULL)
1174         {
1175           /* failed to find position for resuming, outch! Will start from root! */
1176           GNUNET_break (0);
1177           if (pc->all_done != GNUNET_YES)
1178             pc->fi_pos = pc->fi;
1179         }
1180     }
1181   /* generate RESUME event(s) */
1182   GNUNET_FS_file_information_inspect (pc->fi,
1183                                       &fip_signal_resume,
1184                                       pc);
1185   
1186   /* re-start publishing (if needed)... */
1187   if (pc->all_done != GNUNET_YES)
1188     pc->upload_task 
1189       = GNUNET_SCHEDULER_add_with_priority (h->sched,
1190                                             GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1191                                             &GNUNET_FS_publish_main_,
1192                                             pc);       
1193   if (GNUNET_OK !=
1194       GNUNET_BIO_read_close (rh, &emsg))
1195     {
1196       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1197                   _("Failure while resuming publishing operation `%s': %s\n"),
1198                   filename,
1199                   emsg);
1200       GNUNET_free (emsg);
1201     }
1202   GNUNET_free_non_null (ns);
1203   return GNUNET_OK;
1204  cleanup:
1205   GNUNET_free_non_null (pc->nid);
1206   GNUNET_free_non_null (pc->nuid);
1207   GNUNET_free_non_null (fi_root);
1208   GNUNET_free_non_null (fi_pos);
1209   GNUNET_free_non_null (ns);
1210   if ( (rh != NULL) &&
1211        (GNUNET_OK !=
1212         GNUNET_BIO_read_close (rh, &emsg)) )
1213     {
1214       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1215                   _("Failed to resume publishing operation `%s': %s\n"),
1216                   filename,
1217                   emsg);
1218       GNUNET_free (emsg);
1219     }
1220   if (pc->fi != NULL)
1221     GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
1222   if (pc->serialization != NULL)
1223     GNUNET_FS_remove_sync_file_ (h, "publish", pc->serialization);
1224   GNUNET_free_non_null (pc->serialization);
1225   GNUNET_free (pc);
1226   return GNUNET_OK;
1227 }
1228
1229
1230 /**
1231  * Synchronize this publishing struct with its mirror
1232  * on disk.  Note that all internal FS-operations that change
1233  * publishing structs should already call "sync" internally,
1234  * so this function is likely not useful for clients.
1235  * 
1236  * @param pc the struct to sync
1237  */
1238 void
1239 GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc)
1240 {  
1241   struct GNUNET_BIO_WriteHandle *wh;
1242
1243   if (NULL == pc->serialization)
1244     pc->serialization = make_serialization_file_name (pc->h,
1245                                                       "publish");
1246   if (NULL == pc->serialization)
1247     return;
1248   if (NULL == pc->fi)
1249     return;
1250   if (NULL == pc->fi->serialization)
1251     {
1252       GNUNET_break (0);
1253       return;
1254     }
1255   wh = get_write_handle (pc->h, "publish", pc->serialization);
1256   if ( (GNUNET_OK !=
1257         GNUNET_BIO_write_string (wh, pc->nid)) ||
1258        (GNUNET_OK !=
1259         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1260        (GNUNET_OK !=
1261         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1262        (GNUNET_OK !=
1263         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1264        (GNUNET_OK !=
1265         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1266        (GNUNET_OK !=
1267         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1268        (GNUNET_OK !=
1269         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1270    {
1271      (void) GNUNET_BIO_write_close (wh);
1272      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1273      GNUNET_free (pc->serialization);
1274      pc->serialization = NULL;
1275      return;
1276    }
1277  if (GNUNET_OK !=
1278      GNUNET_BIO_write_close (wh))
1279    {
1280      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1281      GNUNET_free (pc->serialization);
1282      pc->serialization = NULL;
1283      return;     
1284    }  
1285 }
1286
1287
1288 /**
1289  * Synchronize this unindex struct with its mirror
1290  * on disk.  Note that all internal FS-operations that change
1291  * publishing structs should already call "sync" internally,
1292  * so this function is likely not useful for clients.
1293  * 
1294  * @param uc the struct to sync
1295  */
1296 void
1297 GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc)
1298 {
1299   struct GNUNET_BIO_WriteHandle *wh;
1300
1301   if (UNINDEX_STATE_ABORTED == uc->state)
1302     return;
1303   if (NULL == uc->serialization)
1304     uc->serialization = make_serialization_file_name (uc->h,
1305                                                       "unindex");
1306   if (NULL == uc->serialization)
1307     return;
1308   wh = get_write_handle (uc->h, "unindex", uc->serialization);
1309   if ( (GNUNET_OK !=
1310         GNUNET_BIO_write_string (wh, uc->filename)) ||
1311        (GNUNET_OK !=
1312         GNUNET_BIO_write_int64 (wh, uc->file_size)) ||
1313        (GNUNET_OK !=
1314         write_start_time (wh, uc->start_time)) ||
1315        (GNUNET_OK !=
1316         GNUNET_BIO_write_int32 (wh, (uint32_t) uc->state)) ||
1317        ( (uc->state == UNINDEX_STATE_FS_NOTIFY) &&
1318          (GNUNET_OK !=
1319           GNUNET_BIO_write (wh, &uc->file_id, sizeof (GNUNET_HashCode))) ) ||
1320        ( (uc->state == UNINDEX_STATE_ERROR) &&
1321          (GNUNET_OK !=
1322           GNUNET_BIO_write_string (wh, uc->emsg)) ) )
1323     {
1324       (void) GNUNET_BIO_write_close (wh);
1325       GNUNET_FS_remove_sync_file_ (uc->h, "publish", uc->serialization);
1326       GNUNET_free (uc->serialization);
1327       uc->serialization = NULL;
1328       return;
1329     }
1330   if (GNUNET_OK !=
1331       GNUNET_BIO_write_close (wh))
1332     {
1333       GNUNET_FS_remove_sync_file_ (uc->h, "unindex", uc->serialization);
1334       GNUNET_free (uc->serialization);
1335       uc->serialization = NULL;
1336       return;     
1337     }  
1338 }
1339
1340
1341 /**
1342  * Serialize an active or pending download request.
1343  * 
1344  * @param cls the 'struct GNUNET_BIO_WriteHandle*'
1345  * @param key unused, can be NULL
1346  * @param value the 'struct DownloadRequest'
1347  * @return GNUNET_YES on success, GNUNET_NO on error
1348  */
1349 static int
1350 write_download_request (void *cls,
1351                         const GNUNET_HashCode *key,
1352                         void *value)
1353 {
1354   struct GNUNET_BIO_WriteHandle *wh = cls;
1355   struct DownloadRequest *dr = value;
1356   
1357   if ( (GNUNET_OK !=
1358         GNUNET_BIO_write (wh, &dr->chk, sizeof (struct ContentHashKey))) ||
1359        (GNUNET_OK !=
1360         GNUNET_BIO_write_int64 (wh, dr->offset)) ||
1361        (GNUNET_OK !=
1362         GNUNET_BIO_write_int32 (wh, dr->depth)) )    
1363     return GNUNET_NO;    
1364   return GNUNET_YES;
1365 }
1366
1367
1368 /**
1369  * Count active download requests.
1370  * 
1371  * @param cls the 'uint32_t*' counter
1372  * @param key unused, can be NULL
1373  * @param value the 'struct DownloadRequest'
1374  * @return GNUNET_YES (continue iteration)
1375  */
1376 static int
1377 count_download_requests (void *cls,
1378                         const GNUNET_HashCode *key,
1379                         void *value)
1380 {
1381   uint32_t *counter = cls;
1382   
1383   (*counter)++;
1384   return GNUNET_YES;
1385 }
1386
1387
1388 /**
1389  * Synchronize this download struct with its mirror
1390  * on disk.  Note that all internal FS-operations that change
1391  * publishing structs should already call "sync" internally,
1392  * so this function is likely not useful for clients.
1393  * 
1394  * @param dc the struct to sync
1395  */
1396 void
1397 GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc)
1398 {
1399   struct GNUNET_BIO_WriteHandle *wh;
1400   struct DownloadRequest *dr;
1401   char pbuf[32];
1402   const char *category;
1403   char *uris;
1404   char *fn;
1405   uint32_t num_pending;
1406
1407   if (dc->parent != NULL)
1408     {
1409       if (dc->parent->serialization == NULL)
1410         return;
1411       GNUNET_snprintf (pbuf,
1412                        sizeof (pbuf),
1413                        "%s%s%s",
1414                        "subdownloads",
1415                        DIR_SEPARATOR_STR,
1416                        dc->parent->serialization);
1417       category = pbuf;
1418     }
1419   else
1420     {
1421       category = "download";
1422     }
1423   if (NULL == dc->serialization)    
1424     dc->serialization = make_serialization_file_name (dc->h, 
1425                                                       category);
1426   if (NULL == dc->serialization)
1427     return;
1428   wh = get_write_handle (dc->h, category, dc->serialization);
1429   if (wh == NULL)
1430     {
1431       GNUNET_free (dc->serialization);
1432       dc->serialization = NULL;
1433       return;
1434     }
1435   GNUNET_assert ( (GNUNET_YES == GNUNET_FS_uri_test_chk (dc->uri)) ||
1436                   (GNUNET_YES == GNUNET_FS_uri_test_loc (dc->uri)) );
1437   uris = GNUNET_FS_uri_to_string (dc->uri);
1438   num_pending = 0;
1439   if (dc->emsg != NULL)
1440     {
1441       dr = dc->pending;
1442       while (dr != NULL)
1443         {
1444           num_pending++;
1445           dr = dr->next;
1446         }
1447       (void) GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1448                                                     &count_download_requests,
1449                                                     &num_pending);
1450     }
1451   GNUNET_assert ( (dc->length == dc->completed) ||
1452                   (dc->emsg != NULL) ||
1453                   (num_pending > 0) );
1454   if ( (GNUNET_OK !=
1455         GNUNET_BIO_write_string (wh, uris)) ||
1456        (GNUNET_OK !=
1457         GNUNET_BIO_write_meta_data (wh, dc->meta)) ||
1458        (GNUNET_OK !=
1459         GNUNET_BIO_write_string (wh, dc->emsg)) ||
1460        (GNUNET_OK !=
1461         GNUNET_BIO_write_string (wh, dc->filename)) ||
1462        (GNUNET_OK !=
1463         GNUNET_BIO_write_string (wh, dc->temp_filename)) ||
1464        (GNUNET_OK !=
1465         GNUNET_BIO_write_int64 (wh, dc->old_file_size)) ||
1466        (GNUNET_OK !=
1467         GNUNET_BIO_write_int64 (wh, dc->offset)) ||
1468        (GNUNET_OK !=
1469         GNUNET_BIO_write_int64 (wh, dc->length)) ||
1470        (GNUNET_OK !=
1471         GNUNET_BIO_write_int64 (wh, dc->completed)) ||
1472        (GNUNET_OK !=
1473         write_start_time (wh, dc->start_time)) ||
1474        (GNUNET_OK !=
1475         GNUNET_BIO_write_int32 (wh, dc->anonymity)) ||
1476        (GNUNET_OK !=
1477         GNUNET_BIO_write_int32 (wh, (uint32_t) dc->options)) ||
1478        (GNUNET_OK !=
1479         GNUNET_BIO_write_int32 (wh, (uint32_t) dc->has_finished)) ||
1480        (GNUNET_OK !=
1481         GNUNET_BIO_write_int32 (wh, num_pending)) )
1482     goto cleanup; 
1483   dr = dc->pending;
1484   while (dr != NULL)
1485     {
1486       if (GNUNET_YES !=
1487           write_download_request (wh, NULL, dr))
1488         goto cleanup;
1489       dr = dr->next;
1490     }
1491   if (GNUNET_SYSERR ==
1492       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1493                                              &write_download_request,
1494                                              wh))
1495     goto cleanup;
1496   while (0 < num_pending--)
1497     {
1498       dr = GNUNET_malloc (sizeof (struct DownloadRequest));
1499
1500       dr->is_pending = GNUNET_YES;
1501       dr->next = dc->pending;
1502       dc->pending = dr;
1503       dr = NULL;
1504     }
1505   GNUNET_free_non_null (uris);
1506   if (GNUNET_OK ==
1507       GNUNET_BIO_write_close (wh))
1508     return; /* done! */
1509  cleanup:
1510   (void) GNUNET_BIO_write_close (wh);
1511   GNUNET_free_non_null (uris);
1512   fn = get_serialization_file_name (dc->h, category, dc->serialization);
1513   if (0 != UNLINK (fn))
1514     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1515   GNUNET_free (fn);
1516   GNUNET_free (dc->serialization);
1517   dc->serialization = NULL;
1518 }
1519
1520
1521 /**
1522  * Synchronize this search result with its mirror
1523  * on disk.  Note that all internal FS-operations that change
1524  * publishing structs should already call "sync" internally,
1525  * so this function is likely not useful for clients.
1526  * 
1527  * @param key key for the search result
1528  * @param sr the struct to sync
1529  */
1530 void
1531 GNUNET_FS_search_result_sync_ (const GNUNET_HashCode *key,
1532                                struct GNUNET_FS_SearchResult *sr)
1533 {
1534   struct GNUNET_BIO_WriteHandle *wh;
1535   char *uris;
1536
1537   GNUNET_assert ( (GNUNET_YES == GNUNET_FS_uri_test_chk (sr->uri)) ||
1538                   (GNUNET_YES == GNUNET_FS_uri_test_loc (sr->uri)) );
1539   uris = NULL;
1540   if (NULL == sr->serialization)
1541     sr->serialization = make_serialization_file_name (sr->sc->h,
1542                                                       "search-results");
1543   if (NULL == sr->serialization)
1544     return;
1545   wh = get_write_handle (sr->sc->h, "search-results", sr->serialization);
1546   uris = GNUNET_FS_uri_to_string (sr->uri);
1547   if ( (GNUNET_OK !=
1548         GNUNET_BIO_write_string (wh, uris)) ||
1549        (GNUNET_OK !=
1550         GNUNET_BIO_write_string (wh, sr->download != NULL ? sr->download->serialization : NULL)) ||
1551        (GNUNET_OK !=
1552         GNUNET_BIO_write_meta_data (wh, sr->meta)) ||
1553        (GNUNET_OK !=
1554         GNUNET_BIO_write (wh, key, sizeof (GNUNET_HashCode))) ||
1555        (GNUNET_OK !=
1556         GNUNET_BIO_write_int32 (wh, sr->mandatory_missing)) ||
1557        (GNUNET_OK !=
1558         GNUNET_BIO_write_int32 (wh, sr->optional_support)) ||
1559        (GNUNET_OK !=
1560         GNUNET_BIO_write_int32 (wh, sr->availability_success)) ||
1561        (GNUNET_OK !=
1562         GNUNET_BIO_write_int32 (wh, sr->availability_trials)) )
1563     goto cleanup;   
1564   if (GNUNET_OK !=
1565       GNUNET_BIO_write_close (wh))
1566     {
1567       wh = NULL;
1568       goto cleanup;
1569     }
1570   GNUNET_free_non_null (uris);
1571   return;
1572  cleanup:
1573   GNUNET_free_non_null (uris);
1574   if (wh != NULL)
1575     (void)  GNUNET_BIO_write_close (wh);
1576   GNUNET_FS_remove_sync_file_ (sr->sc->h, "search-results", sr->serialization);
1577   GNUNET_free (sr->serialization);
1578   sr->serialization = NULL;
1579 }
1580
1581
1582 /**
1583  * Synchronize this search struct with its mirror
1584  * on disk.  Note that all internal FS-operations that change
1585  * publishing structs should already call "sync" internally,
1586  * so this function is likely not useful for clients.
1587  * 
1588  * @param sc the struct to sync
1589  */
1590 void
1591 GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc)
1592 {  
1593   struct GNUNET_BIO_WriteHandle *wh;
1594   struct GNUNET_FS_SearchContext *scc;
1595   char *uris;
1596   char in_pause;
1597
1598   if (NULL == sc->serialization)
1599     sc->serialization = make_serialization_file_name (sc->h,
1600                                                       "search");
1601   if (NULL == sc->serialization)
1602     return;
1603   wh = get_write_handle (sc->h, "search", sc->serialization);
1604   GNUNET_assert ( (GNUNET_YES == GNUNET_FS_uri_test_ksk (sc->uri)) ||
1605                   (GNUNET_YES == GNUNET_FS_uri_test_sks (sc->uri)) );
1606   uris = GNUNET_FS_uri_to_string (sc->uri);
1607   in_pause = (sc->task != GNUNET_SCHEDULER_NO_TASK) ? 'r' : '\0';
1608   if ( (GNUNET_OK !=
1609         GNUNET_BIO_write_string (wh, uris)) ||
1610        (GNUNET_OK !=
1611         write_start_time (wh, sc->start_time)) ||
1612        (GNUNET_OK !=
1613         GNUNET_BIO_write_string (wh, sc->emsg)) ||
1614        (GNUNET_OK !=
1615         GNUNET_BIO_write_int32 (wh, (uint32_t) sc->options)) ||
1616        (GNUNET_OK !=
1617         GNUNET_BIO_write (wh, &in_pause, sizeof (in_pause))) ||
1618        (GNUNET_OK !=
1619         GNUNET_BIO_write_int32 (wh, sc->anonymity)) )
1620     goto cleanup;          
1621   GNUNET_free (uris);
1622   uris = NULL;
1623   scc = sc->child_head;
1624   while (NULL != scc)
1625     {
1626       if (scc->serialization == NULL)
1627         break;
1628       if (GNUNET_OK !=
1629           GNUNET_BIO_write_string (wh, scc->serialization))
1630         goto cleanup;
1631       scc = scc->next;
1632     }
1633   GNUNET_BIO_write_string (wh, NULL);
1634   if (GNUNET_OK !=
1635       GNUNET_BIO_write_close (wh))
1636     {
1637       wh = NULL;
1638       goto cleanup;
1639     }
1640   return;
1641  cleanup:
1642   if (wh != NULL)
1643     (void) GNUNET_BIO_write_close (wh);
1644   GNUNET_free_non_null (uris);
1645   GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1646   GNUNET_free (sc->serialization);
1647   sc->serialization = NULL;
1648 }
1649
1650
1651 /**
1652  * Deserialize information about pending publish operations.
1653  *
1654  * @param h master context
1655  */
1656 static void
1657 deserialize_publish (struct GNUNET_FS_Handle *h)
1658 {
1659   char *dn;
1660
1661   dn = get_serialization_file_name (h, "publish", "");
1662   if (dn == NULL)
1663     return;
1664   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1665   GNUNET_free (dn);
1666 }
1667
1668
1669 /**
1670  * Function called with a filename of serialized unindexing operation
1671  * to deserialize.
1672  *
1673  * @param cls the 'struct GNUNET_FS_Handle*'
1674  * @param filename complete filename (absolute path)
1675  * @return GNUNET_OK (continue to iterate)
1676  */
1677 static int
1678 deserialize_unindex_file (void *cls,
1679                           const char *filename)
1680 {
1681   struct GNUNET_FS_Handle *h = cls;
1682   struct GNUNET_BIO_ReadHandle *rh;
1683   struct GNUNET_FS_UnindexContext *uc;
1684   struct GNUNET_FS_ProgressInfo pi;
1685   char *emsg;
1686   uint32_t state;
1687
1688   uc = GNUNET_malloc (sizeof (struct GNUNET_FS_UnindexContext));
1689   uc->h = h;
1690   uc->serialization = get_serialization_short_name (filename);
1691   rh = GNUNET_BIO_read_open (filename);
1692   if (rh == NULL)
1693     goto cleanup;
1694   if ( (GNUNET_OK !=
1695         GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10*1024)) ||
1696        (GNUNET_OK !=
1697         GNUNET_BIO_read_int64 (rh, &uc->file_size)) ||
1698        (GNUNET_OK !=
1699         read_start_time (rh, &uc->start_time)) ||
1700        (GNUNET_OK !=
1701         GNUNET_BIO_read_int32 (rh, &state)) )
1702     goto cleanup;          
1703   uc->state = (enum UnindexState) state;
1704   switch (state)
1705     {
1706     case UNINDEX_STATE_HASHING:
1707       break;
1708     case UNINDEX_STATE_FS_NOTIFY:
1709       if (GNUNET_OK !=
1710           GNUNET_BIO_read (rh, "unindex-hash", &uc->file_id, sizeof (GNUNET_HashCode)))
1711         goto cleanup;
1712       break;
1713     case UNINDEX_STATE_DS_REMOVE:
1714       break;
1715     case UNINDEX_STATE_COMPLETE:
1716       break;
1717     case UNINDEX_STATE_ERROR:
1718       if (GNUNET_OK !=
1719           GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10*1024))
1720         goto cleanup;
1721       break;
1722     case UNINDEX_STATE_ABORTED:
1723       GNUNET_break (0);
1724       goto cleanup;
1725     default:
1726       GNUNET_break (0);
1727       goto cleanup;
1728     }
1729   pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME;
1730   pi.value.unindex.specifics.resume.message = uc->emsg;
1731   GNUNET_FS_unindex_make_status_ (&pi,
1732                                   uc,
1733                                   (uc->state == UNINDEX_STATE_COMPLETE) 
1734                                   ? uc->file_size
1735                                   : 0);
1736   switch (uc->state)
1737     {
1738     case UNINDEX_STATE_HASHING:
1739       GNUNET_CRYPTO_hash_file (uc->h->sched,
1740                                GNUNET_SCHEDULER_PRIORITY_IDLE,
1741                                uc->filename,
1742                                HASHING_BLOCKSIZE,
1743                                &GNUNET_FS_unindex_process_hash_,
1744                                uc);
1745       break;
1746     case UNINDEX_STATE_FS_NOTIFY:
1747       uc->state = UNINDEX_STATE_HASHING;
1748       GNUNET_FS_unindex_process_hash_ (uc,
1749                                        &uc->file_id);
1750       break;
1751     case UNINDEX_STATE_DS_REMOVE:
1752       GNUNET_FS_unindex_do_remove_ (uc);
1753       break;
1754     case UNINDEX_STATE_COMPLETE:
1755     case UNINDEX_STATE_ERROR:
1756       /* no need to resume any operation, we were done */
1757       break;
1758     default:
1759       break;
1760     }
1761   if (GNUNET_OK !=
1762       GNUNET_BIO_read_close (rh, &emsg))
1763     {
1764       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1765                   _("Failure while resuming unindexing operation `%s': %s\n"),
1766                   filename,
1767                   emsg);
1768       GNUNET_free (emsg);
1769     }
1770   return GNUNET_OK;
1771  cleanup:
1772   GNUNET_free_non_null (uc->filename);
1773   if ( (rh != NULL) &&
1774        (GNUNET_OK !=
1775         GNUNET_BIO_read_close (rh, &emsg)) )
1776     {
1777       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1778                   _("Failed to resume unindexing operation `%s': %s\n"),
1779                   filename,
1780                   emsg);
1781       GNUNET_free (emsg);
1782     }
1783   if (uc->serialization != NULL)
1784     GNUNET_FS_remove_sync_file_ (h, "unindex", uc->serialization);
1785   GNUNET_free_non_null (uc->serialization);
1786   GNUNET_free (uc);
1787   return GNUNET_OK;
1788 }
1789
1790
1791 /**
1792  * Deserialize information about pending publish operations.
1793  *
1794  * @param h master context
1795  */
1796 static void
1797 deserialize_unindex (struct GNUNET_FS_Handle *h)
1798 {
1799   char *dn;
1800
1801   dn = get_serialization_file_name (h, "unindex", "");
1802   if (dn == NULL)
1803     return;
1804   GNUNET_DISK_directory_scan (dn, &deserialize_unindex_file, h);
1805   GNUNET_free (dn);
1806 }
1807
1808
1809 /**
1810  * Deserialize a download.
1811  *
1812  * @param h overall context
1813  * @param rh file to deserialize from
1814  * @param parent parent download
1815  * @param search associated search
1816  * @param serialization name under which the search was serialized
1817  */
1818 static void
1819 deserialize_download (struct GNUNET_FS_Handle *h,
1820                       struct GNUNET_BIO_ReadHandle *rh,
1821                       struct GNUNET_FS_DownloadContext *parent,
1822                       struct GNUNET_FS_SearchResult *search,
1823                       const char *serialization);
1824
1825
1826 /**
1827  * Function called with a filename of serialized search result
1828  * to deserialize.
1829  *
1830  * @param cls the 'struct GNUNET_FS_SearchContext*'
1831  * @param filename complete filename (absolute path)
1832  * @return GNUNET_OK (continue to iterate)
1833  */
1834 static int
1835 deserialize_search_result (void *cls,
1836                            const char *filename)
1837 {
1838   struct GNUNET_FS_SearchContext *sc = cls;
1839   char pbuf[32];
1840   char *ser;
1841   char *uris;
1842   char *emsg;
1843   char *download;
1844   struct GNUNET_BIO_ReadHandle *rh;
1845   struct GNUNET_BIO_ReadHandle *drh;
1846   struct GNUNET_FS_SearchResult *sr;
1847   GNUNET_HashCode key;
1848
1849   ser = get_serialization_short_name (filename);
1850   rh = GNUNET_BIO_read_open (filename);
1851   if (rh == NULL)
1852     {
1853       if (ser != NULL)
1854         {
1855           GNUNET_snprintf (pbuf,
1856                            sizeof (pbuf),
1857                            "%s%s%s",
1858                            "search-results",
1859                            DIR_SEPARATOR_STR,
1860                            sc->serialization);
1861           GNUNET_FS_remove_sync_file_ (sc->h, pbuf, ser);
1862           GNUNET_free (ser);
1863         }
1864       return GNUNET_OK;
1865     }
1866   emsg = NULL;
1867   uris = NULL;
1868   download = NULL;
1869   sr = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchResult));
1870   sr->serialization = ser;  
1871   if ( (GNUNET_OK !=
1872         GNUNET_BIO_read_string (rh, "result-uri", &uris, 10*1024)) ||
1873        (NULL == (sr->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
1874        ( (GNUNET_YES != GNUNET_FS_uri_test_chk (sr->uri)) &&
1875          (GNUNET_YES != GNUNET_FS_uri_test_loc (sr->uri)) ) ||
1876        (GNUNET_OK !=
1877         GNUNET_BIO_read_string (rh, "download-lnk", &download, 16)) ||
1878        (GNUNET_OK !=
1879         GNUNET_BIO_read_meta_data (rh, "result-meta", &sr->meta)) ||
1880        (GNUNET_OK !=
1881         GNUNET_BIO_read (rh, "result-key", &key, sizeof (key))) ||
1882        (GNUNET_OK !=
1883         GNUNET_BIO_read_int32 (rh, &sr->mandatory_missing)) ||
1884        (GNUNET_OK !=
1885         GNUNET_BIO_read_int32 (rh, &sr->optional_support)) ||
1886        (GNUNET_OK !=
1887         GNUNET_BIO_read_int32 (rh, &sr->availability_success)) ||
1888        (GNUNET_OK !=
1889         GNUNET_BIO_read_int32 (rh, &sr->availability_trials)) )
1890     goto cleanup;   
1891   GNUNET_free (uris);
1892   if (download != NULL)
1893     {
1894       drh = get_read_handle (sc->h, 
1895                              "subdownloads",
1896                              download);
1897       deserialize_download (sc->h,
1898                             drh,
1899                             NULL,
1900                             sr,
1901                             download);
1902       if (GNUNET_OK !=
1903           GNUNET_BIO_read_close (drh, &emsg))
1904         {
1905           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1906                       _("Failed to resume sub-download `%s': %s\n"),
1907                       download,
1908                       emsg);
1909           GNUNET_free (emsg);
1910         }
1911       GNUNET_free (download);
1912     }
1913   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map,
1914                                      &key,
1915                                      sr,
1916                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1917   return GNUNET_OK;
1918  cleanup:
1919   GNUNET_free_non_null (download);
1920   GNUNET_free_non_null (emsg);
1921   GNUNET_free_non_null (uris);
1922   if (sr->uri != NULL)
1923     GNUNET_FS_uri_destroy (sr->uri);
1924   if (sr->meta != NULL)
1925     GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1926   GNUNET_free (sr->serialization);
1927   GNUNET_free (sr);  
1928   return GNUNET_OK;
1929 }
1930
1931
1932 /**
1933  * Send the 'resume' signal to the callback; also actually
1934  * resume the download (put it in the queue).  Does this
1935  * recursively for the top-level download and all child
1936  * downloads.
1937  * 
1938  * @param dc download to resume
1939  */
1940 static void
1941 signal_download_resume (struct GNUNET_FS_DownloadContext *dc)
1942 {
1943   struct GNUNET_FS_DownloadContext *dcc;
1944   struct GNUNET_FS_ProgressInfo pi;
1945   
1946   pi.status = GNUNET_FS_STATUS_DOWNLOAD_RESUME;
1947   pi.value.download.specifics.resume.meta = dc->meta;
1948   pi.value.download.specifics.resume.message = dc->emsg;
1949   GNUNET_FS_download_make_status_ (&pi,
1950                                    dc);
1951   dcc = dc->child_head;
1952   while (NULL != dcc)
1953     {
1954       signal_download_resume (dcc);
1955       dcc = dcc->next;
1956     }
1957   if (dc->pending != NULL)
1958     GNUNET_FS_download_start_downloading_ (dc);
1959 }
1960
1961
1962 /**
1963  * Iterator over search results signaling resume to the client for
1964  * each result.
1965  *
1966  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
1967  * @param key current key code
1968  * @param value value in the hash map, the 'struct GNUNET_FS_SearchResult'
1969  * @return GNUNET_YES (we should continue to iterate)
1970  */
1971 static int
1972 signal_result_resume (void *cls,
1973                       const GNUNET_HashCode * key,
1974                       void *value)
1975 {
1976   struct GNUNET_FS_SearchContext *sc = cls;
1977   struct GNUNET_FS_ProgressInfo pi;
1978   struct GNUNET_FS_SearchResult *sr = value;
1979
1980   if (0 == sr->mandatory_missing)
1981     {
1982       pi.status = GNUNET_FS_STATUS_SEARCH_RESUME_RESULT;
1983       pi.value.search.specifics.resume_result.meta = sr->meta;
1984       pi.value.search.specifics.resume_result.uri = sr->uri;
1985       pi.value.search.specifics.resume_result.result = sr;
1986       pi.value.search.specifics.resume_result.availability_rank = 2*sr->availability_success - sr->availability_trials;
1987       pi.value.search.specifics.resume_result.availability_certainty = sr->availability_trials;
1988       pi.value.search.specifics.resume_result.applicability_rank = sr->optional_support;
1989       sr->client_info = GNUNET_FS_search_make_status_ (&pi,
1990                                                        sc);
1991     }
1992   if (sr->download != NULL)
1993     {
1994       signal_download_resume (sr->download);
1995     }
1996   else
1997     {
1998       GNUNET_FS_search_start_probe_ (sr);
1999     }
2000   return GNUNET_YES;
2001 }
2002
2003
2004 /**
2005  * Iterator over search results freeing each.
2006  *
2007  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
2008  * @param key current key code
2009  * @param value value in the hash map, the 'struct GNUNET_FS_SearchResult'
2010  * @return GNUNET_YES (we should continue to iterate)
2011  */
2012 static int
2013 free_result (void *cls,
2014              const GNUNET_HashCode * key,
2015              void *value)
2016 {
2017   struct GNUNET_FS_SearchResult *sr = value;
2018
2019   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
2020   GNUNET_FS_uri_destroy (sr->uri);
2021   GNUNET_free (sr);
2022   return GNUNET_YES;
2023 }
2024
2025
2026 /**
2027  * Free memory allocated by the search context and its children
2028  *
2029  * @param sc search context to free
2030  */
2031 static void
2032 free_search_context (struct GNUNET_FS_SearchContext *sc)
2033 {
2034   struct GNUNET_FS_SearchContext *scc;
2035
2036   while (NULL != (scc = sc->child_head))
2037     {
2038       GNUNET_CONTAINER_DLL_remove (sc->child_head,
2039                                    sc->child_tail,
2040                                    scc);      
2041       free_search_context (scc);
2042     }
2043   GNUNET_free_non_null (sc->emsg);
2044   if (sc->serialization != NULL)
2045     GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
2046   /* FIXME: remove 'pbuf' directory with search results as well! */
2047   GNUNET_free_non_null (sc->serialization);
2048   if (sc->uri != NULL)
2049     GNUNET_FS_uri_destroy (sc->uri);
2050   if (sc->master_result_map != NULL)
2051     {
2052       GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
2053                                              &free_result,
2054                                              sc);
2055       GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
2056     }
2057   GNUNET_free (sc);
2058 }
2059
2060
2061 /**
2062  * Function called with a filename of serialized sub-download
2063  * to deserialize.
2064  *
2065  * @param cls the 'struct GNUNET_FS_DownloadContext*' (parent)
2066  * @param filename complete filename (absolute path)
2067  * @return GNUNET_OK (continue to iterate)
2068  */
2069 static int
2070 deserialize_subdownload (void *cls,
2071                          const char *filename)
2072 {
2073   struct GNUNET_FS_DownloadContext *parent = cls;
2074   char *ser;
2075   char *emsg;
2076   struct GNUNET_BIO_ReadHandle *rh;
2077
2078   ser = get_serialization_short_name (filename);
2079   rh = GNUNET_BIO_read_open (filename);
2080   deserialize_download (parent->h,
2081                         rh,
2082                         parent,
2083                         NULL,
2084                         ser);
2085   if (GNUNET_OK !=
2086       GNUNET_BIO_read_close (rh, &emsg))
2087     {
2088       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2089                   _("Failed to resume sub-download `%s': %s\n"),
2090                   ser,
2091                   emsg);
2092       GNUNET_free (emsg);
2093     }
2094   GNUNET_free (ser);
2095   return GNUNET_OK;
2096 }
2097
2098
2099 /**
2100  * Free this download context and all of its descendants.
2101  * (only works during deserialization since not all possible
2102  * state it taken care of).
2103  *
2104  * @param dc context to free
2105  */
2106 static void
2107 free_download_context (struct GNUNET_FS_DownloadContext *dc)
2108 {
2109   struct GNUNET_FS_DownloadContext *dcc;
2110   struct DownloadRequest *dr;
2111   if (dc->meta != NULL)
2112     GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2113   if (dc->uri != NULL)
2114     GNUNET_FS_uri_destroy (dc->uri);
2115   GNUNET_free_non_null (dc->temp_filename);
2116   GNUNET_free_non_null (dc->emsg);
2117   GNUNET_free_non_null (dc->filename);
2118   while (NULL != (dcc = dc->child_head))
2119     {
2120       GNUNET_CONTAINER_DLL_remove (dc->child_head,
2121                                    dc->child_tail,
2122                                    dcc);
2123       free_download_context (dcc);
2124     }
2125   while (NULL != (dr = dc->pending))
2126     {
2127       dc->pending = dr->next;
2128       GNUNET_free (dr);
2129     }
2130   GNUNET_free (dc);
2131 }
2132
2133
2134 /**
2135  * Deserialize a download.
2136  *
2137  * @param h overall context
2138  * @param rh file to deserialize from
2139  * @param parent parent download
2140  * @param search associated search
2141  * @param serialization name under which the search was serialized
2142  */
2143 static void
2144 deserialize_download (struct GNUNET_FS_Handle *h,
2145                       struct GNUNET_BIO_ReadHandle *rh,
2146                       struct GNUNET_FS_DownloadContext *parent,
2147                       struct GNUNET_FS_SearchResult *search,
2148                       const char *serialization)
2149 {
2150   struct GNUNET_FS_DownloadContext *dc;
2151   struct DownloadRequest *dr;
2152   char pbuf[32];
2153   char *emsg;
2154   char *uris;
2155   char *dn;
2156   uint32_t options;
2157   uint32_t status;
2158   uint32_t num_pending;
2159
2160   uris = NULL;
2161   emsg = NULL;
2162   dr = NULL;
2163   dc = GNUNET_malloc (sizeof (struct GNUNET_FS_DownloadContext));
2164   dc->parent = parent;
2165   dc->h = h;
2166   dc->serialization = GNUNET_strdup (serialization);
2167   if ( (GNUNET_OK !=
2168         GNUNET_BIO_read_string (rh, "download-uri", &uris, 10*1024)) ||
2169        (NULL == (dc->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
2170        ( (GNUNET_YES != GNUNET_FS_uri_test_chk (dc->uri)) &&
2171          (GNUNET_YES != GNUNET_FS_uri_test_loc (dc->uri)) ) ||
2172        (GNUNET_OK !=
2173         GNUNET_BIO_read_meta_data (rh, "download-meta", &dc->meta)) ||
2174        (GNUNET_OK !=
2175         GNUNET_BIO_read_string (rh, "download-emsg", &dc->emsg, 10*1024)) ||
2176        (GNUNET_OK !=
2177         GNUNET_BIO_read_string (rh, "download-fn", &dc->filename, 10*1024)) ||
2178        (GNUNET_OK !=
2179         GNUNET_BIO_read_string (rh, "download-tfn", &dc->temp_filename, 10*1024)) ||
2180        (GNUNET_OK !=
2181         GNUNET_BIO_read_int64 (rh, &dc->old_file_size)) ||
2182        (GNUNET_OK !=
2183         GNUNET_BIO_read_int64 (rh, &dc->offset)) ||
2184        (GNUNET_OK !=
2185         GNUNET_BIO_read_int64 (rh, &dc->length)) ||
2186        (GNUNET_OK !=
2187         GNUNET_BIO_read_int64 (rh, &dc->completed)) ||
2188        (GNUNET_OK !=
2189         read_start_time (rh, &dc->start_time)) ||
2190        (GNUNET_OK !=
2191         GNUNET_BIO_read_int32 (rh, &dc->anonymity)) ||
2192        (GNUNET_OK !=
2193         GNUNET_BIO_read_int32 (rh, &options)) ||
2194        (GNUNET_OK !=
2195         GNUNET_BIO_read_int32 (rh, &status)) ||
2196        (GNUNET_OK !=
2197         GNUNET_BIO_read_int32 (rh, &num_pending)) )
2198     goto cleanup;          
2199   dc->options = (enum GNUNET_FS_DownloadOptions) options;
2200   dc->active = GNUNET_CONTAINER_multihashmap_create (16);
2201   dc->has_finished = (int) status;
2202   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2203   if (GNUNET_FS_uri_test_loc (dc->uri))
2204     GNUNET_assert (GNUNET_OK ==
2205                    GNUNET_FS_uri_loc_get_peer_identity (dc->uri,
2206                                                         &dc->target));
2207   if ( (dc->length > dc->completed) &&
2208        (num_pending == 0) )
2209     goto cleanup;    
2210   while (0 < num_pending--)
2211     {
2212       dr = GNUNET_malloc (sizeof (struct DownloadRequest));
2213       if ( (GNUNET_OK !=
2214             GNUNET_BIO_read (rh, "chk", &dr->chk, sizeof (struct ContentHashKey))) ||
2215            (GNUNET_OK !=
2216             GNUNET_BIO_read_int64 (rh, &dr->offset)) ||
2217            (GNUNET_OK !=
2218             GNUNET_BIO_read_int32 (rh, &dr->depth)) )
2219         goto cleanup;      
2220       dr->is_pending = GNUNET_YES;
2221       dr->next = dc->pending;
2222       dc->pending = dr;
2223       dr = NULL;
2224     }
2225   GNUNET_snprintf (pbuf,
2226                    sizeof (pbuf),
2227                    "%s%s%s",
2228                    "subdownloads",
2229                    DIR_SEPARATOR_STR,
2230                    dc->serialization);
2231   dn = get_serialization_file_name (h, pbuf, "");
2232   if (dn != NULL)
2233     {
2234       GNUNET_DISK_directory_scan (dn, &deserialize_subdownload, dc);
2235       GNUNET_free (dn);
2236     }
2237   if (parent != NULL)
2238     GNUNET_CONTAINER_DLL_insert (parent->child_head,
2239                                  parent->child_tail,
2240                                  dc);
2241   if (search != NULL)
2242     {
2243       dc->search = search;
2244       search->download = dc;
2245     }
2246   signal_download_resume (dc);
2247   GNUNET_free (uris);
2248   return;
2249  cleanup:
2250   GNUNET_free_non_null (uris);
2251   GNUNET_free_non_null (dr);
2252   free_download_context (dc);
2253 }
2254
2255
2256 /**
2257  * Signal resuming of a search to our clients (for the
2258  * top level search and all sub-searches).
2259  *
2260  * @param sc search being resumed
2261  */
2262 static void
2263 signal_search_resume (struct GNUNET_FS_SearchContext *sc)
2264 {
2265   struct GNUNET_FS_SearchContext *scc;
2266   struct GNUNET_FS_ProgressInfo pi;
2267
2268   pi.status = GNUNET_FS_STATUS_SEARCH_RESUME;
2269   pi.value.search.specifics.resume.message = sc->emsg;
2270   pi.value.search.specifics.resume.is_paused = (sc->client == NULL) ? GNUNET_YES : GNUNET_NO;
2271   sc->client_info = GNUNET_FS_search_make_status_ (&pi,
2272                                                    sc);
2273   scc = sc->child_head;
2274   while (NULL != scc)
2275     {
2276       signal_search_resume (scc);
2277       scc = scc->next;
2278     }
2279 }
2280
2281
2282 /**
2283  * Deserialize a search. 
2284  *
2285  * @param h overall context
2286  * @param rh file to deserialize from
2287  * @param parent parent search
2288  * @param serialization name under which the search was serialized
2289  */
2290 static struct GNUNET_FS_SearchContext *
2291 deserialize_search (struct GNUNET_FS_Handle *h,
2292                     struct GNUNET_BIO_ReadHandle *rh,
2293                     struct GNUNET_FS_SearchContext *parent,
2294                     const char *serialization)
2295 {
2296   struct GNUNET_FS_SearchContext *sc;
2297   struct GNUNET_FS_SearchContext *scc;
2298   struct GNUNET_BIO_ReadHandle *rhc;
2299   char pbuf[32];
2300   char *emsg;
2301   char *uris;
2302   char *child_ser;
2303   char *dn;
2304   uint32_t options;
2305   char in_pause;
2306
2307   uris = NULL;
2308   emsg = NULL;
2309   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
2310   sc->parent = parent;
2311   sc->h = h;
2312   sc->serialization = GNUNET_strdup (serialization);
2313   if ( (GNUNET_OK !=
2314         GNUNET_BIO_read_string (rh, "search-uri", &uris, 10*1024)) ||
2315        (NULL == (sc->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
2316        ( (GNUNET_YES != GNUNET_FS_uri_test_ksk (sc->uri)) &&
2317          (GNUNET_YES != GNUNET_FS_uri_test_sks (sc->uri)) ) ||
2318        (GNUNET_OK !=
2319         read_start_time (rh, &sc->start_time)) ||
2320        (GNUNET_OK !=
2321         GNUNET_BIO_read_string (rh, "search-emsg", &sc->emsg, 10*1024)) ||
2322        (GNUNET_OK !=
2323         GNUNET_BIO_read_int32 (rh, &options)) ||
2324        (GNUNET_OK !=
2325         GNUNET_BIO_read (rh, "search-pause", &in_pause, sizeof (in_pause))) ||
2326        (GNUNET_OK !=
2327         GNUNET_BIO_read_int32 (rh, &sc->anonymity)) )
2328     goto cleanup;          
2329   sc->options = (enum GNUNET_FS_SearchOptions) options;
2330   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
2331   GNUNET_snprintf (pbuf,
2332                    sizeof (pbuf),
2333                    "%s%s%s",
2334                    "search-results",
2335                    DIR_SEPARATOR_STR,
2336                    sc->serialization);
2337   dn = get_serialization_file_name (h, pbuf, "");
2338   if (dn != NULL)
2339     {
2340       GNUNET_DISK_directory_scan (dn, &deserialize_search_result, sc);
2341       GNUNET_free (dn);
2342     }
2343   if ( ('\0' == in_pause) &&
2344        (GNUNET_OK !=
2345         GNUNET_FS_search_start_searching_ (sc)) )
2346     {
2347       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2348                   _("Could not resume running search, will resume as paused search\n"));    
2349     }
2350   while (1)
2351     {
2352       if ( (GNUNET_OK !=
2353             GNUNET_BIO_read_string (rh, "child-serialization", &child_ser, 32)))
2354         goto cleanup;
2355       if (child_ser == NULL)
2356         break;    
2357       rhc = get_read_handle (h, "search-children", child_ser);
2358       if (rhc != NULL)
2359         {
2360           scc = deserialize_search (h, rhc, sc, child_ser);
2361           if (scc != NULL)          
2362             GNUNET_CONTAINER_DLL_insert (sc->child_head,
2363                                          sc->child_tail,
2364                                          scc);      
2365           emsg = NULL;
2366           if (GNUNET_OK !=
2367               GNUNET_BIO_read_close (rhc, &emsg))
2368             {
2369               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2370                           _("Failed to resume sub-search `%s': %s\n"),
2371                           child_ser,
2372                           emsg);
2373               GNUNET_free (emsg);
2374             }
2375         }    
2376       GNUNET_free (child_ser);  
2377     }
2378   if (parent != NULL)
2379     GNUNET_CONTAINER_DLL_insert (parent->child_head,
2380                                  parent->child_tail,
2381                                  sc);
2382   signal_search_resume (sc);
2383   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
2384                                          &signal_result_resume,
2385                                          sc);
2386   GNUNET_free (uris);
2387   return sc;
2388  cleanup:
2389   GNUNET_free_non_null (emsg);
2390   free_search_context (sc);
2391   GNUNET_free_non_null (uris);
2392   return NULL;
2393 }
2394
2395
2396 /**
2397  * Function called with a filename of serialized search operation
2398  * to deserialize.
2399  *
2400  * @param cls the 'struct GNUNET_FS_Handle*'
2401  * @param filename complete filename (absolute path)
2402  * @return GNUNET_OK (continue to iterate)
2403  */
2404 static int
2405 deserialize_search_file (void *cls,
2406                           const char *filename)
2407 {
2408   struct GNUNET_FS_Handle *h = cls;
2409   char *ser;
2410   char *emsg;
2411   struct GNUNET_BIO_ReadHandle *rh;
2412   struct GNUNET_FS_SearchContext *sc;
2413
2414   ser = get_serialization_short_name (filename);
2415   rh = GNUNET_BIO_read_open (filename);
2416   if (rh == NULL)
2417     {
2418       if (ser != NULL)
2419         {
2420           GNUNET_FS_remove_sync_file_ (h, "search", ser);
2421           GNUNET_free (ser);
2422         }
2423       return GNUNET_OK;
2424     }
2425   sc = deserialize_search (h, rh, NULL, ser);
2426   GNUNET_free (ser);
2427   if (GNUNET_OK !=
2428       GNUNET_BIO_read_close (rh, &emsg))
2429     {
2430       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2431                   _("Failure while resuming search operation `%s': %s\n"),
2432                   filename,
2433                   emsg);
2434       GNUNET_free (emsg);
2435     }
2436   return GNUNET_OK;
2437 }
2438
2439
2440 /**
2441  * Deserialize information about pending search operations.
2442  *
2443  * @param h master context
2444  */
2445 static void
2446 deserialize_search_master (struct GNUNET_FS_Handle *h)
2447 {
2448   char *dn;
2449
2450   dn = get_serialization_file_name (h, "search", "");
2451   if (dn == NULL)
2452     return;
2453   GNUNET_DISK_directory_scan (dn, &deserialize_search_file, h);
2454   GNUNET_free (dn);
2455 }
2456
2457
2458 /**
2459  * Function called with a filename of serialized download operation
2460  * to deserialize.
2461  *
2462  * @param cls the 'struct GNUNET_FS_Handle*'
2463  * @param filename complete filename (absolute path)
2464  * @return GNUNET_OK (continue to iterate)
2465  */
2466 static int
2467 deserialize_download_file (void *cls,
2468                            const char *filename)
2469 {
2470   struct GNUNET_FS_Handle *h = cls;
2471   char *ser;
2472   char *emsg;
2473   struct GNUNET_BIO_ReadHandle *rh;
2474
2475   ser = get_serialization_short_name (filename);
2476   rh = GNUNET_BIO_read_open (filename);
2477   if (rh == NULL)
2478     {
2479       if (ser != NULL)
2480         {
2481           GNUNET_FS_remove_sync_file_ (h, "download", ser);
2482           GNUNET_free (ser);
2483         }
2484       return GNUNET_OK;
2485     }
2486   deserialize_download (h, rh, NULL, NULL, ser);
2487   GNUNET_free (ser);
2488   if (GNUNET_OK !=
2489       GNUNET_BIO_read_close (rh, &emsg))
2490     {
2491       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2492                   _("Failure while resuming download operation `%s': %s\n"),
2493                   filename,
2494                   emsg);
2495       GNUNET_free (emsg);
2496     }
2497   return GNUNET_OK;
2498 }
2499
2500
2501 /**
2502  * Deserialize information about pending download operations.
2503  *
2504  * @param h master context
2505  */
2506 static void
2507 deserialize_download_master (struct GNUNET_FS_Handle *h)
2508 {
2509   char *dn;
2510
2511   dn = get_serialization_file_name (h, "download", "");
2512   if (dn == NULL)
2513     return;
2514   GNUNET_DISK_directory_scan (dn, &deserialize_download_file, h);
2515   GNUNET_free (dn);
2516 }
2517
2518
2519 /**
2520  * Setup a connection to the file-sharing service.
2521  *
2522  * @param sched scheduler to use
2523  * @param cfg configuration to use
2524  * @param client_name unique identifier for this client 
2525  * @param upcb function to call to notify about FS actions
2526  * @param upcb_cls closure for upcb
2527  * @param flags specific attributes for fs-operations
2528  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
2529  * @return NULL on error
2530  */
2531 struct GNUNET_FS_Handle *
2532 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
2533                  const struct GNUNET_CONFIGURATION_Handle *cfg,
2534                  const char *client_name,
2535                  GNUNET_FS_ProgressCallback upcb,
2536                  void *upcb_cls,
2537                  enum GNUNET_FS_Flags flags,
2538                  ...)
2539 {
2540   struct GNUNET_FS_Handle *ret;
2541   struct GNUNET_CLIENT_Connection *client;
2542   enum GNUNET_FS_OPTIONS opt;
2543   va_list ap;
2544
2545   client = GNUNET_CLIENT_connect (sched,
2546                                   "fs",
2547                                   cfg);
2548   if (NULL == client)
2549     return NULL;
2550   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
2551   ret->sched = sched;
2552   ret->cfg = cfg;
2553   ret->client_name = GNUNET_strdup (client_name);
2554   ret->upcb = upcb;
2555   ret->upcb_cls = upcb_cls;
2556   ret->client = client;
2557   ret->flags = flags;
2558   ret->max_parallel_downloads = 1;
2559   ret->max_parallel_requests = 1;
2560   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
2561   va_start (ap, flags);  
2562   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
2563     {
2564       switch (opt)
2565         {
2566         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
2567           ret->max_parallel_downloads = va_arg (ap, unsigned int);
2568           break;
2569         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
2570           ret->max_parallel_requests = va_arg (ap, unsigned int);
2571           break;
2572         default:
2573           GNUNET_break (0);
2574           GNUNET_free (ret->client_name);
2575           GNUNET_free (ret);
2576           va_end (ap);
2577           return NULL;
2578         }
2579     }
2580   va_end (ap);
2581   // FIXME: setup receive-loop with client (do we need one?)
2582   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
2583     {
2584       /* FIXME: could write one generic deserialization
2585          function instead of these four... */
2586       deserialize_publish (ret);
2587       deserialize_search_master (ret);
2588       deserialize_download_master (ret);
2589       deserialize_unindex (ret);
2590     }
2591   return ret;
2592 }
2593
2594
2595 /**
2596  * Close our connection with the file-sharing service.
2597  * The callback given to GNUNET_FS_start will no longer be
2598  * called after this function returns.
2599  *
2600  * @param h handle that was returned from GNUNET_FS_start
2601  */                    
2602 void 
2603 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
2604 {
2605   /* generate SUSPEND events and clean up state */
2606   while (h->top_head != NULL)
2607     h->top_head->ssf (h->top_head->ssf_cls);
2608   // FIXME: terminate receive-loop with client  (do we need one?)
2609   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
2610     GNUNET_SCHEDULER_cancel (h->sched,
2611                              h->queue_job);
2612   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
2613   GNUNET_free (h->client_name);
2614   GNUNET_free (h);
2615 }
2616
2617
2618 /* end of fs.c */