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