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