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