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