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