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