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