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