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