94777fb05926bb09a20f6942e99b6a624d6ab3ec
[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   GNUNET_free_non_null (ksks);
667   GNUNET_free_non_null (chks);
668   return ret;
669  cleanup:
670   GNUNET_free_non_null (ksks);
671   GNUNET_free_non_null (chks);
672   GNUNET_free_non_null (filename);
673   GNUNET_FS_file_information_destroy (ret, NULL, NULL);
674   return NULL;
675 }
676
677
678 /**
679  * Using the given serialization filename, try to deserialize
680  * the file-information tree associated with it.
681  *
682  * @param h master context
683  * @param filename name of the file (without directory) with
684  *        the infromation
685  * @return NULL on error
686  */
687 static struct GNUNET_FS_FileInformation *
688 deserialize_file_information (struct GNUNET_FS_Handle *h,
689                               const char *filename)
690 {
691   struct GNUNET_FS_FileInformation *ret;
692   struct GNUNET_BIO_ReadHandle *rh;
693   char *emsg;
694
695   rh = get_read_handle (h, "publish-fi", filename);
696   if (rh == NULL)
697     return NULL;
698   ret = deserialize_fi_node (h, filename, rh);
699   if (GNUNET_OK !=
700       GNUNET_BIO_read_close (rh, &emsg))
701     {
702       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
703                   _("Failed to resume publishing information `%s': %s\n"),
704                   filename,
705                   emsg);
706       GNUNET_free (emsg);
707     }
708   return ret;
709 }
710
711
712 /**
713  * Given a serialization name (full absolute path), return the
714  * basename of the file (without the path), which must only
715  * consist of the 6 random characters.
716  * 
717  * @param fullname name to extract the basename from
718  * @return copy of the basename, NULL on error
719  */
720 static char *
721 get_serialization_short_name (const char *fullname)
722 {
723   const char *end;
724   const char *nxt;
725
726   end = NULL;
727   nxt = fullname;
728   /* FIXME: we could do this faster since we know
729      the length of 'end'... */
730   while ('\0' != nxt)
731     {
732       if (DIR_SEPARATOR == *nxt)
733         end = nxt + 1;
734       nxt++;
735     }
736   if ( (end == NULL) ||
737        (strlen (end) == 0) )
738     {
739       GNUNET_break (0);
740       return NULL;
741     }
742   GNUNET_break (6 == strlen (end));
743   return GNUNET_strdup (end);  
744 }
745
746
747 /**
748  * Create a new random name for serialization.  Also checks if persistence
749  * is enabled and returns NULL if not.
750  *
751  * @param h master context
752  * @param ext component of the path 
753  * @return NULL on errror
754  */
755 static char *
756 make_serialization_file_name (struct GNUNET_FS_Handle *h,
757                               const char *ext)
758 {
759   char *fn;
760   char *dn;
761   char *ret;
762
763   if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE))
764     return NULL; /* persistence not requested */
765   dn = get_serialization_file_name (h, ext, "");
766   fn = GNUNET_DISK_mktemp (dn);
767   GNUNET_free (dn);
768   if (fn == NULL)
769     return NULL; /* epic fail */
770   ret = get_serialization_short_name (fn);
771   GNUNET_free (fn);
772   return ret;
773 }
774
775
776 /**
777  * Copy all of the data from the reader to the write handle.
778  *
779  * @param wh write handle
780  * @param fi file with reader
781  * @return GNUNET_OK on success
782  */
783 static int
784 copy_from_reader (struct GNUNET_BIO_WriteHandle *wh,
785                   struct GNUNET_FS_FileInformation * fi)
786 {
787   char buf[32 * 1024];
788   uint64_t off;
789   size_t ret;
790   char *emsg;
791
792   emsg = NULL;
793   off = 0;
794   while (off < fi->data.file.file_size)
795     {
796       ret = fi->data.file.reader (fi->data.file.reader_cls,
797                                   off, sizeof (buf),
798                                   buf,
799                                   &emsg);
800       if (ret == 0)
801         {
802           GNUNET_free (emsg);
803           return GNUNET_SYSERR;
804         }
805       if (GNUNET_OK != 
806           GNUNET_BIO_write (wh, buf, ret))
807         return GNUNET_SYSERR;
808       off += ret;
809     }
810   return GNUNET_OK;
811 }
812
813
814 /**
815  * Create a temporary file on disk to store the current
816  * state of "fi" in.
817  *
818  * @param fi file information to sync with disk
819  */
820 void
821 GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation * fi)
822 {
823   char *fn;
824   struct GNUNET_BIO_WriteHandle *wh;
825   char b;
826   char *ksks;
827   char *chks;
828
829   if (NULL == fi->serialization)    
830     fi->serialization = make_serialization_file_name (fi->h, "publish-fi");
831   if (NULL == fi->serialization)
832     return;
833   wh = get_write_handle (fi->h, "publish-fi", fi->serialization);
834   if (wh == NULL)
835     {
836       GNUNET_free (fi->serialization);
837       fi->serialization = NULL;
838       return;
839     }
840   if (GNUNET_YES == fi->is_directory)
841     b = 4;
842   else if (GNUNET_YES == fi->data.file.index_start_confirmed)
843     b = 3;
844   else if (GNUNET_YES == fi->data.file.have_hash)
845     b = 2;
846   else if (GNUNET_YES == fi->data.file.do_index)
847     b = 1;
848   else
849     b = 0;
850   if (fi->keywords != NULL)
851     ksks = GNUNET_FS_uri_to_string (fi->keywords);
852   else
853     ksks = NULL;
854   if (fi->chk_uri != NULL)
855     chks = GNUNET_FS_uri_to_string (fi->chk_uri);
856   else
857     chks = NULL;
858   if ( (GNUNET_OK !=
859         GNUNET_BIO_write (wh, &b, sizeof (b))) ||
860        (GNUNET_OK != 
861         GNUNET_BIO_write_meta_data (wh, fi->meta)) ||
862        (GNUNET_OK !=
863         GNUNET_BIO_write_string (wh, ksks)) ||
864        (GNUNET_OK !=
865         GNUNET_BIO_write_string (wh, chks)) ||
866        (GNUNET_OK != 
867         GNUNET_BIO_write_int64 (wh, fi->expirationTime.value)) ||
868        (GNUNET_OK != 
869         GNUNET_BIO_write_int64 (wh, fi->start_time.value)) ||
870        (GNUNET_OK !=
871         GNUNET_BIO_write_string (wh, fi->emsg)) ||
872        (GNUNET_OK !=
873         GNUNET_BIO_write_string (wh, fi->filename)) ||
874        (GNUNET_OK != 
875         GNUNET_BIO_write_int32 (wh, fi->anonymity)) ||
876        (GNUNET_OK != 
877         GNUNET_BIO_write_int32 (wh, fi->priority)) )
878     goto cleanup;
879   GNUNET_free_non_null (chks);
880   chks = NULL;
881   GNUNET_free_non_null (ksks);
882   ksks = NULL;
883   
884   switch (b)
885     {
886     case 0: /* file-insert */
887       if (GNUNET_OK !=
888           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
889         goto cleanup;
890       if ( (GNUNET_NO == fi->is_published) &&
891            (NULL == fi->filename) )     
892         if (GNUNET_OK != 
893             copy_from_reader (wh, fi))
894           goto cleanup;
895       break;
896     case 1: /* file-index, no hash */
897       if (NULL == fi->filename)
898         goto cleanup;
899       if (GNUNET_OK !=
900           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
901         goto cleanup;
902       break;
903     case 2: /* file-index-with-hash */
904     case 3: /* file-index-with-hash-confirmed */
905       if (NULL == fi->filename)
906         goto cleanup;
907       if ( (GNUNET_OK !=
908             GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) ||
909            (GNUNET_OK !=
910             GNUNET_BIO_write (wh, &fi->data.file.file_id, sizeof (GNUNET_HashCode))) )
911         goto cleanup;
912       break;
913     case 4: /* directory */
914       if ( (GNUNET_OK !=
915             GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) ||
916            (GNUNET_OK !=
917             GNUNET_BIO_write (wh, fi->data.dir.dir_data, (uint32_t) fi->data.dir.dir_size)) ||
918            (GNUNET_OK !=
919             GNUNET_BIO_write_string (wh, fi->data.dir.entries->serialization)) )
920         goto cleanup;
921       break;
922     default:
923       GNUNET_assert (0);
924       goto cleanup;
925     }
926   if (GNUNET_OK !=
927       GNUNET_BIO_write_string (wh, fi->next->serialization))
928     goto cleanup;  
929   if (GNUNET_OK ==
930       GNUNET_BIO_write_close (wh))
931     return; /* done! */
932  cleanup:
933   (void) GNUNET_BIO_write_close (wh);
934   GNUNET_free_non_null (chks);
935   GNUNET_free_non_null (ksks);
936   fn = get_serialization_file_name (fi->h, "publish-fi", fi->serialization);
937   if (0 != UNLINK (fn))
938     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
939   GNUNET_free (fn);
940   GNUNET_free (fi->serialization);
941   fi->serialization = NULL;  
942 }
943
944
945
946 /**
947  * Find the entry in the file information struct where the
948  * serialization filename matches the given name.
949  *
950  * @param pos file information to search
951  * @param srch filename to search for
952  * @return NULL if srch was not found in this subtree
953  */
954 static struct GNUNET_FS_FileInformation *
955 find_file_position (struct GNUNET_FS_FileInformation *pos,
956                     const char *srch)
957 {
958   struct GNUNET_FS_FileInformation *r;
959
960   while (pos != NULL)
961     {
962       if (0 == strcmp (srch,
963                        pos->serialization))
964         return pos;
965       if (pos->is_directory)
966         {
967           r = find_file_position (pos->data.dir.entries,
968                                   srch);
969           if (r != NULL)
970             return r;
971         }
972       pos = pos->next;
973     }
974   return NULL;
975 }
976
977
978 /**
979  * Signal the FS's progress function that we are resuming
980  * an upload.
981  *
982  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
983  * @param fi the entry in the publish-structure
984  * @param length length of the file or directory
985  * @param meta metadata for the file or directory (can be modified)
986  * @param uri pointer to the keywords that will be used for this entry (can be modified)
987  * @param anonymity pointer to selected anonymity level (can be modified)
988  * @param priority pointer to selected priority (can be modified)
989  * @param expirationTime pointer to selected expiration time (can be modified)
990  * @param client_info pointer to client context set upon creation (can be modified)
991  * @return GNUNET_OK to continue (always)
992  */
993 static int
994 fip_signal_resume(void *cls,
995                   struct GNUNET_FS_FileInformation *fi,
996                   uint64_t length,
997                   struct GNUNET_CONTAINER_MetaData *meta,
998                   struct GNUNET_FS_Uri **uri,
999                   uint32_t *anonymity,
1000                   uint32_t *priority,
1001                   struct GNUNET_TIME_Absolute *expirationTime,
1002                   void **client_info)
1003 {
1004   struct GNUNET_FS_PublishContext *sc = cls;
1005   struct GNUNET_FS_ProgressInfo pi;
1006
1007   pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME;
1008   pi.value.publish.specifics.resume.message = sc->fi->emsg;
1009   pi.value.publish.specifics.resume.chk_uri = sc->fi->chk_uri;
1010   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1011   return GNUNET_OK;
1012 }
1013
1014
1015 /**
1016  * Function called with a filename of serialized publishing operation
1017  * to deserialize.
1018  *
1019  * @param cls the 'struct GNUNET_FS_Handle*'
1020  * @param filename complete filename (absolute path)
1021  * @return GNUNET_OK (continue to iterate)
1022  */
1023 static int
1024 deserialize_publish_file (void *cls,
1025                           const char *filename)
1026 {
1027   struct GNUNET_FS_Handle *h = cls;
1028   struct GNUNET_BIO_ReadHandle *rh;
1029   struct GNUNET_FS_PublishContext *pc;
1030   int32_t options;
1031   int32_t all_done;
1032   char *fi_root;
1033   char *ns;
1034   char *fi_pos;
1035   char *emsg;
1036
1037   pc = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
1038   pc->h = h;
1039   pc->serialization = get_serialization_short_name (filename);
1040   fi_root = NULL;
1041   fi_pos = NULL;
1042   ns = NULL;
1043   rh = GNUNET_BIO_read_open (filename);
1044   if (rh == NULL)
1045     goto cleanup;
1046   if ( (GNUNET_OK !=
1047         GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) ||
1048        (GNUNET_OK !=
1049         GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) ||
1050        (GNUNET_OK !=
1051         GNUNET_BIO_read_int32 (rh, &options)) ||
1052        (GNUNET_OK !=
1053         GNUNET_BIO_read_int32 (rh, &all_done)) ||
1054        (GNUNET_OK !=
1055         GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) ||
1056        (GNUNET_OK !=
1057         GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) ||
1058        (GNUNET_OK !=
1059         GNUNET_BIO_read_string (rh, "publish-ns", &ns, 1024)) )
1060     goto cleanup;          
1061   pc->options = options;
1062   pc->all_done = all_done;
1063   pc->fi = deserialize_file_information (h, fi_root);
1064   if (pc->fi == NULL)
1065     goto cleanup;    
1066   if (ns != NULL)
1067     {
1068       pc->namespace = GNUNET_FS_namespace_create (h, ns);
1069       if (pc->namespace == NULL)
1070         {
1071           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1072                       _("Failed to recover namespace `%s', cannot resume publishing operation.\n"),
1073                       ns);
1074           goto cleanup;
1075         }
1076     }
1077   if (fi_pos != NULL)
1078     {
1079       pc->fi_pos = find_file_position (pc->fi,
1080                                        fi_pos);
1081       GNUNET_free (fi_pos);
1082       fi_pos = NULL;
1083       if (pc->fi_pos == NULL)
1084         {
1085           /* failed to find position for resuming, outch! Will start from root! */
1086           GNUNET_break (0);
1087           if (pc->all_done != GNUNET_YES)
1088             pc->fi_pos = pc->fi;
1089         }
1090     }
1091   /* generate RESUME event(s) */
1092   GNUNET_FS_file_information_inspect (pc->fi,
1093                                       &fip_signal_resume,
1094                                       pc);
1095   
1096   /* re-start publishing (if needed)... */
1097   if (pc->all_done != GNUNET_YES)
1098     pc->upload_task 
1099       = GNUNET_SCHEDULER_add_with_priority (h->sched,
1100                                             GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1101                                             &GNUNET_FS_publish_main_,
1102                                             pc);       
1103   if (GNUNET_OK !=
1104       GNUNET_BIO_read_close (rh, &emsg))
1105     {
1106       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1107                   _("Failure while resuming publishing operation `%s': %s\n"),
1108                   filename,
1109                   emsg);
1110       GNUNET_free (emsg);
1111     }
1112   GNUNET_free_non_null (ns);
1113   return GNUNET_OK;
1114  cleanup:
1115   GNUNET_free_non_null (pc->nid);
1116   GNUNET_free_non_null (pc->nuid);
1117   GNUNET_free_non_null (fi_root);
1118   GNUNET_free_non_null (fi_pos);
1119   GNUNET_free_non_null (ns);
1120   if ( (rh != NULL) &&
1121        (GNUNET_OK !=
1122         GNUNET_BIO_read_close (rh, &emsg)) )
1123     {
1124       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1125                   _("Failed to resume publishing operation `%s': %s\n"),
1126                   filename,
1127                   emsg);
1128       GNUNET_free (emsg);
1129     }
1130   if (pc->fi != NULL)
1131     GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
1132   if (pc->serialization != NULL)
1133     GNUNET_FS_remove_sync_file_ (h, "publish", pc->serialization);
1134   GNUNET_free_non_null (pc->serialization);
1135   GNUNET_free (pc);
1136   return GNUNET_OK;
1137 }
1138
1139
1140 /**
1141  * Synchronize this publishing struct with its mirror
1142  * on disk.  Note that all internal FS-operations that change
1143  * publishing structs should already call "sync" internally,
1144  * so this function is likely not useful for clients.
1145  * 
1146  * @param pc the struct to sync
1147  */
1148 void
1149 GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc)
1150 {  
1151   struct GNUNET_BIO_WriteHandle *wh;
1152
1153   if (NULL == pc->serialization)
1154     pc->serialization = make_serialization_file_name (pc->h,
1155                                                       "publish");
1156   if (NULL == pc->serialization)
1157     return;
1158   if (NULL == pc->fi)
1159     return;
1160   if (NULL == pc->fi->serialization)
1161     {
1162       GNUNET_break (0);
1163       return;
1164     }
1165   wh = get_write_handle (pc->h, "publish", pc->serialization);
1166   if ( (GNUNET_OK !=
1167         GNUNET_BIO_write_string (wh, pc->nid)) ||
1168        (GNUNET_OK !=
1169         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1170        (GNUNET_OK !=
1171         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1172        (GNUNET_OK !=
1173         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1174        (GNUNET_OK !=
1175         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1176        (GNUNET_OK !=
1177         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1178        (GNUNET_OK !=
1179         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1180    {
1181      (void) GNUNET_BIO_write_close (wh);
1182      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1183      GNUNET_free (pc->serialization);
1184      pc->serialization = NULL;
1185      return;
1186    }
1187  if (GNUNET_OK !=
1188      GNUNET_BIO_write_close (wh))
1189    {
1190      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1191      GNUNET_free (pc->serialization);
1192      pc->serialization = NULL;
1193      return;     
1194    }  
1195 }
1196
1197
1198 /**
1199  * Synchronize this unindex struct with its mirror
1200  * on disk.  Note that all internal FS-operations that change
1201  * publishing structs should already call "sync" internally,
1202  * so this function is likely not useful for clients.
1203  * 
1204  * @param uc the struct to sync
1205  */
1206 void
1207 GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc)
1208 {
1209   struct GNUNET_BIO_WriteHandle *wh;
1210
1211   if (UNINDEX_STATE_ABORTED == uc->state)
1212     return;
1213   if (NULL == uc->serialization)
1214     uc->serialization = make_serialization_file_name (uc->h,
1215                                                       "unindex");
1216   if (NULL == uc->serialization)
1217     return;
1218   wh = get_write_handle (uc->h, "unindex", uc->serialization);
1219   if ( (GNUNET_OK !=
1220         GNUNET_BIO_write_string (wh, uc->filename)) ||
1221        (GNUNET_OK !=
1222         GNUNET_BIO_write_int64 (wh, uc->file_size)) ||
1223        (GNUNET_OK !=
1224         GNUNET_BIO_write_int64 (wh, uc->start_time.value)) ||
1225        (GNUNET_OK !=
1226         GNUNET_BIO_write_int32 (wh, (uint32_t) uc->state)) ||
1227        ( (uc->state == UNINDEX_STATE_FS_NOTIFY) &&
1228          (GNUNET_OK !=
1229           GNUNET_BIO_write (wh, &uc->file_id, sizeof (GNUNET_HashCode))) ) ||
1230        ( (uc->state == UNINDEX_STATE_ERROR) &&
1231          (GNUNET_OK !=
1232           GNUNET_BIO_write_string (wh, uc->emsg)) ) )
1233     {
1234       (void) GNUNET_BIO_write_close (wh);
1235       GNUNET_FS_remove_sync_file_ (uc->h, "publish", uc->serialization);
1236       GNUNET_free (uc->serialization);
1237       uc->serialization = NULL;
1238       return;
1239     }
1240   if (GNUNET_OK !=
1241       GNUNET_BIO_write_close (wh))
1242     {
1243       GNUNET_FS_remove_sync_file_ (uc->h, "unindex", uc->serialization);
1244       GNUNET_free (uc->serialization);
1245       uc->serialization = NULL;
1246       return;     
1247     }  
1248 }
1249
1250
1251 /**
1252  * Synchronize this search struct with its mirror
1253  * on disk.  Note that all internal FS-operations that change
1254  * publishing structs should already call "sync" internally,
1255  * so this function is likely not useful for clients.
1256  * 
1257  * @param sc the struct to sync
1258  */
1259 void
1260 GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc)
1261 {  
1262   struct GNUNET_BIO_WriteHandle *wh;
1263
1264   if (NULL == sc->serialization)
1265     sc->serialization = make_serialization_file_name (sc->h,
1266                                                       "search");
1267   if (NULL == sc->serialization)
1268     return;
1269   wh = get_write_handle (sc->h, "search", sc->serialization);
1270 #if 0
1271   if ( (GNUNET_OK !=
1272         GNUNET_BIO_write_string (wh, pc->nid)) ||
1273        (GNUNET_OK !=
1274         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1275        (GNUNET_OK !=
1276         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1277        (GNUNET_OK !=
1278         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1279        (GNUNET_OK !=
1280         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1281        (GNUNET_OK !=
1282         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1283        (GNUNET_OK !=
1284         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1285    {
1286      (void) GNUNET_BIO_write_close (wh);
1287      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1288      GNUNET_free (pc->serialization);
1289      pc->serialization = NULL;
1290      return;
1291    }
1292 #endif
1293   /* FIXME: do search-specific deserialization here! */
1294   if (GNUNET_OK !=
1295       GNUNET_BIO_write_close (wh))
1296     {
1297       GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1298       GNUNET_free (sc->serialization);
1299       sc->serialization = NULL;
1300       return;     
1301     }  
1302 }
1303
1304
1305 /**
1306  * Deserialize information about pending publish operations.
1307  *
1308  * @param h master context
1309  */
1310 static void
1311 deserialize_publish (struct GNUNET_FS_Handle *h)
1312 {
1313   char *dn;
1314
1315   dn = get_serialization_file_name (h, "publish", "");
1316   if (dn == NULL)
1317     return;
1318   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1319   GNUNET_free (dn);
1320 }
1321
1322
1323
1324
1325 /**
1326  * Function called with a filename of serialized unindexing operation
1327  * to deserialize.
1328  *
1329  * @param cls the 'struct GNUNET_FS_Handle*'
1330  * @param filename complete filename (absolute path)
1331  * @return GNUNET_OK (continue to iterate)
1332  */
1333 static int
1334 deserialize_unindex_file (void *cls,
1335                           const char *filename)
1336 {
1337   struct GNUNET_FS_Handle *h = cls;
1338   struct GNUNET_BIO_ReadHandle *rh;
1339   struct GNUNET_FS_UnindexContext *uc;
1340   struct GNUNET_FS_ProgressInfo pi;
1341   char *emsg;
1342   uint32_t state;
1343
1344   uc = GNUNET_malloc (sizeof (struct GNUNET_FS_UnindexContext));
1345   uc->h = h;
1346   uc->serialization = get_serialization_short_name (filename);
1347   rh = GNUNET_BIO_read_open (filename);
1348   if (rh == NULL)
1349     goto cleanup;
1350   if ( (GNUNET_OK !=
1351         GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10*1024)) ||
1352        (GNUNET_OK !=
1353         GNUNET_BIO_read_int64 (rh, &uc->file_size)) ||
1354        (GNUNET_OK !=
1355         GNUNET_BIO_read_int64 (rh, &uc->start_time.value)) ||
1356        (GNUNET_OK !=
1357         GNUNET_BIO_read_int32 (rh, &state)) )
1358     goto cleanup;          
1359   uc->state = (enum UnindexState) state;
1360   switch (state)
1361     {
1362     case UNINDEX_STATE_HASHING:
1363       break;
1364     case UNINDEX_STATE_FS_NOTIFY:
1365       if (GNUNET_OK !=
1366           GNUNET_BIO_read (rh, "unindex-hash", &uc->file_id, sizeof (GNUNET_HashCode)))
1367         goto cleanup;
1368       break;
1369     case UNINDEX_STATE_DS_REMOVE:
1370       break;
1371     case UNINDEX_STATE_COMPLETE:
1372       break;
1373     case UNINDEX_STATE_ERROR:
1374       if (GNUNET_OK !=
1375           GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10*1024))
1376         goto cleanup;
1377       break;
1378     case UNINDEX_STATE_ABORTED:
1379       GNUNET_break (0);
1380       goto cleanup;
1381     default:
1382       GNUNET_break (0);
1383       goto cleanup;
1384     }
1385   pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME;
1386   pi.value.unindex.specifics.resume.message = uc->emsg;
1387   GNUNET_FS_unindex_make_status_ (&pi,
1388                                   uc,
1389                                   (uc->state == UNINDEX_STATE_COMPLETE) 
1390                                   ? uc->file_size
1391                                   : 0);
1392   switch (uc->state)
1393     {
1394     case UNINDEX_STATE_HASHING:
1395       GNUNET_CRYPTO_hash_file (uc->h->sched,
1396                                GNUNET_SCHEDULER_PRIORITY_IDLE,
1397                                uc->filename,
1398                                HASHING_BLOCKSIZE,
1399                                &GNUNET_FS_unindex_process_hash_,
1400                                uc);
1401       break;
1402     case UNINDEX_STATE_FS_NOTIFY:
1403       uc->state = UNINDEX_STATE_HASHING;
1404       GNUNET_FS_unindex_process_hash_ (uc,
1405                                        &uc->file_id);
1406       break;
1407     case UNINDEX_STATE_DS_REMOVE:
1408       GNUNET_FS_unindex_do_remove_ (uc);
1409       break;
1410     case UNINDEX_STATE_COMPLETE:
1411     case UNINDEX_STATE_ERROR:
1412       /* no need to resume any operation, we were done */
1413       break;
1414     default:
1415       break;
1416     }
1417   if (GNUNET_OK !=
1418       GNUNET_BIO_read_close (rh, &emsg))
1419     {
1420       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1421                   _("Failure while resuming unindexing operation `%s': %s\n"),
1422                   filename,
1423                   emsg);
1424       GNUNET_free (emsg);
1425     }
1426   return GNUNET_OK;
1427  cleanup:
1428   GNUNET_free_non_null (uc->filename);
1429   if ( (rh != NULL) &&
1430        (GNUNET_OK !=
1431         GNUNET_BIO_read_close (rh, &emsg)) )
1432     {
1433       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1434                   _("Failed to resume unindexing operation `%s': %s\n"),
1435                   filename,
1436                   emsg);
1437       GNUNET_free (emsg);
1438     }
1439   if (uc->serialization != NULL)
1440     GNUNET_FS_remove_sync_file_ (h, "unindex", uc->serialization);
1441   GNUNET_free_non_null (uc->serialization);
1442   GNUNET_free (uc);
1443   return GNUNET_OK;
1444 }
1445
1446
1447 /**
1448  * Deserialize information about pending publish operations.
1449  *
1450  * @param h master context
1451  */
1452 static void
1453 deserialize_unindex (struct GNUNET_FS_Handle *h)
1454 {
1455   char *dn;
1456
1457   dn = get_serialization_file_name (h, "unindex", "");
1458   if (dn == NULL)
1459     return;
1460   GNUNET_DISK_directory_scan (dn, &deserialize_unindex_file, h);
1461   GNUNET_free (dn);
1462 }
1463
1464
1465
1466 /**
1467  * Function called with a filename of serialized search operation
1468  * to deserialize.
1469  *
1470  * @param cls the 'struct GNUNET_FS_Handle*'
1471  * @param filename complete filename (absolute path)
1472  * @return GNUNET_OK (continue to iterate)
1473  */
1474 static int
1475 deserialize_search_file (void *cls,
1476                           const char *filename)
1477 {
1478   /* FIXME */
1479   // Deserialize Search:
1480   // * for each query, read file with search results
1481   // * for each search result with active download, deserialize download
1482   // * for each directory search result, check for active downloads of contents
1483   return GNUNET_OK;
1484 }
1485
1486
1487 /**
1488  * Deserialize information about pending search operations.
1489  *
1490  * @param h master context
1491  */
1492 static void
1493 deserialize_search (struct GNUNET_FS_Handle *h)
1494 {
1495   char *dn;
1496
1497   dn = get_serialization_file_name (h, "search", "");
1498   if (dn == NULL)
1499     return;
1500   GNUNET_DISK_directory_scan (dn, &deserialize_search_file, h);
1501   GNUNET_free (dn);
1502 }
1503
1504
1505 /**
1506  * Setup a connection to the file-sharing service.
1507  *
1508  * @param sched scheduler to use
1509  * @param cfg configuration to use
1510  * @param client_name unique identifier for this client 
1511  * @param upcb function to call to notify about FS actions
1512  * @param upcb_cls closure for upcb
1513  * @param flags specific attributes for fs-operations
1514  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
1515  * @return NULL on error
1516  */
1517 struct GNUNET_FS_Handle *
1518 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
1519                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1520                  const char *client_name,
1521                  GNUNET_FS_ProgressCallback upcb,
1522                  void *upcb_cls,
1523                  enum GNUNET_FS_Flags flags,
1524                  ...)
1525 {
1526   struct GNUNET_FS_Handle *ret;
1527   struct GNUNET_CLIENT_Connection *client;
1528   enum GNUNET_FS_OPTIONS opt;
1529   va_list ap;
1530
1531   client = GNUNET_CLIENT_connect (sched,
1532                                   "fs",
1533                                   cfg);
1534   if (NULL == client)
1535     return NULL;
1536   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
1537   ret->sched = sched;
1538   ret->cfg = cfg;
1539   ret->client_name = GNUNET_strdup (client_name);
1540   ret->upcb = upcb;
1541   ret->upcb_cls = upcb_cls;
1542   ret->client = client;
1543   ret->flags = flags;
1544   ret->max_parallel_downloads = 1;
1545   ret->max_parallel_requests = 1;
1546   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
1547   va_start (ap, flags);  
1548   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
1549     {
1550       switch (opt)
1551         {
1552         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
1553           ret->max_parallel_downloads = va_arg (ap, unsigned int);
1554           break;
1555         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
1556           ret->max_parallel_requests = va_arg (ap, unsigned int);
1557           break;
1558         default:
1559           GNUNET_break (0);
1560           GNUNET_free (ret->client_name);
1561           GNUNET_free (ret);
1562           va_end (ap);
1563           return NULL;
1564         }
1565     }
1566   va_end (ap);
1567   // FIXME: setup receive-loop with client (do we need one?)
1568   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
1569     {
1570       /* FIXME: could write one generic deserialization
1571          function instead of these four... */
1572       deserialize_publish (ret);
1573       deserialize_search (ret);
1574       /* FIXME: deserialize downloads that are NOT part of searches */
1575       deserialize_unindex (ret);
1576     }
1577   return ret;
1578 }
1579
1580
1581 /**
1582  * Close our connection with the file-sharing service.
1583  * The callback given to GNUNET_FS_start will no longer be
1584  * called after this function returns.
1585  *
1586  * @param h handle that was returned from GNUNET_FS_start
1587  */                    
1588 void 
1589 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
1590 {
1591   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & h->flags))
1592     {
1593       // FIXME: generate SUSPEND events and clean up state!
1594     }
1595   // FIXME: terminate receive-loop with client  (do we need one?)
1596   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
1597     GNUNET_SCHEDULER_cancel (h->sched,
1598                              h->queue_job);
1599   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1600   GNUNET_free (h->client_name);
1601   GNUNET_free (h);
1602 }
1603
1604
1605 /* end of fs.c */