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