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