finishing initial coding of fs-publish serialization/deserialization
[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  * Return the full filename where we would store state information
329  * (for serialization/deserialization).
330  *
331  * @param h master context
332  * @param ext component of the path 
333  * @param ent entity identifier (or emtpy string for the directory)
334  * @return NULL on error
335  */
336 static char *
337 get_serialization_file_name (struct GNUNET_FS_Handle *h,
338                              const char *ext,
339                              const char *ent)
340 {
341   char *basename;
342   char *ret;
343   if (GNUNET_OK !=
344       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
345                                                "fs",
346                                                "STATE_DIR",
347                                                &basename))
348     return NULL;
349   GNUNET_asprintf (&ret,
350                    "%s%s%s-%s%s%s",
351                    basename,
352                    DIR_SEPARATOR_STR,
353                    h->client_name,
354                    ext,
355                    DIR_SEPARATOR_STR,
356                    ent);
357   GNUNET_free (basename);
358   return ret;
359 }
360
361
362 /**
363  * Return a read handle for deserialization.
364  *
365  * @param h master context
366  * @param ext component of the path 
367  * @param ent entity identifier (or emtpy string for the directory)
368  * @return NULL on error
369  */
370 static struct GNUNET_BIO_ReadHandle *
371 get_read_handle (struct GNUNET_FS_Handle *h,
372                  const char *ext,
373                  const char *ent)
374 {
375   char *fn;
376   struct GNUNET_BIO_ReadHandle *ret;
377
378   fn = get_serialization_file_name (h, ext, ent);
379   if (fn == NULL)
380     return NULL;
381   ret = GNUNET_BIO_read_open (fn);
382   GNUNET_free (fn);
383   return ret;
384 }
385
386
387 /**
388  * Return a write handle for serialization.
389  *
390  * @param h master context
391  * @param ext component of the path 
392  * @param ent entity identifier (or emtpy string for the directory)
393  * @return NULL on error
394  */
395 static struct GNUNET_BIO_WriteHandle *
396 get_write_handle (struct GNUNET_FS_Handle *h,
397                  const char *ext,
398                  const char *ent)
399 {
400   char *fn;
401   struct GNUNET_BIO_WriteHandle *ret;
402
403   fn = get_serialization_file_name (h, ext, ent);
404   if (fn == NULL)
405     return NULL;
406   ret = GNUNET_BIO_write_open (fn);
407   GNUNET_free (fn);
408   return ret;
409 }
410
411
412 /**
413  * Remove serialization/deserialization file from disk.
414  *
415  * @param h master context
416  * @param ext component of the path 
417  * @param ent entity identifier 
418  */
419 static void
420 remove_sync_file (struct GNUNET_FS_Handle *h,
421                   const char *ext,
422                   const char *ent)
423 {
424   char *filename;
425
426   if ( (NULL == ent) ||
427        (0 == strlen (ent)) )
428     {
429       GNUNET_break (0);
430       return;
431     }
432   filename = get_serialization_file_name (h, ext, ent);
433   if (0 != UNLINK (filename))
434     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
435                               "unlink", 
436                               filename);
437   GNUNET_free (filename);
438 }
439
440
441
442 /**
443  * Using the given serialization filename, try to deserialize
444  * the file-information tree associated with it.
445  *
446  * @param h master context
447  * @param filename name of the file (without directory) with
448  *        the infromation
449  * @return NULL on error
450  */
451 static struct GNUNET_FS_FileInformation *
452 deserialize_file_information (struct GNUNET_FS_Handle *h,
453                               const char *filename);
454
455
456 /**
457  * Using the given serialization filename, try to deserialize
458  * the file-information tree associated with it.
459  *
460  * @param h master context
461  * @param fn name of the file (without directory) with
462  *        the infromation
463  * @param rh handle for reading
464  * @return NULL on error
465  */
466 static struct GNUNET_FS_FileInformation *
467 deserialize_fi_node (struct GNUNET_FS_Handle *h,
468                      const char *fn,
469                      struct GNUNET_BIO_ReadHandle *rh)
470 {
471   struct GNUNET_FS_FileInformation *ret;
472   struct GNUNET_FS_FileInformation *nxt;
473   char b;
474   char *ksks;
475   char *chks;
476   char *filename;
477   uint32_t dsize;
478
479   if (GNUNET_OK !=
480       GNUNET_BIO_read (rh, "status flag", &b, sizeof(b)))
481     {
482       GNUNET_break (0);
483       return NULL;
484     }
485   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
486   ksks = NULL;
487   chks = NULL;
488   filename = NULL;
489   if ( (GNUNET_OK !=
490         GNUNET_BIO_read_meta_data (rh, "metadata", &ret->meta)) ||
491        (GNUNET_OK !=
492         GNUNET_BIO_read_string (rh, "ksk-uri", &ksks, 32*1024)) ||
493        ( (ksks != NULL) &&
494          (NULL == 
495           (ret->keywords = GNUNET_FS_uri_parse (ksks, NULL))) ) ||
496        (GNUNET_YES !=
497         GNUNET_FS_uri_test_ksk (ret->keywords)) ||
498        (GNUNET_OK !=
499         GNUNET_BIO_read_string (rh, "chk-uri", &chks, 1024)) ||
500        ( (chks != NULL) &&
501          ( (NULL == 
502             (ret->chk_uri = GNUNET_FS_uri_parse (chks, NULL))) ||
503            (GNUNET_YES !=
504             GNUNET_FS_uri_test_chk (ret->chk_uri)) ) ) ||
505        (GNUNET_OK !=
506         GNUNET_BIO_read_int64 (rh, &ret->expirationTime.value)) ||
507        (GNUNET_OK !=
508         GNUNET_BIO_read_int64 (rh, &ret->start_time.value)) ||
509        (GNUNET_OK !=
510         GNUNET_BIO_read_string (rh, "emsg", &ret->emsg, 16*1024)) ||
511        (GNUNET_OK !=
512         GNUNET_BIO_read_string (rh, "fn", &ret->filename, 16*1024)) ||
513        (GNUNET_OK !=
514         GNUNET_BIO_read_int32 (rh, &ret->anonymity)) ||
515        (GNUNET_OK !=
516         GNUNET_BIO_read_int32 (rh, &ret->priority)) )
517     goto cleanup;
518   switch (b)
519     {
520     case 0: /* file-insert */
521       if (GNUNET_OK !=
522           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
523         goto cleanup;
524       ret->is_directory = GNUNET_NO;
525       ret->data.file.do_index = GNUNET_NO;
526       ret->data.file.have_hash = GNUNET_NO;
527       ret->data.file.index_start_confirmed = GNUNET_NO;
528       /* FIXME: what's our approach for dealing with the
529          'reader' and 'reader_cls' fields?  I guess the only
530          good way would be to dump "small" files into 
531          'rh' and to not support serialization of "large"
532          files (!?) */
533       break;
534     case 1: /* file-index, no hash */
535       if (NULL == ret->filename)
536         goto cleanup;
537       if (GNUNET_OK !=
538           GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size))
539         goto cleanup;
540       ret->is_directory = GNUNET_NO;
541       ret->data.file.do_index = GNUNET_YES;
542       ret->data.file.have_hash = GNUNET_NO;
543       ret->data.file.index_start_confirmed = GNUNET_NO;
544       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
545       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
546       break;
547     case 2: /* file-index-with-hash */
548       if (NULL == ret->filename)
549         goto cleanup;
550       if ( (GNUNET_OK !=
551             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
552            (GNUNET_OK !=
553             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
554         goto cleanup;
555       ret->is_directory = GNUNET_NO;
556       ret->data.file.do_index = GNUNET_YES;
557       ret->data.file.have_hash = GNUNET_YES;
558       ret->data.file.index_start_confirmed = GNUNET_NO;
559       ret->data.file.reader = &GNUNET_FS_data_reader_file_;
560       ret->data.file.reader_cls = GNUNET_FS_make_file_reader_context_ (ret->filename);
561       break;
562     case 3: /* file-index-with-hash-confirmed */
563       if (NULL == ret->filename)
564         goto cleanup;
565       if ( (GNUNET_OK !=
566             GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) ||
567            (GNUNET_OK !=
568             GNUNET_BIO_read (rh, "fileid", &ret->data.file.file_id, sizeof (GNUNET_HashCode))) )
569         goto cleanup;
570
571       ret->is_directory = GNUNET_NO;
572       ret->data.file.do_index = GNUNET_YES;
573       ret->data.file.have_hash = GNUNET_YES;
574       ret->data.file.index_start_confirmed = GNUNET_YES;
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       break;
578     case 4: /* directory */
579       if ( (GNUNET_OK !=
580             GNUNET_BIO_read_int32 (rh, &dsize)) ||
581            (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large (dsize))) ||
582            (GNUNET_OK !=
583             GNUNET_BIO_read (rh, "dir-data", ret->data.dir.dir_data, dsize)) ||
584            (GNUNET_OK !=
585             GNUNET_BIO_read_string (rh, "ent-filename", &filename, 16*1024)) )
586         goto cleanup;
587       ret->data.dir.dir_size = (uint32_t) dsize;
588       ret->is_directory = GNUNET_YES;
589       if (filename != NULL)
590         {
591           ret->data.dir.entries = deserialize_file_information (h, filename);
592           GNUNET_free (filename);
593           filename = NULL;
594           nxt = ret->data.dir.entries;
595           while (nxt != NULL)
596             {
597               nxt->dir = ret;
598               nxt = nxt->next;
599             }  
600         }
601       break;
602     default:
603       GNUNET_break (0);
604       goto cleanup;
605     }
606   /* FIXME: adjust ret->start_time! */
607   ret->serialization = GNUNET_strdup (fn);
608   if (GNUNET_OK !=
609       GNUNET_BIO_read_string (rh, "nxt-filename", &filename, 16*1024))
610     goto cleanup;  
611   if (filename != NULL)
612     {
613       ret->next = deserialize_file_information (h, filename);
614       GNUNET_free (filename);
615       filename = NULL;
616     }
617   return ret;
618  cleanup:
619   GNUNET_free_non_null (ksks);
620   GNUNET_free_non_null (chks);
621   GNUNET_free_non_null (filename);
622   GNUNET_FS_file_information_destroy (ret, NULL, NULL);
623   return NULL;
624 }
625
626
627 /**
628  * Using the given serialization filename, try to deserialize
629  * the file-information tree associated with it.
630  *
631  * @param h master context
632  * @param filename name of the file (without directory) with
633  *        the infromation
634  * @return NULL on error
635  */
636 static struct GNUNET_FS_FileInformation *
637 deserialize_file_information (struct GNUNET_FS_Handle *h,
638                               const char *filename)
639 {
640   struct GNUNET_FS_FileInformation *ret;
641   struct GNUNET_BIO_ReadHandle *rh;
642   char *emsg;
643
644   rh = get_read_handle (h, "publish-fi", filename);
645   if (rh == NULL)
646     return NULL;
647   ret = deserialize_fi_node (h, filename, rh);
648   if (GNUNET_OK !=
649       GNUNET_BIO_read_close (rh, &emsg))
650     {
651       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
652                   _("Failed to resume publishing information `%s': %s\n"),
653                   filename,
654                   emsg);
655       GNUNET_free (emsg);
656     }
657   return ret;
658 }
659
660
661 /**
662  * Given a serialization name (full absolute path), return the
663  * basename of the file (without the path), which must only
664  * consist of the 6 random characters.
665  * 
666  * @param fullname name to extract the basename from
667  * @return copy of the basename, NULL on error
668  */
669 static char *
670 get_serialization_short_name (const char *fullname)
671 {
672   const char *end;
673   const char *nxt;
674
675   end = NULL;
676   nxt = fullname;
677   /* FIXME: we could do this faster since we know
678      the length of 'end'... */
679   while ('\0' != nxt)
680     {
681       if (DIR_SEPARATOR == *nxt)
682         end = nxt + 1;
683       nxt++;
684     }
685   if ( (end == NULL) ||
686        (strlen (end) == 0) )
687     {
688       GNUNET_break (0);
689       return NULL;
690     }
691   GNUNET_break (6 == strlen (end));
692   return GNUNET_strdup (end);  
693 }
694
695
696 /**
697  * Create a new random name for serialization.  Also checks if persistence
698  * is enabled and returns NULL if not.
699  *
700  * @param h master context
701  * @param ext component of the path 
702  * @return NULL on errror
703  */
704 static char *
705 make_serialization_file_name (struct GNUNET_FS_Handle *h,
706                               const char *ext)
707 {
708   char *fn;
709   char *dn;
710   char *ret;
711
712   if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE))
713     return NULL; /* persistence not requested */
714   dn = get_serialization_file_name (h, ext, "");
715   fn = GNUNET_DISK_mktemp (dn);
716   GNUNET_free (dn);
717   if (fn == NULL)
718     return NULL; /* epic fail */
719   ret = get_serialization_short_name (fn);
720   GNUNET_free (fn);
721   return ret;
722 }
723
724
725 /**
726  * Copy all of the data from the reader to the write handle.
727  *
728  * @param wh write handle
729  * @param fi file with reader
730  * @return GNUNET_OK on success
731  */
732 static int
733 copy_from_reader (struct GNUNET_BIO_WriteHandle *wh,
734                   struct GNUNET_FS_FileInformation * fi)
735 {
736   char buf[32 * 1024];
737   uint64_t off;
738   size_t ret;
739   char *emsg;
740
741   emsg = NULL;
742   off = 0;
743   while (off < fi->data.file.file_size)
744     {
745       ret = fi->data.file.reader (fi->data.file.reader_cls,
746                                   off, sizeof (buf),
747                                   buf,
748                                   &emsg);
749       if (ret == 0)
750         {
751           GNUNET_free (emsg);
752           return GNUNET_SYSERR;
753         }
754       if (GNUNET_OK != 
755           GNUNET_BIO_write (wh, buf, ret))
756         return GNUNET_SYSERR;
757       off += ret;
758     }
759   return GNUNET_OK;
760 }
761
762
763 /**
764  * Create a temporary file on disk to store the current
765  * state of "fi" in.
766  *
767  * @param fi file information to sync with disk
768  */
769 void
770 GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation * fi)
771 {
772   char *fn;
773   struct GNUNET_BIO_WriteHandle *wh;
774   char b;
775   char *ksks;
776   char *chks;
777
778   if (NULL == fi->serialization)    
779     fi->serialization = make_serialization_file_name (fi->h, "publish-fi");
780   if (NULL == fi->serialization)
781     return;
782   wh = get_write_handle (fi->h, "publish-fi", fi->serialization);
783   if (wh == NULL)
784     {
785       GNUNET_free (fi->serialization);
786       fi->serialization = NULL;
787       return;
788     }
789   if (GNUNET_YES == fi->is_directory)
790     b = 4;
791   else if (GNUNET_YES == fi->data.file.index_start_confirmed)
792     b = 3;
793   else if (GNUNET_YES == fi->data.file.have_hash)
794     b = 2;
795   else if (GNUNET_YES == fi->data.file.do_index)
796     b = 1;
797   else
798     b = 0;
799   if (fi->keywords != NULL)
800     ksks = GNUNET_FS_uri_to_string (fi->keywords);
801   else
802     ksks = NULL;
803   if (fi->chk_uri != NULL)
804     chks = GNUNET_FS_uri_to_string (fi->chk_uri);
805   else
806     chks = NULL;
807   if ( (GNUNET_OK !=
808         GNUNET_BIO_write (wh, &b, sizeof (b))) ||
809        (GNUNET_OK != 
810         GNUNET_BIO_write_meta_data (wh, fi->meta)) ||
811        (GNUNET_OK !=
812         GNUNET_BIO_write_string (wh, ksks)) ||
813        (GNUNET_OK !=
814         GNUNET_BIO_write_string (wh, chks)) ||
815        (GNUNET_OK != 
816         GNUNET_BIO_write_int64 (wh, fi->expirationTime.value)) ||
817        (GNUNET_OK != 
818         GNUNET_BIO_write_int64 (wh, fi->start_time.value)) ||
819        (GNUNET_OK !=
820         GNUNET_BIO_write_string (wh, fi->emsg)) ||
821        (GNUNET_OK !=
822         GNUNET_BIO_write_string (wh, fi->filename)) ||
823        (GNUNET_OK != 
824         GNUNET_BIO_write_int32 (wh, fi->anonymity)) ||
825        (GNUNET_OK != 
826         GNUNET_BIO_write_int32 (wh, fi->priority)) )
827     goto cleanup;
828   GNUNET_free_non_null (chks);
829   chks = NULL;
830   GNUNET_free_non_null (ksks);
831   ksks = NULL;
832   
833   switch (b)
834     {
835     case 0: /* file-insert */
836       if (GNUNET_OK !=
837           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
838         goto cleanup;
839       if ( (GNUNET_NO == fi->is_published) &&
840            (NULL == fi->filename) )     
841         if (GNUNET_OK != 
842             copy_from_reader (wh, fi))
843           goto cleanup;
844       break;
845     case 1: /* file-index, no hash */
846       if (NULL == fi->filename)
847         goto cleanup;
848       if (GNUNET_OK !=
849           GNUNET_BIO_write_int64 (wh, fi->data.file.file_size))
850         goto cleanup;
851       break;
852     case 2: /* file-index-with-hash */
853     case 3: /* file-index-with-hash-confirmed */
854       if (NULL == fi->filename)
855         goto cleanup;
856       if ( (GNUNET_OK !=
857             GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) ||
858            (GNUNET_OK !=
859             GNUNET_BIO_write (wh, &fi->data.file.file_id, sizeof (GNUNET_HashCode))) )
860         goto cleanup;
861       break;
862     case 4: /* directory */
863       if ( (GNUNET_OK !=
864             GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) ||
865            (GNUNET_OK !=
866             GNUNET_BIO_write (wh, fi->data.dir.dir_data, (uint32_t) fi->data.dir.dir_size)) ||
867            (GNUNET_OK !=
868             GNUNET_BIO_write_string (wh, fi->data.dir.entries->serialization)) )
869         goto cleanup;
870       break;
871     default:
872       GNUNET_assert (0);
873       goto cleanup;
874     }
875   if (GNUNET_OK !=
876       GNUNET_BIO_write_string (wh, fi->next->serialization))
877     goto cleanup;  
878   if (GNUNET_OK ==
879       GNUNET_BIO_write_close (wh))
880     return; /* done! */
881  cleanup:
882   (void) GNUNET_BIO_write_close (wh);
883   GNUNET_free_non_null (chks);
884   GNUNET_free_non_null (ksks);
885   fn = get_serialization_file_name (fi->h, "publish-fi", fi->serialization);
886   if (0 != UNLINK (fn))
887     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
888   GNUNET_free (fn);
889   GNUNET_free (fi->serialization);
890   fi->serialization = NULL;  
891 }
892
893
894
895 /**
896  * Find the entry in the file information struct where the
897  * serialization filename matches the given name.
898  *
899  * @param pos file information to search
900  * @param srch filename to search for
901  * @return NULL if srch was not found in this subtree
902  */
903 static struct GNUNET_FS_FileInformation *
904 find_file_position (struct GNUNET_FS_FileInformation *pos,
905                     const char *srch)
906 {
907   struct GNUNET_FS_FileInformation *r;
908
909   while (pos != NULL)
910     {
911       if (0 == strcmp (srch,
912                        pos->serialization))
913         return pos;
914       if (pos->is_directory)
915         {
916           r = find_file_position (pos->data.dir.entries,
917                                   srch);
918           if (r != NULL)
919             return r;
920         }
921       pos = pos->next;
922     }
923   return NULL;
924 }
925
926
927 /**
928  * Signal the FS's progress function that we are resuming
929  * an upload.
930  *
931  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
932  * @param fi the entry in the publish-structure
933  * @param length length of the file or directory
934  * @param meta metadata for the file or directory (can be modified)
935  * @param uri pointer to the keywords that will be used for this entry (can be modified)
936  * @param anonymity pointer to selected anonymity level (can be modified)
937  * @param priority pointer to selected priority (can be modified)
938  * @param expirationTime pointer to selected expiration time (can be modified)
939  * @param client_info pointer to client context set upon creation (can be modified)
940  * @return GNUNET_OK to continue (always)
941  */
942 static int
943 fip_signal_resume(void *cls,
944                   struct GNUNET_FS_FileInformation *fi,
945                   uint64_t length,
946                   struct GNUNET_CONTAINER_MetaData *meta,
947                   struct GNUNET_FS_Uri **uri,
948                   uint32_t *anonymity,
949                   uint32_t *priority,
950                   struct GNUNET_TIME_Absolute *expirationTime,
951                   void **client_info)
952 {
953   struct GNUNET_FS_PublishContext *sc = cls;
954   struct GNUNET_FS_ProgressInfo pi;
955
956   pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME;
957   pi.value.publish.specifics.resume.message = sc->fi->emsg;
958   pi.value.publish.specifics.resume.chk_uri = sc->fi->chk_uri;
959   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
960   return GNUNET_OK;
961 }
962
963
964 /**
965  * Function called with a filename of serialized publishing operation
966  * to deserialize.
967  *
968  * @param cls the 'struct GNUNET_FS_Handle*'
969  * @param filename complete filename (absolute path)
970  * @return GNUNET_OK (continue to iterate)
971  */
972 static int
973 deserialize_publish_file (void *cls,
974                           const char *filename)
975 {
976   struct GNUNET_FS_Handle *h = cls;
977   struct GNUNET_BIO_ReadHandle *rh;
978   struct GNUNET_FS_PublishContext *pc;
979   int32_t options;
980   int32_t all_done;
981   char *fi_root;
982   char *ns;
983   char *fi_pos;
984   char *emsg;
985
986   pc = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
987   pc->h = h;
988   fi_root = NULL;
989   fi_pos = NULL;
990   ns = NULL;
991   rh = GNUNET_BIO_read_open (filename);
992   if (rh == NULL)
993     goto cleanup;
994   if ( (GNUNET_OK !=
995         GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) ||
996        (GNUNET_OK !=
997         GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) ||
998        (GNUNET_OK !=
999         GNUNET_BIO_read_int32 (rh, &options)) ||
1000        (GNUNET_OK !=
1001         GNUNET_BIO_read_int32 (rh, &all_done)) ||
1002        (GNUNET_OK !=
1003         GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) ||
1004        (GNUNET_OK !=
1005         GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) ||
1006        (GNUNET_OK !=
1007         GNUNET_BIO_read_string (rh, "publish-ns", &ns, 1024)) )
1008     goto cleanup;          
1009   pc->options = options;
1010   pc->all_done = all_done;
1011   pc->fi = deserialize_file_information (h, fi_root);
1012   if (pc->fi == NULL)
1013     goto cleanup;    
1014   if (ns != NULL)
1015     {
1016       pc->namespace = GNUNET_FS_namespace_create (h, ns);
1017       if (pc->namespace == NULL)
1018         {
1019           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1020                       _("Failed to recover namespace `%s', cannot resume publishing operation.\n"),
1021                       ns);
1022           goto cleanup;
1023         }
1024     }
1025   if (fi_pos != NULL)
1026     {
1027       pc->fi_pos = find_file_position (pc->fi,
1028                                        fi_pos);
1029       GNUNET_free (fi_pos);
1030       if (pc->fi_pos == NULL)
1031         {
1032           /* failed to find position for resuming, outch! Will start from root! */
1033           GNUNET_break (0);
1034           if (pc->all_done != GNUNET_YES)
1035             pc->fi_pos = pc->fi;
1036         }
1037     }
1038   pc->serialization = get_serialization_short_name (filename);
1039   /* generate RESUME event(s) */
1040   GNUNET_FS_file_information_inspect (pc->fi,
1041                                       &fip_signal_resume,
1042                                       pc);
1043   
1044   /* re-start publishing (if needed)... */
1045   if (pc->all_done != GNUNET_YES)
1046     pc->upload_task 
1047       = GNUNET_SCHEDULER_add_with_priority (h->sched,
1048                                             GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1049                                             &GNUNET_FS_publish_main_,
1050                                             pc);       
1051   if (GNUNET_OK !=
1052       GNUNET_BIO_read_close (rh, &emsg))
1053     {
1054       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1055                   _("Failed to resume publishing operation `%s': %s\n"),
1056                   filename,
1057                   emsg);
1058       GNUNET_free (emsg);
1059     }
1060   return GNUNET_OK;
1061  cleanup:
1062   GNUNET_free_non_null (pc->nid);
1063   GNUNET_free_non_null (pc->nuid);
1064   GNUNET_free_non_null (fi_root);
1065   GNUNET_free_non_null (ns);
1066   if ( (rh != NULL) &&
1067        (GNUNET_OK !=
1068         GNUNET_BIO_read_close (rh, &emsg)) )
1069     {
1070       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1071                   _("Failed to resume publishing operation `%s': %s\n"),
1072                   filename,
1073                   emsg);
1074       GNUNET_free (emsg);
1075     }
1076   if (pc->fi != NULL)
1077     GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
1078   remove_sync_file (h, "publish", pc->serialization);
1079   GNUNET_free_non_null (pc->serialization);
1080   GNUNET_free (pc);
1081   return GNUNET_OK;
1082 }
1083
1084
1085 /**
1086  * Synchronize this publishing struct with its mirror
1087  * on disk.  Note that all internal FS-operations that change
1088  * publishing structs should already call "sync" internally,
1089  * so this function is likely not useful for clients.
1090  * 
1091  * @param pc the struct to sync
1092  */
1093 void
1094 GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc)
1095 {  
1096   struct GNUNET_BIO_WriteHandle *wh;
1097
1098   if (NULL == pc->serialization)
1099     pc->serialization = make_serialization_file_name (pc->h,
1100                                                       "publish");
1101   if (NULL == pc->serialization)
1102     return;
1103   if (NULL == pc->fi)
1104     return;
1105   if (NULL == pc->fi->serialization)
1106     {
1107       GNUNET_break (0);
1108       return;
1109     }
1110   wh = get_write_handle (pc->h, "publish", pc->serialization);
1111  if ( (GNUNET_OK !=
1112         GNUNET_BIO_write_string (wh, pc->nid)) ||
1113        (GNUNET_OK !=
1114         GNUNET_BIO_write_string (wh, pc->nuid)) ||
1115        (GNUNET_OK !=
1116         GNUNET_BIO_write_int32 (wh, pc->options)) ||
1117        (GNUNET_OK !=
1118         GNUNET_BIO_write_int32 (wh, pc->all_done)) ||
1119        (GNUNET_OK !=
1120         GNUNET_BIO_write_string (wh, pc->fi->serialization)) ||
1121        (GNUNET_OK !=
1122         GNUNET_BIO_write_string (wh, (pc->fi_pos == NULL) ? NULL : pc->fi_pos->serialization)) ||
1123        (GNUNET_OK !=
1124         GNUNET_BIO_write_string (wh, (pc->namespace == NULL) ? NULL : pc->namespace->name)) )
1125    {
1126      (void) GNUNET_BIO_write_close (wh);
1127      remove_sync_file (pc->h, "publish", pc->serialization);
1128      GNUNET_free (pc->serialization);
1129      pc->serialization = NULL;
1130      return;
1131    }
1132  if (GNUNET_OK !=
1133      GNUNET_BIO_write_close (wh))
1134    {
1135      remove_sync_file (pc->h, "publish", pc->serialization);
1136      GNUNET_free (pc->serialization);
1137      pc->serialization = NULL;
1138      return;     
1139    }  
1140 }
1141
1142
1143 /**
1144  * Deserialize information about pending publish operations.
1145  *
1146  * @param h master context
1147  */
1148 static void
1149 deserialize_publish (struct GNUNET_FS_Handle *h)
1150 {
1151   char *dn;
1152
1153   dn = get_serialization_file_name (h, "publish", "");
1154   if (dn == NULL)
1155     return;
1156   GNUNET_DISK_directory_scan (dn, &deserialize_publish_file, h);
1157   GNUNET_free (dn);
1158 }
1159
1160
1161 /**
1162  * Setup a connection to the file-sharing service.
1163  *
1164  * @param sched scheduler to use
1165  * @param cfg configuration to use
1166  * @param client_name unique identifier for this client 
1167  * @param upcb function to call to notify about FS actions
1168  * @param upcb_cls closure for upcb
1169  * @param flags specific attributes for fs-operations
1170  * @param ... list of optional options, terminated with GNUNET_FS_OPTIONS_END
1171  * @return NULL on error
1172  */
1173 struct GNUNET_FS_Handle *
1174 GNUNET_FS_start (struct GNUNET_SCHEDULER_Handle *sched,
1175                  const struct GNUNET_CONFIGURATION_Handle *cfg,
1176                  const char *client_name,
1177                  GNUNET_FS_ProgressCallback upcb,
1178                  void *upcb_cls,
1179                  enum GNUNET_FS_Flags flags,
1180                  ...)
1181 {
1182   struct GNUNET_FS_Handle *ret;
1183   struct GNUNET_CLIENT_Connection *client;
1184   enum GNUNET_FS_OPTIONS opt;
1185   va_list ap;
1186
1187   client = GNUNET_CLIENT_connect (sched,
1188                                   "fs",
1189                                   cfg);
1190   if (NULL == client)
1191     return NULL;
1192   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Handle));
1193   ret->sched = sched;
1194   ret->cfg = cfg;
1195   ret->client_name = GNUNET_strdup (client_name);
1196   ret->upcb = upcb;
1197   ret->upcb_cls = upcb_cls;
1198   ret->client = client;
1199   ret->flags = flags;
1200   ret->max_parallel_downloads = 1;
1201   ret->max_parallel_requests = 1;
1202   ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */
1203   va_start (ap, flags);  
1204   while (GNUNET_FS_OPTIONS_END != (opt = va_arg (ap, enum GNUNET_FS_OPTIONS)))
1205     {
1206       switch (opt)
1207         {
1208         case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM:
1209           ret->max_parallel_downloads = va_arg (ap, unsigned int);
1210           break;
1211         case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM:
1212           ret->max_parallel_requests = va_arg (ap, unsigned int);
1213           break;
1214         default:
1215           GNUNET_break (0);
1216           GNUNET_free (ret->client_name);
1217           GNUNET_free (ret);
1218           va_end (ap);
1219           return NULL;
1220         }
1221     }
1222   va_end (ap);
1223   // FIXME: setup receive-loop with client (do we need one?)
1224
1225   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags))
1226     {
1227       deserialize_publish (ret);
1228       /* FIXME: not implemented! */
1229       // Deserialize Search:
1230       // * read search queries
1231       // * for each query, read file with search results
1232       // * for each search result with active download, deserialize download
1233       // * for each directory search result, check for active downloads of contents
1234       // Deserialize Download:
1235       // * always part of search???
1236       // Deserialize Unindex:
1237       // * read FNs for unindex with progress offset
1238     }
1239   return ret;
1240 }
1241
1242
1243 /**
1244  * Close our connection with the file-sharing service.
1245  * The callback given to GNUNET_FS_start will no longer be
1246  * called after this function returns.
1247  *
1248  * @param h handle that was returned from GNUNET_FS_start
1249  */                    
1250 void 
1251 GNUNET_FS_stop (struct GNUNET_FS_Handle *h)
1252 {
1253   if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & h->flags))
1254     {
1255       // FIXME: generate SUSPEND events and clean up state!
1256     }
1257   // FIXME: terminate receive-loop with client  (do we need one?)
1258   if (h->queue_job != GNUNET_SCHEDULER_NO_TASK)
1259     GNUNET_SCHEDULER_cancel (h->sched,
1260                              h->queue_job);
1261   GNUNET_CLIENT_disconnect (h->client, GNUNET_NO);
1262   GNUNET_free (h->client_name);
1263   GNUNET_free (h);
1264 }
1265
1266
1267 /* end of fs.c */