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