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