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