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