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