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