5b8dc3e90cffb03096399f71a45be4a676cc7e60
[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       run_time = GNUNET_TIME_relative_multiply (h->avg_block_latency,
131                                                 qe->blocks * qe->start_times);
132       end_time = GNUNET_TIME_absolute_add (qe->start_time,
133                                            run_time);
134       rst = GNUNET_TIME_absolute_get_remaining (end_time);
135       restart_at = GNUNET_TIME_relative_min (rst, restart_at);
136       if (rst.value > 0)
137         continue;       
138       stop_job (qe);
139     }
140   h->queue_job = GNUNET_SCHEDULER_add_delayed (h->sched,
141                                                restart_at,
142                                                &process_job_queue,
143                                                h);
144 }
145
146
147 /**
148  * Add a job to the queue.
149  *
150  * @param h handle to the overall FS state
151  * @param start function to call to begin the job
152  * @param stop function to call to pause the job, or on dequeue (if the job was running)
153  * @param cls closure for start and stop
154  * @param blocks number of blocks this jobs uses
155  * @return queue handle
156  */
157 struct GNUNET_FS_QueueEntry *
158 GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h,
159                   GNUNET_FS_QueueStart start,
160                   GNUNET_FS_QueueStop stop,
161                   void *cls,
162                   unsigned int blocks)
163 {
164   struct GNUNET_FS_QueueEntry *qe;
165
166   qe = GNUNET_malloc (sizeof (struct GNUNET_FS_QueueEntry));
167   qe->h = h;
168   qe->start = start;
169   qe->stop = stop;
170   qe->cls = cls;
171   qe->queue_time = GNUNET_TIME_absolute_get ();
172   qe->blocks = blocks;
173   GNUNET_CONTAINER_DLL_insert_after (h->pending_head,
174                                      h->pending_tail,
175                                      h->pending_tail,
176                                      qe);
177   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
178     GNUNET_SCHEDULER_cancel (h->sched,
179                              h->queue_job);
180   h->queue_job 
181     = GNUNET_SCHEDULER_add_now (h->sched,
182                                 &process_job_queue,
183                                 h);
184   return qe;
185 }
186
187
188 /**
189  * Dequeue a job from the queue.
190  * @param qh handle for the job
191  */
192 void
193 GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qh)
194 {
195   struct GNUNET_FS_Handle *h;
196
197   h = qh->h;
198   if (qh->client != NULL)    
199     stop_job (qh);    
200   GNUNET_CONTAINER_DLL_remove (h->pending_head,
201                                h->pending_tail,
202                                qh);
203   GNUNET_free (qh);
204   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
205     GNUNET_SCHEDULER_cancel (h->sched,
206                              h->queue_job);
207   h->queue_job 
208     = GNUNET_SCHEDULER_add_now (h->sched,
209                                 &process_job_queue,
210                                 h);
211 }
212
213
214
215
216 /**
217  * Closure for "data_reader_file".
218  */
219 struct FileInfo
220 {
221   /**
222    * Name of the file to read.
223    */
224   char *filename;
225
226   /**
227    * File descriptor, NULL if it has not yet been opened.
228    */
229   struct GNUNET_DISK_FileHandle *fd;
230 };
231
232
233 /**
234  * Function that provides data by reading from a file.
235  *
236  * @param cls closure (points to the file information)
237  * @param offset offset to read from; it is possible
238  *            that the caller might need to go backwards
239  *            a bit at times
240  * @param max maximum number of bytes that should be 
241  *            copied to buf; readers are not allowed
242  *            to provide less data unless there is an error;
243  *            a value of "0" will be used at the end to allow
244  *            the reader to clean up its internal state
245  * @param buf where the reader should write the data
246  * @param emsg location for the reader to store an error message
247  * @return number of bytes written, usually "max", 0 on error
248  */
249 size_t
250 GNUNET_FS_data_reader_file_(void *cls, 
251                             uint64_t offset,
252                             size_t max, 
253                             void *buf,
254                             char **emsg)
255 {
256   struct FileInfo *fi = cls;
257   ssize_t ret;
258
259   if (max == 0)
260     {
261       if (fi->fd != NULL)
262         GNUNET_DISK_file_close (fi->fd);
263       GNUNET_free (fi->filename);
264       GNUNET_free (fi);
265       return 0;
266     }  
267   if (fi->fd == NULL)
268     {
269       fi->fd = GNUNET_DISK_file_open (fi->filename,
270                                       GNUNET_DISK_OPEN_READ,
271                                       GNUNET_DISK_PERM_NONE);
272       if (fi->fd == NULL)
273         {
274           GNUNET_asprintf (emsg, 
275                            _("Could not open file `%s': %s"),
276                            fi->filename,
277                            STRERROR (errno));
278           return 0;
279         }
280     }
281   GNUNET_DISK_file_seek (fi->fd, offset, GNUNET_DISK_SEEK_SET);
282   ret = GNUNET_DISK_file_read (fi->fd, buf, max);
283   if (ret == -1)
284     {
285       GNUNET_asprintf (emsg, 
286                        _("Could not read file `%s': %s"),
287                        fi->filename,
288                        STRERROR (errno));
289       return 0;
290     }
291   if (ret != max)
292     {
293       GNUNET_asprintf (emsg, 
294                        _("Short read reading from file `%s'!"),
295                        fi->filename);
296       return 0;
297     }
298   return max;
299 }
300
301
302 /**
303  * Create the closure for the 'GNUNET_FS_data_reader_file_' callback.
304  *
305  * @param filename file to read
306  * @return closure to use, NULL on error
307  */
308 void *
309 GNUNET_FS_make_file_reader_context_ (const char *filename)
310 {
311   struct FileInfo *fi;
312
313   fi = GNUNET_malloc (sizeof(struct FileInfo));
314   fi->filename = GNUNET_STRINGS_filename_expand (filename);
315   if (fi->filename == NULL)
316     {
317       GNUNET_free (fi);
318       return NULL;
319     }
320   return fi;
321 }
322
323
324 /**
325  * Function that provides data by copying from a buffer.
326  *
327  * @param cls closure (points to the buffer)
328  * @param offset offset to read from; it is possible
329  *            that the caller might need to go backwards
330  *            a bit at times
331  * @param max maximum number of bytes that should be 
332  *            copied to buf; readers are not allowed
333  *            to provide less data unless there is an error;
334  *            a value of "0" will be used at the end to allow
335  *            the reader to clean up its internal state
336  * @param buf where the reader should write the data
337  * @param emsg location for the reader to store an error message
338  * @return number of bytes written, usually "max", 0 on error
339  */
340 size_t
341 GNUNET_FS_data_reader_copy_ (void *cls, 
342                              uint64_t offset,
343                              size_t max, 
344                              void *buf,
345                              char **emsg)
346 {
347   char *data = cls;
348
349   if (max == 0)
350     {
351       GNUNET_free_non_null (data);
352       return 0;
353     }  
354   memcpy (buf, &data[offset], max);
355   return max;
356 }
357
358
359
360 /**
361  * Return the full filename where we would store state information
362  * (for serialization/deserialization).
363  *
364  * @param h master context
365  * @param ext component of the path 
366  * @param ent entity identifier (or emtpy string for the directory)
367  * @return NULL on error
368  */
369 static char *
370 get_serialization_file_name (struct GNUNET_FS_Handle *h,
371                              const char *ext,
372                              const char *ent)
373 {
374   char *basename;
375   char *ret;
376   if (GNUNET_OK !=
377       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
378                                                "fs",
379                                                "STATE_DIR",
380                                                &basename))
381     return NULL;
382   GNUNET_asprintf (&ret,
383                    "%s%s%s-%s%s%s",
384                    basename,
385                    DIR_SEPARATOR_STR,
386                    h->client_name,
387                    ext,
388                    DIR_SEPARATOR_STR,
389                    ent);
390   GNUNET_free (basename);
391   return ret;
392 }
393
394
395 /**
396  * Return a read handle for deserialization.
397  *
398  * @param h master context
399  * @param ext component of the path 
400  * @param ent entity identifier (or emtpy string for the directory)
401  * @return NULL on error
402  */
403 static struct GNUNET_BIO_ReadHandle *
404 get_read_handle (struct GNUNET_FS_Handle *h,
405                  const char *ext,
406                  const char *ent)
407 {
408   char *fn;
409   struct GNUNET_BIO_ReadHandle *ret;
410
411   fn = get_serialization_file_name (h, ext, ent);
412   if (fn == NULL)
413     return NULL;
414   ret = GNUNET_BIO_read_open (fn);
415   GNUNET_free (fn);
416   return ret;
417 }
418
419
420 /**
421  * Return a write handle for serialization.
422  *
423  * @param h master context
424  * @param ext component of the path 
425  * @param ent entity identifier (or emtpy string for the directory)
426  * @return NULL on error
427  */
428 static struct GNUNET_BIO_WriteHandle *
429 get_write_handle (struct GNUNET_FS_Handle *h,
430                  const char *ext,
431                  const char *ent)
432 {
433   char *fn;
434   struct GNUNET_BIO_WriteHandle *ret;
435
436   fn = get_serialization_file_name (h, ext, ent);
437   if (fn == NULL)
438     return NULL;
439   ret = GNUNET_BIO_write_open (fn);
440   GNUNET_free (fn);
441   return ret;
442 }
443
444
445 /**
446  * Remove serialization/deserialization file from disk.
447  *
448  * @param h master context
449  * @param ext component of the path 
450  * @param ent entity identifier 
451  */
452 void
453 GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h,
454                              const char *ext,
455                              const char *ent)
456 {
457   char *filename;
458
459   if ( (NULL == ent) ||
460        (0 == strlen (ent)) )
461     {
462       GNUNET_break (0);
463       return;
464     }
465   filename = get_serialization_file_name (h, ext, ent);
466   if (0 != UNLINK (filename))
467     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
468                               "unlink", 
469                               filename);
470   GNUNET_free (filename);
471 }
472
473
474
475 /**
476  * Using the given serialization filename, try to deserialize
477  * the file-information tree associated with it.
478  *
479  * @param h master context
480  * @param filename name of the file (without directory) with
481  *        the infromation
482  * @return NULL on error
483  */
484 static struct GNUNET_FS_FileInformation *
485 deserialize_file_information (struct GNUNET_FS_Handle *h,
486                               const char *filename);
487
488
489 /**
490  * Using the given serialization filename, try to deserialize
491  * the file-information tree associated with it.
492  *
493  * @param h master context
494  * @param fn name of the file (without directory) with
495  *        the infromation
496  * @param rh handle for reading
497  * @return NULL on error
498  */
499 static struct GNUNET_FS_FileInformation *
500 deserialize_fi_node (struct GNUNET_FS_Handle *h,
501                      const char *fn,
502                      struct GNUNET_BIO_ReadHandle *rh)
503 {
504   struct GNUNET_FS_FileInformation *ret;
505   struct GNUNET_FS_FileInformation *nxt;
506   char b;
507   char *ksks;
508   char *chks;
509   char *filename;
510   uint32_t dsize;
511
512   if (GNUNET_OK !=
513       GNUNET_BIO_read (rh, "status flag", &b, sizeof(b)))
514     {
515       GNUNET_break (0);
516       return NULL;
517     }
518   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
519   ksks = NULL;
520   chks = NULL;
521   filename = NULL;
522   if ( (GNUNET_OK !=
523         GNUNET_BIO_read_meta_data (rh, "metadata", &ret->meta)) ||
524        (GNUNET_OK !=
525         GNUNET_BIO_read_string (rh, "ksk-uri", &ksks, 32*1024)) ||
526        ( (ksks != NULL) &&
527          (NULL == 
528           (ret->keywords = GNUNET_FS_uri_parse (ksks, NULL))) ) ||
529        (GNUNET_YES !=
530         GNUNET_FS_uri_test_ksk (ret->keywords)) ||
531        (GNUNET_OK !=
532         GNUNET_BIO_read_string (rh, "chk-uri", &chks, 1024)) ||
533        ( (chks != NULL) &&
534          ( (NULL == 
535             (ret->chk_uri = GNUNET_FS_uri_parse (chks, NULL))) ||
536            (GNUNET_YES !=
537             GNUNET_FS_uri_test_chk (ret->chk_uri)) ) ) ||
538        (GNUNET_OK !=
539         GNUNET_BIO_read_int64 (rh, &ret->expirationTime.value)) ||
540        (GNUNET_OK !=
541         GNUNET_BIO_read_int64 (rh, &ret->start_time.value)) ||
542        (GNUNET_OK !=
543         GNUNET_BIO_read_string (rh, "emsg", &ret->emsg, 16*1024)) ||
544        (GNUNET_OK !=
545         GNUNET_BIO_read_string (rh, "fn", &ret->filename, 16*1024)) ||
546        (GNUNET_OK !=
547         GNUNET_BIO_read_int32 (rh, &ret->anonymity)) ||
548        (GNUNET_OK !=
549         GNUNET_BIO_read_int32 (rh, &ret->priority)) )
550     goto cleanup;
551   switch (b)
552     {
553     case 0: /* file-insert */
554       if (GNUNET_OK !=
555           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
556         goto cleanup;
557       ret->is_directory = GNUNET_NO;
558       ret->data.file.do_index = GNUNET_NO;
559       ret->data.file.have_hash = GNUNET_NO;
560       ret->data.file.index_start_confirmed = GNUNET_NO;
561       if (GNUNET_NO == ret->is_published) 
562         {
563           if (NULL == ret->filename)
564             {
565               ret->data.file.reader = &GNUNET_FS_data_reader_copy_;
566               ret->data.file.reader_cls = GNUNET_malloc_large (ret->data.file.file_size);
567               if (ret->data.file.reader_cls == NULL)
568                 goto cleanup;
569               if (GNUNET_OK !=
570                   GNUNET_BIO_read (rh, "file-data", ret->data.file.reader_cls, ret->data.file.file_size))
571                 goto cleanup;
572             }      
573           else
574             {
575               ret->data.file.reader = &GNUNET_FS_data_reader_file_;
576               ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
577             }
578         }
579       break;
580     case 1: /* file-index, no hash */
581       if (NULL == ret->filename)
582         goto cleanup;
583       if (GNUNET_OK !=
584           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
585         goto cleanup;
586       ret->is_directory = GNUNET_NO;
587       ret->data.file.do_index = GNUNET_YES;
588       ret->data.file.have_hash = GNUNET_NO;
589       ret->data.file.index_start_confirmed = GNUNET_NO;
590       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
591       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
592       break;
593     case 2: /* file-index-with-hash */
594       if (NULL == ret->filename)
595         goto cleanup;
596       if ( (GNUNET_OK !=
597             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
598            (GNUNET_OK !=
599             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
600         goto cleanup;
601       ret->is_directory = GNUNET_NO;
602       ret->data.file.do_index = GNUNET_YES;
603       ret->data.file.have_hash = GNUNET_YES;
604       ret->data.file.index_start_confirmed = GNUNET_NO;
605       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
606       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
607       break;
608     case 3: /* file-index-with-hash-confirmed */
609       if (NULL == ret->filename)
610         goto cleanup;
611       if ( (GNUNET_OK !=
612             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
613            (GNUNET_OK !=
614             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
615         goto cleanup;
616
617       ret->is_directory = GNUNET_NO;
618       ret->data.file.do_index = GNUNET_YES;
619       ret->data.file.have_hash = GNUNET_YES;
620       ret->data.file.index_start_confirmed = GNUNET_YES;
621       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
622       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
623       break;
624     case 4: /* directory */
625       if ( (GNUNET_OK !=
626             GNUNET_BIO_read_int32 (rh, &dsize)) ||
627            (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large (dsize))) ||
628            (GNUNET_OK !=
629             GNUNET_BIO_read (rh, "dir-data", ret->data.dir.dir_data, dsize)) ||
630            (GNUNET_OK !=
631             GNUNET_BIO_read_string (rh, "ent-filename", &filename, 16*1024)) )
632         goto cleanup;
633       ret->data.dir.dir_size = (uint32_t) dsize;
634       ret->is_directory = GNUNET_YES;
635       if (filename != NULL)
636         {
637           ret->data.dir.entries = deserialize_file_information (h, filename);
638           GNUNET_free (filename);
639           filename = NULL;
640           nxt = ret->data.dir.entries;
641           while (nxt != NULL)
642             {
643               nxt->dir = ret;
644               nxt = nxt->next;
645             }  
646         }
647       break;
648     default:
649       GNUNET_break (0);
650       goto cleanup;
651     }
652   /* FIXME: adjust ret->start_time! */
653   ret->serialization = GNUNET_strdup (fn);
654   if (GNUNET_OK !=
655       GNUNET_BIO_read_string (rh, "nxt-filename", &filename, 16*1024))
656     goto cleanup;  
657   if (filename != NULL)
658     {
659       ret->next = deserialize_file_information (h, filename);
660       GNUNET_free (filename);
661       filename = NULL;
662     }
663   GNUNET_free_non_null (ksks);
664   GNUNET_free_non_null (chks);
665   return ret;
666  cleanup:
667   GNUNET_free_non_null (ksks);
668   GNUNET_free_non_null (chks);
669   GNUNET_free_non_null (filename);
670   GNUNET_FS_file_information_destroy (ret, NULL, NULL);
671   return NULL;
672 }
673
674
675 /**
676  * Using the given serialization filename, try to deserialize
677  * the file-information tree associated with it.
678  *
679  * @param h master context
680  * @param filename name of the file (without directory) with
681  *        the infromation
682  * @return NULL on error
683  */
684 static struct GNUNET_FS_FileInformation *
685 deserialize_file_information (struct GNUNET_FS_Handle *h,
686                               const char *filename)
687 {
688   struct GNUNET_FS_FileInformation *ret;
689   struct GNUNET_BIO_ReadHandle *rh;
690   char *emsg;
691
692   rh = get_read_handle (h, "publish-fi", filename);
693   if (rh == NULL)
694     return NULL;
695   ret = deserialize_fi_node (h, filename, rh);
696   if (GNUNET_OK !=
697       GNUNET_BIO_read_close (rh, &emsg))
698     {
699       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
700                   _("Failed to resume publishing information `%s': %s\n"),
701                   filename,
702                   emsg);
703       GNUNET_free (emsg);
704     }
705   return ret;
706 }
707
708
709 /**
710  * Given a serialization name (full absolute path), return the
711  * basename of the file (without the path), which must only
712  * consist of the 6 random characters.
713  * 
714  * @param fullname name to extract the basename from
715  * @return copy of the basename, NULL on error
716  */
717 static char *
718 get_serialization_short_name (const char *fullname)
719 {
720   const char *end;
721   const char *nxt;
722
723   end = NULL;
724   nxt = fullname;
725   /* FIXME: we could do this faster since we know
726      the length of 'end'... */
727   while ('\0' != nxt)
728     {
729       if (DIR_SEPARATOR == *nxt)
730         end = nxt + 1;
731       nxt++;
732     }
733   if ( (end == NULL) ||
734        (strlen (end) == 0) )
735     {
736       GNUNET_break (0);
737       return NULL;
738     }
739   GNUNET_break (6 == strlen (end));
740   return GNUNET_strdup (end);  
741 }
742
743
744 /**
745  * Create a new random name for serialization.  Also checks if persistence
746  * is enabled and returns NULL if not.
747  *
748  * @param h master context
749  * @param ext component of the path 
750  * @return NULL on errror
751  */
752 static char *
753 make_serialization_file_name (struct GNUNET_FS_Handle *h,
754                               const char *ext)
755 {
756   char *fn;
757   char *dn;
758   char *ret;
759
760   if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE))
761     return NULL; /* persistence not requested */
762   dn = get_serialization_file_name (h, ext, "");
763   fn = GNUNET_DISK_mktemp (dn);
764   GNUNET_free (dn);
765   if (fn == NULL)
766     return NULL; /* epic fail */
767   ret = get_serialization_short_name (fn);
768   GNUNET_free (fn);
769   return ret;
770 }
771
772
773 /**
774  * Copy all of the data from the reader to the write handle.
775  *
776  * @param wh write handle
777  * @param fi file with reader
778  * @return GNUNET_OK on success
779  */
780 static int
781 copy_from_reader (struct GNUNET_BIO_WriteHandle *wh,
782                   struct GNUNET_FS_FileInformation * fi)
783 {
784   char buf[32 * 1024];
785   uint64_t off;
786   size_t ret;
787   char *emsg;
788
789   emsg = NULL;
790   off = 0;
791   while (off < fi->data.file.file_size)
792     {
793       ret = fi->data.file.reader (fi->data.file.reader_cls,
794                                   off, sizeof (buf),
795                                   buf,
796                                   &emsg);
797       if (ret == 0)
798         {
799           GNUNET_free (emsg);
800           return GNUNET_SYSERR;
801         }
802       if (GNUNET_OK != 
803           GNUNET_BIO_write (wh, buf, ret))
804         return GNUNET_SYSERR;
805       off += ret;
806     }
807   return GNUNET_OK;
808 }
809
810
811 /**
812  * Create a temporary file on disk to store the current
813  * state of "fi" in.
814  *
815  * @param fi file information to sync with disk
816  */
817 void
818 GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation * fi)
819 {
820   char *fn;
821   struct GNUNET_BIO_WriteHandle *wh;
822   char b;
823   char *ksks;
824   char *chks;
825
826   if (NULL == fi->serialization)    
827     fi->serialization = make_serialization_file_name (fi->h, "publish-fi");
828   if (NULL == fi->serialization)
829     return;
830   wh = get_write_handle (fi->h, "publish-fi", fi->serialization);
831   if (wh == NULL)
832     {
833       GNUNET_free (fi->serialization);
834       fi->serialization = NULL;
835       return;
836     }
837   if (GNUNET_YES == fi->is_directory)
838     b = 4;
839   else if (GNUNET_YES == fi->data.file.index_start_confirmed)
840     b = 3;
841   else if (GNUNET_YES == fi->data.file.have_hash)
842     b = 2;
843   else if (GNUNET_YES == fi->data.file.do_index)
844     b = 1;
845   else
846     b = 0;
847   if (fi->keywords != NULL)
848     ksks = GNUNET_FS_uri_to_string (fi->keywords);
849   else
850     ksks = NULL;
851   if (fi->chk_uri != NULL)
852     chks = GNUNET_FS_uri_to_string (fi->chk_uri);
853   else
854     chks = NULL;
855   if ( (GNUNET_OK !=
856         GNUNET_BIO_write (wh, &b, sizeof (b))) ||
857        (GNUNET_OK != 
858         GNUNET_BIO_write_meta_data (wh, fi->meta)) ||
859        (GNUNET_OK !=
860         GNUNET_BIO_write_string (wh, ksks)) ||
861        (GNUNET_OK !=
862         GNUNET_BIO_write_string (wh, chks)) ||
863        (GNUNET_OK != 
864         GNUNET_BIO_write_int64 (wh, fi->expirationTime.value)) ||
865        (GNUNET_OK != 
866         GNUNET_BIO_write_int64 (wh, fi->start_time.value)) ||
867        (GNUNET_OK !=
868         GNUNET_BIO_write_string (wh, fi->emsg)) ||
869        (GNUNET_OK !=
870         GNUNET_BIO_write_string (wh, fi->filename)) ||
871        (GNUNET_OK != 
872         GNUNET_BIO_write_int32 (wh, fi->anonymity)) ||
873        (GNUNET_OK != 
874         GNUNET_BIO_write_int32 (wh, fi->priority)) )
875     goto cleanup;
876   GNUNET_free_non_null (chks);
877   chks = NULL;
878   GNUNET_free_non_null (ksks);
879   ksks = NULL;
880   
881   switch (b)
882     {
883     case 0: /* file-insert */
884       if (GNUNET_OK !=
885           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
886         goto cleanup;
887       if ( (GNUNET_NO == fi->is_published) &&
888            (NULL == fi->filename) )     
889         if (GNUNET_OK != 
890             copy_from_reader (wh, fi))
891           goto cleanup;
892       break;
893     case 1: /* file-index, no hash */
894       if (NULL == fi->filename)
895         goto cleanup;
896       if (GNUNET_OK !=
897           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
898         goto cleanup;
899       break;
900     case 2: /* file-index-with-hash */
901     case 3: /* file-index-with-hash-confirmed */
902       if (NULL == fi->filename)
903         goto cleanup;
904       if ( (GNUNET_OK !=
905             GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) ||
906            (GNUNET_OK !=
907             GNUNET_BIO_write (wh, &fi->data.file.file_id, sizeof (GNUNET_HashCode))) )
908         goto cleanup;
909       break;
910     case 4: /* directory */
911       if ( (GNUNET_OK !=
912             GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) ||
913            (GNUNET_OK !=
914             GNUNET_BIO_write (wh, fi->data.dir.dir_data, (uint32_t) fi->data.dir.dir_size)) ||
915            (GNUNET_OK !=
916             GNUNET_BIO_write_string (wh, fi->data.dir.entries->serialization)) )
917         goto cleanup;
918       break;
919     default:
920       GNUNET_assert (0);
921       goto cleanup;
922     }
923   if (GNUNET_OK !=
924       GNUNET_BIO_write_string (wh, fi->next->serialization))
925     goto cleanup;  
926   if (GNUNET_OK ==
927       GNUNET_BIO_write_close (wh))
928     return; /* done! */
929  cleanup:
930   (void) GNUNET_BIO_write_close (wh);
931   GNUNET_free_non_null (chks);
932   GNUNET_free_non_null (ksks);
933   fn = get_serialization_file_name (fi->h, "publish-fi", fi->serialization);
934   if (0 != UNLINK (fn))
935     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
936   GNUNET_free (fn);
937   GNUNET_free (fi->serialization);
938   fi->serialization = NULL;  
939 }
940
941
942
943 /**
944  * Find the entry in the file information struct where the
945  * serialization filename matches the given name.
946  *
947  * @param pos file information to search
948  * @param srch filename to search for
949  * @return NULL if srch was not found in this subtree
950  */
951 static struct GNUNET_FS_FileInformation *
952 find_file_position (struct GNUNET_FS_FileInformation *pos,
953                     const char *srch)
954 {
955   struct GNUNET_FS_FileInformation *r;
956
957   while (pos != NULL)
958     {
959       if (0 == strcmp (srch,
960                        pos->serialization))
961         return pos;
962       if (pos->is_directory)
963         {
964           r = find_file_position (pos->data.dir.entries,
965                                   srch);
966           if (r != NULL)
967             return r;
968         }
969       pos = pos->next;
970     }
971   return NULL;
972 }
973
974
975 /**
976  * Signal the FS's progress function that we are resuming
977  * an upload.
978  *
979  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
980  * @param fi the entry in the publish-structure
981  * @param length length of the file or directory
982  * @param meta metadata for the file or directory (can be modified)
983  * @param uri pointer to the keywords that will be used for this entry (can be modified)
984  * @param anonymity pointer to selected anonymity level (can be modified)
985  * @param priority pointer to selected priority (can be modified)
986  * @param expirationTime pointer to selected expiration time (can be modified)
987  * @param client_info pointer to client context set upon creation (can be modified)
988  * @return GNUNET_OK to continue (always)
989  */
990 static int
991 fip_signal_resume(void *cls,
992                   struct GNUNET_FS_FileInformation *fi,
993                   uint64_t length,
994                   struct GNUNET_CONTAINER_MetaData *meta,
995                   struct GNUNET_FS_Uri **uri,
996                   uint32_t *anonymity,
997                   uint32_t *priority,
998                   struct GNUNET_TIME_Absolute *expirationTime,
999                   void **client_info)
1000 {
1001   struct GNUNET_FS_PublishContext *sc = cls;
1002   struct GNUNET_FS_ProgressInfo pi;
1003
1004   pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME;
1005   pi.value.publish.specifics.resume.message = sc->fi->emsg;
1006   pi.value.publish.specifics.resume.chk_uri = sc->fi->chk_uri;
1007   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1008   return GNUNET_OK;
1009 }
1010
1011
1012 /**
1013  * Function called with a filename of serialized publishing operation
1014  * to deserialize.
1015  *
1016  * @param cls the 'struct GNUNET_FS_Handle*'
1017  * @param filename complete filename (absolute path)
1018  * @return GNUNET_OK (continue to iterate)
1019  */
1020 static int
1021 deserialize_publish_file (void *cls,
1022                           const char *filename)
1023 {
1024   struct GNUNET_FS_Handle *h = cls;
1025   struct GNUNET_BIO_ReadHandle *rh;
1026   struct GNUNET_FS_PublishContext *pc;
1027   int32_t options;
1028   int32_t all_done;
1029   char *fi_root;
1030   char *ns;
1031   char *fi_pos;
1032   char *emsg;
1033
1034   pc = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
1035   pc->h = h;
1036   pc->serialization = get_serialization_short_name (filename);
1037   fi_root = NULL;
1038   fi_pos = NULL;
1039   ns = NULL;
1040   rh = GNUNET_BIO_read_open (filename);
1041   if (rh == NULL)
1042     goto cleanup;
1043   if ( (GNUNET_OK !=
1044         GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) ||
1045        (GNUNET_OK !=
1046         GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) ||
1047        (GNUNET_OK !=
1048         GNUNET_BIO_read_int32 (rh, &options)) ||
1049        (GNUNET_OK !=
1050         GNUNET_BIO_read_int32 (rh, &all_done)) ||
1051        (GNUNET_OK !=
1052         GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) ||
1053        (GNUNET_OK !=
1054         GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) ||
1055        (GNUNET_OK !=
1056         GNUNET_BIO_read_string (rh, "publish-ns", &ns, 1024)) )
1057     goto cleanup;          
1058   pc->options = options;
1059   pc->all_done = all_done;
1060   pc->fi = deserialize_file_information (h, fi_root);
1061   if (pc->fi == NULL)
1062     goto cleanup;    
1063   if (ns != NULL)
1064     {
1065       pc->namespace = GNUNET_FS_namespace_create (h, ns);
1066       if (pc->namespace == NULL)
1067         {
1068           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1069                       _("Failed to recover namespace `%s', cannot resume publishing operation.\n"),
1070                       ns);
1071           goto cleanup;
1072         }
1073     }
1074   if (fi_pos != NULL)
1075     {
1076       pc->fi_pos = find_file_position (pc->fi,
1077                                        fi_pos);
1078       GNUNET_free (fi_pos);
1079       fi_pos = NULL;
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   GNUNET_free_non_null (ns);
1110   return GNUNET_OK;
1111  cleanup:
1112   GNUNET_free_non_null (pc->nid);
1113   GNUNET_free_non_null (pc->nuid);
1114   GNUNET_free_non_null (fi_root);
1115   GNUNET_free_non_null (fi_pos);
1116   GNUNET_free_non_null (ns);
1117   if ( (rh != NULL) &&
1118        (GNUNET_OK !=
1119         GNUNET_BIO_read_close (rh, &emsg)) )
1120     {
1121       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1122                   _("Failed to resume publishing operation `%s': %s\n"),
1123                   filename,
1124                   emsg);
1125       GNUNET_free (emsg);
1126     }
1127   if (pc->fi != NULL)
1128     GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
1129   if (pc->serialization != NULL)
1130     GNUNET_FS_remove_sync_file_ (h, "publish", pc->serialization);
1131   GNUNET_free_non_null (pc->serialization);
1132   GNUNET_free (pc);
1133   return GNUNET_OK;
1134 }
1135
1136
1137 /**
1138  * Synchronize this publishing struct with its mirror
1139  * on disk.  Note that all internal FS-operations that change
1140  * publishing structs should already call "sync" internally,
1141  * so this function is likely not useful for clients.
1142  * 
1143  * @param pc the struct to sync
1144  */
1145 void
1146 GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc)
1147 {  
1148   struct GNUNET_BIO_WriteHandle *wh;
1149
1150   if (NULL == pc->serialization)
1151     pc->serialization = make_serialization_file_name (pc->h,
1152                                                       "publish");
1153   if (NULL == pc->serialization)
1154     return;
1155   if (NULL == pc->fi)
1156     return;
1157   if (NULL == pc->fi->serialization)
1158     {
1159       GNUNET_break (0);
1160       return;
1161     }
1162   wh = get_write_handle (pc->h, "publish", pc->serialization);
1163   if ( (GNUNET_OK !=
1164         GNUNET_BIO_write_string (wh, pc->nid)) ||
1165        (GNUNET_OK !=
1166         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1167        (GNUNET_OK !=
1168         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1169        (GNUNET_OK !=
1170         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1171        (GNUNET_OK !=
1172         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1173        (GNUNET_OK !=
1174         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1175        (GNUNET_OK !=
1176         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1177    {
1178      (void) GNUNET_BIO_write_close (wh);
1179      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1180      GNUNET_free (pc->serialization);
1181      pc->serialization = NULL;
1182      return;
1183    }
1184  if (GNUNET_OK !=
1185      GNUNET_BIO_write_close (wh))
1186    {
1187      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1188      GNUNET_free (pc->serialization);
1189      pc->serialization = NULL;
1190      return;     
1191    }  
1192 }
1193
1194
1195 /**
1196  * Synchronize this unindex struct with its mirror
1197  * on disk.  Note that all internal FS-operations that change
1198  * publishing structs should already call "sync" internally,
1199  * so this function is likely not useful for clients.
1200  * 
1201  * @param uc the struct to sync
1202  */
1203 void
1204 GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc)
1205 {
1206   struct GNUNET_BIO_WriteHandle *wh;
1207
1208   if (UNINDEX_STATE_ABORTED == uc->state)
1209     return;
1210   if (NULL == uc->serialization)
1211     uc->serialization = make_serialization_file_name (uc->h,
1212                                                       "unindex");
1213   if (NULL == uc->serialization)
1214     return;
1215   wh = get_write_handle (uc->h, "unindex", uc->serialization);
1216   if ( (GNUNET_OK !=
1217         GNUNET_BIO_write_string (wh, uc->filename)) ||
1218        (GNUNET_OK !=
1219         GNUNET_BIO_write_int64 (wh, uc->file_size)) ||
1220        (GNUNET_OK !=
1221         GNUNET_BIO_write_int64 (wh, uc->start_time.value)) ||
1222        (GNUNET_OK !=
1223         GNUNET_BIO_write_int32 (wh, (uint32_t) uc->state)) ||
1224        ( (uc->state == UNINDEX_STATE_FS_NOTIFY) &&
1225          (GNUNET_OK !=
1226           GNUNET_BIO_write (wh, &uc->file_id, sizeof (GNUNET_HashCode))) ) ||
1227        ( (uc->state == UNINDEX_STATE_ERROR) &&
1228          (GNUNET_OK !=
1229           GNUNET_BIO_write_string (wh, uc->emsg)) ) )
1230     {
1231       (void) GNUNET_BIO_write_close (wh);
1232       GNUNET_FS_remove_sync_file_ (uc->h, "publish", uc->serialization);
1233       GNUNET_free (uc->serialization);
1234       uc->serialization = NULL;
1235       return;
1236     }
1237   if (GNUNET_OK !=
1238       GNUNET_BIO_write_close (wh))
1239     {
1240       GNUNET_FS_remove_sync_file_ (uc->h, "unindex", uc->serialization);
1241       GNUNET_free (uc->serialization);
1242       uc->serialization = NULL;
1243       return;     
1244     }  
1245 }
1246
1247
1248 /**
1249  * Synchronize this search result with its mirror
1250  * on disk.  Note that all internal FS-operations that change
1251  * publishing structs should already call "sync" internally,
1252  * so this function is likely not useful for clients.
1253  * 
1254  * @param sc the struct to sync
1255  */
1256 void
1257 GNUNET_FS_search_result_sync_ (struct SearchResult *sr)
1258 {
1259   /* FIXME */
1260 }
1261
1262
1263 /**
1264  * Synchronize this search struct with its mirror
1265  * on disk.  Note that all internal FS-operations that change
1266  * publishing structs should already call "sync" internally,
1267  * so this function is likely not useful for clients.
1268  * 
1269  * @param sc the struct to sync
1270  */
1271 void
1272 GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc)
1273 {  
1274   struct GNUNET_BIO_WriteHandle *wh;
1275
1276   if (NULL == sc->serialization)
1277     sc->serialization = make_serialization_file_name (sc->h,
1278                                                       "search");
1279   if (NULL == sc->serialization)
1280     return;
1281   wh = get_write_handle (sc->h, "search", sc->serialization);
1282 #if 0
1283   if ( (GNUNET_OK !=
1284         GNUNET_BIO_write_string (wh, pc->nid)) ||
1285        (GNUNET_OK !=
1286         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1287        (GNUNET_OK !=
1288         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1289        (GNUNET_OK !=
1290         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1291        (GNUNET_OK !=
1292         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1293        (GNUNET_OK !=
1294         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1295        (GNUNET_OK !=
1296         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1297    {
1298      (void) GNUNET_BIO_write_close (wh);
1299      GNUNET_FS_remove_sync_file_ (pc->h, "publish", pc->serialization);
1300      GNUNET_free (pc->serialization);
1301      pc->serialization = NULL;
1302      return;
1303    }
1304 #endif
1305   /* FIXME: do search-specific serialization here! */
1306   if (GNUNET_OK !=
1307       GNUNET_BIO_write_close (wh))
1308     {
1309       GNUNET_FS_remove_sync_file_ (sc->h, "search", sc->serialization);
1310       GNUNET_free (sc->serialization);
1311       sc->serialization = NULL;
1312       return;     
1313     }  
1314 }
1315
1316
1317 /**
1318  * Deserialize information about pending publish operations.
1319  *
1320  * @param h master context
1321  */
1322 static void
1323 deserialize_publish (struct GNUNET_FS_Handle *h)
1324 {
1325   char *dn;
1326
1327   dn = get_serialization_file_name (h, "publish", "");
1328   if (dn == NULL)
1329     return;
1330   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1331   GNUNET_free (dn);
1332 }
1333
1334
1335
1336
1337 /**
1338  * Function called with a filename of serialized unindexing operation
1339  * to deserialize.
1340  *
1341  * @param cls the 'struct GNUNET_FS_Handle*'
1342  * @param filename complete filename (absolute path)
1343  * @return GNUNET_OK (continue to iterate)
1344  */
1345 static int
1346 deserialize_unindex_file (void *cls,
1347                           const char *filename)
1348 {
1349   struct GNUNET_FS_Handle *h = cls;
1350   struct GNUNET_BIO_ReadHandle *rh;
1351   struct GNUNET_FS_UnindexContext *uc;
1352   struct GNUNET_FS_ProgressInfo pi;
1353   char *emsg;
1354   uint32_t state;
1355
1356   uc = GNUNET_malloc (sizeof (struct GNUNET_FS_UnindexContext));
1357   uc->h = h;
1358   uc->serialization = get_serialization_short_name (filename);
1359   rh = GNUNET_BIO_read_open (filename);
1360   if (rh == NULL)
1361     goto cleanup;
1362   if ( (GNUNET_OK !=
1363         GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10*1024)) ||
1364        (GNUNET_OK !=
1365         GNUNET_BIO_read_int64 (rh, &uc->file_size)) ||
1366        (GNUNET_OK !=
1367         GNUNET_BIO_read_int64 (rh, &uc->start_time.value)) ||
1368        (GNUNET_OK !=
1369         GNUNET_BIO_read_int32 (rh, &state)) )
1370     goto cleanup;          
1371   uc->state = (enum UnindexState) state;
1372   switch (state)
1373     {
1374     case UNINDEX_STATE_HASHING:
1375       break;
1376     case UNINDEX_STATE_FS_NOTIFY:
1377       if (GNUNET_OK !=
1378           GNUNET_BIO_read (rh, "unindex-hash", &uc->file_id, sizeof (GNUNET_HashCode)))
1379         goto cleanup;
1380       break;
1381     case UNINDEX_STATE_DS_REMOVE:
1382       break;
1383     case UNINDEX_STATE_COMPLETE:
1384       break;
1385     case UNINDEX_STATE_ERROR:
1386       if (GNUNET_OK !=
1387           GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10*1024))
1388         goto cleanup;
1389       break;
1390     case UNINDEX_STATE_ABORTED:
1391       GNUNET_break (0);
1392       goto cleanup;
1393     default:
1394       GNUNET_break (0);
1395       goto cleanup;
1396     }
1397   pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME;
1398   pi.value.unindex.specifics.resume.message = uc->emsg;
1399   GNUNET_FS_unindex_make_status_ (&pi,
1400                                   uc,
1401                                   (uc->state == UNINDEX_STATE_COMPLETE) 
1402                                   ? uc->file_size
1403                                   : 0);
1404   switch (uc->state)
1405     {
1406     case UNINDEX_STATE_HASHING:
1407       GNUNET_CRYPTO_hash_file (uc->h->sched,
1408                                GNUNET_SCHEDULER_PRIORITY_IDLE,
1409                                uc->filename,
1410                                HASHING_BLOCKSIZE,
1411                                &GNUNET_FS_unindex_process_hash_,
1412                                uc);
1413       break;
1414     case UNINDEX_STATE_FS_NOTIFY:
1415       uc->state = UNINDEX_STATE_HASHING;
1416       GNUNET_FS_unindex_process_hash_ (uc,
1417                                        &uc->file_id);
1418       break;
1419     case UNINDEX_STATE_DS_REMOVE:
1420       GNUNET_FS_unindex_do_remove_ (uc);
1421       break;
1422     case UNINDEX_STATE_COMPLETE:
1423     case UNINDEX_STATE_ERROR:
1424       /* no need to resume any operation, we were done */
1425       break;
1426     default:
1427       break;
1428     }
1429   if (GNUNET_OK !=
1430       GNUNET_BIO_read_close (rh, &emsg))
1431     {
1432       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1433                   _("Failure while resuming unindexing operation `%s': %s\n"),
1434                   filename,
1435                   emsg);
1436       GNUNET_free (emsg);
1437     }
1438   return GNUNET_OK;
1439  cleanup:
1440   GNUNET_free_non_null (uc->filename);
1441   if ( (rh != NULL) &&
1442        (GNUNET_OK !=
1443         GNUNET_BIO_read_close (rh, &emsg)) )
1444     {
1445       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1446                   _("Failed to resume unindexing operation `%s': %s\n"),
1447                   filename,
1448                   emsg);
1449       GNUNET_free (emsg);
1450     }
1451   if (uc->serialization != NULL)
1452     GNUNET_FS_remove_sync_file_ (h, "unindex", uc->serialization);
1453   GNUNET_free_non_null (uc->serialization);
1454   GNUNET_free (uc);
1455   return GNUNET_OK;
1456 }
1457
1458
1459 /**
1460  * Deserialize information about pending publish operations.
1461  *
1462  * @param h master context
1463  */
1464 static void
1465 deserialize_unindex (struct GNUNET_FS_Handle *h)
1466 {
1467   char *dn;
1468
1469   dn = get_serialization_file_name (h, "unindex", "");
1470   if (dn == NULL)
1471     return;
1472   GNUNET_DISK_directory_scan (dn, &deserialize_unindex_file, h);
1473   GNUNET_free (dn);
1474 }
1475
1476
1477 /**
1478  * Function called with a filename of serialized search result
1479  * to deserialize.
1480  *
1481  * @param cls the 'struct GNUNET_FS_SearchContext*'
1482  * @param filename complete filename (absolute path)
1483  * @return GNUNET_OK (continue to iterate)
1484  */
1485 static int
1486 deserialize_search_result (void *cls,
1487                            const char *filename)
1488 {
1489   struct GNUNET_FS_SearchContext *sc = cls;
1490   char pbuf[32];
1491   char *ser;
1492   char *uris;
1493   char *emsg;
1494   struct GNUNET_BIO_ReadHandle *rh;
1495   struct SearchResult *sr;
1496   GNUNET_HashCode key;
1497
1498   ser = get_serialization_short_name (filename);
1499   rh = GNUNET_BIO_read_open (filename);
1500   if (rh == NULL)
1501     {
1502       if (ser != NULL)
1503         {
1504           GNUNET_snprintf (pbuf,
1505                            sizeof (pbuf),
1506                            "%s%s%s",
1507                            "search-results",
1508                            DIR_SEPARATOR_STR,
1509                            sc->serialization);
1510           GNUNET_FS_remove_sync_file_ (sc->h, pbuf, ser);
1511           GNUNET_free (ser);
1512         }
1513       return GNUNET_OK;
1514     }
1515   emsg = NULL;
1516   uris = NULL;
1517   sr = GNUNET_malloc (sizeof (struct SearchResult));
1518   sr->serialization = ser;  
1519   if ( (GNUNET_OK !=
1520         GNUNET_BIO_read_string (rh, "result-uri", &uris, 10*1024)) ||
1521        (NULL == (sr->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
1522        ( (GNUNET_YES != GNUNET_FS_uri_test_chk (sr->uri)) &&
1523          (GNUNET_YES != GNUNET_FS_uri_test_loc (sr->uri)) ) ||
1524        (GNUNET_OK !=
1525         GNUNET_BIO_read_meta_data (rh, "result-meta", &sr->meta)) ||
1526        (GNUNET_OK !=
1527         GNUNET_BIO_read (rh, "result-key", &key, sizeof (key))) ||
1528        (GNUNET_OK !=
1529         GNUNET_BIO_read_int32 (rh, &sr->mandatory_missing)) ||
1530        (GNUNET_OK !=
1531         GNUNET_BIO_read_int32 (rh, &sr->optional_support)) ||
1532        (GNUNET_OK !=
1533         GNUNET_BIO_read_int32 (rh, &sr->availability_success)) ||
1534        (GNUNET_OK !=
1535         GNUNET_BIO_read_int32 (rh, &sr->availability_trials)) )
1536     goto cleanup;   
1537   GNUNET_free (uris);
1538   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map,
1539                                      &key,
1540                                      sr,
1541                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1542   return GNUNET_OK;
1543  cleanup:
1544   GNUNET_free_non_null (emsg);
1545   GNUNET_free_non_null (uris);
1546   if (sr->uri != NULL)
1547     GNUNET_FS_uri_destroy (sr->uri);
1548   if (sr->meta != NULL)
1549     GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1550   GNUNET_free (sr->serialization);
1551   GNUNET_free (sr);  
1552   return GNUNET_OK;
1553 }
1554
1555
1556 /**
1557  * Iterator over search results signaling resume to the client for
1558  * each result.
1559  *
1560  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
1561  * @param key current key code
1562  * @param value value in the hash map, the 'struct SearchResult'
1563  * @return GNUNET_YES (we should continue to iterate)
1564  */
1565 static int
1566 signal_result_resume (void *cls,
1567                       const GNUNET_HashCode * key,
1568                       void *value)
1569 {
1570   struct GNUNET_FS_SearchContext *sc = cls;
1571   struct GNUNET_FS_ProgressInfo pi;
1572   struct SearchResult *sr = value;
1573
1574   if (0 == sr->mandatory_missing)
1575     {
1576       pi.status = GNUNET_FS_STATUS_SEARCH_RESUME_RESULT;
1577       pi.value.search.specifics.resume_result.meta = sr->meta;
1578       pi.value.search.specifics.resume_result.uri = sr->uri;
1579       pi.value.search.specifics.resume_result.availability_rank = 2*sr->availability_success - sr->availability_trials;
1580       pi.value.search.specifics.resume_result.availability_certainty = sr->availability_trials;
1581       pi.value.search.specifics.resume_result.applicability_rank = sr->optional_support;
1582       sr->client_info = GNUNET_FS_search_make_status_ (&pi,
1583                                                        sc);
1584     }
1585   GNUNET_FS_search_start_probe_ (sr);
1586   return GNUNET_YES;
1587 }
1588
1589
1590 /**
1591  * Iterator over search results freeing each.
1592  *
1593  * @param cls closure, the 'struct GNUNET_FS_SearchContext'
1594  * @param key current key code
1595  * @param value value in the hash map, the 'struct SearchResult'
1596  * @return GNUNET_YES (we should continue to iterate)
1597  */
1598 static int
1599 free_result (void *cls,
1600              const GNUNET_HashCode * key,
1601              void *value)
1602 {
1603   struct SearchResult *sr = value;
1604
1605   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1606   GNUNET_FS_uri_destroy (sr->uri);
1607   GNUNET_free (sr);
1608   return GNUNET_YES;
1609 }
1610
1611
1612 /**
1613  * Deserialize a search. 
1614  *
1615  * @param h overall context
1616  * @param rh file to deserialize from
1617  * @param parent parent search
1618  * @param serialization name under which the search was serialized
1619  */
1620 static struct GNUNET_FS_SearchContext *
1621 deserialize_search (struct GNUNET_FS_Handle *h,
1622                     struct GNUNET_BIO_ReadHandle *rh,
1623                     struct GNUNET_FS_SearchContext *parent,
1624                     const char *serialization)
1625 {
1626   struct GNUNET_FS_SearchContext *sc;
1627   char pbuf[32];
1628   struct GNUNET_FS_ProgressInfo pi;
1629   char *emsg;
1630   char *uris;
1631   char *child_ser;
1632   char *dn;
1633   uint32_t options;
1634   char in_pause;
1635
1636   uris = NULL;
1637   child_ser = NULL;
1638   emsg = NULL;
1639   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
1640   sc->parent = parent;
1641   sc->h = h;
1642   sc->serialization = GNUNET_strdup (serialization);
1643   if ( (GNUNET_OK !=
1644         GNUNET_BIO_read_string (rh, "search-uri", &uris, 10*1024)) ||
1645        (NULL == (sc->uri = GNUNET_FS_uri_parse (uris, &emsg))) ||       
1646        ( (GNUNET_YES != GNUNET_FS_uri_test_ksk (sc->uri)) &&
1647          (GNUNET_YES != GNUNET_FS_uri_test_sks (sc->uri)) ) ||
1648        (GNUNET_OK !=
1649         GNUNET_BIO_read_int64 (rh, &sc->start_time.value)) ||
1650        (GNUNET_OK !=
1651         GNUNET_BIO_read_string (rh, "child-serialization", &child_ser, 32)) ||
1652        (GNUNET_OK !=
1653         GNUNET_BIO_read_string (rh, "search-emsg", &sc->emsg, 10*1024)) ||
1654        (GNUNET_OK !=
1655         GNUNET_BIO_read_int32 (rh, &options)) ||
1656        (GNUNET_OK !=
1657         GNUNET_BIO_read (rh, "search-pause", &in_pause, sizeof (in_pause))) ||
1658        (GNUNET_OK !=
1659         GNUNET_BIO_read_int32 (rh, &sc->anonymity)) )
1660     goto cleanup;          
1661   /* FIXME: adjust start_time.value */
1662   sc->options = (enum GNUNET_FS_SearchOptions) options;
1663   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
1664   GNUNET_snprintf (pbuf,
1665                    sizeof (pbuf),
1666                    "%s%s%s",
1667                    "search-results",
1668                    DIR_SEPARATOR_STR,
1669                    sc->serialization);
1670   dn = get_serialization_file_name (h, pbuf, "");
1671   if (dn != NULL)
1672     {
1673       GNUNET_DISK_directory_scan (dn, &deserialize_search_result, sc);
1674       GNUNET_free (dn);
1675     }
1676   if ('\0' == in_pause)
1677     {
1678       if (GNUNET_OK !=
1679           GNUNET_FS_search_start_searching_ (sc))
1680         goto cleanup;
1681     }
1682   if (child_ser != NULL)
1683     {
1684       /* FIXME: deserialize child-search! */
1685     }
1686   if (parent != NULL)
1687     GNUNET_CONTAINER_DLL_insert (parent->child_head,
1688                                  parent->child_tail,
1689                                  sc);
1690   pi.status = GNUNET_FS_STATUS_SEARCH_RESUME;
1691   pi.value.search.specifics.resume.message = sc->emsg;
1692   pi.value.search.specifics.resume.is_paused = ('\0' == in_pause) ? GNUNET_NO : GNUNET_YES;
1693   sc->client_info = GNUNET_FS_search_make_status_ (&pi,
1694                                                    sc);
1695   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1696                                          &signal_result_resume,
1697                                          sc);
1698   return sc;
1699  cleanup:
1700   GNUNET_free_non_null (child_ser);
1701   GNUNET_free_non_null (sc->emsg);
1702   GNUNET_free_non_null (emsg);
1703   if (sc->serialization != NULL)
1704     GNUNET_FS_remove_sync_file_ (h, "search", sc->serialization);
1705   /* FIXME: remove 'pbuf' directory with search results as well! */
1706   GNUNET_free_non_null (sc->serialization);
1707   if (sc->uri != NULL)
1708     GNUNET_FS_uri_destroy (sc->uri);
1709   if (sc->master_result_map != NULL)
1710     {
1711       GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1712                                              &free_result,
1713                                              sc);
1714       GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1715     }
1716   GNUNET_free (sc);
1717   GNUNET_free_non_null (uris);
1718   return NULL;
1719 }
1720
1721
1722 /**
1723  * Function called with a filename of serialized search operation
1724  * to deserialize.
1725  *
1726  * @param cls the 'struct GNUNET_FS_Handle*'
1727  * @param filename complete filename (absolute path)
1728  * @return GNUNET_OK (continue to iterate)
1729  */
1730 static int
1731 deserialize_search_file (void *cls,
1732                           const char *filename)
1733 {
1734   struct GNUNET_FS_Handle *h = cls;
1735   char *ser;
1736   char *emsg;
1737   struct GNUNET_BIO_ReadHandle *rh;
1738   struct GNUNET_FS_SearchContext *sc;
1739
1740   ser = get_serialization_short_name (filename);
1741   rh = GNUNET_BIO_read_open (filename);
1742   if (rh == NULL)
1743     {
1744       if (ser != NULL)
1745         {
1746           GNUNET_FS_remove_sync_file_ (h, "search", ser);
1747           GNUNET_free (ser);
1748         }
1749       return GNUNET_OK;
1750     }
1751   sc = deserialize_search (h, rh, NULL, ser);
1752   GNUNET_free (ser);
1753   if (GNUNET_OK !=
1754       GNUNET_BIO_read_close (rh, &emsg))
1755     {
1756       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1757                   _("Failure while resuming unindexing operation `%s': %s\n"),
1758                   filename,
1759                   emsg);
1760       GNUNET_free (emsg);
1761     }
1762   return GNUNET_OK;
1763 }
1764
1765
1766 /**
1767  * Deserialize information about pending search operations.
1768  *
1769  * @param h master context
1770  */
1771 static void
1772 deserialize_search_master (struct GNUNET_FS_Handle *h)
1773 {
1774   char *dn;
1775
1776   dn = get_serialization_file_name (h, "search", "");
1777   if (dn == NULL)
1778     return;
1779   GNUNET_DISK_directory_scan (dn, &deserialize_search_file, h);
1780   GNUNET_free (dn);
1781 }
1782
1783
1784 /**
1785  * Setup a connection to the file-sharing service.
1786  *
1787  * @param sched scheduler to use
1788  * @param cfg configuration to use
1789  * @param client_name unique identifier for this client 
1790  * @param upcb function to call to notify about FS actions
1791  * @param upcb_cls closure for upcb
1792  * @param flags specific attributes for fs-operations
1793  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
1794  * @return NULL on error
1795  */
1796 struct GNUNET_FS_Handle *
1797 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
1798                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1799                  const char *client_name,
1800                  GNUNET_FS_ProgressCallback upcb,
1801                  void *upcb_cls,
1802                  enum GNUNET_FS_Flags flags,
1803                  ...)
1804 {
1805   struct GNUNET_FS_Handle *ret;
1806   struct GNUNET_CLIENT_Connection *client;
1807   enum GNUNET_FS_OPTIONS opt;
1808   va_list ap;
1809
1810   client = GNUNET_CLIENT_connect (sched,
1811                                   "fs",
1812                                   cfg);
1813   if (NULL == client)
1814     return NULL;
1815   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
1816   ret->sched = sched;
1817   ret->cfg = cfg;
1818   ret->client_name = GNUNET_strdup (client_name);
1819   ret->upcb = upcb;
1820   ret->upcb_cls = upcb_cls;
1821   ret->client = client;
1822   ret->flags = flags;
1823   ret->max_parallel_downloads = 1;
1824   ret->max_parallel_requests = 1;
1825   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
1826   va_start (ap, flags);  
1827   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
1828     {
1829       switch (opt)
1830         {
1831         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
1832           ret->max_parallel_downloads = va_arg (ap, unsigned int);
1833           break;
1834         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
1835           ret->max_parallel_requests = va_arg (ap, unsigned int);
1836           break;
1837         default:
1838           GNUNET_break (0);
1839           GNUNET_free (ret->client_name);
1840           GNUNET_free (ret);
1841           va_end (ap);
1842           return NULL;
1843         }
1844     }
1845   va_end (ap);
1846   // FIXME: setup receive-loop with client (do we need one?)
1847   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
1848     {
1849       /* FIXME: could write one generic deserialization
1850          function instead of these four... */
1851       deserialize_publish (ret);
1852       deserialize_search_master (ret);
1853       /* FIXME: deserialize downloads that are NOT part of searches */
1854       deserialize_unindex (ret);
1855     }
1856   return ret;
1857 }
1858
1859
1860 /**
1861  * Close our connection with the file-sharing service.
1862  * The callback given to GNUNET_FS_start will no longer be
1863  * called after this function returns.
1864  *
1865  * @param h handle that was returned from GNUNET_FS_start
1866  */                    
1867 void 
1868 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
1869 {
1870   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & h->flags))
1871     {
1872       // FIXME: generate SUSPEND events and clean up state!
1873     }
1874   // FIXME: terminate receive-loop with client  (do we need one?)
1875   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
1876     GNUNET_SCHEDULER_cancel (h->sched,
1877                              h->queue_job);
1878   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1879   GNUNET_free (h->client_name);
1880   GNUNET_free (h);
1881 }
1882
1883
1884 /* end of fs.c */