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