93990aafa72b91b5cde40f1a72def899bba145bd
[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  * Synchronize this download struct with its mirror
1249  * on disk.  Note that all internal FS-operations that change
1250  * publishing structs should already call "sync" internally,
1251  * so this function is likely not useful for clients.
1252  * 
1253  * @param dc the struct to sync
1254  */
1255 void
1256 GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc)
1257 {
1258   /* FIXME */
1259 }
1260
1261
1262 /**
1263  * Synchronize this search result with its mirror
1264  * on disk.  Note that all internal FS-operations that change
1265  * publishing structs should already call "sync" internally,
1266  * so this function is likely not useful for clients.
1267  * 
1268  * @param key key for the search result
1269  * @param sr the struct to sync
1270  */
1271 void
1272 GNUNET_FS_search_result_sync_ (const GNUNET_HashCode *key,
1273                                struct SearchResult *sr)
1274 {
1275   struct GNUNET_BIO_WriteHandle *wh;
1276   char *uris;
1277
1278   GNUNET_assert ( (GNUNET_YES == GNUNET_FS_uri_test_chk (sr->uri)) ||
1279                   (GNUNET_YES == GNUNET_FS_uri_test_loc (sr->uri)) );
1280   uris = NULL;
1281   if (NULL == sr->serialization)
1282     sr->serialization = make_serialization_file_name (sr->sc->h,
1283                                                       "search-results");
1284   if (NULL == sr->serialization)
1285     return;
1286   wh = get_write_handle (sr->sc->h, "search-results", sr->serialization);
1287   uris = GNUNET_FS_uri_to_string (sr->uri);
1288   if ( (GNUNET_OK !=
1289         GNUNET_BIO_write_string (wh, uris)) ||
1290        (GNUNET_OK !=
1291         GNUNET_BIO_write_meta_data (wh, sr->meta)) ||
1292        (GNUNET_OK !=
1293         GNUNET_BIO_write (wh, key, sizeof (GNUNET_HashCode))) ||
1294        (GNUNET_OK !=
1295         GNUNET_BIO_write_int32 (wh, sr->mandatory_missing)) ||
1296        (GNUNET_OK !=
1297         GNUNET_BIO_write_int32 (wh, sr->optional_support)) ||
1298        (GNUNET_OK !=
1299         GNUNET_BIO_write_int32 (wh, sr->availability_success)) ||
1300        (GNUNET_OK !=
1301         GNUNET_BIO_write_int32 (wh, sr->availability_trials)) )
1302     goto cleanup;   
1303   if (GNUNET_OK !=
1304       GNUNET_BIO_write_close (wh))
1305     {
1306       wh = NULL;
1307       goto cleanup;
1308     }
1309   GNUNET_free_non_null (uris);
1310   return;
1311  cleanup:
1312   GNUNET_free_non_null (uris);
1313   if (wh != NULL)
1314     (void)  GNUNET_BIO_write_close (wh);
1315   GNUNET_FS_remove_sync_file_ (sr->sc->h, "search-results", sr->serialization);
1316   GNUNET_free (sr->serialization);
1317   sr->serialization = NULL;
1318 }
1319
1320
1321 /**
1322  * Synchronize this search struct with its mirror
1323  * on disk.  Note that all internal FS-operations that change
1324  * publishing structs should already call "sync" internally,
1325  * so this function is likely not useful for clients.
1326  * 
1327  * @param sc the struct to sync
1328  */
1329 void
1330 GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc)
1331 {  
1332   struct GNUNET_BIO_WriteHandle *wh;
1333   struct GNUNET_FS_SearchContext *scc;
1334   char *uris;
1335   char in_pause;
1336
1337   if (NULL == sc->serialization)
1338     sc->serialization = make_serialization_file_name (sc->h,
1339                                                       "search");
1340   if (NULL == sc->serialization)
1341     return;
1342   wh = get_write_handle (sc->h, "search", sc->serialization);
1343   GNUNET_assert ( (GNUNET_YES == GNUNET_FS_uri_test_ksk (sc->uri)) ||
1344                   (GNUNET_YES == GNUNET_FS_uri_test_sks (sc->uri)) );
1345   uris = GNUNET_FS_uri_to_string (sc->uri);
1346   in_pause = (sc->task != GNUNET_SCHEDULER_NO_TASK) ? 'r' : '\0';
1347   if ( (GNUNET_OK !=
1348         GNUNET_BIO_write_string (wh, uris)) ||
1349        (GNUNET_OK !=
1350         GNUNET_BIO_write_int64 (wh, sc->start_time.value)) ||
1351        (GNUNET_OK !=
1352         GNUNET_BIO_write_string (wh, sc->emsg)) ||
1353        (GNUNET_OK !=
1354         GNUNET_BIO_write_int32 (wh, (uint32_t) sc->options)) ||
1355        (GNUNET_OK !=
1356         GNUNET_BIO_write (wh, &in_pause, sizeof (in_pause))) ||
1357        (GNUNET_OK !=
1358         GNUNET_BIO_write_int32 (wh, sc->anonymity)) )
1359     goto cleanup;          
1360   GNUNET_free (uris);
1361   uris = NULL;
1362   scc = sc->child_head;
1363   while (NULL != scc)
1364     {
1365       if (scc->serialization == NULL)
1366         break;
1367       if (GNUNET_OK !=
1368           GNUNET_BIO_write_string (wh, scc->serialization))
1369         goto cleanup;
1370       scc = scc->next;
1371     }
1372   GNUNET_BIO_write_string (wh, NULL);
1373   if (GNUNET_OK !=
1374       GNUNET_BIO_write_close (wh))
1375     {
1376       wh = NULL;
1377       goto cleanup;
1378     }
1379   return;
1380  cleanup:
1381   if (wh != NULL)
1382     (void) GNUNET_BIO_write_close (wh);
1383   GNUNET_free_non_null (uris);
1384   GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1385   GNUNET_free (sc->serialization);
1386   sc->serialization = NULL;
1387 }
1388
1389
1390 /**
1391  * Deserialize information about pending publish operations.
1392  *
1393  * @param h master context
1394  */
1395 static void
1396 deserialize_publish (struct GNUNET_FS_Handle *h)
1397 {
1398   char *dn;
1399
1400   dn = get_serialization_file_name (h, "publish", "");
1401   if (dn == NULL)
1402     return;
1403   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1404   GNUNET_free (dn);
1405 }
1406
1407
1408 /**
1409  * Function called with a filename of serialized unindexing operation
1410  * to deserialize.
1411  *
1412  * @param cls the 'struct GNUNET_FS_Handle*'
1413  * @param filename complete filename (absolute path)
1414  * @return GNUNET_OK (continue to iterate)
1415  */
1416 static int
1417 deserialize_unindex_file (void *cls,
1418                           const char *filename)
1419 {
1420   struct GNUNET_FS_Handle *h = cls;
1421   struct GNUNET_BIO_ReadHandle *rh;
1422   struct GNUNET_FS_UnindexContext *uc;
1423   struct GNUNET_FS_ProgressInfo pi;
1424   char *emsg;
1425   uint32_t state;
1426
1427   uc = GNUNET_malloc (sizeof (struct GNUNET_FS_UnindexContext));
1428   uc->h = h;
1429   uc->serialization = get_serialization_short_name (filename);
1430   rh = GNUNET_BIO_read_open (filename);
1431   if (rh == NULL)
1432     goto cleanup;
1433   if ( (GNUNET_OK !=
1434         GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10*1024)) ||
1435        (GNUNET_OK !=
1436         GNUNET_BIO_read_int64 (rh, &uc->file_size)) ||
1437        (GNUNET_OK !=
1438         GNUNET_BIO_read_int64 (rh, &uc->start_time.value)) ||
1439        (GNUNET_OK !=
1440         GNUNET_BIO_read_int32 (rh, &state)) )
1441     goto cleanup;          
1442   uc->state = (enum UnindexState) state;
1443   switch (state)
1444     {
1445     case UNINDEX_STATE_HASHING:
1446       break;
1447     case UNINDEX_STATE_FS_NOTIFY:
1448       if (GNUNET_OK !=
1449           GNUNET_BIO_read (rh, "unindex-hash", &uc->file_id, sizeof (GNUNET_HashCode)))
1450         goto cleanup;
1451       break;
1452     case UNINDEX_STATE_DS_REMOVE:
1453       break;
1454     case UNINDEX_STATE_COMPLETE:
1455       break;
1456     case UNINDEX_STATE_ERROR:
1457       if (GNUNET_OK !=
1458           GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10*1024))
1459         goto cleanup;
1460       break;
1461     case UNINDEX_STATE_ABORTED:
1462       GNUNET_break (0);
1463       goto cleanup;
1464     default:
1465       GNUNET_break (0);
1466       goto cleanup;
1467     }
1468   pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME;
1469   pi.value.unindex.specifics.resume.message = uc->emsg;
1470   GNUNET_FS_unindex_make_status_ (&pi,
1471                                   uc,
1472                                   (uc->state == UNINDEX_STATE_COMPLETE) 
1473                                   ? uc->file_size
1474                                   : 0);
1475   switch (uc->state)
1476     {
1477     case UNINDEX_STATE_HASHING:
1478       GNUNET_CRYPTO_hash_file (uc->h->sched,
1479                                GNUNET_SCHEDULER_PRIORITY_IDLE,
1480                                uc->filename,
1481                                HASHING_BLOCKSIZE,
1482                                &GNUNET_FS_unindex_process_hash_,
1483                                uc);
1484       break;
1485     case UNINDEX_STATE_FS_NOTIFY:
1486       uc->state = UNINDEX_STATE_HASHING;
1487       GNUNET_FS_unindex_process_hash_ (uc,
1488                                        &uc->file_id);
1489       break;
1490     case UNINDEX_STATE_DS_REMOVE:
1491       GNUNET_FS_unindex_do_remove_ (uc);
1492       break;
1493     case UNINDEX_STATE_COMPLETE:
1494     case UNINDEX_STATE_ERROR:
1495       /* no need to resume any operation, we were done */
1496       break;
1497     default:
1498       break;
1499     }
1500   if (GNUNET_OK !=
1501       GNUNET_BIO_read_close (rh, &emsg))
1502     {
1503       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1504                   _("Failure while resuming unindexing operation `%s': %s\n"),
1505                   filename,
1506                   emsg);
1507       GNUNET_free (emsg);
1508     }
1509   return GNUNET_OK;
1510  cleanup:
1511   GNUNET_free_non_null (uc->filename);
1512   if ( (rh != NULL) &&
1513        (GNUNET_OK !=
1514         GNUNET_BIO_read_close (rh, &emsg)) )
1515     {
1516       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1517                   _("Failed to resume unindexing operation `%s': %s\n"),
1518                   filename,
1519                   emsg);
1520       GNUNET_free (emsg);
1521     }
1522   if (uc->serialization != NULL)
1523     GNUNET_FS_remove_sync_file_ (h, "unindex", uc->serialization);
1524   GNUNET_free_non_null (uc->serialization);
1525   GNUNET_free (uc);
1526   return GNUNET_OK;
1527 }
1528
1529
1530 /**
1531  * Deserialize information about pending publish operations.
1532  *
1533  * @param h master context
1534  */
1535 static void
1536 deserialize_unindex (struct GNUNET_FS_Handle *h)
1537 {
1538   char *dn;
1539
1540   dn = get_serialization_file_name (h, "unindex", "");
1541   if (dn == NULL)
1542     return;
1543   GNUNET_DISK_directory_scan (dn, &deserialize_unindex_file, h);
1544   GNUNET_free (dn);
1545 }
1546
1547
1548 /**
1549  * Function called with a filename of serialized search result
1550  * to deserialize.
1551  *
1552  * @param cls the 'struct GNUNET_FS_SearchContext*'
1553  * @param filename complete filename (absolute path)
1554  * @return GNUNET_OK (continue to iterate)
1555  */
1556 static int
1557 deserialize_search_result (void *cls,
1558                            const char *filename)
1559 {
1560   struct GNUNET_FS_SearchContext *sc = cls;
1561   char pbuf[32];
1562   char *ser;
1563   char *uris;
1564   char *emsg;
1565   struct GNUNET_BIO_ReadHandle *rh;
1566   struct SearchResult *sr;
1567   GNUNET_HashCode key;
1568
1569   ser = get_serialization_short_name (filename);
1570   rh = GNUNET_BIO_read_open (filename);
1571   if (rh == NULL)
1572     {
1573       if (ser != NULL)
1574         {
1575           GNUNET_snprintf (pbuf,
1576                            sizeof (pbuf),
1577                            "%s%s%s",
1578                            "search-results",
1579                            DIR_SEPARATOR_STR,
1580                            sc->serialization);
1581           GNUNET_FS_remove_sync_file_ (sc->h, pbuf, ser);
1582           GNUNET_free (ser);
1583         }
1584       return GNUNET_OK;
1585     }
1586   emsg = NULL;
1587   uris = NULL;
1588   sr = GNUNET_malloc (sizeof (struct SearchResult));
1589   sr->serialization = ser;  
1590   if ( (GNUNET_OK !=
1591         GNUNET_BIO_read_string (rh, "result-uri", &uris, 10*1024)) ||
1592        (NULL == (sr->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
1593        ( (GNUNET_YES != GNUNET_FS_uri_test_chk (sr->uri)) &&
1594          (GNUNET_YES != GNUNET_FS_uri_test_loc (sr->uri)) ) ||
1595        (GNUNET_OK !=
1596         GNUNET_BIO_read_meta_data (rh, "result-meta", &sr->meta)) ||
1597        (GNUNET_OK !=
1598         GNUNET_BIO_read (rh, "result-key", &key, sizeof (key))) ||
1599        (GNUNET_OK !=
1600         GNUNET_BIO_read_int32 (rh, &sr->mandatory_missing)) ||
1601        (GNUNET_OK !=
1602         GNUNET_BIO_read_int32 (rh, &sr->optional_support)) ||
1603        (GNUNET_OK !=
1604         GNUNET_BIO_read_int32 (rh, &sr->availability_success)) ||
1605        (GNUNET_OK !=
1606         GNUNET_BIO_read_int32 (rh, &sr->availability_trials)) )
1607     goto cleanup;   
1608   GNUNET_free (uris);
1609   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map,
1610                                      &key,
1611                                      sr,
1612                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1613   return GNUNET_OK;
1614  cleanup:
1615   GNUNET_free_non_null (emsg);
1616   GNUNET_free_non_null (uris);
1617   if (sr->uri != NULL)
1618     GNUNET_FS_uri_destroy (sr->uri);
1619   if (sr->meta != NULL)
1620     GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1621   GNUNET_free (sr->serialization);
1622   GNUNET_free (sr);  
1623   return GNUNET_OK;
1624 }
1625
1626
1627 /**
1628  * Iterator over search results signaling resume to the client for
1629  * each result.
1630  *
1631  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
1632  * @param key current key code
1633  * @param value value in the hash map, the 'struct SearchResult'
1634  * @return GNUNET_YES (we should continue to iterate)
1635  */
1636 static int
1637 signal_result_resume (void *cls,
1638                       const GNUNET_HashCode * key,
1639                       void *value)
1640 {
1641   struct GNUNET_FS_SearchContext *sc = cls;
1642   struct GNUNET_FS_ProgressInfo pi;
1643   struct SearchResult *sr = value;
1644
1645   if (0 == sr->mandatory_missing)
1646     {
1647       pi.status = GNUNET_FS_STATUS_SEARCH_RESUME_RESULT;
1648       pi.value.search.specifics.resume_result.meta = sr->meta;
1649       pi.value.search.specifics.resume_result.uri = sr->uri;
1650       pi.value.search.specifics.resume_result.availability_rank = 2*sr->availability_success - sr->availability_trials;
1651       pi.value.search.specifics.resume_result.availability_certainty = sr->availability_trials;
1652       pi.value.search.specifics.resume_result.applicability_rank = sr->optional_support;
1653       sr->client_info = GNUNET_FS_search_make_status_ (&pi,
1654                                                        sc);
1655     }
1656   GNUNET_FS_search_start_probe_ (sr);
1657   return GNUNET_YES;
1658 }
1659
1660
1661 /**
1662  * Iterator over search results freeing each.
1663  *
1664  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
1665  * @param key current key code
1666  * @param value value in the hash map, the 'struct SearchResult'
1667  * @return GNUNET_YES (we should continue to iterate)
1668  */
1669 static int
1670 free_result (void *cls,
1671              const GNUNET_HashCode * key,
1672              void *value)
1673 {
1674   struct SearchResult *sr = value;
1675
1676   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1677   GNUNET_FS_uri_destroy (sr->uri);
1678   GNUNET_free (sr);
1679   return GNUNET_YES;
1680 }
1681
1682
1683 /**
1684  * Free memory allocated by the search context and its children
1685  *
1686  * @param sc search context to free
1687  */
1688 static void
1689 free_search_context (struct GNUNET_FS_SearchContext *sc)
1690 {
1691   struct GNUNET_FS_SearchContext *scc;
1692
1693   while (NULL != (scc = sc->child_head))
1694     {
1695       GNUNET_CONTAINER_DLL_remove (sc->child_head,
1696                                    sc->child_tail,
1697                                    scc);      
1698       free_search_context (scc);
1699     }
1700   GNUNET_free_non_null (sc->emsg);
1701   if (sc->serialization != NULL)
1702     GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1703   /* FIXME: remove 'pbuf' directory with search results as well! */
1704   GNUNET_free_non_null (sc->serialization);
1705   if (sc->uri != NULL)
1706     GNUNET_FS_uri_destroy (sc->uri);
1707   if (sc->master_result_map != NULL)
1708     {
1709       GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1710                                              &free_result,
1711                                              sc);
1712       GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1713     }
1714   GNUNET_free (sc);
1715 }
1716
1717
1718 /**
1719  * Deserialize a download.
1720  *
1721  * @param h overall context
1722  * @param rh file to deserialize from
1723  * @param parent parent download
1724  * @param serialization name under which the search was serialized
1725  */
1726 static void
1727 deserialize_download (struct GNUNET_FS_Handle *h,
1728                       struct GNUNET_BIO_ReadHandle *rh,
1729                       struct GNUNET_FS_DownloadContext *parent,
1730                       const char *serialization);
1731
1732
1733 /**
1734  * Function called with a filename of serialized sub-download
1735  * to deserialize.
1736  *
1737  * @param cls the 'struct GNUNET_FS_DownloadContext*' (parent)
1738  * @param filename complete filename (absolute path)
1739  * @return GNUNET_OK (continue to iterate)
1740  */
1741 static int
1742 deserialize_subdownload (void *cls,
1743                          const char *filename)
1744 {
1745   struct GNUNET_FS_DownloadContext *parent = cls;
1746   char *ser;
1747   char *emsg;
1748   struct GNUNET_BIO_ReadHandle *rh;
1749
1750   ser = get_serialization_short_name (filename);
1751   rh = GNUNET_BIO_read_open (filename);
1752   deserialize_download (parent->h,
1753                         rh,
1754                         parent,
1755                         ser);
1756   if (GNUNET_OK !=
1757       GNUNET_BIO_read_close (rh, &emsg))
1758     {
1759       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1760                   _("Failed to resume sub-download `%s': %s\n"),
1761                   ser,
1762                   emsg);
1763       GNUNET_free (emsg);
1764     }
1765   GNUNET_free (ser);
1766   return GNUNET_OK;
1767 }
1768
1769
1770 /**
1771  * Send the 'resume' signal to the callback; also actually
1772  * resume the download (put it in the queue).  Does this
1773  * recursively for the top-level download and all child
1774  * downloads.
1775  * 
1776  * @param dc download to resume
1777  */
1778 static void
1779 signal_download_resume (struct GNUNET_FS_DownloadContext *dc)
1780 {
1781   struct GNUNET_FS_DownloadContext *dcc;
1782   struct GNUNET_FS_ProgressInfo pi;
1783   
1784   pi.status = GNUNET_FS_STATUS_DOWNLOAD_RESUME;
1785   pi.value.download.specifics.resume.meta = dc->meta;
1786   pi.value.download.specifics.resume.message = dc->emsg;
1787   GNUNET_FS_download_make_status_ (&pi,
1788                                    dc);
1789   dcc = dc->child_head;
1790   while (NULL != dcc)
1791     {
1792       signal_download_resume (dcc);
1793       dcc = dcc->next;
1794     }
1795   if (dc->pending != NULL)
1796     GNUNET_FS_download_start_downloading_ (dc);
1797 }
1798
1799
1800 /**
1801  * Free this download context and all of its descendants.
1802  * (only works during deserialization since not all possible
1803  * state it taken care of).
1804  *
1805  * @param dc context to free
1806  */
1807 static void
1808 free_download_context (struct GNUNET_FS_DownloadContext *dc)
1809 {
1810   struct GNUNET_FS_DownloadContext *dcc;
1811   struct DownloadRequest *dr;
1812   if (dc->meta != NULL)
1813     GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1814   if (dc->uri != NULL)
1815     GNUNET_FS_uri_destroy (dc->uri);
1816   GNUNET_free_non_null (dc->temp_filename);
1817   GNUNET_free_non_null (dc->emsg);
1818   GNUNET_free_non_null (dc->filename);
1819   while (NULL != (dcc = dc->child_head))
1820     {
1821       GNUNET_CONTAINER_DLL_remove (dc->child_head,
1822                                    dc->child_tail,
1823                                    dcc);
1824       free_download_context (dcc);
1825     }
1826   while (NULL != (dr = dc->pending))
1827     {
1828       dc->pending = dr->next;
1829       GNUNET_free (dr);
1830     }
1831   GNUNET_free (dc);
1832 }
1833
1834
1835 /**
1836  * Deserialize a download.
1837  *
1838  * @param h overall context
1839  * @param rh file to deserialize from
1840  * @param parent parent download
1841  * @param serialization name under which the search was serialized
1842  */
1843 static void
1844 deserialize_download (struct GNUNET_FS_Handle *h,
1845                       struct GNUNET_BIO_ReadHandle *rh,
1846                       struct GNUNET_FS_DownloadContext *parent,
1847                       const char *serialization)
1848 {
1849   struct GNUNET_FS_DownloadContext *dc;
1850   struct DownloadRequest *dr;
1851   char pbuf[32];
1852   char *emsg;
1853   char *uris;
1854   char *dn;
1855   uint32_t options;
1856   uint32_t status;
1857   uint32_t num_pending;
1858
1859   uris = NULL;
1860   emsg = NULL;
1861   dr = NULL;
1862   dc = GNUNET_malloc (sizeof (struct GNUNET_FS_DownloadContext));
1863   dc->parent = parent;
1864   dc->h = h;
1865   dc->serialization = GNUNET_strdup (serialization);
1866   if ( (GNUNET_OK !=
1867         GNUNET_BIO_read_string (rh, "download-uri", &uris, 10*1024)) ||
1868        (NULL == (dc->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
1869        ( (GNUNET_YES != GNUNET_FS_uri_test_chk (dc->uri)) &&
1870          (GNUNET_YES != GNUNET_FS_uri_test_loc (dc->uri)) ) ||
1871        (GNUNET_OK !=
1872         GNUNET_BIO_read_meta_data (rh, "download-meta", &dc->meta)) ||
1873        (GNUNET_OK !=
1874         GNUNET_BIO_read_string (rh, "download-emsg", &dc->emsg, 10*1024)) ||
1875        (GNUNET_OK !=
1876         GNUNET_BIO_read_string (rh, "download-fn", &dc->filename, 10*1024)) ||
1877        (GNUNET_OK !=
1878         GNUNET_BIO_read_string (rh, "download-tfn", &dc->temp_filename, 10*1024)) ||
1879        (GNUNET_OK !=
1880         GNUNET_BIO_read_int64 (rh, &dc->old_file_size)) ||
1881        (GNUNET_OK !=
1882         GNUNET_BIO_read_int64 (rh, &dc->offset)) ||
1883        (GNUNET_OK !=
1884         GNUNET_BIO_read_int64 (rh, &dc->length)) ||
1885        (GNUNET_OK !=
1886         GNUNET_BIO_read_int64 (rh, &dc->completed)) ||
1887        (GNUNET_OK !=
1888         GNUNET_BIO_read_int64 (rh, &dc->start_time.value)) ||
1889        (GNUNET_OK !=
1890         GNUNET_BIO_read_int32 (rh, &dc->anonymity)) ||
1891        (GNUNET_OK !=
1892         GNUNET_BIO_read_int32 (rh, &options)) ||
1893        (GNUNET_OK !=
1894         GNUNET_BIO_read_int32 (rh, &status)) ||
1895        (GNUNET_OK !=
1896         GNUNET_BIO_read_int32 (rh, &num_pending)) )
1897     goto cleanup;          
1898   /* FIXME: adjust start_time.value */
1899   dc->options = (enum GNUNET_FS_DownloadOptions) options;
1900   dc->active = GNUNET_CONTAINER_multihashmap_create (16);
1901   dc->has_finished = (int) status;
1902   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
1903   if (GNUNET_FS_uri_test_loc (dc->uri))
1904     GNUNET_assert (GNUNET_OK ==
1905                    GNUNET_FS_uri_loc_get_peer_identity (dc->uri,
1906                                                         &dc->target));
1907   if ( (dc->length > dc->completed) &&
1908        (num_pending == 0) )
1909     goto cleanup;    
1910   while (0 < num_pending--)
1911     {
1912       dr = GNUNET_malloc (sizeof (struct DownloadRequest));
1913       if ( (GNUNET_OK !=
1914             GNUNET_BIO_read (rh, "chk", &dr->chk, sizeof (struct ContentHashKey))) ||
1915            (GNUNET_OK !=
1916             GNUNET_BIO_read_int64 (rh, &dr->offset)) ||
1917            (GNUNET_OK !=
1918             GNUNET_BIO_read_int32 (rh, &dr->depth)) )
1919         goto cleanup;      
1920       dr->is_pending = GNUNET_YES;
1921       dr->next = dc->pending;
1922       dc->pending = dr;
1923       dr = NULL;
1924     }
1925   GNUNET_snprintf (pbuf,
1926                    sizeof (pbuf),
1927                    "%s%s%s",
1928                    "subdownloads",
1929                    DIR_SEPARATOR_STR,
1930                    dc->serialization);
1931   dn = get_serialization_file_name (h, pbuf, "");
1932   if (dn != NULL)
1933     {
1934       GNUNET_DISK_directory_scan (dn, &deserialize_subdownload, dc);
1935       GNUNET_free (dn);
1936     }
1937   if (parent != NULL)
1938     GNUNET_CONTAINER_DLL_insert (parent->child_head,
1939                                  parent->child_tail,
1940                                  dc);
1941   signal_download_resume (dc);
1942   GNUNET_free (uris);
1943   return;
1944  cleanup:
1945   GNUNET_free_non_null (uris);
1946   GNUNET_free_non_null (dr);
1947   free_download_context (dc);
1948 }
1949
1950
1951 /**
1952  * Signal resuming of a search to our clients (for the
1953  * top level search and all sub-searches).
1954  *
1955  * @param sc search being resumed
1956  */
1957 static void
1958 signal_search_resume (struct GNUNET_FS_SearchContext *sc)
1959 {
1960   struct GNUNET_FS_SearchContext *scc;
1961   struct GNUNET_FS_ProgressInfo pi;
1962
1963   pi.status = GNUNET_FS_STATUS_SEARCH_RESUME;
1964   pi.value.search.specifics.resume.message = sc->emsg;
1965   pi.value.search.specifics.resume.is_paused = (sc->client == NULL) ? GNUNET_YES : GNUNET_NO;
1966   sc->client_info = GNUNET_FS_search_make_status_ (&pi,
1967                                                    sc);
1968   scc = sc->child_head;
1969   while (NULL != scc)
1970     {
1971       signal_search_resume (scc);
1972       scc = scc->next;
1973     }
1974 }
1975
1976
1977 /**
1978  * Deserialize a search. 
1979  *
1980  * @param h overall context
1981  * @param rh file to deserialize from
1982  * @param parent parent search
1983  * @param serialization name under which the search was serialized
1984  */
1985 static struct GNUNET_FS_SearchContext *
1986 deserialize_search (struct GNUNET_FS_Handle *h,
1987                     struct GNUNET_BIO_ReadHandle *rh,
1988                     struct GNUNET_FS_SearchContext *parent,
1989                     const char *serialization)
1990 {
1991   struct GNUNET_FS_SearchContext *sc;
1992   struct GNUNET_FS_SearchContext *scc;
1993   struct GNUNET_BIO_ReadHandle *rhc;
1994   char pbuf[32];
1995   char *emsg;
1996   char *uris;
1997   char *child_ser;
1998   char *dn;
1999   uint32_t options;
2000   char in_pause;
2001
2002   uris = NULL;
2003   emsg = NULL;
2004   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
2005   sc->parent = parent;
2006   sc->h = h;
2007   sc->serialization = GNUNET_strdup (serialization);
2008   if ( (GNUNET_OK !=
2009         GNUNET_BIO_read_string (rh, "search-uri", &uris, 10*1024)) ||
2010        (NULL == (sc->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
2011        ( (GNUNET_YES != GNUNET_FS_uri_test_ksk (sc->uri)) &&
2012          (GNUNET_YES != GNUNET_FS_uri_test_sks (sc->uri)) ) ||
2013        (GNUNET_OK !=
2014         GNUNET_BIO_read_int64 (rh, &sc->start_time.value)) ||
2015        (GNUNET_OK !=
2016         GNUNET_BIO_read_string (rh, "search-emsg", &sc->emsg, 10*1024)) ||
2017        (GNUNET_OK !=
2018         GNUNET_BIO_read_int32 (rh, &options)) ||
2019        (GNUNET_OK !=
2020         GNUNET_BIO_read (rh, "search-pause", &in_pause, sizeof (in_pause))) ||
2021        (GNUNET_OK !=
2022         GNUNET_BIO_read_int32 (rh, &sc->anonymity)) )
2023     goto cleanup;          
2024   /* FIXME: adjust start_time.value */
2025   sc->options = (enum GNUNET_FS_SearchOptions) options;
2026   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
2027   GNUNET_snprintf (pbuf,
2028                    sizeof (pbuf),
2029                    "%s%s%s",
2030                    "search-results",
2031                    DIR_SEPARATOR_STR,
2032                    sc->serialization);
2033   dn = get_serialization_file_name (h, pbuf, "");
2034   if (dn != NULL)
2035     {
2036       GNUNET_DISK_directory_scan (dn, &deserialize_search_result, sc);
2037       GNUNET_free (dn);
2038     }
2039   if ( ('\0' == in_pause) &&
2040        (GNUNET_OK !=
2041         GNUNET_FS_search_start_searching_ (sc)) )
2042     {
2043       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2044                   _("Could not resume running search, will resume as paused search\n"));    
2045     }
2046   while (1)
2047     {
2048       if ( (GNUNET_OK !=
2049             GNUNET_BIO_read_string (rh, "child-serialization", &child_ser, 32)))
2050         goto cleanup;
2051       if (child_ser == NULL)
2052         break;    
2053       rhc = get_read_handle (h, "search-children", child_ser);
2054       if (rhc != NULL)
2055         {
2056           scc = deserialize_search (h, rhc, sc, child_ser);
2057           if (scc != NULL)          
2058             GNUNET_CONTAINER_DLL_insert (sc->child_head,
2059                                          sc->child_tail,
2060                                          scc);      
2061           emsg = NULL;
2062           if (GNUNET_OK !=
2063               GNUNET_BIO_read_close (rhc, &emsg))
2064             {
2065               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2066                           _("Failed to resume sub-search `%s': %s\n"),
2067                           child_ser,
2068                           emsg);
2069               GNUNET_free (emsg);
2070             }
2071         }    
2072       GNUNET_free (child_ser);  
2073     }
2074   if (parent != NULL)
2075     GNUNET_CONTAINER_DLL_insert (parent->child_head,
2076                                  parent->child_tail,
2077                                  sc);
2078   signal_search_resume (sc);
2079   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
2080                                          &signal_result_resume,
2081                                          sc);
2082   GNUNET_free (uris);
2083   return sc;
2084  cleanup:
2085   GNUNET_free_non_null (emsg);
2086   free_search_context (sc);
2087   GNUNET_free_non_null (uris);
2088   return NULL;
2089 }
2090
2091
2092 /**
2093  * Function called with a filename of serialized search operation
2094  * to deserialize.
2095  *
2096  * @param cls the 'struct GNUNET_FS_Handle*'
2097  * @param filename complete filename (absolute path)
2098  * @return GNUNET_OK (continue to iterate)
2099  */
2100 static int
2101 deserialize_search_file (void *cls,
2102                           const char *filename)
2103 {
2104   struct GNUNET_FS_Handle *h = cls;
2105   char *ser;
2106   char *emsg;
2107   struct GNUNET_BIO_ReadHandle *rh;
2108   struct GNUNET_FS_SearchContext *sc;
2109
2110   ser = get_serialization_short_name (filename);
2111   rh = GNUNET_BIO_read_open (filename);
2112   if (rh == NULL)
2113     {
2114       if (ser != NULL)
2115         {
2116           GNUNET_FS_remove_sync_file_ (h, "search", ser);
2117           GNUNET_free (ser);
2118         }
2119       return GNUNET_OK;
2120     }
2121   sc = deserialize_search (h, rh, NULL, ser);
2122   GNUNET_free (ser);
2123   if (GNUNET_OK !=
2124       GNUNET_BIO_read_close (rh, &emsg))
2125     {
2126       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2127                   _("Failure while resuming search operation `%s': %s\n"),
2128                   filename,
2129                   emsg);
2130       GNUNET_free (emsg);
2131     }
2132   return GNUNET_OK;
2133 }
2134
2135
2136 /**
2137  * Deserialize information about pending search operations.
2138  *
2139  * @param h master context
2140  */
2141 static void
2142 deserialize_search_master (struct GNUNET_FS_Handle *h)
2143 {
2144   char *dn;
2145
2146   dn = get_serialization_file_name (h, "search", "");
2147   if (dn == NULL)
2148     return;
2149   GNUNET_DISK_directory_scan (dn, &deserialize_search_file, h);
2150   GNUNET_free (dn);
2151 }
2152
2153
2154 /**
2155  * Function called with a filename of serialized download operation
2156  * to deserialize.
2157  *
2158  * @param cls the 'struct GNUNET_FS_Handle*'
2159  * @param filename complete filename (absolute path)
2160  * @return GNUNET_OK (continue to iterate)
2161  */
2162 static int
2163 deserialize_download_file (void *cls,
2164                            const char *filename)
2165 {
2166   struct GNUNET_FS_Handle *h = cls;
2167   char *ser;
2168   char *emsg;
2169   struct GNUNET_BIO_ReadHandle *rh;
2170
2171   ser = get_serialization_short_name (filename);
2172   rh = GNUNET_BIO_read_open (filename);
2173   if (rh == NULL)
2174     {
2175       if (ser != NULL)
2176         {
2177           GNUNET_FS_remove_sync_file_ (h, "download", ser);
2178           GNUNET_free (ser);
2179         }
2180       return GNUNET_OK;
2181     }
2182   deserialize_download (h, rh, NULL, ser);
2183   GNUNET_free (ser);
2184   if (GNUNET_OK !=
2185       GNUNET_BIO_read_close (rh, &emsg))
2186     {
2187       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2188                   _("Failure while resuming download operation `%s': %s\n"),
2189                   filename,
2190                   emsg);
2191       GNUNET_free (emsg);
2192     }
2193   return GNUNET_OK;
2194 }
2195
2196
2197 /**
2198  * Deserialize information about pending download operations.
2199  *
2200  * @param h master context
2201  */
2202 static void
2203 deserialize_download_master (struct GNUNET_FS_Handle *h)
2204 {
2205   char *dn;
2206
2207   dn = get_serialization_file_name (h, "download", "");
2208   if (dn == NULL)
2209     return;
2210   GNUNET_DISK_directory_scan (dn, &deserialize_download_file, h);
2211   GNUNET_free (dn);
2212 }
2213
2214
2215 /**
2216  * Setup a connection to the file-sharing service.
2217  *
2218  * @param sched scheduler to use
2219  * @param cfg configuration to use
2220  * @param client_name unique identifier for this client 
2221  * @param upcb function to call to notify about FS actions
2222  * @param upcb_cls closure for upcb
2223  * @param flags specific attributes for fs-operations
2224  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
2225  * @return NULL on error
2226  */
2227 struct GNUNET_FS_Handle *
2228 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
2229                  const struct GNUNET_CONFIGURATION_Handle *cfg,
2230                  const char *client_name,
2231                  GNUNET_FS_ProgressCallback upcb,
2232                  void *upcb_cls,
2233                  enum GNUNET_FS_Flags flags,
2234                  ...)
2235 {
2236   struct GNUNET_FS_Handle *ret;
2237   struct GNUNET_CLIENT_Connection *client;
2238   enum GNUNET_FS_OPTIONS opt;
2239   va_list ap;
2240
2241   client = GNUNET_CLIENT_connect (sched,
2242                                   "fs",
2243                                   cfg);
2244   if (NULL == client)
2245     return NULL;
2246   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
2247   ret->sched = sched;
2248   ret->cfg = cfg;
2249   ret->client_name = GNUNET_strdup (client_name);
2250   ret->upcb = upcb;
2251   ret->upcb_cls = upcb_cls;
2252   ret->client = client;
2253   ret->flags = flags;
2254   ret->max_parallel_downloads = 1;
2255   ret->max_parallel_requests = 1;
2256   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
2257   va_start (ap, flags);  
2258   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
2259     {
2260       switch (opt)
2261         {
2262         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
2263           ret->max_parallel_downloads = va_arg (ap, unsigned int);
2264           break;
2265         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
2266           ret->max_parallel_requests = va_arg (ap, unsigned int);
2267           break;
2268         default:
2269           GNUNET_break (0);
2270           GNUNET_free (ret->client_name);
2271           GNUNET_free (ret);
2272           va_end (ap);
2273           return NULL;
2274         }
2275     }
2276   va_end (ap);
2277   // FIXME: setup receive-loop with client (do we need one?)
2278   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
2279     {
2280       /* FIXME: could write one generic deserialization
2281          function instead of these four... */
2282       deserialize_publish (ret);
2283       deserialize_search_master (ret);
2284       deserialize_download_master (ret);
2285       deserialize_unindex (ret);
2286     }
2287   return ret;
2288 }
2289
2290
2291 /**
2292  * Close our connection with the file-sharing service.
2293  * The callback given to GNUNET_FS_start will no longer be
2294  * called after this function returns.
2295  *
2296  * @param h handle that was returned from GNUNET_FS_start
2297  */                    
2298 void 
2299 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
2300 {
2301   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & h->flags))
2302     {
2303       // FIXME: generate SUSPEND events and clean up state!
2304     }
2305   // FIXME: terminate receive-loop with client  (do we need one?)
2306   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
2307     GNUNET_SCHEDULER_cancel (h->sched,
2308                              h->queue_job);
2309   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
2310   GNUNET_free (h->client_name);
2311   GNUNET_free (h);
2312 }
2313
2314
2315 /* end of fs.c */