c25e1919e736331a85ba3ba475260c4df4a071e3
[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
32
33 /**
34  * Start the given job (send signal, remove from pending queue, update
35  * counters and state).
36  *
37  * @param qe job to start
38  */
39 static void
40 start_job (struct GNUNET_FS_QueueEntry *qe)
41 {
42   qe->client = GNUNET_CLIENT_connect (qe->h->sched, "fs", qe->h->cfg);
43   if (qe->client == NULL)
44     {
45       GNUNET_break (0);
46       return;
47     }
48   qe->start (qe->cls, qe->client);
49   qe->start_times++;
50   qe->h->active_blocks += qe->blocks;
51   qe->start_time = GNUNET_TIME_absolute_get ();
52   GNUNET_CONTAINER_DLL_remove (qe->h->pending_head,
53                                qe->h->pending_tail,
54                                qe);
55   GNUNET_CONTAINER_DLL_insert_after (qe->h->running_head,
56                                      qe->h->running_tail,
57                                      qe->h->running_tail,
58                                      qe);
59 }
60
61
62 /**
63  * Stop the given job (send signal, remove from active queue, update
64  * counters and state).
65  *
66  * @param qe job to stop
67  */
68 static void
69 stop_job (struct GNUNET_FS_QueueEntry *qe)
70 {
71   qe->client = NULL;
72   qe->stop (qe->cls);
73   qe->h->active_downloads--;
74   qe->h->active_blocks -= qe->blocks;
75   qe->run_time = GNUNET_TIME_relative_add (qe->run_time,
76                                            GNUNET_TIME_absolute_get_duration (qe->start_time));
77   GNUNET_CONTAINER_DLL_remove (qe->h->running_head,
78                                qe->h->running_tail,
79                                qe);
80   GNUNET_CONTAINER_DLL_insert_after (qe->h->pending_head,
81                                      qe->h->pending_tail,
82                                      qe->h->pending_tail,
83                                      qe);
84 }
85
86
87 /**
88  * Process the jobs in the job queue, possibly starting some
89  * and stopping others.
90  *
91  * @param cls the 'struct GNUNET_FS_Handle'
92  * @param tc scheduler context
93  */
94 static void
95 process_job_queue (void *cls,
96                    const struct GNUNET_SCHEDULER_TaskContext *tc)
97 {
98   struct GNUNET_FS_Handle *h = cls;
99   struct GNUNET_FS_QueueEntry *qe;
100   struct GNUNET_FS_QueueEntry *next;
101   struct GNUNET_TIME_Relative run_time;
102   struct GNUNET_TIME_Relative restart_at;
103   struct GNUNET_TIME_Relative rst;
104   struct GNUNET_TIME_Absolute end_time;
105
106   h->queue_job = GNUNET_SCHEDULER_NO_TASK;
107   next = h->pending_head;
108   while (NULL != (qe = next))
109     {
110       next = qe->next;
111       if (h->running_head == NULL)
112         {
113           start_job (qe);
114           continue;
115         }
116       if ( (qe->blocks + h->active_blocks <= h->max_parallel_requests) &&
117            (h->active_downloads + 1 <= h->max_parallel_downloads) )
118         {
119           start_job (qe);
120           continue;
121         }
122     }
123   if (h->pending_head == NULL)
124     return; /* no need to stop anything */
125   restart_at = GNUNET_TIME_UNIT_FOREVER_REL;
126   next = h->running_head;
127   while (NULL != (qe = next))
128     {
129       next = qe->next;
130       /* FIXME: might be faster/simpler to do this calculation only once
131          when we start a job (OTOH, this would allow us to dynamically
132          and easily adjust qe->blocks over time, given the right API...) */
133       run_time = GNUNET_TIME_relative_multiply (h->avg_block_latency,
134                                                 qe->blocks * qe->start_times);
135       end_time = GNUNET_TIME_absolute_add (qe->start_time,
136                                            run_time);
137       rst = GNUNET_TIME_absolute_get_remaining (end_time);
138       restart_at = GNUNET_TIME_relative_min (rst, restart_at);
139       if (rst.value > 0)
140         continue;       
141       stop_job (qe);
142     }
143   h->queue_job = GNUNET_SCHEDULER_add_delayed (h->sched,
144                                                restart_at,
145                                                &process_job_queue,
146                                                h);
147 }
148
149
150 /**
151  * Add a job to the queue.
152  *
153  * @param h handle to the overall FS state
154  * @param start function to call to begin the job
155  * @param stop function to call to pause the job, or on dequeue (if the job was running)
156  * @param cls closure for start and stop
157  * @param blocks number of blocks this jobs uses
158  * @return queue handle
159  */
160 struct GNUNET_FS_QueueEntry *
161 GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h,
162                   GNUNET_FS_QueueStart start,
163                   GNUNET_FS_QueueStop stop,
164                   void *cls,
165                   unsigned int blocks)
166 {
167   struct GNUNET_FS_QueueEntry *qe;
168
169   qe = GNUNET_malloc (sizeof (struct GNUNET_FS_QueueEntry));
170   qe->h = h;
171   qe->start = start;
172   qe->stop = stop;
173   qe->cls = cls;
174   qe->queue_time = GNUNET_TIME_absolute_get ();
175   qe->blocks = blocks;
176   GNUNET_CONTAINER_DLL_insert_after (h->pending_head,
177                                      h->pending_tail,
178                                      h->pending_tail,
179                                      qe);
180   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
181     GNUNET_SCHEDULER_cancel (h->sched,
182                              h->queue_job);
183   h->queue_job 
184     = GNUNET_SCHEDULER_add_now (h->sched,
185                                 &process_job_queue,
186                                 h);
187   return qe;
188 }
189
190
191 /**
192  * Dequeue a job from the queue.
193  * @param qh handle for the job
194  */
195 void
196 GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qh)
197 {
198   struct GNUNET_FS_Handle *h;
199
200   h = qh->h;
201   if (qh->client != NULL)    
202     stop_job (qh);    
203   GNUNET_CONTAINER_DLL_remove (h->pending_head,
204                                h->pending_tail,
205                                qh);
206   GNUNET_free (qh);
207   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
208     GNUNET_SCHEDULER_cancel (h->sched,
209                              h->queue_job);
210   h->queue_job 
211     = GNUNET_SCHEDULER_add_now (h->sched,
212                                 &process_job_queue,
213                                 h);
214 }
215
216
217
218
219 /**
220  * Closure for "data_reader_file".
221  */
222 struct FileInfo
223 {
224   /**
225    * Name of the file to read.
226    */
227   char *filename;
228
229   /**
230    * File descriptor, NULL if it has not yet been opened.
231    */
232   struct GNUNET_DISK_FileHandle *fd;
233 };
234
235
236 /**
237  * Function that provides data by reading from a file.
238  *
239  * @param cls closure (points to the file information)
240  * @param offset offset to read from; it is possible
241  *            that the caller might need to go backwards
242  *            a bit at times
243  * @param max maximum number of bytes that should be 
244  *            copied to buf; readers are not allowed
245  *            to provide less data unless there is an error;
246  *            a value of "0" will be used at the end to allow
247  *            the reader to clean up its internal state
248  * @param buf where the reader should write the data
249  * @param emsg location for the reader to store an error message
250  * @return number of bytes written, usually "max", 0 on error
251  */
252 size_t
253 GNUNET_FS_data_reader_file_(void *cls, 
254                             uint64_t offset,
255                             size_t max, 
256                             void *buf,
257                             char **emsg)
258 {
259   struct FileInfo *fi = cls;
260   ssize_t ret;
261
262   if (max == 0)
263     {
264       if (fi->fd != NULL)
265         GNUNET_DISK_file_close (fi->fd);
266       GNUNET_free (fi->filename);
267       GNUNET_free (fi);
268       return 0;
269     }  
270   if (fi->fd == NULL)
271     {
272       fi->fd = GNUNET_DISK_file_open (fi->filename,
273                                       GNUNET_DISK_OPEN_READ,
274                                       GNUNET_DISK_PERM_NONE);
275       if (fi->fd == NULL)
276         {
277           GNUNET_asprintf (emsg, 
278                            _("Could not open file `%s': %s"),
279                            fi->filename,
280                            STRERROR (errno));
281           return 0;
282         }
283     }
284   GNUNET_DISK_file_seek (fi->fd, offset, GNUNET_DISK_SEEK_SET);
285   ret = GNUNET_DISK_file_read (fi->fd, buf, max);
286   if (ret == -1)
287     {
288       GNUNET_asprintf (emsg, 
289                        _("Could not read file `%s': %s"),
290                        fi->filename,
291                        STRERROR (errno));
292       return 0;
293     }
294   if (ret != max)
295     {
296       GNUNET_asprintf (emsg, 
297                        _("Short read reading from file `%s'!"),
298                        fi->filename);
299       return 0;
300     }
301   return max;
302 }
303
304
305 /**
306  * Create the closure for the 'GNUNET_FS_data_reader_file_' callback.
307  *
308  * @param filename file to read
309  * @return closure to use, NULL on error
310  */
311 void *
312 GNUNET_FS_make_file_reader_context_ (const char *filename)
313 {
314   struct FileInfo *fi;
315
316   fi = GNUNET_malloc (sizeof(struct FileInfo));
317   fi->filename = GNUNET_STRINGS_filename_expand (filename);
318   if (fi->filename == NULL)
319     {
320       GNUNET_free (fi);
321       return NULL;
322     }
323   return fi;
324 }
325
326
327 /**
328  * Function that provides data by copying from a buffer.
329  *
330  * @param cls closure (points to the buffer)
331  * @param offset offset to read from; it is possible
332  *            that the caller might need to go backwards
333  *            a bit at times
334  * @param max maximum number of bytes that should be 
335  *            copied to buf; readers are not allowed
336  *            to provide less data unless there is an error;
337  *            a value of "0" will be used at the end to allow
338  *            the reader to clean up its internal state
339  * @param buf where the reader should write the data
340  * @param emsg location for the reader to store an error message
341  * @return number of bytes written, usually "max", 0 on error
342  */
343 size_t
344 GNUNET_FS_data_reader_copy_ (void *cls, 
345                              uint64_t offset,
346                              size_t max, 
347                              void *buf,
348                              char **emsg)
349 {
350   char *data = cls;
351
352   if (max == 0)
353     {
354       GNUNET_free_non_null (data);
355       return 0;
356     }  
357   memcpy (buf, &data[offset], max);
358   return max;
359 }
360
361
362
363 /**
364  * Return the full filename where we would store state information
365  * (for serialization/deserialization).
366  *
367  * @param h master context
368  * @param ext component of the path 
369  * @param ent entity identifier (or emtpy string for the directory)
370  * @return NULL on error
371  */
372 static char *
373 get_serialization_file_name (struct GNUNET_FS_Handle *h,
374                              const char *ext,
375                              const char *ent)
376 {
377   char *basename;
378   char *ret;
379   if (GNUNET_OK !=
380       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
381                                                "fs",
382                                                "STATE_DIR",
383                                                &basename))
384     return NULL;
385   GNUNET_asprintf (&ret,
386                    "%s%s%s-%s%s%s",
387                    basename,
388                    DIR_SEPARATOR_STR,
389                    h->client_name,
390                    ext,
391                    DIR_SEPARATOR_STR,
392                    ent);
393   GNUNET_free (basename);
394   return ret;
395 }
396
397
398 /**
399  * Return a read handle for deserialization.
400  *
401  * @param h master context
402  * @param ext component of the path 
403  * @param ent entity identifier (or emtpy string for the directory)
404  * @return NULL on error
405  */
406 static struct GNUNET_BIO_ReadHandle *
407 get_read_handle (struct GNUNET_FS_Handle *h,
408                  const char *ext,
409                  const char *ent)
410 {
411   char *fn;
412   struct GNUNET_BIO_ReadHandle *ret;
413
414   fn = get_serialization_file_name (h, ext, ent);
415   if (fn == NULL)
416     return NULL;
417   ret = GNUNET_BIO_read_open (fn);
418   GNUNET_free (fn);
419   return ret;
420 }
421
422
423 /**
424  * Return a write handle for serialization.
425  *
426  * @param h master context
427  * @param ext component of the path 
428  * @param ent entity identifier (or emtpy string for the directory)
429  * @return NULL on error
430  */
431 static struct GNUNET_BIO_WriteHandle *
432 get_write_handle (struct GNUNET_FS_Handle *h,
433                  const char *ext,
434                  const char *ent)
435 {
436   char *fn;
437   struct GNUNET_BIO_WriteHandle *ret;
438
439   fn = get_serialization_file_name (h, ext, ent);
440   if (fn == NULL)
441     return NULL;
442   ret = GNUNET_BIO_write_open (fn);
443   GNUNET_free (fn);
444   return ret;
445 }
446
447
448 /**
449  * Remove serialization/deserialization file from disk.
450  *
451  * @param h master context
452  * @param ext component of the path 
453  * @param ent entity identifier 
454  */
455 void
456 GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h,
457                              const char *ext,
458                              const char *ent)
459 {
460   char *filename;
461
462   if ( (NULL == ent) ||
463        (0 == strlen (ent)) )
464     {
465       GNUNET_break (0);
466       return;
467     }
468   filename = get_serialization_file_name (h, ext, ent);
469   if (0 != UNLINK (filename))
470     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
471                               "unlink", 
472                               filename);
473   GNUNET_free (filename);
474 }
475
476
477
478 /**
479  * Using the given serialization filename, try to deserialize
480  * the file-information tree associated with it.
481  *
482  * @param h master context
483  * @param filename name of the file (without directory) with
484  *        the infromation
485  * @return NULL on error
486  */
487 static struct GNUNET_FS_FileInformation *
488 deserialize_file_information (struct GNUNET_FS_Handle *h,
489                               const char *filename);
490
491
492 /**
493  * Using the given serialization filename, try to deserialize
494  * the file-information tree associated with it.
495  *
496  * @param h master context
497  * @param fn name of the file (without directory) with
498  *        the infromation
499  * @param rh handle for reading
500  * @return NULL on error
501  */
502 static struct GNUNET_FS_FileInformation *
503 deserialize_fi_node (struct GNUNET_FS_Handle *h,
504                      const char *fn,
505                      struct GNUNET_BIO_ReadHandle *rh)
506 {
507   struct GNUNET_FS_FileInformation *ret;
508   struct GNUNET_FS_FileInformation *nxt;
509   char b;
510   char *ksks;
511   char *chks;
512   char *filename;
513   uint32_t dsize;
514
515   if (GNUNET_OK !=
516       GNUNET_BIO_read (rh, "status flag", &b, sizeof(b)))
517     {
518       GNUNET_break (0);
519       return NULL;
520     }
521   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
522   ksks = NULL;
523   chks = NULL;
524   filename = NULL;
525   if ( (GNUNET_OK !=
526         GNUNET_BIO_read_meta_data (rh, "metadata", &ret->meta)) ||
527        (GNUNET_OK !=
528         GNUNET_BIO_read_string (rh, "ksk-uri", &ksks, 32*1024)) ||
529        ( (ksks != NULL) &&
530          (NULL == 
531           (ret->keywords = GNUNET_FS_uri_parse (ksks, NULL))) ) ||
532        (GNUNET_YES !=
533         GNUNET_FS_uri_test_ksk (ret->keywords)) ||
534        (GNUNET_OK !=
535         GNUNET_BIO_read_string (rh, "chk-uri", &chks, 1024)) ||
536        ( (chks != NULL) &&
537          ( (NULL == 
538             (ret->chk_uri = GNUNET_FS_uri_parse (chks, NULL))) ||
539            (GNUNET_YES !=
540             GNUNET_FS_uri_test_chk (ret->chk_uri)) ) ) ||
541        (GNUNET_OK !=
542         GNUNET_BIO_read_int64 (rh, &ret->expirationTime.value)) ||
543        (GNUNET_OK !=
544         GNUNET_BIO_read_int64 (rh, &ret->start_time.value)) ||
545        (GNUNET_OK !=
546         GNUNET_BIO_read_string (rh, "emsg", &ret->emsg, 16*1024)) ||
547        (GNUNET_OK !=
548         GNUNET_BIO_read_string (rh, "fn", &ret->filename, 16*1024)) ||
549        (GNUNET_OK !=
550         GNUNET_BIO_read_int32 (rh, &ret->anonymity)) ||
551        (GNUNET_OK !=
552         GNUNET_BIO_read_int32 (rh, &ret->priority)) )
553     goto cleanup;
554   switch (b)
555     {
556     case 0: /* file-insert */
557       if (GNUNET_OK !=
558           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
559         goto cleanup;
560       ret->is_directory = GNUNET_NO;
561       ret->data.file.do_index = GNUNET_NO;
562       ret->data.file.have_hash = GNUNET_NO;
563       ret->data.file.index_start_confirmed = GNUNET_NO;
564       if (GNUNET_NO == ret->is_published) 
565         {
566           if (NULL == ret->filename)
567             {
568               ret->data.file.reader = &GNUNET_FS_data_reader_copy_;
569               ret->data.file.reader_cls = GNUNET_malloc_large (ret->data.file.file_size);
570               if (ret->data.file.reader_cls == NULL)
571                 goto cleanup;
572               if (GNUNET_OK !=
573                   GNUNET_BIO_read (rh, "file-data", ret->data.file.reader_cls, ret->data.file.file_size))
574                 goto cleanup;
575             }      
576           else
577             {
578               ret->data.file.reader = &GNUNET_FS_data_reader_file_;
579               ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
580             }
581         }
582       break;
583     case 1: /* file-index, no hash */
584       if (NULL == ret->filename)
585         goto cleanup;
586       if (GNUNET_OK !=
587           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
588         goto cleanup;
589       ret->is_directory = GNUNET_NO;
590       ret->data.file.do_index = GNUNET_YES;
591       ret->data.file.have_hash = GNUNET_NO;
592       ret->data.file.index_start_confirmed = GNUNET_NO;
593       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
594       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
595       break;
596     case 2: /* file-index-with-hash */
597       if (NULL == ret->filename)
598         goto cleanup;
599       if ( (GNUNET_OK !=
600             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
601            (GNUNET_OK !=
602             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
603         goto cleanup;
604       ret->is_directory = GNUNET_NO;
605       ret->data.file.do_index = GNUNET_YES;
606       ret->data.file.have_hash = GNUNET_YES;
607       ret->data.file.index_start_confirmed = GNUNET_NO;
608       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
609       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
610       break;
611     case 3: /* file-index-with-hash-confirmed */
612       if (NULL == ret->filename)
613         goto cleanup;
614       if ( (GNUNET_OK !=
615             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
616            (GNUNET_OK !=
617             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
618         goto cleanup;
619
620       ret->is_directory = GNUNET_NO;
621       ret->data.file.do_index = GNUNET_YES;
622       ret->data.file.have_hash = GNUNET_YES;
623       ret->data.file.index_start_confirmed = GNUNET_YES;
624       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
625       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
626       break;
627     case 4: /* directory */
628       if ( (GNUNET_OK !=
629             GNUNET_BIO_read_int32 (rh, &dsize)) ||
630            (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large (dsize))) ||
631            (GNUNET_OK !=
632             GNUNET_BIO_read (rh, "dir-data", ret->data.dir.dir_data, dsize)) ||
633            (GNUNET_OK !=
634             GNUNET_BIO_read_string (rh, "ent-filename", &filename, 16*1024)) )
635         goto cleanup;
636       ret->data.dir.dir_size = (uint32_t) dsize;
637       ret->is_directory = GNUNET_YES;
638       if (filename != NULL)
639         {
640           ret->data.dir.entries = deserialize_file_information (h, filename);
641           GNUNET_free (filename);
642           filename = NULL;
643           nxt = ret->data.dir.entries;
644           while (nxt != NULL)
645             {
646               nxt->dir = ret;
647               nxt = nxt->next;
648             }  
649         }
650       break;
651     default:
652       GNUNET_break (0);
653       goto cleanup;
654     }
655   /* FIXME: adjust ret->start_time! */
656   ret->serialization = GNUNET_strdup (fn);
657   if (GNUNET_OK !=
658       GNUNET_BIO_read_string (rh, "nxt-filename", &filename, 16*1024))
659     goto cleanup;  
660   if (filename != NULL)
661     {
662       ret->next = deserialize_file_information (h, filename);
663       GNUNET_free (filename);
664       filename = NULL;
665     }
666   return ret;
667  cleanup:
668   GNUNET_free_non_null (ksks);
669   GNUNET_free_non_null (chks);
670   GNUNET_free_non_null (filename);
671   GNUNET_FS_file_information_destroy (ret, NULL, NULL);
672   return NULL;
673 }
674
675
676 /**
677  * Using the given serialization filename, try to deserialize
678  * the file-information tree associated with it.
679  *
680  * @param h master context
681  * @param filename name of the file (without directory) with
682  *        the infromation
683  * @return NULL on error
684  */
685 static struct GNUNET_FS_FileInformation *
686 deserialize_file_information (struct GNUNET_FS_Handle *h,
687                               const char *filename)
688 {
689   struct GNUNET_FS_FileInformation *ret;
690   struct GNUNET_BIO_ReadHandle *rh;
691   char *emsg;
692
693   rh = get_read_handle (h, "publish-fi", filename);
694   if (rh == NULL)
695     return NULL;
696   ret = deserialize_fi_node (h, filename, rh);
697   if (GNUNET_OK !=
698       GNUNET_BIO_read_close (rh, &emsg))
699     {
700       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
701                   _("Failed to resume publishing information `%s': %s\n"),
702                   filename,
703                   emsg);
704       GNUNET_free (emsg);
705     }
706   return ret;
707 }
708
709
710 /**
711  * Given a serialization name (full absolute path), return the
712  * basename of the file (without the path), which must only
713  * consist of the 6 random characters.
714  * 
715  * @param fullname name to extract the basename from
716  * @return copy of the basename, NULL on error
717  */
718 static char *
719 get_serialization_short_name (const char *fullname)
720 {
721   const char *end;
722   const char *nxt;
723
724   end = NULL;
725   nxt = fullname;
726   /* FIXME: we could do this faster since we know
727      the length of 'end'... */
728   while ('\0' != nxt)
729     {
730       if (DIR_SEPARATOR == *nxt)
731         end = nxt + 1;
732       nxt++;
733     }
734   if ( (end == NULL) ||
735        (strlen (end) == 0) )
736     {
737       GNUNET_break (0);
738       return NULL;
739     }
740   GNUNET_break (6 == strlen (end));
741   return GNUNET_strdup (end);  
742 }
743
744
745 /**
746  * Create a new random name for serialization.  Also checks if persistence
747  * is enabled and returns NULL if not.
748  *
749  * @param h master context
750  * @param ext component of the path 
751  * @return NULL on errror
752  */
753 static char *
754 make_serialization_file_name (struct GNUNET_FS_Handle *h,
755                               const char *ext)
756 {
757   char *fn;
758   char *dn;
759   char *ret;
760
761   if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE))
762     return NULL; /* persistence not requested */
763   dn = get_serialization_file_name (h, ext, "");
764   fn = GNUNET_DISK_mktemp (dn);
765   GNUNET_free (dn);
766   if (fn == NULL)
767     return NULL; /* epic fail */
768   ret = get_serialization_short_name (fn);
769   GNUNET_free (fn);
770   return ret;
771 }
772
773
774 /**
775  * Copy all of the data from the reader to the write handle.
776  *
777  * @param wh write handle
778  * @param fi file with reader
779  * @return GNUNET_OK on success
780  */
781 static int
782 copy_from_reader (struct GNUNET_BIO_WriteHandle *wh,
783                   struct GNUNET_FS_FileInformation * fi)
784 {
785   char buf[32 * 1024];
786   uint64_t off;
787   size_t ret;
788   char *emsg;
789
790   emsg = NULL;
791   off = 0;
792   while (off < fi->data.file.file_size)
793     {
794       ret = fi->data.file.reader (fi->data.file.reader_cls,
795                                   off, sizeof (buf),
796                                   buf,
797                                   &emsg);
798       if (ret == 0)
799         {
800           GNUNET_free (emsg);
801           return GNUNET_SYSERR;
802         }
803       if (GNUNET_OK != 
804           GNUNET_BIO_write (wh, buf, ret))
805         return GNUNET_SYSERR;
806       off += ret;
807     }
808   return GNUNET_OK;
809 }
810
811
812 /**
813  * Create a temporary file on disk to store the current
814  * state of "fi" in.
815  *
816  * @param fi file information to sync with disk
817  */
818 void
819 GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation * fi)
820 {
821   char *fn;
822   struct GNUNET_BIO_WriteHandle *wh;
823   char b;
824   char *ksks;
825   char *chks;
826
827   if (NULL == fi->serialization)    
828     fi->serialization = make_serialization_file_name (fi->h, "publish-fi");
829   if (NULL == fi->serialization)
830     return;
831   wh = get_write_handle (fi->h, "publish-fi", fi->serialization);
832   if (wh == NULL)
833     {
834       GNUNET_free (fi->serialization);
835       fi->serialization = NULL;
836       return;
837     }
838   if (GNUNET_YES == fi->is_directory)
839     b = 4;
840   else if (GNUNET_YES == fi->data.file.index_start_confirmed)
841     b = 3;
842   else if (GNUNET_YES == fi->data.file.have_hash)
843     b = 2;
844   else if (GNUNET_YES == fi->data.file.do_index)
845     b = 1;
846   else
847     b = 0;
848   if (fi->keywords != NULL)
849     ksks = GNUNET_FS_uri_to_string (fi->keywords);
850   else
851     ksks = NULL;
852   if (fi->chk_uri != NULL)
853     chks = GNUNET_FS_uri_to_string (fi->chk_uri);
854   else
855     chks = NULL;
856   if ( (GNUNET_OK !=
857         GNUNET_BIO_write (wh, &b, sizeof (b))) ||
858        (GNUNET_OK != 
859         GNUNET_BIO_write_meta_data (wh, fi->meta)) ||
860        (GNUNET_OK !=
861         GNUNET_BIO_write_string (wh, ksks)) ||
862        (GNUNET_OK !=
863         GNUNET_BIO_write_string (wh, chks)) ||
864        (GNUNET_OK != 
865         GNUNET_BIO_write_int64 (wh, fi->expirationTime.value)) ||
866        (GNUNET_OK != 
867         GNUNET_BIO_write_int64 (wh, fi->start_time.value)) ||
868        (GNUNET_OK !=
869         GNUNET_BIO_write_string (wh, fi->emsg)) ||
870        (GNUNET_OK !=
871         GNUNET_BIO_write_string (wh, fi->filename)) ||
872        (GNUNET_OK != 
873         GNUNET_BIO_write_int32 (wh, fi->anonymity)) ||
874        (GNUNET_OK != 
875         GNUNET_BIO_write_int32 (wh, fi->priority)) )
876     goto cleanup;
877   GNUNET_free_non_null (chks);
878   chks = NULL;
879   GNUNET_free_non_null (ksks);
880   ksks = NULL;
881   
882   switch (b)
883     {
884     case 0: /* file-insert */
885       if (GNUNET_OK !=
886           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
887         goto cleanup;
888       if ( (GNUNET_NO == fi->is_published) &&
889            (NULL == fi->filename) )     
890         if (GNUNET_OK != 
891             copy_from_reader (wh, fi))
892           goto cleanup;
893       break;
894     case 1: /* file-index, no hash */
895       if (NULL == fi->filename)
896         goto cleanup;
897       if (GNUNET_OK !=
898           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
899         goto cleanup;
900       break;
901     case 2: /* file-index-with-hash */
902     case 3: /* file-index-with-hash-confirmed */
903       if (NULL == fi->filename)
904         goto cleanup;
905       if ( (GNUNET_OK !=
906             GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) ||
907            (GNUNET_OK !=
908             GNUNET_BIO_write (wh, &fi->data.file.file_id, sizeof (GNUNET_HashCode))) )
909         goto cleanup;
910       break;
911     case 4: /* directory */
912       if ( (GNUNET_OK !=
913             GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) ||
914            (GNUNET_OK !=
915             GNUNET_BIO_write (wh, fi->data.dir.dir_data, (uint32_t) fi->data.dir.dir_size)) ||
916            (GNUNET_OK !=
917             GNUNET_BIO_write_string (wh, fi->data.dir.entries->serialization)) )
918         goto cleanup;
919       break;
920     default:
921       GNUNET_assert (0);
922       goto cleanup;
923     }
924   if (GNUNET_OK !=
925       GNUNET_BIO_write_string (wh, fi->next->serialization))
926     goto cleanup;  
927   if (GNUNET_OK ==
928       GNUNET_BIO_write_close (wh))
929     return; /* done! */
930  cleanup:
931   (void) GNUNET_BIO_write_close (wh);
932   GNUNET_free_non_null (chks);
933   GNUNET_free_non_null (ksks);
934   fn = get_serialization_file_name (fi->h, "publish-fi", fi->serialization);
935   if (0 != UNLINK (fn))
936     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
937   GNUNET_free (fn);
938   GNUNET_free (fi->serialization);
939   fi->serialization = NULL;  
940 }
941
942
943
944 /**
945  * Find the entry in the file information struct where the
946  * serialization filename matches the given name.
947  *
948  * @param pos file information to search
949  * @param srch filename to search for
950  * @return NULL if srch was not found in this subtree
951  */
952 static struct GNUNET_FS_FileInformation *
953 find_file_position (struct GNUNET_FS_FileInformation *pos,
954                     const char *srch)
955 {
956   struct GNUNET_FS_FileInformation *r;
957
958   while (pos != NULL)
959     {
960       if (0 == strcmp (srch,
961                        pos->serialization))
962         return pos;
963       if (pos->is_directory)
964         {
965           r = find_file_position (pos->data.dir.entries,
966                                   srch);
967           if (r != NULL)
968             return r;
969         }
970       pos = pos->next;
971     }
972   return NULL;
973 }
974
975
976 /**
977  * Signal the FS's progress function that we are resuming
978  * an upload.
979  *
980  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
981  * @param fi the entry in the publish-structure
982  * @param length length of the file or directory
983  * @param meta metadata for the file or directory (can be modified)
984  * @param uri pointer to the keywords that will be used for this entry (can be modified)
985  * @param anonymity pointer to selected anonymity level (can be modified)
986  * @param priority pointer to selected priority (can be modified)
987  * @param expirationTime pointer to selected expiration time (can be modified)
988  * @param client_info pointer to client context set upon creation (can be modified)
989  * @return GNUNET_OK to continue (always)
990  */
991 static int
992 fip_signal_resume(void *cls,
993                   struct GNUNET_FS_FileInformation *fi,
994                   uint64_t length,
995                   struct GNUNET_CONTAINER_MetaData *meta,
996                   struct GNUNET_FS_Uri **uri,
997                   uint32_t *anonymity,
998                   uint32_t *priority,
999                   struct GNUNET_TIME_Absolute *expirationTime,
1000                   void **client_info)
1001 {
1002   struct GNUNET_FS_PublishContext *sc = cls;
1003   struct GNUNET_FS_ProgressInfo pi;
1004
1005   pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME;
1006   pi.value.publish.specifics.resume.message = sc->fi->emsg;
1007   pi.value.publish.specifics.resume.chk_uri = sc->fi->chk_uri;
1008   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1009   return GNUNET_OK;
1010 }
1011
1012
1013 /**
1014  * Function called with a filename of serialized publishing operation
1015  * to deserialize.
1016  *
1017  * @param cls the 'struct GNUNET_FS_Handle*'
1018  * @param filename complete filename (absolute path)
1019  * @return GNUNET_OK (continue to iterate)
1020  */
1021 static int
1022 deserialize_publish_file (void *cls,
1023                           const char *filename)
1024 {
1025   struct GNUNET_FS_Handle *h = cls;
1026   struct GNUNET_BIO_ReadHandle *rh;
1027   struct GNUNET_FS_PublishContext *pc;
1028   int32_t options;
1029   int32_t all_done;
1030   char *fi_root;
1031   char *ns;
1032   char *fi_pos;
1033   char *emsg;
1034
1035   pc = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
1036   pc->h = h;
1037   pc->serialization = get_serialization_short_name (filename);
1038   fi_root = NULL;
1039   fi_pos = NULL;
1040   ns = NULL;
1041   rh = GNUNET_BIO_read_open (filename);
1042   if (rh == NULL)
1043     goto cleanup;
1044   if ( (GNUNET_OK !=
1045         GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) ||
1046        (GNUNET_OK !=
1047         GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) ||
1048        (GNUNET_OK !=
1049         GNUNET_BIO_read_int32 (rh, &options)) ||
1050        (GNUNET_OK !=
1051         GNUNET_BIO_read_int32 (rh, &all_done)) ||
1052        (GNUNET_OK !=
1053         GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) ||
1054        (GNUNET_OK !=
1055         GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) ||
1056        (GNUNET_OK !=
1057         GNUNET_BIO_read_string (rh, "publish-ns", &ns, 1024)) )
1058     goto cleanup;          
1059   pc->options = options;
1060   pc->all_done = all_done;
1061   pc->fi = deserialize_file_information (h, fi_root);
1062   if (pc->fi == NULL)
1063     goto cleanup;    
1064   if (ns != NULL)
1065     {
1066       pc->namespace = GNUNET_FS_namespace_create (h, ns);
1067       if (pc->namespace == NULL)
1068         {
1069           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1070                       _("Failed to recover namespace `%s', cannot resume publishing operation.\n"),
1071                       ns);
1072           goto cleanup;
1073         }
1074     }
1075   if (fi_pos != NULL)
1076     {
1077       pc->fi_pos = find_file_position (pc->fi,
1078                                        fi_pos);
1079       GNUNET_free (fi_pos);
1080       if (pc->fi_pos == NULL)
1081         {
1082           /* failed to find position for resuming, outch! Will start from root! */
1083           GNUNET_break (0);
1084           if (pc->all_done != GNUNET_YES)
1085             pc->fi_pos = pc->fi;
1086         }
1087     }
1088   /* generate RESUME event(s) */
1089   GNUNET_FS_file_information_inspect (pc->fi,
1090                                       &fip_signal_resume,
1091                                       pc);
1092   
1093   /* re-start publishing (if needed)... */
1094   if (pc->all_done != GNUNET_YES)
1095     pc->upload_task 
1096       = GNUNET_SCHEDULER_add_with_priority (h->sched,
1097                                             GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1098                                             &GNUNET_FS_publish_main_,
1099                                             pc);       
1100   if (GNUNET_OK !=
1101       GNUNET_BIO_read_close (rh, &emsg))
1102     {
1103       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1104                   _("Failure while resuming publishing operation `%s': %s\n"),
1105                   filename,
1106                   emsg);
1107       GNUNET_free (emsg);
1108     }
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 (ns);
1115   if ( (rh != NULL) &&
1116        (GNUNET_OK !=
1117         GNUNET_BIO_read_close (rh, &emsg)) )
1118     {
1119       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1120                   _("Failed to resume publishing operation `%s': %s\n"),
1121                   filename,
1122                   emsg);
1123       GNUNET_free (emsg);
1124     }
1125   if (pc->fi != NULL)
1126     GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
1127   if (pc->serialization != NULL)
1128     GNUNET_FS_remove_sync_file_ (h, "publish", pc->serialization);
1129   GNUNET_free_non_null (pc->serialization);
1130   GNUNET_free (pc);
1131   return GNUNET_OK;
1132 }
1133
1134
1135 /**
1136  * Synchronize this publishing struct with its mirror
1137  * on disk.  Note that all internal FS-operations that change
1138  * publishing structs should already call "sync" internally,
1139  * so this function is likely not useful for clients.
1140  * 
1141  * @param pc the struct to sync
1142  */
1143 void
1144 GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc)
1145 {  
1146   struct GNUNET_BIO_WriteHandle *wh;
1147
1148   if (NULL == pc->serialization)
1149     pc->serialization = make_serialization_file_name (pc->h,
1150                                                       "publish");
1151   if (NULL == pc->serialization)
1152     return;
1153   if (NULL == pc->fi)
1154     return;
1155   if (NULL == pc->fi->serialization)
1156     {
1157       GNUNET_break (0);
1158       return;
1159     }
1160   wh = get_write_handle (pc->h, "publish", pc->serialization);
1161   if ( (GNUNET_OK !=
1162         GNUNET_BIO_write_string (wh, pc->nid)) ||
1163        (GNUNET_OK !=
1164         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1165        (GNUNET_OK !=
1166         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1167        (GNUNET_OK !=
1168         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1169        (GNUNET_OK !=
1170         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1171        (GNUNET_OK !=
1172         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1173        (GNUNET_OK !=
1174         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1175    {
1176      (void) GNUNET_BIO_write_close (wh);
1177      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1178      GNUNET_free (pc->serialization);
1179      pc->serialization = NULL;
1180      return;
1181    }
1182  if (GNUNET_OK !=
1183      GNUNET_BIO_write_close (wh))
1184    {
1185      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1186      GNUNET_free (pc->serialization);
1187      pc->serialization = NULL;
1188      return;     
1189    }  
1190 }
1191
1192
1193 /**
1194  * Synchronize this unindex struct with its mirror
1195  * on disk.  Note that all internal FS-operations that change
1196  * publishing structs should already call "sync" internally,
1197  * so this function is likely not useful for clients.
1198  * 
1199  * @param uc the struct to sync
1200  */
1201 void
1202 GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc)
1203 {
1204   struct GNUNET_BIO_WriteHandle *wh;
1205
1206   if (UNINDEX_STATE_ABORTED == uc->state)
1207     return;
1208   if (NULL == uc->serialization)
1209     uc->serialization = make_serialization_file_name (uc->h,
1210                                                       "unindex");
1211   if (NULL == uc->serialization)
1212     return;
1213   wh = get_write_handle (uc->h, "unindex", uc->serialization);
1214   if ( (GNUNET_OK !=
1215         GNUNET_BIO_write_string (wh, uc->filename)) ||
1216        (GNUNET_OK !=
1217         GNUNET_BIO_write_int64 (wh, uc->file_size)) ||
1218        (GNUNET_OK !=
1219         GNUNET_BIO_write_int64 (wh, uc->start_time.value)) ||
1220        (GNUNET_OK !=
1221         GNUNET_BIO_write_int32 (wh, (uint32_t) uc->state)) ||
1222        ( (uc->state == UNINDEX_STATE_FS_NOTIFY) &&
1223          (GNUNET_OK !=
1224           GNUNET_BIO_write (wh, &uc->file_id, sizeof (GNUNET_HashCode))) ) ||
1225        ( (uc->state == UNINDEX_STATE_ERROR) &&
1226          (GNUNET_OK !=
1227           GNUNET_BIO_write_string (wh, uc->emsg)) ) )
1228     {
1229       (void) GNUNET_BIO_write_close (wh);
1230       GNUNET_FS_remove_sync_file_ (uc->h, "publish", uc->serialization);
1231       GNUNET_free (uc->serialization);
1232       uc->serialization = NULL;
1233       return;
1234     }
1235   if (GNUNET_OK !=
1236       GNUNET_BIO_write_close (wh))
1237     {
1238       GNUNET_FS_remove_sync_file_ (uc->h, "unindex", uc->serialization);
1239       GNUNET_free (uc->serialization);
1240       uc->serialization = NULL;
1241       return;     
1242     }  
1243 }
1244
1245
1246 /**
1247  * Synchronize this search struct with its mirror
1248  * on disk.  Note that all internal FS-operations that change
1249  * publishing structs should already call "sync" internally,
1250  * so this function is likely not useful for clients.
1251  * 
1252  * @param sc the struct to sync
1253  */
1254 void
1255 GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc)
1256 {  
1257   struct GNUNET_BIO_WriteHandle *wh;
1258
1259   if (NULL == sc->serialization)
1260     sc->serialization = make_serialization_file_name (sc->h,
1261                                                       "search");
1262   if (NULL == sc->serialization)
1263     return;
1264   wh = get_write_handle (sc->h, "search", sc->serialization);
1265 #if 0
1266   if ( (GNUNET_OK !=
1267         GNUNET_BIO_write_string (wh, pc->nid)) ||
1268        (GNUNET_OK !=
1269         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1270        (GNUNET_OK !=
1271         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1272        (GNUNET_OK !=
1273         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1274        (GNUNET_OK !=
1275         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1276        (GNUNET_OK !=
1277         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1278        (GNUNET_OK !=
1279         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1280    {
1281      (void) GNUNET_BIO_write_close (wh);
1282      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1283      GNUNET_free (pc->serialization);
1284      pc->serialization = NULL;
1285      return;
1286    }
1287 #endif
1288   /* FIXME: do search-specific deserialization here! */
1289   if (GNUNET_OK !=
1290       GNUNET_BIO_write_close (wh))
1291     {
1292       GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1293       GNUNET_free (sc->serialization);
1294       sc->serialization = NULL;
1295       return;     
1296     }  
1297 }
1298
1299
1300 /**
1301  * Deserialize information about pending publish operations.
1302  *
1303  * @param h master context
1304  */
1305 static void
1306 deserialize_publish (struct GNUNET_FS_Handle *h)
1307 {
1308   char *dn;
1309
1310   dn = get_serialization_file_name (h, "publish", "");
1311   if (dn == NULL)
1312     return;
1313   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1314   GNUNET_free (dn);
1315 }
1316
1317
1318
1319
1320 /**
1321  * Function called with a filename of serialized unindexing operation
1322  * to deserialize.
1323  *
1324  * @param cls the 'struct GNUNET_FS_Handle*'
1325  * @param filename complete filename (absolute path)
1326  * @return GNUNET_OK (continue to iterate)
1327  */
1328 static int
1329 deserialize_unindex_file (void *cls,
1330                           const char *filename)
1331 {
1332   struct GNUNET_FS_Handle *h = cls;
1333   struct GNUNET_BIO_ReadHandle *rh;
1334   struct GNUNET_FS_UnindexContext *uc;
1335   struct GNUNET_FS_ProgressInfo pi;
1336   char *emsg;
1337   uint32_t state;
1338
1339   uc = GNUNET_malloc (sizeof (struct GNUNET_FS_UnindexContext));
1340   uc->h = h;
1341   uc->serialization = get_serialization_short_name (filename);
1342   rh = GNUNET_BIO_read_open (filename);
1343   if (rh == NULL)
1344     goto cleanup;
1345   if ( (GNUNET_OK !=
1346         GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10*1024)) ||
1347        (GNUNET_OK !=
1348         GNUNET_BIO_read_int64 (rh, &uc->file_size)) ||
1349        (GNUNET_OK !=
1350         GNUNET_BIO_read_int64 (rh, &uc->start_time.value)) ||
1351        (GNUNET_OK !=
1352         GNUNET_BIO_read_int32 (rh, &state)) )
1353     goto cleanup;          
1354   uc->state = (enum UnindexState) state;
1355   switch (state)
1356     {
1357     case UNINDEX_STATE_HASHING:
1358       break;
1359     case UNINDEX_STATE_FS_NOTIFY:
1360       if (GNUNET_OK !=
1361           GNUNET_BIO_read (rh, "unindex-hash", &uc->file_id, sizeof (GNUNET_HashCode)))
1362         goto cleanup;
1363       break;
1364     case UNINDEX_STATE_DS_REMOVE:
1365       break;
1366     case UNINDEX_STATE_COMPLETE:
1367       break;
1368     case UNINDEX_STATE_ERROR:
1369       if (GNUNET_OK !=
1370           GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10*1024))
1371         goto cleanup;
1372       break;
1373     case UNINDEX_STATE_ABORTED:
1374       GNUNET_break (0);
1375       goto cleanup;
1376     default:
1377       GNUNET_break (0);
1378       goto cleanup;
1379     }
1380   pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME;
1381   pi.value.unindex.specifics.resume.message = uc->emsg;
1382   GNUNET_FS_unindex_make_status_ (&pi,
1383                                   uc,
1384                                   (uc->state == UNINDEX_STATE_COMPLETE) 
1385                                   ? uc->file_size
1386                                   : 0);
1387   switch (uc->state)
1388     {
1389     case UNINDEX_STATE_HASHING:
1390       GNUNET_CRYPTO_hash_file (uc->h->sched,
1391                                GNUNET_SCHEDULER_PRIORITY_IDLE,
1392                                uc->filename,
1393                                HASHING_BLOCKSIZE,
1394                                &GNUNET_FS_unindex_process_hash_,
1395                                uc);
1396       break;
1397     case UNINDEX_STATE_FS_NOTIFY:
1398       uc->state = UNINDEX_STATE_HASHING;
1399       GNUNET_FS_unindex_process_hash_ (uc,
1400                                        &uc->file_id);
1401       break;
1402     case UNINDEX_STATE_DS_REMOVE:
1403       GNUNET_FS_unindex_do_remove_ (uc);
1404       break;
1405     case UNINDEX_STATE_COMPLETE:
1406     case UNINDEX_STATE_ERROR:
1407       /* no need to resume any operation, we were done */
1408       break;
1409     default:
1410       break;
1411     }
1412   if (GNUNET_OK !=
1413       GNUNET_BIO_read_close (rh, &emsg))
1414     {
1415       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1416                   _("Failure while resuming unindexing operation `%s': %s\n"),
1417                   filename,
1418                   emsg);
1419       GNUNET_free (emsg);
1420     }
1421   return GNUNET_OK;
1422  cleanup:
1423   GNUNET_free_non_null (uc->filename);
1424   if ( (rh != NULL) &&
1425        (GNUNET_OK !=
1426         GNUNET_BIO_read_close (rh, &emsg)) )
1427     {
1428       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1429                   _("Failed to resume unindexing operation `%s': %s\n"),
1430                   filename,
1431                   emsg);
1432       GNUNET_free (emsg);
1433     }
1434   if (uc->serialization != NULL)
1435     GNUNET_FS_remove_sync_file_ (h, "unindex", uc->serialization);
1436   GNUNET_free_non_null (uc->serialization);
1437   GNUNET_free (uc);
1438   return GNUNET_OK;
1439 }
1440
1441
1442 /**
1443  * Deserialize information about pending publish operations.
1444  *
1445  * @param h master context
1446  */
1447 static void
1448 deserialize_unindex (struct GNUNET_FS_Handle *h)
1449 {
1450   char *dn;
1451
1452   dn = get_serialization_file_name (h, "unindex", "");
1453   if (dn == NULL)
1454     return;
1455   GNUNET_DISK_directory_scan (dn, &deserialize_unindex_file, h);
1456   GNUNET_free (dn);
1457 }
1458
1459
1460
1461 /**
1462  * Function called with a filename of serialized search operation
1463  * to deserialize.
1464  *
1465  * @param cls the 'struct GNUNET_FS_Handle*'
1466  * @param filename complete filename (absolute path)
1467  * @return GNUNET_OK (continue to iterate)
1468  */
1469 static int
1470 deserialize_search_file (void *cls,
1471                           const char *filename)
1472 {
1473   /* FIXME */
1474   // Deserialize Search:
1475   // * for each query, read file with search results
1476   // * for each search result with active download, deserialize download
1477   // * for each directory search result, check for active downloads of contents
1478   return GNUNET_OK;
1479 }
1480
1481
1482 /**
1483  * Deserialize information about pending search operations.
1484  *
1485  * @param h master context
1486  */
1487 static void
1488 deserialize_search (struct GNUNET_FS_Handle *h)
1489 {
1490   char *dn;
1491
1492   dn = get_serialization_file_name (h, "search", "");
1493   if (dn == NULL)
1494     return;
1495   GNUNET_DISK_directory_scan (dn, &deserialize_search_file, h);
1496   GNUNET_free (dn);
1497 }
1498
1499
1500 /**
1501  * Setup a connection to the file-sharing service.
1502  *
1503  * @param sched scheduler to use
1504  * @param cfg configuration to use
1505  * @param client_name unique identifier for this client 
1506  * @param upcb function to call to notify about FS actions
1507  * @param upcb_cls closure for upcb
1508  * @param flags specific attributes for fs-operations
1509  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
1510  * @return NULL on error
1511  */
1512 struct GNUNET_FS_Handle *
1513 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
1514                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1515                  const char *client_name,
1516                  GNUNET_FS_ProgressCallback upcb,
1517                  void *upcb_cls,
1518                  enum GNUNET_FS_Flags flags,
1519                  ...)
1520 {
1521   struct GNUNET_FS_Handle *ret;
1522   struct GNUNET_CLIENT_Connection *client;
1523   enum GNUNET_FS_OPTIONS opt;
1524   va_list ap;
1525
1526   client = GNUNET_CLIENT_connect (sched,
1527                                   "fs",
1528                                   cfg);
1529   if (NULL == client)
1530     return NULL;
1531   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
1532   ret->sched = sched;
1533   ret->cfg = cfg;
1534   ret->client_name = GNUNET_strdup (client_name);
1535   ret->upcb = upcb;
1536   ret->upcb_cls = upcb_cls;
1537   ret->client = client;
1538   ret->flags = flags;
1539   ret->max_parallel_downloads = 1;
1540   ret->max_parallel_requests = 1;
1541   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
1542   va_start (ap, flags);  
1543   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
1544     {
1545       switch (opt)
1546         {
1547         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
1548           ret->max_parallel_downloads = va_arg (ap, unsigned int);
1549           break;
1550         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
1551           ret->max_parallel_requests = va_arg (ap, unsigned int);
1552           break;
1553         default:
1554           GNUNET_break (0);
1555           GNUNET_free (ret->client_name);
1556           GNUNET_free (ret);
1557           va_end (ap);
1558           return NULL;
1559         }
1560     }
1561   va_end (ap);
1562   // FIXME: setup receive-loop with client (do we need one?)
1563   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
1564     {
1565       /* FIXME: could write one generic deserialization
1566          function instead of these four... */
1567       deserialize_publish (ret);
1568       deserialize_search (ret);
1569       /* FIXME: deserialize downloads that are NOT part of searches */
1570       deserialize_unindex (ret);
1571     }
1572   return ret;
1573 }
1574
1575
1576 /**
1577  * Close our connection with the file-sharing service.
1578  * The callback given to GNUNET_FS_start will no longer be
1579  * called after this function returns.
1580  *
1581  * @param h handle that was returned from GNUNET_FS_start
1582  */                    
1583 void 
1584 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
1585 {
1586   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & h->flags))
1587     {
1588       // FIXME: generate SUSPEND events and clean up state!
1589     }
1590   // FIXME: terminate receive-loop with client  (do we need one?)
1591   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
1592     GNUNET_SCHEDULER_cancel (h->sched,
1593                              h->queue_job);
1594   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1595   GNUNET_free (h->client_name);
1596   GNUNET_free (h);
1597 }
1598
1599
1600 /* end of fs.c */