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