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