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