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