-simplify logic
[oweals/gnunet.git] / src / fs / fs_publish.c
1 /*
2      This file is part of GNUnet.
3      (C) 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 3, 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  * @file fs/fs_publish.c
22  * @brief publish a file or directory in GNUnet
23  * @see https://gnunet.org/encoding
24  * @author Krista Bennett
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_signatures.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_fs_service.h"
32 #include "fs_api.h"
33 #include "fs_tree.h"
34
35
36 /**
37  * Fill in all of the generic fields for
38  * a publish event and call the callback.
39  *
40  * @param pi structure to fill in
41  * @param pc overall publishing context
42  * @param p file information for the file being published
43  * @param offset where in the file are we so far
44  * @return value returned from callback
45  */
46 void *
47 GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
48                                 struct GNUNET_FS_PublishContext *pc,
49                                 const struct GNUNET_FS_FileInformation *p,
50                                 uint64_t offset)
51 {
52   pi->value.publish.pc = pc;
53   pi->value.publish.fi = p;
54   pi->value.publish.cctx = p->client_info;
55   pi->value.publish.pctx = (NULL == p->dir) ? NULL : p->dir->client_info;
56   pi->value.publish.filename = p->filename;
57   pi->value.publish.size =
58       (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size;
59   pi->value.publish.eta =
60       GNUNET_TIME_calculate_eta (p->start_time, offset,
61                                  pi->value.publish.size);
62   pi->value.publish.completed = offset;
63   pi->value.publish.duration =
64       GNUNET_TIME_absolute_get_duration (p->start_time);
65   pi->value.publish.anonymity = p->bo.anonymity_level;
66   pi->fsh = pc->h;
67   return pc->h->upcb (pc->h->upcb_cls, pi);
68 }
69
70
71 /**
72  * Cleanup the publish context, we're done with it.
73  *
74  * @param pc struct to clean up
75  */
76 static void
77 publish_cleanup (struct GNUNET_FS_PublishContext *pc)
78 {
79   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
80               "Cleaning up publish context (done!)\n");
81   if (NULL != pc->fhc)
82   {
83     GNUNET_CRYPTO_hash_file_cancel (pc->fhc);
84     pc->fhc = NULL;
85   }
86   GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
87   GNUNET_free_non_null (pc->nid);
88   GNUNET_free_non_null (pc->nuid);
89   GNUNET_free_non_null (pc->serialization);
90   if (NULL != pc->dsh)
91   {
92     GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO);
93     pc->dsh = NULL;
94   }
95   if (NULL != pc->client)
96   {
97     GNUNET_CLIENT_disconnect (pc->client);
98     pc->client = NULL;
99   }
100   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
101   GNUNET_free (pc);
102 }
103
104
105 /**
106  * Function called by the datastore API with
107  * the result from the PUT request.
108  *
109  * @param cls the `struct GNUNET_FS_PublishContext *`
110  * @param success #GNUNET_OK on success
111  * @param min_expiration minimum expiration time required for content to be stored
112  * @param msg error message (or NULL)
113  */
114 static void
115 ds_put_cont (void *cls, int success,
116              struct GNUNET_TIME_Absolute min_expiration,
117              const char *msg)
118 {
119   struct GNUNET_FS_PublishContext *pc = cls;
120   struct GNUNET_FS_ProgressInfo pi;
121
122   pc->qre = NULL;
123   if (GNUNET_SYSERR == success)
124   {
125     GNUNET_asprintf (&pc->fi_pos->emsg,
126                      _("Publishing failed: %s"),
127                      msg);
128     pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
129     pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
130     pi.value.publish.specifics.error.message = pc->fi_pos->emsg;
131     pc->fi_pos->client_info =
132         GNUNET_FS_publish_make_status_ (&pi, pc, pc->fi_pos, 0);
133     if ((pc->fi_pos->is_directory != GNUNET_YES) &&
134         (pc->fi_pos->filename != NULL) &&
135         (pc->fi_pos->data.file.do_index == GNUNET_YES))
136     {
137       /* run unindex to clean up */
138       GNUNET_FS_unindex_start (pc->h, pc->fi_pos->filename, NULL);
139     }
140   }
141   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
142   pc->upload_task =
143       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
144                                           &GNUNET_FS_publish_main_, pc);
145 }
146
147
148 /**
149  * Generate the callback that signals clients
150  * that a file (or directory) has been completely
151  * published.
152  *
153  * @param p the completed upload
154  * @param pc context of the publication
155  */
156 static void
157 signal_publish_completion (struct GNUNET_FS_FileInformation *p,
158                            struct GNUNET_FS_PublishContext *pc)
159 {
160   struct GNUNET_FS_ProgressInfo pi;
161
162   pi.status = GNUNET_FS_STATUS_PUBLISH_COMPLETED;
163   pi.value.publish.eta = GNUNET_TIME_UNIT_ZERO;
164   pi.value.publish.specifics.completed.chk_uri = p->chk_uri;
165   pi.value.publish.specifics.completed.sks_uri = p->sks_uri;
166   p->client_info =
167       GNUNET_FS_publish_make_status_ (&pi, pc, p,
168                                       p->data.file.file_size);
169 }
170
171
172 /**
173  * Generate the callback that signals clients
174  * that a file (or directory) has encountered
175  * a problem during publication.
176  *
177  * @param p the upload that had trouble
178  * @param pc context of the publication
179  * @param emsg error message
180  */
181 static void
182 signal_publish_error (struct GNUNET_FS_FileInformation *p,
183                       struct GNUNET_FS_PublishContext *pc,
184                       const char *emsg)
185 {
186   struct GNUNET_FS_ProgressInfo pi;
187
188   p->emsg = GNUNET_strdup (emsg);
189   pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
190   pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
191   pi.value.publish.specifics.error.message = emsg;
192   p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
193   if ((p->is_directory != GNUNET_YES) && (p->filename != NULL) &&
194       (p->data.file.do_index == GNUNET_YES))
195   {
196     /* run unindex to clean up */
197     GNUNET_FS_unindex_start (pc->h, p->filename, NULL);
198   }
199
200 }
201
202
203 /**
204  * Datastore returns from reservation cancel request.
205  *
206  * @param cls the `struct GNUNET_FS_PublishContext *`
207  * @param success success code (not used)
208  * @param min_expiration minimum expiration time required for content to be stored
209  * @param msg error message (typically NULL, not used)
210  */
211 static void
212 finish_release_reserve (void *cls, int success,
213                         struct GNUNET_TIME_Absolute min_expiration,
214                         const char *msg)
215 {
216   struct GNUNET_FS_PublishContext *pc = cls;
217
218   pc->qre = NULL;
219   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
220               "Releasing reserve done!\n");
221   signal_publish_completion (pc->fi, pc);
222   pc->all_done = GNUNET_YES;
223   GNUNET_FS_publish_sync_ (pc);
224 }
225
226
227 /**
228  * We've finished publishing the SBlock as part of a larger upload.
229  * Check the result and complete the larger upload.
230  *
231  * @param cls the `struct GNUNET_FS_PublishContext *` of the larger upload
232  * @param uri URI of the published SBlock
233  * @param emsg NULL on success, otherwise error message
234  */
235 static void
236 publish_sblocks_cont (void *cls,
237                       const struct GNUNET_FS_Uri *uri,
238                       const char *emsg)
239 {
240   struct GNUNET_FS_PublishContext *pc = cls;
241
242   pc->sks_pc = NULL;
243   if (NULL != emsg)
244   {
245     signal_publish_error (pc->fi, pc, emsg);
246     GNUNET_FS_publish_sync_ (pc);
247     return;
248   }
249   if (NULL != uri)
250   {
251     /* sks publication, remember namespace URI */
252     pc->fi->sks_uri = GNUNET_FS_uri_dup (uri);
253   }
254   GNUNET_assert (pc->qre == NULL);
255   if ((pc->dsh != NULL) && (pc->rid != 0))
256   {
257     pc->qre =
258         GNUNET_DATASTORE_release_reserve (pc->dsh, pc->rid, UINT_MAX, UINT_MAX,
259                                           GNUNET_TIME_UNIT_FOREVER_REL,
260                                           &finish_release_reserve, pc);
261   }
262   else
263   {
264     finish_release_reserve (pc, GNUNET_OK, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
265   }
266 }
267
268
269 /**
270  * We are almost done publishing the structure,
271  * add SBlocks (if needed).
272  *
273  * @param pc overall upload data
274  */
275 static void
276 publish_sblock (struct GNUNET_FS_PublishContext *pc)
277 {
278   if (NULL != pc->ns)
279     pc->sks_pc = GNUNET_FS_publish_sks (pc->h,
280                                         pc->ns,
281                                         pc->nid,
282                                         pc->nuid,
283                                         pc->fi->meta,
284                                         pc->fi->chk_uri,
285                                         &pc->fi->bo,
286                                         pc->options,
287                                         &publish_sblocks_cont, pc);
288   else
289     publish_sblocks_cont (pc, NULL, NULL);
290 }
291
292
293 /**
294  * We've finished publishing a KBlock as part of a larger upload.
295  * Check the result and continue the larger upload.
296  *
297  * @param cls the `struct GNUNET_FS_PublishContext *`
298  *        of the larger upload
299  * @param uri URI of the published blocks
300  * @param emsg NULL on success, otherwise error message
301  */
302 static void
303 publish_kblocks_cont (void *cls,
304                       const struct GNUNET_FS_Uri *uri,
305                       const char *emsg)
306 {
307   struct GNUNET_FS_PublishContext *pc = cls;
308   struct GNUNET_FS_FileInformation *p = pc->fi_pos;
309
310   pc->ksk_pc = NULL;
311   if (NULL != emsg)
312   {
313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
314                 "Error uploading KSK blocks: %s\n",
315                 emsg);
316     signal_publish_error (p, pc, emsg);
317     GNUNET_FS_file_information_sync_ (p);
318     GNUNET_FS_publish_sync_ (pc);
319     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
320     pc->upload_task =
321       GNUNET_SCHEDULER_add_with_priority
322       (GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
323        &GNUNET_FS_publish_main_,
324        pc);
325     return;
326   }
327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
328               "KSK blocks published, moving on to next file\n");
329   if (NULL != p->dir)
330     signal_publish_completion (p, pc);
331   /* move on to next file */
332   if (NULL != p->next)
333     pc->fi_pos = p->next;
334   else
335     pc->fi_pos = p->dir;
336   GNUNET_FS_publish_sync_ (pc);
337   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
338   pc->upload_task =
339       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
340                                           &GNUNET_FS_publish_main_, pc);
341 }
342
343
344 /**
345  * Function called by the tree encoder to obtain
346  * a block of plaintext data (for the lowest level
347  * of the tree).
348  *
349  * @param cls our publishing context
350  * @param offset identifies which block to get
351  * @param max (maximum) number of bytes to get; returning
352  *        fewer will also cause errors
353  * @param buf where to copy the plaintext buffer
354  * @param emsg location to store an error message (on error)
355  * @return number of bytes copied to buf, 0 on error
356  */
357 static size_t
358 block_reader (void *cls,
359               uint64_t offset,
360               size_t max,
361               void *buf,
362               char **emsg)
363 {
364   struct GNUNET_FS_PublishContext *pc = cls;
365   struct GNUNET_FS_FileInformation *p;
366   const char *dd;
367   size_t pt_size;
368
369   p = pc->fi_pos;
370   if (GNUNET_YES == p->is_directory)
371   {
372     pt_size = GNUNET_MIN (max, p->data.dir.dir_size - offset);
373     dd = p->data.dir.dir_data;
374     memcpy (buf, &dd[offset], pt_size);
375   }
376   else
377   {
378     if (UINT64_MAX == offset)
379     {
380       if (&GNUNET_FS_data_reader_file_ == p->data.file.reader)
381       {
382         /* force closing the file to avoid keeping too many files open */
383         p->data.file.reader (p->data.file.reader_cls, offset, 0, NULL, NULL);
384       }
385       return 0;
386     }
387     pt_size = GNUNET_MIN (max, p->data.file.file_size - offset);
388     if (0 == pt_size)
389       return 0;                 /* calling reader with pt_size==0
390                                  * might free buf, so don't! */
391     if (pt_size !=
392         p->data.file.reader (p->data.file.reader_cls, offset, pt_size, buf,
393                              emsg))
394       return 0;
395   }
396   return pt_size;
397 }
398
399
400 /**
401  * The tree encoder has finished processing a
402  * file.   Call it's finish method and deal with
403  * the final result.
404  *
405  * @param cls our publishing context
406  * @param tc scheduler's task context (not used)
407  */
408 static void
409 encode_cont (void *cls,
410              const struct GNUNET_SCHEDULER_TaskContext *tc)
411 {
412   struct GNUNET_FS_PublishContext *pc = cls;
413   struct GNUNET_FS_FileInformation *p;
414   struct GNUNET_FS_ProgressInfo pi;
415   char *emsg;
416   uint64_t flen;
417
418   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
419               "Finished with tree encoder\n");
420   p = pc->fi_pos;
421   p->chk_uri = GNUNET_FS_tree_encoder_get_uri (p->te);
422   GNUNET_FS_file_information_sync_ (p);
423   GNUNET_FS_tree_encoder_finish (p->te, &emsg);
424   p->te = NULL;
425   if (NULL != emsg)
426   {
427     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
428                 "Error during tree walk: %s\n",
429                 emsg);
430     GNUNET_asprintf (&p->emsg,
431                      _("Publishing failed: %s"),
432                      emsg);
433     GNUNET_free (emsg);
434     pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
435     pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
436     pi.value.publish.specifics.error.message = p->emsg;
437     p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
438   }
439   else
440   {
441     /* final progress event */
442     GNUNET_assert (NULL != p->chk_uri);
443     flen = GNUNET_FS_uri_chk_get_file_size (p->chk_uri);
444     pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS;
445     pi.value.publish.specifics.progress.data = NULL;
446     pi.value.publish.specifics.progress.offset = flen;
447     pi.value.publish.specifics.progress.data_len = 0;
448     pi.value.publish.specifics.progress.depth = GNUNET_FS_compute_depth (flen);
449     p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, flen);
450   }
451   /* continue with main */  /* continue with main */
452   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
453   pc->upload_task =
454       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
455                                           &GNUNET_FS_publish_main_, pc);
456 }
457
458
459 /**
460  * Function called asking for the current (encoded)
461  * block to be processed.  After processing the
462  * client should either call #GNUNET_FS_tree_encoder_next
463  * or (on error) #GNUNET_FS_tree_encoder_finish.
464  *
465  * @param cls closure
466  * @param chk content hash key for the block
467  * @param offset offset of the block in the file
468  * @param depth depth of the block in the file, 0 for DBLOCK
469  * @param type type of the block (IBLOCK or DBLOCK)
470  * @param block the (encrypted) block
471  * @param block_size size of @a block (in bytes)
472  */
473 static void
474 block_proc (void *cls,
475             const struct ContentHashKey *chk,
476             uint64_t offset,
477             unsigned int depth,
478             enum GNUNET_BLOCK_Type type,
479             const void *block,
480             uint16_t block_size)
481 {
482   struct GNUNET_FS_PublishContext *pc = cls;
483   struct GNUNET_FS_FileInformation *p;
484   struct OnDemandBlock odb;
485
486   p = pc->fi_pos;
487   if (NULL == pc->dsh)
488   {
489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Waiting for datastore connection\n");
490     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
491     pc->upload_task =
492         GNUNET_SCHEDULER_add_with_priority
493         (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, pc);
494     return;
495   }
496
497   if ( (GNUNET_YES != p->is_directory) &&
498        (GNUNET_YES == p->data.file.do_index) &&
499        (GNUNET_BLOCK_TYPE_FS_DBLOCK == type) )
500   {
501     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502                 "Indexing block `%s' for offset %llu with index size %u\n",
503                 GNUNET_h2s (&chk->query), (unsigned long long) offset,
504                 sizeof (struct OnDemandBlock));
505     odb.offset = GNUNET_htonll (offset);
506     odb.file_id = p->data.file.file_id;
507     GNUNET_assert (pc->qre == NULL);
508     pc->qre =
509         GNUNET_DATASTORE_put (pc->dsh, (p->is_directory == GNUNET_YES) ? 0 : pc->rid,
510                               &chk->query, sizeof (struct OnDemandBlock), &odb,
511                               GNUNET_BLOCK_TYPE_FS_ONDEMAND,
512                               p->bo.content_priority, p->bo.anonymity_level,
513                               p->bo.replication_level, p->bo.expiration_time,
514                               -2, 1, GNUNET_CONSTANTS_SERVICE_TIMEOUT,
515                               &ds_put_cont, pc);
516     return;
517   }
518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
519               "Publishing block `%s' for offset %llu with size %u\n",
520               GNUNET_h2s (&chk->query), (unsigned long long) offset,
521               (unsigned int) block_size);
522   GNUNET_assert (pc->qre == NULL);
523   pc->qre =
524       GNUNET_DATASTORE_put (pc->dsh, (p->is_directory == GNUNET_YES) ? 0 : pc->rid,
525                             &chk->query, block_size, block, type,
526                             p->bo.content_priority, p->bo.anonymity_level,
527                             p->bo.replication_level, p->bo.expiration_time, -2,
528                             1, GNUNET_CONSTANTS_SERVICE_TIMEOUT, &ds_put_cont,
529                             pc);
530 }
531
532
533 /**
534  * Function called with information about our
535  * progress in computing the tree encoding.
536  *
537  * @param cls closure
538  * @param offset where are we in the file
539  * @param pt_block plaintext of the currently processed block
540  * @param pt_size size of @a pt_block
541  * @param depth depth of the block in the tree, 0 for DBLOCK
542  */
543 static void
544 progress_proc (void *cls, uint64_t offset,
545                const void *pt_block,
546                size_t pt_size,
547                unsigned int depth)
548 {
549   struct GNUNET_FS_PublishContext *pc = cls;
550   struct GNUNET_FS_FileInformation *p;
551   struct GNUNET_FS_FileInformation *par;
552   struct GNUNET_FS_ProgressInfo pi;
553
554   p = pc->fi_pos;
555   pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS;
556   pi.value.publish.specifics.progress.data = pt_block;
557   pi.value.publish.specifics.progress.offset = offset;
558   pi.value.publish.specifics.progress.data_len = pt_size;
559   pi.value.publish.specifics.progress.depth = depth;
560   p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, offset);
561   if ( (0 != depth) ||
562        (GNUNET_YES == p->is_directory) )
563     return;
564   while (NULL != (par = p->dir))
565   {
566     p = par;
567     GNUNET_assert (GNUNET_YES == par->is_directory);
568     p->data.dir.contents_completed += pt_size;
569     pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY;
570     pi.value.publish.specifics.progress_directory.completed = p->data.dir.contents_completed;
571     pi.value.publish.specifics.progress_directory.total = p->data.dir.contents_size;
572     pi.value.publish.specifics.progress_directory.eta = GNUNET_TIME_calculate_eta (p->start_time,
573                                                                                    p->data.dir.contents_completed,
574                                                                                    p->data.dir.contents_size);
575     p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
576
577   }
578 }
579
580
581 /**
582  * We are uploading a file or directory; load (if necessary) the next
583  * block into memory, encrypt it and send it to the FS service.  Then
584  * continue with the main task.
585  *
586  * @param pc overall upload data
587  */
588 static void
589 publish_content (struct GNUNET_FS_PublishContext *pc)
590 {
591   struct GNUNET_FS_FileInformation *p;
592   char *emsg;
593   struct GNUNET_FS_DirectoryBuilder *db;
594   struct GNUNET_FS_FileInformation *dirpos;
595   void *raw_data;
596   uint64_t size;
597
598   p = pc->fi_pos;
599   GNUNET_assert (NULL != p);
600   if (NULL == p->te)
601   {
602     if (GNUNET_YES == p->is_directory)
603     {
604       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating directory\n");
605       db = GNUNET_FS_directory_builder_create (p->meta);
606       dirpos = p->data.dir.entries;
607       while (NULL != dirpos)
608       {
609         if (GNUNET_YES == dirpos->is_directory)
610         {
611           raw_data = dirpos->data.dir.dir_data;
612           dirpos->data.dir.dir_data = NULL;
613         }
614         else
615         {
616           raw_data = NULL;
617           if ((dirpos->data.file.file_size < MAX_INLINE_SIZE) &&
618               (dirpos->data.file.file_size > 0))
619           {
620             raw_data = GNUNET_malloc (dirpos->data.file.file_size);
621             emsg = NULL;
622             if (dirpos->data.file.file_size !=
623                 dirpos->data.file.reader (dirpos->data.file.reader_cls, 0,
624                                           dirpos->data.file.file_size, raw_data,
625                                           &emsg))
626             {
627               GNUNET_free_non_null (emsg);
628               GNUNET_free (raw_data);
629               raw_data = NULL;
630             }
631             dirpos->data.file.reader (dirpos->data.file.reader_cls, UINT64_MAX, 0, 0, NULL);
632           }
633         }
634         GNUNET_FS_directory_builder_add (db, dirpos->chk_uri, dirpos->meta,
635                                          raw_data);
636         GNUNET_free_non_null (raw_data);
637         dirpos = dirpos->next;
638       }
639       GNUNET_free_non_null (p->data.dir.dir_data);
640       p->data.dir.dir_data = NULL;
641       p->data.dir.dir_size = 0;
642       GNUNET_FS_directory_builder_finish (db, &p->data.dir.dir_size,
643                                           &p->data.dir.dir_data);
644       GNUNET_FS_file_information_sync_ (p);
645     }
646     size = (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size;
647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
648                 "Creating tree encoder\n");
649     p->te =
650         GNUNET_FS_tree_encoder_create (pc->h, size, pc, &block_reader,
651                                        &block_proc, &progress_proc,
652                                        &encode_cont);
653
654   }
655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
656               "Processing next block from tree\n");
657   GNUNET_FS_tree_encoder_next (p->te);
658 }
659
660
661 /**
662  * Process the response (or lack thereof) from
663  * the "fs" service to our 'start index' request.
664  *
665  * @param cls closure (of type `struct GNUNET_FS_PublishContext *`)
666  * @param msg the response we got
667  */
668 static void
669 process_index_start_response (void *cls,
670                               const struct GNUNET_MessageHeader *msg)
671 {
672   struct GNUNET_FS_PublishContext *pc = cls;
673   struct GNUNET_FS_FileInformation *p;
674   const char *emsg;
675   uint16_t msize;
676
677   GNUNET_CLIENT_disconnect (pc->client);
678   pc->client = NULL;
679   p = pc->fi_pos;
680   if (NULL == msg)
681   {
682     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
683                 _("Can not index file `%s': %s.  Will try to insert instead.\n"),
684                 p->filename,
685                 _("timeout on index-start request to `fs' service"));
686     p->data.file.do_index = GNUNET_NO;
687     GNUNET_FS_file_information_sync_ (p);
688     publish_content (pc);
689     return;
690   }
691   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK)
692   {
693     msize = ntohs (msg->size);
694     emsg = (const char *) &msg[1];
695     if ((msize <= sizeof (struct GNUNET_MessageHeader)) ||
696         (emsg[msize - sizeof (struct GNUNET_MessageHeader) - 1] != '\0'))
697       emsg = gettext_noop ("unknown error");
698     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
699                 _
700                 ("Can not index file `%s': %s.  Will try to insert instead.\n"),
701                 p->filename, gettext (emsg));
702     p->data.file.do_index = GNUNET_NO;
703     GNUNET_FS_file_information_sync_ (p);
704     publish_content (pc);
705     return;
706   }
707   p->data.file.index_start_confirmed = GNUNET_YES;
708   /* success! continue with indexing */
709   GNUNET_FS_file_information_sync_ (p);
710   publish_content (pc);
711 }
712
713
714 /**
715  * Function called once the hash computation over an
716  * indexed file has completed.
717  *
718  * @param cls closure, our publishing context
719  * @param res resulting hash, NULL on error
720  */
721 static void
722 hash_for_index_cb (void *cls,
723                    const struct GNUNET_HashCode *res)
724 {
725   struct GNUNET_FS_PublishContext *pc = cls;
726   struct GNUNET_FS_FileInformation *p;
727   struct IndexStartMessage *ism;
728   size_t slen;
729   struct GNUNET_CLIENT_Connection *client;
730   uint64_t dev;
731   uint64_t ino;
732   char *fn;
733
734   pc->fhc = NULL;
735   p = pc->fi_pos;
736   if (NULL == res)
737   {
738     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
739                 _("Can not index file `%s': %s.  Will try to insert instead.\n"),
740                 p->filename,
741                 _("failed to compute hash"));
742     p->data.file.do_index = GNUNET_NO;
743     GNUNET_FS_file_information_sync_ (p);
744     publish_content (pc);
745     return;
746   }
747   if (GNUNET_YES == p->data.file.index_start_confirmed)
748   {
749     publish_content (pc);
750     return;
751   }
752   fn = GNUNET_STRINGS_filename_expand (p->filename);
753   GNUNET_assert (fn != NULL);
754   slen = strlen (fn) + 1;
755   if (slen >=
756       GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (struct IndexStartMessage))
757   {
758     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
759                 _
760                 ("Can not index file `%s': %s.  Will try to insert instead.\n"),
761                 fn, _("filename too long"));
762     GNUNET_free (fn);
763     p->data.file.do_index = GNUNET_NO;
764     GNUNET_FS_file_information_sync_ (p);
765     publish_content (pc);
766     return;
767   }
768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hash of indexed file `%s' is `%s'\n",
769               p->filename, GNUNET_h2s (res));
770   if (0 != (pc->options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
771   {
772     p->data.file.file_id = *res;
773     p->data.file.have_hash = GNUNET_YES;
774     p->data.file.index_start_confirmed = GNUNET_YES;
775     GNUNET_FS_file_information_sync_ (p);
776     publish_content (pc);
777     GNUNET_free (fn);
778     return;
779   }
780   client = GNUNET_CLIENT_connect ("fs", pc->h->cfg);
781   if (NULL == client)
782   {
783     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
784                 _("Can not index file `%s': %s.  Will try to insert instead.\n"),
785                 p->filename,
786                 _("could not connect to `fs' service"));
787     p->data.file.do_index = GNUNET_NO;
788     publish_content (pc);
789     GNUNET_free (fn);
790     return;
791   }
792   if (p->data.file.have_hash != GNUNET_YES)
793   {
794     p->data.file.file_id = *res;
795     p->data.file.have_hash = GNUNET_YES;
796     GNUNET_FS_file_information_sync_ (p);
797   }
798   ism = GNUNET_malloc (sizeof (struct IndexStartMessage) + slen);
799   ism->header.size = htons (sizeof (struct IndexStartMessage) + slen);
800   ism->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_START);
801   if (GNUNET_OK == GNUNET_DISK_file_get_identifiers (p->filename, &dev, &ino))
802   {
803     ism->device = GNUNET_htonll (dev);
804     ism->inode = GNUNET_htonll (ino);
805   }
806   else
807   {
808     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809                 _("Failed to get file identifiers for `%s'\n"), p->filename);
810   }
811   ism->file_id = *res;
812   memcpy (&ism[1], fn, slen);
813   GNUNET_free (fn);
814   pc->client = client;
815   GNUNET_break (GNUNET_YES ==
816                 GNUNET_CLIENT_transmit_and_get_response (client, &ism->header,
817                                                          GNUNET_TIME_UNIT_FOREVER_REL,
818                                                          GNUNET_YES,
819                                                          &process_index_start_response,
820                                                          pc));
821   GNUNET_free (ism);
822 }
823
824
825 /**
826  * We've computed the CHK/LOC URI, now publish the KSKs (if applicable).
827  *
828  * @param pc publishing context to do this for
829  */
830 static void
831 publish_kblocks (struct GNUNET_FS_PublishContext *pc)
832 {
833   struct GNUNET_FS_FileInformation *p;
834
835   p = pc->fi_pos;
836   /* upload of "p" complete, publish KBlocks! */
837   if (NULL != p->keywords)
838   {
839     pc->ksk_pc = GNUNET_FS_publish_ksk (pc->h,
840                                         p->keywords,
841                                         p->meta,
842                                         p->chk_uri,
843                                         &p->bo,
844                                         pc->options,
845                                         &publish_kblocks_cont, pc);
846   }
847   else
848   {
849     publish_kblocks_cont (pc, p->chk_uri, NULL);
850   }
851 }
852
853
854 /**
855  * Process the response (or lack thereof) from
856  * the "fs" service to our LOC sign request.
857  *
858  * @param cls closure (of type `struct GNUNET_FS_PublishContext *`)
859  * @param msg the response we got
860  */
861 static void
862 process_signature_response (void *cls,
863                             const struct GNUNET_MessageHeader *msg)
864 {
865   struct GNUNET_FS_PublishContext *pc = cls;
866   const struct ResponseLocSignatureMessage *sig;
867   struct GNUNET_FS_FileInformation *p;
868
869   p = pc->fi_pos;
870   if (NULL == msg)
871   {
872     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
873                 _("Can not create LOC URI. Will continue with CHK instead.\n"));
874     publish_kblocks (pc);
875     return;
876   }
877   if (sizeof (struct ResponseLocSignatureMessage) !=
878       ntohs (msg->size))
879   {
880     GNUNET_break (0);
881     publish_kblocks (pc);
882     return;
883   }
884   sig = (const struct ResponseLocSignatureMessage *) msg;
885   p->chk_uri->type = GNUNET_FS_URI_LOC;
886   /* p->data.loc.fi kept from CHK before */
887   p->chk_uri->data.loc.peer = sig->peer;
888   p->chk_uri->data.loc.expirationTime = GNUNET_TIME_absolute_ntoh (sig->expiration_time);
889   p->chk_uri->data.loc.contentSignature = sig->signature;
890   GNUNET_FS_file_information_sync_ (p);
891   GNUNET_FS_publish_sync_ (pc);
892   publish_kblocks (pc);
893 }
894
895
896 /**
897  * We're publishing without anonymity. Contact the FS service
898  * to create a signed LOC URI for further processing, then
899  * continue with KSKs.
900  *
901  * @param pc the publishing context do to this for
902  */
903 static void
904 create_loc_uri (struct GNUNET_FS_PublishContext *pc)
905 {
906   struct RequestLocSignatureMessage req;
907   struct GNUNET_FS_FileInformation *p;
908
909   if (NULL == pc->client)
910     pc->client = GNUNET_CLIENT_connect ("fs", pc->h->cfg);
911   if (NULL == pc->client)
912   {
913     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
914                 _("Can not create LOC URI. Will continue with CHK instead.\n"));
915     publish_kblocks (pc);
916     return;
917   }
918   p = pc->fi_pos;
919   req.header.size = htons (sizeof (struct RequestLocSignatureMessage));
920   req.header.type = htons (GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN);
921   req.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT);
922   req.expiration_time = GNUNET_TIME_absolute_hton (p->bo.expiration_time);
923   req.chk = p->chk_uri->data.chk.chk;
924   req.file_length = GNUNET_htonll (p->chk_uri->data.chk.file_length);
925   GNUNET_break (GNUNET_YES ==
926                 GNUNET_CLIENT_transmit_and_get_response (pc->client,
927                                                          &req.header,
928                                                          GNUNET_TIME_UNIT_FOREVER_REL,
929                                                          GNUNET_YES,
930                                                          &process_signature_response,
931                                                          pc));
932 }
933
934
935 /**
936  * Main function that performs the upload.
937  *
938  * @param cls `struct GNUNET_FS_PublishContext *` identifies the upload
939  * @param tc task context
940  */
941 void
942 GNUNET_FS_publish_main_ (void *cls,
943                          const struct GNUNET_SCHEDULER_TaskContext *tc)
944 {
945   struct GNUNET_FS_PublishContext *pc = cls;
946   struct GNUNET_FS_ProgressInfo pi;
947   struct GNUNET_FS_FileInformation *p;
948   char *fn;
949
950   pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
951   p = pc->fi_pos;
952   if (NULL == p)
953   {
954     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955                 "Publishing complete, now publishing SKS and KSK blocks.\n");
956     /* upload of entire hierarchy complete,
957      * publish namespace entries */
958     GNUNET_FS_publish_sync_ (pc);
959     publish_sblock (pc);
960     return;
961   }
962   /* find starting position */
963   while ( (GNUNET_YES == p->is_directory) &&
964           (NULL != p->data.dir.entries) &&
965           (NULL == p->emsg) &&
966           (NULL == p->data.dir.entries->chk_uri) )
967   {
968     p = p->data.dir.entries;
969     pc->fi_pos = p;
970     GNUNET_FS_publish_sync_ (pc);
971   }
972   /* abort on error */
973   if (NULL != p->emsg)
974   {
975     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
976                 "Error uploading: %s\n",
977                 p->emsg);
978     /* error with current file, abort all
979      * related files as well! */
980     while (NULL != p->dir)
981     {
982       fn = GNUNET_CONTAINER_meta_data_get_by_type (p->meta,
983                                                    EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME);
984       p = p->dir;
985       if (fn != NULL)
986       {
987         GNUNET_asprintf (&p->emsg,
988                          _("Recursive upload failed at `%s': %s"),
989                          fn,
990                          p->emsg);
991         GNUNET_free (fn);
992       }
993       else
994       {
995         GNUNET_asprintf (&p->emsg,
996                          _("Recursive upload failed: %s"),
997                          p->emsg);
998       }
999       pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
1000       pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
1001       pi.value.publish.specifics.error.message = p->emsg;
1002       p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
1003     }
1004     pc->all_done = GNUNET_YES;
1005     GNUNET_FS_publish_sync_ (pc);
1006     return;
1007   }
1008   /* handle completion */
1009   if (NULL != p->chk_uri)
1010   {
1011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1012                 "File upload complete, now publishing KSK blocks.\n");
1013     GNUNET_FS_publish_sync_ (pc);
1014
1015     if ( (0 == p->bo.anonymity_level) &&
1016          (GNUNET_YES !=
1017           GNUNET_FS_uri_test_loc (p->chk_uri)) )
1018     {
1019       /* zero anonymity, box CHK URI in LOC URI */
1020       create_loc_uri (pc);
1021     }
1022     else
1023     {
1024       publish_kblocks (pc);
1025     }
1026     return;
1027   }
1028   if ((GNUNET_YES != p->is_directory) && (p->data.file.do_index))
1029   {
1030     if (NULL == p->filename)
1031     {
1032       p->data.file.do_index = GNUNET_NO;
1033       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1034                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
1035                   "<no-name>",
1036                   _("needs to be an actual file"));
1037       GNUNET_FS_file_information_sync_ (p);
1038       publish_content (pc);
1039       return;
1040     }
1041     if (p->data.file.have_hash)
1042     {
1043       hash_for_index_cb (pc, &p->data.file.file_id);
1044     }
1045     else
1046     {
1047       p->start_time = GNUNET_TIME_absolute_get ();
1048       pc->fhc =
1049           GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, p->filename,
1050                                    HASHING_BLOCKSIZE, &hash_for_index_cb, pc);
1051     }
1052     return;
1053   }
1054   publish_content (pc);
1055 }
1056
1057
1058 /**
1059  * Signal the FS's progress function that we are starting
1060  * an upload.
1061  *
1062  * @param cls closure (of type `struct GNUNET_FS_PublishContext *`)
1063  * @param fi the entry in the publish-structure
1064  * @param length length of the file or directory
1065  * @param meta metadata for the file or directory (can be modified)
1066  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1067  * @param bo block options
1068  * @param do_index should we index?
1069  * @param client_info pointer to client context set upon creation (can be modified)
1070  * @return #GNUNET_OK to continue (always)
1071  */
1072 static int
1073 fip_signal_start (void *cls,
1074                   struct GNUNET_FS_FileInformation *fi,
1075                   uint64_t length,
1076                   struct GNUNET_CONTAINER_MetaData *meta,
1077                   struct GNUNET_FS_Uri **uri,
1078                   struct GNUNET_FS_BlockOptions *bo,
1079                   int *do_index,
1080                   void **client_info)
1081 {
1082   struct GNUNET_FS_PublishContext *pc = cls;
1083   struct GNUNET_FS_ProgressInfo pi;
1084   unsigned int kc;
1085   uint64_t left;
1086
1087   if (GNUNET_YES == pc->skip_next_fi_callback)
1088   {
1089     pc->skip_next_fi_callback = GNUNET_NO;
1090     return GNUNET_OK;
1091   }
1092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1093               "Starting publish operation\n");
1094   if (*do_index)
1095   {
1096     /* space for on-demand blocks */
1097     pc->reserve_space +=
1098         ((length + DBLOCK_SIZE -
1099           1) / DBLOCK_SIZE) * sizeof (struct OnDemandBlock);
1100   }
1101   else
1102   {
1103     /* space for DBlocks */
1104     pc->reserve_space += length;
1105   }
1106   /* entries for IBlocks and DBlocks, space for IBlocks */
1107   left = length;
1108   while (1)
1109   {
1110     left = (left + DBLOCK_SIZE - 1) / DBLOCK_SIZE;
1111     pc->reserve_entries += left;
1112     if (left <= 1)
1113       break;
1114     left = left * sizeof (struct ContentHashKey);
1115     pc->reserve_space += left;
1116   }
1117   pc->reserve_entries++;
1118   /* entries and space for keywords */
1119   if (NULL != *uri)
1120   {
1121     kc = GNUNET_FS_uri_ksk_get_keyword_count (*uri);
1122     pc->reserve_entries += kc;
1123     pc->reserve_space += GNUNET_SERVER_MAX_MESSAGE_SIZE * kc;
1124   }
1125   pi.status = GNUNET_FS_STATUS_PUBLISH_START;
1126   *client_info = GNUNET_FS_publish_make_status_ (&pi, pc, fi, 0);
1127   GNUNET_FS_file_information_sync_ (fi);
1128   if ((fi->is_directory) && (fi->dir != NULL))
1129   {
1130     /* We are a directory, and we are not top-level; process entries in directory */
1131     pc->skip_next_fi_callback = GNUNET_YES;
1132     GNUNET_FS_file_information_inspect (fi, &fip_signal_start, pc);
1133   }
1134   return GNUNET_OK;
1135 }
1136
1137
1138 /**
1139  * Actually signal the FS's progress function that we are suspending
1140  * an upload.
1141  *
1142  * @param fi the entry in the publish-structure
1143  * @param pc the publish context of which a file is being suspended
1144  */
1145 static void
1146 suspend_operation (struct GNUNET_FS_FileInformation *fi,
1147                    struct GNUNET_FS_PublishContext *pc)
1148 {
1149   struct GNUNET_FS_ProgressInfo pi;
1150   uint64_t off;
1151
1152   if (NULL != pc->ksk_pc)
1153   {
1154     GNUNET_FS_publish_ksk_cancel (pc->ksk_pc);
1155     pc->ksk_pc = NULL;
1156   }
1157   if (NULL != pc->sks_pc)
1158   {
1159     GNUNET_FS_publish_sks_cancel (pc->sks_pc);
1160     pc->sks_pc = NULL;
1161   }
1162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1163               "Suspending publish operation\n");
1164   GNUNET_free_non_null (fi->serialization);
1165   fi->serialization = NULL;
1166   off = (NULL == fi->chk_uri) ? 0 : (GNUNET_YES == fi->is_directory) ? fi->data.dir.dir_size : fi->data.file.file_size;
1167   pi.status = GNUNET_FS_STATUS_PUBLISH_SUSPEND;
1168   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, fi, off));
1169   if (NULL != pc->qre)
1170   {
1171     GNUNET_DATASTORE_cancel (pc->qre);
1172     pc->qre = NULL;
1173   }
1174   if (NULL != pc->dsh)
1175   {
1176     GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO);
1177     pc->dsh = NULL;
1178   }
1179   pc->rid = 0;
1180 }
1181
1182
1183 /**
1184  * Signal the FS's progress function that we are suspending
1185  * an upload.  Performs the recursion.
1186  *
1187  * @param cls closure (of type `struct GNUNET_FS_PublishContext *`)
1188  * @param fi the entry in the publish-structure
1189  * @param length length of the file or directory
1190  * @param meta metadata for the file or directory (can be modified)
1191  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1192  * @param bo block options
1193  * @param do_index should we index?
1194  * @param client_info pointer to client context set upon creation (can be modified)
1195  * @return #GNUNET_OK to continue (always)
1196  */
1197 static int
1198 fip_signal_suspend (void *cls,
1199                     struct GNUNET_FS_FileInformation *fi,
1200                     uint64_t length,
1201                     struct GNUNET_CONTAINER_MetaData *meta,
1202                     struct GNUNET_FS_Uri **uri,
1203                     struct GNUNET_FS_BlockOptions *bo,
1204                     int *do_index,
1205                     void **client_info)
1206 {
1207   struct GNUNET_FS_PublishContext *pc = cls;
1208
1209   if (GNUNET_YES == pc->skip_next_fi_callback)
1210   {
1211     pc->skip_next_fi_callback = GNUNET_NO;
1212     return GNUNET_OK;
1213   }
1214   if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta))
1215   {
1216     /* process entries in directory */
1217     pc->skip_next_fi_callback = GNUNET_YES;
1218     GNUNET_FS_file_information_inspect (fi, &fip_signal_suspend, pc);
1219   }
1220   suspend_operation (fi, pc);
1221   *client_info = NULL;
1222   return GNUNET_OK;
1223 }
1224
1225
1226 /**
1227  * Create SUSPEND event for the given publish operation
1228  * and then clean up our state (without stop signal).
1229  *
1230  * @param cls the `struct GNUNET_FS_PublishContext` to signal for
1231  */
1232 void
1233 GNUNET_FS_publish_signal_suspend_ (void *cls)
1234 {
1235   struct GNUNET_FS_PublishContext *pc = cls;
1236
1237   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1238   {
1239     GNUNET_SCHEDULER_cancel (pc->upload_task);
1240     pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1241   }
1242   pc->skip_next_fi_callback = GNUNET_YES;
1243   GNUNET_FS_file_information_inspect (pc->fi, &fip_signal_suspend, pc);
1244   suspend_operation (pc->fi, pc);
1245   GNUNET_FS_end_top (pc->h, pc->top);
1246   pc->top = NULL;
1247   publish_cleanup (pc);
1248 }
1249
1250
1251 /**
1252  * We have gotten a reply for our space reservation request.
1253  * Either fail (insufficient space) or start publishing for good.
1254  *
1255  * @param cls the `struct GNUNET_FS_PublishContext *`
1256  * @param success positive reservation ID on success
1257  * @param min_expiration minimum expiration time required for content to be stored
1258  * @param msg error message on error, otherwise NULL
1259  */
1260 static void
1261 finish_reserve (void *cls, int success,
1262                 struct GNUNET_TIME_Absolute min_expiration,
1263                 const char *msg)
1264 {
1265   struct GNUNET_FS_PublishContext *pc = cls;
1266
1267   pc->qre = NULL;
1268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reservation complete (%d)!\n", success);
1269   if ((msg != NULL) || (success <= 0))
1270   {
1271     GNUNET_asprintf (&pc->fi->emsg,
1272                      _("Insufficient space for publishing: %s"),
1273                      msg);
1274     signal_publish_error (pc->fi, pc, pc->fi->emsg);
1275     return;
1276   }
1277   pc->rid = success;
1278   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == pc->upload_task);
1279   pc->upload_task =
1280       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1281                                           &GNUNET_FS_publish_main_, pc);
1282 }
1283
1284
1285 /**
1286  * Calculate the total size of all of the files in the directory structure.
1287  *
1288  * @param fi file structure to traverse
1289  */
1290 static uint64_t
1291 compute_contents_size (struct GNUNET_FS_FileInformation *fi)
1292 {
1293   struct GNUNET_FS_FileInformation *ent;
1294
1295   if (GNUNET_YES != fi->is_directory)
1296     return fi->data.file.file_size;
1297   fi->data.dir.contents_size = 0;
1298   for (ent = fi->data.dir.entries; NULL != ent; ent = ent->next)
1299     fi->data.dir.contents_size += compute_contents_size (ent);
1300   return fi->data.dir.contents_size;
1301 }
1302
1303
1304 /**
1305  * Publish a file or directory.
1306  *
1307  * @param h handle to the file sharing subsystem
1308  * @param fi information about the file or directory structure to publish
1309  * @param ns namespace to publish the file in, NULL for no namespace
1310  * @param nid identifier to use for the publishd content in the namespace
1311  *        (can be NULL, must be NULL if namespace is NULL)
1312  * @param nuid update-identifier that will be used for future updates
1313  *        (can be NULL, must be NULL if namespace or nid is NULL)
1314  * @param options options for the publication
1315  * @return context that can be used to control the publish operation
1316  */
1317 struct GNUNET_FS_PublishContext *
1318 GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h,
1319                          struct GNUNET_FS_FileInformation *fi,
1320                          const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns,
1321                          const char *nid,
1322                          const char *nuid,
1323                          enum GNUNET_FS_PublishOptions options)
1324 {
1325   struct GNUNET_FS_PublishContext *ret;
1326   struct GNUNET_DATASTORE_Handle *dsh;
1327
1328   GNUNET_assert (NULL != h);
1329   compute_contents_size (fi);
1330   if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1331   {
1332     dsh = GNUNET_DATASTORE_connect (h->cfg);
1333     if (NULL == dsh)
1334       return NULL;
1335   }
1336   else
1337   {
1338     dsh = NULL;
1339   }
1340   ret = GNUNET_new (struct GNUNET_FS_PublishContext);
1341   ret->dsh = dsh;
1342   ret->h = h;
1343   ret->fi = fi;
1344   if (NULL != ns)
1345   {
1346     ret->ns = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey);
1347     *ret->ns = *ns;
1348     GNUNET_assert (NULL != nid);
1349     ret->nid = GNUNET_strdup (nid);
1350     if (NULL != nuid)
1351       ret->nuid = GNUNET_strdup (nuid);
1352   }
1353   ret->options = options;
1354   /* signal start */
1355   GNUNET_FS_file_information_inspect (ret->fi, &fip_signal_start, ret);
1356   ret->fi_pos = ret->fi;
1357   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_publish_signal_suspend_, ret);
1358   GNUNET_FS_publish_sync_ (ret);
1359   if (NULL != ret->dsh)
1360   {
1361     GNUNET_assert (NULL == ret->qre);
1362     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1363                 _("Reserving space for %u entries and %llu bytes for publication\n"),
1364                 (unsigned int) ret->reserve_entries,
1365                 (unsigned long long) ret->reserve_space);
1366     ret->qre =
1367         GNUNET_DATASTORE_reserve (ret->dsh, ret->reserve_space,
1368                                   ret->reserve_entries,
1369                                   UINT_MAX, UINT_MAX,
1370                                   GNUNET_TIME_UNIT_FOREVER_REL,
1371                                   &finish_reserve,
1372                                   ret);
1373   }
1374   else
1375   {
1376     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == ret->upload_task);
1377     ret->upload_task =
1378         GNUNET_SCHEDULER_add_with_priority
1379         (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, ret);
1380   }
1381   return ret;
1382 }
1383
1384
1385 /**
1386  * Signal the FS's progress function that we are stopping
1387  * an upload.
1388  *
1389  * @param cls closure (of type `struct GNUNET_FS_PublishContext *`)
1390  * @param fi the entry in the publish-structure
1391  * @param length length of the file or directory
1392  * @param meta metadata for the file or directory (can be modified)
1393  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1394  * @param bo block options (can be modified)
1395  * @param do_index should we index?
1396  * @param client_info pointer to client context set upon creation (can be modified)
1397  * @return #GNUNET_OK to continue (always)
1398  */
1399 static int
1400 fip_signal_stop (void *cls,
1401                  struct GNUNET_FS_FileInformation *fi,
1402                  uint64_t length,
1403                  struct GNUNET_CONTAINER_MetaData *meta,
1404                  struct GNUNET_FS_Uri **uri,
1405                  struct GNUNET_FS_BlockOptions *bo,
1406                  int *do_index, void **client_info)
1407 {
1408   struct GNUNET_FS_PublishContext *pc = cls;
1409   struct GNUNET_FS_ProgressInfo pi;
1410   uint64_t off;
1411
1412   if (GNUNET_YES == pc->skip_next_fi_callback)
1413   {
1414     pc->skip_next_fi_callback = GNUNET_NO;
1415     return GNUNET_OK;
1416   }
1417   if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta))
1418   {
1419     /* process entries in directory first */
1420     pc->skip_next_fi_callback = GNUNET_YES;
1421     GNUNET_FS_file_information_inspect (fi, &fip_signal_stop, pc);
1422   }
1423   if (NULL != fi->serialization)
1424   {
1425     GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO,
1426                                  fi->serialization);
1427     GNUNET_free (fi->serialization);
1428     fi->serialization = NULL;
1429   }
1430   off = (fi->chk_uri == NULL) ? 0 : length;
1431   pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED;
1432   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, fi, off));
1433   *client_info = NULL;
1434   return GNUNET_OK;
1435 }
1436
1437
1438 /**
1439  * Stop an upload.  Will abort incomplete uploads (but
1440  * not remove blocks that have already been publishd) or
1441  * simply clean up the state for completed uploads.
1442  * Must NOT be called from within the event callback!
1443  *
1444  * @param pc context for the upload to stop
1445  */
1446 void
1447 GNUNET_FS_publish_stop (struct GNUNET_FS_PublishContext *pc)
1448 {
1449   struct GNUNET_FS_ProgressInfo pi;
1450   uint64_t off;
1451
1452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453               "Publish stop called\n");
1454   GNUNET_FS_end_top (pc->h, pc->top);
1455   if (NULL != pc->ksk_pc)
1456   {
1457     GNUNET_FS_publish_ksk_cancel (pc->ksk_pc);
1458     pc->ksk_pc = NULL;
1459   }
1460   if (NULL != pc->sks_pc)
1461   {
1462     GNUNET_FS_publish_sks_cancel (pc->sks_pc);
1463     pc->sks_pc = NULL;
1464   }
1465   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1466   {
1467     GNUNET_SCHEDULER_cancel (pc->upload_task);
1468     pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1469   }
1470   pc->skip_next_fi_callback = GNUNET_YES;
1471   GNUNET_FS_file_information_inspect (pc->fi, &fip_signal_stop, pc);
1472
1473   if (NULL != pc->fi->serialization)
1474   {
1475     GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO,
1476                                  pc->fi->serialization);
1477     GNUNET_free (pc->fi->serialization);
1478     pc->fi->serialization = NULL;
1479   }
1480   off = (NULL == pc->fi->chk_uri) ? 0 : GNUNET_ntohll (pc->fi->chk_uri->data.chk.file_length);
1481
1482   if (NULL != pc->serialization)
1483   {
1484     GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH,
1485                                  pc->serialization);
1486     GNUNET_free (pc->serialization);
1487     pc->serialization = NULL;
1488   }
1489   if (NULL != pc->qre)
1490   {
1491     GNUNET_DATASTORE_cancel (pc->qre);
1492     pc->qre = NULL;
1493   }
1494   pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED;
1495   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, pc->fi, off));
1496   publish_cleanup (pc);
1497 }
1498
1499
1500 /* end of fs_publish.c */