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