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