fix fs testcase
[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 /**
22  * @file fs/fs_publish.c
23  * @brief publish a file or directory in GNUnet
24  * @see http://gnunet.org/encoding
25  * @author Krista Bennett
26  * @author Christian Grothoff
27  */
28
29 #include "platform.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_signatures.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_fs_service.h"
34 #include "fs.h"
35 #include "fs_tree.h"
36
37 #define DEBUG_PUBLISH GNUNET_NO
38
39
40 /**
41  * Context for "ds_put_cont".
42  */
43 struct PutContCtx
44 {
45   /**
46    * Current publishing context.
47    */
48   struct GNUNET_FS_PublishContext *sc;
49
50   /**
51    * Specific file with the block.
52    */
53   struct GNUNET_FS_FileInformation *p;
54
55   /**
56    * Function to run next, if any (can be NULL).
57    */
58   GNUNET_SCHEDULER_Task cont;
59
60   /**
61    * Closure for cont.
62    */
63   void *cont_cls;
64 };
65
66
67 /**
68  * Fill in all of the generic fields for 
69  * a publish event and call the callback.
70  *
71  * @param pi structure to fill in
72  * @param sc overall publishing context
73  * @param p file information for the file being published
74  * @param offset where in the file are we so far
75  * @return value returned from callback
76  */
77 void *
78 GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
79                                 struct GNUNET_FS_PublishContext *sc,
80                                 const struct GNUNET_FS_FileInformation *p,
81                                 uint64_t offset)
82 {
83   pi->value.publish.pc = sc;
84   pi->value.publish.fi = p;
85   pi->value.publish.cctx
86     = p->client_info;
87   pi->value.publish.pctx
88     = (NULL == p->dir) ? NULL : p->dir->client_info;
89   pi->value.publish.filename = p->filename;
90   pi->value.publish.size 
91     = (p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size;
92   pi->value.publish.eta 
93     = GNUNET_TIME_calculate_eta (p->start_time,
94                                  offset,
95                                  pi->value.publish.size);
96   pi->value.publish.completed = offset;
97   pi->value.publish.duration = GNUNET_TIME_absolute_get_duration (p->start_time);
98   pi->value.publish.anonymity = p->anonymity;
99   return sc->h->upcb (sc->h->upcb_cls,
100                       pi);
101 }
102
103
104 /**
105  * Cleanup the publish context, we're done with it.
106  *
107  * @param cls struct to clean up after
108  * @param tc scheduler context
109  */
110 static void
111 publish_cleanup (void *cls,
112                  const struct GNUNET_SCHEDULER_TaskContext *tc)
113 {
114   struct GNUNET_FS_PublishContext *pc = cls;
115
116   if (pc->fhc != NULL)
117     {
118       GNUNET_CRYPTO_hash_file_cancel (pc->fhc);
119       pc->fhc = NULL;
120     }
121   GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL);
122   if (pc->namespace != NULL)
123     GNUNET_FS_namespace_delete (pc->namespace, GNUNET_NO);
124   GNUNET_free_non_null (pc->nid);  
125   GNUNET_free_non_null (pc->nuid);
126   GNUNET_free_non_null (pc->serialization);
127   if (pc->dsh != NULL)
128     {
129       GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO);
130       pc->dsh = NULL;
131     }
132   if (pc->client != NULL)
133     GNUNET_CLIENT_disconnect (pc->client, GNUNET_NO);
134   GNUNET_free (pc);
135 }
136
137
138 /**
139  * Function called by the datastore API with
140  * the result from the PUT request.
141  *
142  * @param cls our closure
143  * @param success GNUNET_OK on success
144  * @param msg error message (or NULL)
145  */
146 static void
147 ds_put_cont (void *cls,
148              int success,
149              const char *msg)
150 {
151   struct PutContCtx *pcc = cls;
152   struct GNUNET_FS_ProgressInfo pi;
153
154   if (GNUNET_SYSERR == pcc->sc->in_network_wait)
155     {
156       /* we were aborted in the meantime, finish shutdown! */
157       GNUNET_SCHEDULER_add_continuation (pcc->sc->h->sched,                                      
158                                          &publish_cleanup,
159                                          pcc->sc,
160                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
161       GNUNET_free (pcc);
162       return;
163     }
164   GNUNET_assert (GNUNET_YES == pcc->sc->in_network_wait);
165   pcc->sc->in_network_wait = GNUNET_NO;
166   if (GNUNET_OK != success)
167     {
168       GNUNET_asprintf (&pcc->p->emsg, 
169                        _("Publishing failed: %s"),
170                        msg);
171       pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
172       pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
173       pi.value.publish.specifics.error.message = pcc->p->emsg;
174       pcc->p->client_info = GNUNET_FS_publish_make_status_ (&pi, pcc->sc, pcc->p, 0);
175       if ( (pcc->p->is_directory == GNUNET_NO) &&
176            (pcc->p->filename != NULL) &&
177            (pcc->p->data.file.do_index == GNUNET_YES) )
178         {
179           /* run unindex to clean up */
180           GNUNET_FS_unindex_start (pcc->sc->h,
181                                    pcc->p->filename,
182                                    NULL);
183         }          
184     }
185   if (NULL != pcc->cont)
186     pcc->sc->upload_task 
187       = GNUNET_SCHEDULER_add_with_priority (pcc->sc->h->sched,
188                                             GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
189                                             pcc->cont,
190                                             pcc->cont_cls);
191   GNUNET_free (pcc);
192 }
193
194
195 /**
196  * Generate the callback that signals clients
197  * that a file (or directory) has been completely
198  * published.
199  *
200  * @param p the completed upload
201  * @param sc context of the publication
202  */
203 static void 
204 signal_publish_completion (struct GNUNET_FS_FileInformation *p,
205                            struct GNUNET_FS_PublishContext *sc)
206 {
207   struct GNUNET_FS_ProgressInfo pi;
208   
209   pi.status = GNUNET_FS_STATUS_PUBLISH_COMPLETED;
210   pi.value.publish.eta = GNUNET_TIME_UNIT_ZERO;
211   pi.value.publish.specifics.completed.chk_uri = p->chk_uri;
212   p->client_info = GNUNET_FS_publish_make_status_ (&pi, sc, p,
213                                                    GNUNET_ntohll (p->chk_uri->data.chk.file_length));
214 }
215
216
217 /**
218  * Generate the callback that signals clients
219  * that a file (or directory) has encountered
220  * a problem during publication.
221  *
222  * @param p the upload that had trouble
223  * @param sc context of the publication
224  * @param emsg error message
225  */
226 static void 
227 signal_publish_error (struct GNUNET_FS_FileInformation *p,
228                       struct GNUNET_FS_PublishContext *sc,
229                       const char *emsg)
230 {
231   struct GNUNET_FS_ProgressInfo pi;
232   
233   p->emsg = GNUNET_strdup (emsg);
234   pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
235   pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
236   pi.value.publish.specifics.error.message =emsg;
237   p->client_info = GNUNET_FS_publish_make_status_ (&pi, sc, p, 0);
238   if ( (p->is_directory == GNUNET_NO) &&
239        (p->filename != NULL) &&
240        (p->data.file.do_index == GNUNET_YES) )
241     {
242       /* run unindex to clean up */
243       GNUNET_FS_unindex_start (sc->h,
244                                p->filename,
245                                NULL);
246     }      
247   
248 }
249
250
251 /**
252  * Datastore returns from reservation cancel request.
253  * 
254  * @param cls the 'struct GNUNET_FS_PublishContext'
255  * @param success success code (not used)
256  * @param msg error message (typically NULL, not used)
257  */
258 static void
259 finish_release_reserve (void *cls,
260                         int success,
261                         const char *msg)
262 {
263   struct GNUNET_FS_PublishContext *pc = cls;
264
265   pc->qre = NULL;
266   signal_publish_completion (pc->fi, pc);
267   pc->all_done = GNUNET_YES;
268   GNUNET_FS_publish_sync_ (pc);
269 }
270
271
272 /**
273  * We've finished publishing the SBlock as part of a larger upload.
274  * Check the result and complete the larger upload.
275  *
276  * @param cls the "struct GNUNET_FS_PublishContext*" of the larger upload
277  * @param uri URI of the published SBlock
278  * @param emsg NULL on success, otherwise error message
279  */
280 static void
281 publish_sblocks_cont (void *cls,
282                       const struct GNUNET_FS_Uri *uri,
283                       const char *emsg)
284 {
285   struct GNUNET_FS_PublishContext *pc = cls;
286   if (NULL != emsg)
287     {
288       signal_publish_error (pc->fi,
289                             pc,
290                             emsg);
291       GNUNET_FS_publish_sync_ (pc);
292       return;
293     }  
294   GNUNET_assert (pc->qre == NULL);
295   if ( (pc->dsh != NULL) &&
296        (pc->rid != 0) )
297     {
298       pc->qre = GNUNET_DATASTORE_release_reserve (pc->dsh,
299                                                   pc->rid,
300                                                   UINT_MAX,
301                                                   UINT_MAX,
302                                                   GNUNET_TIME_UNIT_FOREVER_REL,
303                                                   &finish_release_reserve,
304                                                   pc);
305     }
306   else
307     {
308       finish_release_reserve (pc, GNUNET_OK, NULL);
309     }
310 }
311
312
313 /**
314  * We are almost done publishing the structure,
315  * add SBlocks (if needed).
316  *
317  * @param sc overall upload data
318  */
319 static void
320 publish_sblock (struct GNUNET_FS_PublishContext *sc)
321 {
322   if (NULL != sc->namespace)
323     GNUNET_FS_publish_sks (sc->h,
324                            sc->namespace,
325                            sc->nid,
326                            sc->nuid,
327                            sc->fi->meta,
328                            sc->fi->chk_uri,
329                            sc->fi->expirationTime,
330                            sc->fi->anonymity,
331                            sc->fi->priority,
332                            sc->options,
333                            &publish_sblocks_cont,
334                            sc);
335   else
336     publish_sblocks_cont (sc, NULL, NULL);
337 }
338
339
340 /**
341  * We've finished publishing a KBlock as part of a larger upload.
342  * Check the result and continue the larger upload.
343  *
344  * @param cls the "struct GNUNET_FS_PublishContext*"
345  *        of the larger upload
346  * @param uri URI of the published blocks
347  * @param emsg NULL on success, otherwise error message
348  */
349 static void
350 publish_kblocks_cont (void *cls,
351                       const struct GNUNET_FS_Uri *uri,
352                       const char *emsg)
353 {
354   struct GNUNET_FS_PublishContext *pc = cls;
355   struct GNUNET_FS_FileInformation *p = pc->fi_pos;
356
357   if (NULL != emsg)
358     {
359 #if DEBUG_PUBLISH
360       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
361                   "Error uploading KSK blocks: %s\n",
362                   emsg);
363 #endif
364       signal_publish_error (p, pc, emsg);
365       GNUNET_FS_file_information_sync_ (p);
366       GNUNET_FS_publish_sync_ (pc);
367       pc->upload_task 
368         = GNUNET_SCHEDULER_add_with_priority (pc->h->sched,
369                                               GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
370                                               &GNUNET_FS_publish_main_,
371                                               pc);
372       return;
373     }
374 #if DEBUG_PUBLISH
375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
376               "KSK blocks published, moving on to next file\n");
377 #endif
378   if (NULL != p->dir)
379     signal_publish_completion (p, pc);    
380   /* move on to next file */
381   if (NULL != p->next)
382     pc->fi_pos = p->next;
383   else
384     pc->fi_pos = p->dir;
385   GNUNET_FS_publish_sync_ (pc);
386   pc->upload_task 
387     = GNUNET_SCHEDULER_add_with_priority (pc->h->sched,
388                                           GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
389                                           &GNUNET_FS_publish_main_,
390                                           pc);
391 }
392
393
394 /**
395  * Function called by the tree encoder to obtain
396  * a block of plaintext data (for the lowest level
397  * of the tree).
398  *
399  * @param cls our publishing context
400  * @param offset identifies which block to get
401  * @param max (maximum) number of bytes to get; returning
402  *        fewer will also cause errors
403  * @param buf where to copy the plaintext buffer
404  * @param emsg location to store an error message (on error)
405  * @return number of bytes copied to buf, 0 on error
406  */
407 static size_t
408 block_reader (void *cls,
409               uint64_t offset,
410               size_t max, 
411               void *buf,
412               char **emsg)
413 {
414   struct GNUNET_FS_PublishContext *sc = cls;
415   struct GNUNET_FS_FileInformation *p;
416   size_t pt_size;
417   const char *dd;
418
419   p = sc->fi_pos;
420   if (p->is_directory)
421     {
422       pt_size = GNUNET_MIN(max,
423                            p->data.dir.dir_size - offset);
424       dd = p->data.dir.dir_data;
425       memcpy (buf,
426               &dd[offset],
427               pt_size);
428     }
429   else
430     {
431       pt_size = GNUNET_MIN(max,
432                            p->data.file.file_size - offset);
433       if (pt_size == 0)
434         return 0; /* calling reader with pt_size==0 
435                      might free buf, so don't! */
436       if (pt_size !=
437           p->data.file.reader (p->data.file.reader_cls,
438                                offset,
439                                pt_size,
440                                buf,
441                                emsg))
442         return 0;
443     }
444   return pt_size;
445 }
446
447
448 /**
449  * The tree encoder has finished processing a
450  * file.   Call it's finish method and deal with
451  * the final result.
452  *
453  * @param cls our publishing context
454  * @param tc scheduler's task context (not used)
455  */
456 static void 
457 encode_cont (void *cls,
458              const struct GNUNET_SCHEDULER_TaskContext *tc)
459 {
460   struct GNUNET_FS_PublishContext *sc = cls;
461   struct GNUNET_FS_FileInformation *p;
462   struct GNUNET_FS_ProgressInfo pi;
463   char *emsg;
464
465   p = sc->fi_pos;
466   GNUNET_FS_tree_encoder_finish (p->te,
467                                  &p->chk_uri,
468                                  &emsg);
469   p->te = NULL;
470   if (NULL != emsg)
471     {
472 #if DEBUG_PUBLISH
473       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
474                   "Error during tree walk: %s\n",
475                   emsg);
476 #endif
477       GNUNET_asprintf (&p->emsg, 
478                        _("Publishing failed: %s"),
479                        emsg);
480       GNUNET_free (emsg);
481       pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
482       pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
483       pi.value.publish.specifics.error.message = p->emsg;
484       p->client_info =  GNUNET_FS_publish_make_status_ (&pi, sc, p, 0);
485     }
486 #if DEBUG_PUBLISH
487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
488               "Finished with tree encoder\n");
489 #endif  
490   /* final progress event */
491   pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS;
492   pi.value.publish.specifics.progress.data = NULL;
493   pi.value.publish.specifics.progress.offset = GNUNET_FS_uri_chk_get_file_size (p->chk_uri);
494   pi.value.publish.specifics.progress.data_len = 0;
495   pi.value.publish.specifics.progress.depth = 0;
496   p->client_info = GNUNET_FS_publish_make_status_ (&pi, sc, p, 
497                                                    GNUNET_FS_uri_chk_get_file_size (p->chk_uri));
498
499   /* continue with main */
500   sc->upload_task 
501     = GNUNET_SCHEDULER_add_with_priority (sc->h->sched,
502                                           GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
503                                           &GNUNET_FS_publish_main_,
504                                           sc);
505 }
506
507
508 /**
509  * Function called asking for the current (encoded)
510  * block to be processed.  After processing the
511  * client should either call "GNUNET_FS_tree_encode_next"
512  * or (on error) "GNUNET_FS_tree_encode_finish".
513  *
514  * @param cls closure
515  * @param query the query for the block (key for lookup in the datastore)
516  * @param offset offset of the block in the file
517  * @param type type of the block (IBLOCK or DBLOCK)
518  * @param block the (encrypted) block
519  * @param block_size size of block (in bytes)
520  */
521 static void 
522 block_proc (void *cls,
523             const GNUNET_HashCode *query,
524             uint64_t offset,
525             enum GNUNET_BLOCK_Type type,
526             const void *block,
527             uint16_t block_size)
528 {
529   struct GNUNET_FS_PublishContext *sc = cls;
530   struct GNUNET_FS_FileInformation *p;
531   struct PutContCtx * dpc_cls;
532   struct OnDemandBlock odb;
533
534   p = sc->fi_pos;
535   if (NULL == sc->dsh)
536     {
537 #if DEBUG_PUBLISH
538       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
539                   "Waiting for datastore connection\n");
540 #endif
541       sc->upload_task
542         = GNUNET_SCHEDULER_add_with_priority (sc->h->sched,
543                                               GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
544                                               &GNUNET_FS_publish_main_,
545                                               sc);
546       return;
547     }
548   
549   GNUNET_assert (GNUNET_NO == sc->in_network_wait);
550   sc->in_network_wait = GNUNET_YES;
551   dpc_cls = GNUNET_malloc(sizeof(struct PutContCtx));
552   dpc_cls->cont = &GNUNET_FS_publish_main_;
553   dpc_cls->cont_cls = sc;
554   dpc_cls->sc = sc;
555   dpc_cls->p = p;
556   if ( (! p->is_directory) &&
557        (GNUNET_YES == p->data.file.do_index) &&
558        (type == GNUNET_BLOCK_TYPE_DBLOCK) )
559     {
560 #if DEBUG_PUBLISH
561       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
562                   "Indexing block `%s' for offset %llu with index size %u\n",
563                   GNUNET_h2s (query),
564                   (unsigned long long) offset,
565                   sizeof (struct OnDemandBlock));
566 #endif
567       odb.offset = GNUNET_htonll (offset);
568       odb.file_id = p->data.file.file_id;
569       GNUNET_DATASTORE_put (sc->dsh,
570                             (p->is_directory) ? 0 : sc->rid,
571                             query,
572                             sizeof(struct OnDemandBlock),
573                             &odb,
574                             GNUNET_BLOCK_TYPE_ONDEMAND,
575                             p->priority,
576                             p->anonymity,
577                             p->expirationTime,
578                             -2, 1,
579                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
580                             &ds_put_cont,
581                             dpc_cls);     
582       return;
583     }
584 #if DEBUG_PUBLISH
585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
586               "Publishing block `%s' for offset %llu with size %u\n",
587               GNUNET_h2s (query),
588               (unsigned long long) offset,
589               (unsigned int) block_size);
590 #endif
591   GNUNET_DATASTORE_put (sc->dsh,
592                         (p->is_directory) ? 0 : sc->rid,
593                         query,
594                         block_size,
595                         block,
596                         type,
597                         p->priority,
598                         p->anonymity,
599                         p->expirationTime,
600                         -2, 1,
601                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
602                         &ds_put_cont,
603                         dpc_cls);
604 }
605
606
607 /**
608  * Function called with information about our
609  * progress in computing the tree encoding.
610  *
611  * @param cls closure
612  * @param offset where are we in the file
613  * @param pt_block plaintext of the currently processed block
614  * @param pt_size size of pt_block
615  * @param depth depth of the block in the tree
616  */
617 static void 
618 progress_proc (void *cls,
619                uint64_t offset,
620                const void *pt_block,
621                size_t pt_size,
622                unsigned int depth)
623 {                      
624   struct GNUNET_FS_PublishContext *sc = cls;
625   struct GNUNET_FS_FileInformation *p;
626   struct GNUNET_FS_ProgressInfo pi;
627
628   p = sc->fi_pos;
629   pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS;
630   pi.value.publish.specifics.progress.data = pt_block;
631   pi.value.publish.specifics.progress.offset = offset;
632   pi.value.publish.specifics.progress.data_len = pt_size;
633   pi.value.publish.specifics.progress.depth = depth;
634   p->client_info = GNUNET_FS_publish_make_status_ (&pi, sc, p, offset);
635 }
636
637
638 /**
639  * We are uploading a file or directory; load (if necessary) the next
640  * block into memory, encrypt it and send it to the FS service.  Then
641  * continue with the main task.
642  *
643  * @param sc overall upload data
644  */
645 static void
646 publish_content (struct GNUNET_FS_PublishContext *sc) 
647 {
648   struct GNUNET_FS_FileInformation *p;
649   char *emsg;
650   struct GNUNET_FS_DirectoryBuilder *db;
651   struct GNUNET_FS_FileInformation *dirpos;
652   void *raw_data;
653   uint64_t size;
654
655   p = sc->fi_pos;
656   GNUNET_assert (p != NULL);
657   if (NULL == p->te)
658     {
659       if (p->is_directory)
660         {
661 #if DEBUG_PUBLISH
662           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
663                       "Creating directory\n");
664 #endif
665           db = GNUNET_FS_directory_builder_create (p->meta);
666           dirpos = p->data.dir.entries;
667           while (NULL != dirpos)
668             {
669               if (dirpos->is_directory)
670                 {
671                   raw_data = dirpos->data.dir.dir_data;
672                   dirpos->data.dir.dir_data = NULL;
673                 }
674               else
675                 {
676                   raw_data = NULL;
677                   if ( (dirpos->data.file.file_size < MAX_INLINE_SIZE) &&
678                        (dirpos->data.file.file_size > 0) )
679                     {
680                       raw_data = GNUNET_malloc (dirpos->data.file.file_size);
681                       emsg = NULL;
682                       if (dirpos->data.file.file_size !=
683                           dirpos->data.file.reader (dirpos->data.file.reader_cls,
684                                                     0,
685                                                     dirpos->data.file.file_size,
686                                                     raw_data,
687                                                     &emsg))
688                         {
689                           GNUNET_free_non_null (emsg);
690                           GNUNET_free (raw_data);
691                           raw_data = NULL;
692                         } 
693                     }
694                 }
695               GNUNET_FS_directory_builder_add (db,
696                                                dirpos->chk_uri,
697                                                dirpos->meta,
698                                                raw_data);
699               GNUNET_free_non_null (raw_data);
700               dirpos = dirpos->next;
701             }
702           GNUNET_FS_directory_builder_finish (db,
703                                               &p->data.dir.dir_size,
704                                               &p->data.dir.dir_data);
705           GNUNET_FS_file_information_sync_ (p);
706         }
707       size = (p->is_directory) 
708         ? p->data.dir.dir_size 
709         : p->data.file.file_size;
710 #if DEBUG_PUBLISH
711       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
712                   "Creating tree encoder\n");
713 #endif
714       p->te = GNUNET_FS_tree_encoder_create (sc->h,
715                                              size,
716                                              sc,
717                                              &block_reader,
718                                              &block_proc,
719                                              &progress_proc,
720                                              &encode_cont);
721
722     }
723 #if DEBUG_PUBLISH
724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
725               "Processing next block from tree\n");
726 #endif
727   GNUNET_FS_tree_encoder_next (p->te);
728 }
729
730
731 /**
732  * Process the response (or lack thereof) from
733  * the "fs" service to our 'start index' request.
734  *
735  * @param cls closure (of type "struct GNUNET_FS_PublishContext*"_)
736  * @param msg the response we got
737  */
738 static void
739 process_index_start_response (void *cls,
740                               const struct GNUNET_MessageHeader *msg)
741 {
742   struct GNUNET_FS_PublishContext *sc = cls;
743   struct GNUNET_FS_FileInformation *p;
744   const char *emsg;
745   uint16_t msize;
746
747   GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
748   sc->client = NULL;
749   p = sc->fi_pos;
750   if (msg == NULL)
751     {
752       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
753                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
754                   p->filename,
755                   _("timeout on index-start request to `fs' service"));
756       p->data.file.do_index = GNUNET_NO;
757       GNUNET_FS_file_information_sync_ (p);
758       publish_content (sc);
759       return;
760     }
761   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK)
762     {
763       msize = ntohs (msg->size);
764       emsg = (const char *) &msg[1];
765       if ( (msize <= sizeof (struct GNUNET_MessageHeader)) ||
766            (emsg[msize - sizeof(struct GNUNET_MessageHeader) - 1] != '\0') )
767         emsg = gettext_noop ("unknown error");
768       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
769                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
770                   p->filename,
771                   gettext (emsg));
772       p->data.file.do_index = GNUNET_NO;
773       GNUNET_FS_file_information_sync_ (p);
774       publish_content (sc);
775       return;
776     }
777   p->data.file.index_start_confirmed = GNUNET_YES;
778   /* success! continue with indexing */
779   GNUNET_FS_file_information_sync_ (p);
780   publish_content (sc);
781 }
782
783
784 /**
785  * Function called once the hash computation over an
786  * indexed file has completed.
787  *
788  * @param cls closure, our publishing context
789  * @param res resulting hash, NULL on error
790  */
791 static void 
792 hash_for_index_cb (void *cls,
793                    const GNUNET_HashCode *
794                    res)
795 {
796   struct GNUNET_FS_PublishContext *sc = cls;
797   struct GNUNET_FS_FileInformation *p;
798   struct IndexStartMessage *ism;
799   size_t slen;
800   struct GNUNET_CLIENT_Connection *client;
801   uint64_t dev;
802   uint64_t ino;
803   char *fn;
804
805   sc->fhc = NULL;
806   p = sc->fi_pos;
807   if (NULL == res) 
808     {
809       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
810                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
811                   p->filename,
812                   _("failed to compute hash"));
813       p->data.file.do_index = GNUNET_NO;
814       GNUNET_FS_file_information_sync_ (p);
815       publish_content (sc);
816       return;
817     }
818   if (GNUNET_YES == p->data.file.index_start_confirmed)
819     {
820       publish_content (sc);
821       return;
822     }
823   fn = GNUNET_STRINGS_filename_expand (p->filename);
824   GNUNET_assert (fn != NULL);
825   slen = strlen (fn) + 1;
826   if (slen >= GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof(struct IndexStartMessage))
827     {
828       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
829                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
830                   fn,
831                   _("filename too long"));
832       GNUNET_free (fn);
833       p->data.file.do_index = GNUNET_NO;
834       GNUNET_FS_file_information_sync_ (p);
835       publish_content (sc);
836       return;
837     }
838 #if DEBUG_PUBLISH
839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840               "Hash of indexed file `%s' is `%s'\n",
841               p->filename,
842               GNUNET_h2s (res));
843 #endif
844   client = GNUNET_CLIENT_connect (sc->h->sched,
845                                   "fs",
846                                   sc->h->cfg);
847   if (NULL == client)
848     {
849       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
850                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
851                   p->filename,
852                   _("could not connect to `fs' service"));
853       p->data.file.do_index = GNUNET_NO;
854       publish_content (sc);
855       GNUNET_free (fn);
856       return;
857     }
858   if (p->data.file.have_hash != GNUNET_YES)
859     {
860       p->data.file.file_id = *res;
861       p->data.file.have_hash = GNUNET_YES;
862       GNUNET_FS_file_information_sync_ (p);
863     }
864   ism = GNUNET_malloc (sizeof(struct IndexStartMessage) +
865                        slen);
866   ism->header.size = htons(sizeof(struct IndexStartMessage) +
867                            slen);
868   ism->header.type = htons(GNUNET_MESSAGE_TYPE_FS_INDEX_START);
869   if (GNUNET_OK ==
870       GNUNET_DISK_file_get_identifiers (p->filename,
871                                         &dev,
872                                         &ino))
873     {
874       ism->device = GNUNET_htonll (dev);
875       ism->inode = GNUNET_htonll(ino);
876     }
877 #if DEBUG_PUBLISH
878   else
879     {
880       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881                   _("Failed to get file identifiers for `%s'\n"),
882                   p->filename);
883     }
884 #endif
885   ism->file_id = *res;
886   memcpy (&ism[1],
887           fn,
888           slen);
889   GNUNET_free (fn);
890   sc->client = client;
891   GNUNET_break (GNUNET_YES ==
892                 GNUNET_CLIENT_transmit_and_get_response (client,
893                                                          &ism->header,
894                                                          GNUNET_TIME_UNIT_FOREVER_REL,
895                                                          GNUNET_YES,
896                                                          &process_index_start_response,
897                                                          sc));
898   GNUNET_free (ism);
899 }
900
901
902 /**
903  * Main function that performs the upload.
904  *
905  * @param cls "struct GNUNET_FS_PublishContext" identifies the upload
906  * @param tc task context
907  */
908 void
909 GNUNET_FS_publish_main_ (void *cls,
910                          const struct GNUNET_SCHEDULER_TaskContext *tc)
911 {
912   struct GNUNET_FS_PublishContext *pc = cls;
913   struct GNUNET_FS_ProgressInfo pi;
914   struct GNUNET_FS_FileInformation *p;
915   struct GNUNET_FS_Uri *loc;
916   char *fn;
917
918   pc->upload_task = GNUNET_SCHEDULER_NO_TASK;  
919   p = pc->fi_pos;
920   if (NULL == p)
921     {
922 #if DEBUG_PUBLISH
923       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924                   "Publishing complete, now publishing SKS and KSK blocks.\n");
925 #endif
926       /* upload of entire hierarchy complete,
927          publish namespace entries */
928       GNUNET_FS_publish_sync_ (pc);
929       publish_sblock (pc);
930       return;
931     }
932   /* find starting position */
933   while ( (p->is_directory) &&
934           (NULL != p->data.dir.entries) &&
935           (NULL == p->emsg) &&
936           (NULL == p->data.dir.entries->chk_uri) )
937     {
938       p = p->data.dir.entries;
939       pc->fi_pos = p;
940       GNUNET_FS_publish_sync_ (pc);
941     }
942   /* abort on error */
943   if (NULL != p->emsg)
944     {
945 #if DEBUG_PUBLISH
946       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
947                   "Error uploading: %s\n",
948                   p->emsg);
949 #endif
950       /* error with current file, abort all
951          related files as well! */
952       while (NULL != p->dir)
953         {
954           fn = GNUNET_CONTAINER_meta_data_get_by_type (p->meta,
955                                                        EXTRACTOR_METATYPE_FILENAME);
956           p = p->dir;
957           if (fn != NULL)
958             {
959               GNUNET_asprintf (&p->emsg, 
960                                _("Recursive upload failed at `%s': %s"),
961                                fn,
962                                p->emsg);
963               GNUNET_free (fn);
964             }
965           else
966             {
967               GNUNET_asprintf (&p->emsg, 
968                                _("Recursive upload failed: %s"),
969                                p->emsg);              
970             }
971           pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
972           pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
973           pi.value.publish.specifics.error.message = p->emsg;
974           p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
975         }
976       pc->all_done = GNUNET_YES;
977       GNUNET_FS_publish_sync_ (pc);
978       return;
979     }
980   /* handle completion */
981   if (NULL != p->chk_uri)
982     {
983 #if DEBUG_PUBLISH
984       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985                   "File upload complete, now publishing KSK blocks.\n");
986 #endif
987       if (0 == p->anonymity)
988         {
989           /* zero anonymity, box CHK URI in LOC URI */
990           loc = GNUNET_FS_uri_loc_create (p->chk_uri,
991                                           pc->h->cfg,
992                                           p->expirationTime);
993           GNUNET_FS_uri_destroy (p->chk_uri);
994           p->chk_uri = loc;
995         }
996       GNUNET_FS_publish_sync_ (pc);
997       /* upload of "p" complete, publish KBlocks! */
998       if (p->keywords != NULL)
999         {
1000           GNUNET_FS_publish_ksk (pc->h,
1001                                  p->keywords,
1002                                  p->meta,
1003                                  p->chk_uri,
1004                                  p->expirationTime,
1005                                  p->anonymity,
1006                                  p->priority,
1007                                  pc->options,
1008                                  &publish_kblocks_cont,
1009                                  pc);
1010         }
1011       else
1012         {
1013           publish_kblocks_cont (pc,
1014                                 p->chk_uri,
1015                                 NULL);
1016         }
1017       return;
1018     }
1019   if ( (!p->is_directory) &&
1020        (p->data.file.do_index) )
1021     {
1022       if (NULL == p->filename)
1023         {
1024           p->data.file.do_index = GNUNET_NO;
1025           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1026                       _("Can not index file `%s': %s.  Will try to insert instead.\n"),
1027                       "<no-name>",
1028                       _("needs to be an actual file"));
1029           GNUNET_FS_file_information_sync_ (p);
1030           publish_content (pc);
1031           return;
1032         }      
1033       if (p->data.file.have_hash)
1034         {
1035           hash_for_index_cb (pc,
1036                              &p->data.file.file_id);
1037         }
1038       else
1039         {
1040           p->start_time = GNUNET_TIME_absolute_get ();
1041           pc->fhc = GNUNET_CRYPTO_hash_file (pc->h->sched,
1042                                              GNUNET_SCHEDULER_PRIORITY_IDLE,
1043                                              p->filename,
1044                                              HASHING_BLOCKSIZE,
1045                                              &hash_for_index_cb,
1046                                              pc);
1047         }
1048       return;
1049     }
1050   publish_content (pc);
1051 }
1052
1053
1054 /**
1055  * Signal the FS's progress function that we are starting
1056  * an upload.
1057  *
1058  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1059  * @param fi the entry in the publish-structure
1060  * @param length length of the file or directory
1061  * @param meta metadata for the file or directory (can be modified)
1062  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1063  * @param anonymity pointer to selected anonymity level (can be modified)
1064  * @param priority pointer to selected priority (can be modified)
1065  * @param do_index should we index?
1066  * @param expirationTime pointer to selected expiration time (can be modified)
1067  * @param client_info pointer to client context set upon creation (can be modified)
1068  * @return GNUNET_OK to continue (always)
1069  */
1070 static int
1071 fip_signal_start(void *cls,
1072                  struct GNUNET_FS_FileInformation *fi,
1073                  uint64_t length,
1074                  struct GNUNET_CONTAINER_MetaData *meta,
1075                  struct GNUNET_FS_Uri **uri,
1076                  uint32_t *anonymity,
1077                  uint32_t *priority,
1078                  int *do_index,
1079                  struct GNUNET_TIME_Absolute *expirationTime,
1080                  void **client_info)
1081 {
1082   struct GNUNET_FS_PublishContext *sc = cls;
1083   struct GNUNET_FS_ProgressInfo pi;
1084   unsigned int kc;
1085   uint64_t left;
1086
1087   if (*do_index)
1088     {
1089       /* space for on-demand blocks */
1090       sc->reserve_space += ((length + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * sizeof (struct OnDemandBlock);
1091     }
1092   else
1093     {
1094       /* space for DBlocks */
1095       sc->reserve_space += length;
1096     }
1097   /* entries for IBlocks and DBlocks, space for IBlocks */
1098   left = length;
1099   while (1)
1100     {
1101       left = (left + DBLOCK_SIZE - 1) / DBLOCK_SIZE;
1102       sc->reserve_entries += left;
1103       if (left <= 1)
1104         break;
1105       left = left * sizeof (struct ContentHashKey);
1106       sc->reserve_space += left;
1107     }
1108   sc->reserve_entries++;
1109   /* entries and space for keywords */
1110   if (NULL != *uri)
1111     {
1112       kc = GNUNET_FS_uri_ksk_get_keyword_count (*uri);
1113       sc->reserve_entries += kc;
1114       sc->reserve_space += GNUNET_SERVER_MAX_MESSAGE_SIZE * kc;
1115     }  
1116   pi.status = GNUNET_FS_STATUS_PUBLISH_START;
1117   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1118   GNUNET_FS_file_information_sync_ (fi);
1119   return GNUNET_OK;
1120 }
1121
1122
1123 /**
1124  * Signal the FS's progress function that we are suspending
1125  * an upload.
1126  *
1127  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1128  * @param fi the entry in the publish-structure
1129  * @param length length of the file or directory
1130  * @param meta metadata for the file or directory (can be modified)
1131  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1132  * @param anonymity pointer to selected anonymity level (can be modified)
1133  * @param priority pointer to selected priority (can be modified)
1134  * @param do_index should we index?
1135  * @param expirationTime pointer to selected expiration time (can be modified)
1136  * @param client_info pointer to client context set upon creation (can be modified)
1137  * @return GNUNET_OK to continue (always)
1138  */
1139 static int
1140 fip_signal_suspend(void *cls,
1141                    struct GNUNET_FS_FileInformation *fi,
1142                    uint64_t length,
1143                    struct GNUNET_CONTAINER_MetaData *meta,
1144                    struct GNUNET_FS_Uri **uri,
1145                    uint32_t *anonymity,
1146                    uint32_t *priority,
1147                    int *do_index,
1148                    struct GNUNET_TIME_Absolute *expirationTime,
1149                    void **client_info)
1150 {
1151   struct GNUNET_FS_PublishContext*sc = cls;
1152   struct GNUNET_FS_ProgressInfo pi;
1153   uint64_t off;
1154
1155   GNUNET_free_non_null (fi->serialization);
1156   fi->serialization = NULL;    
1157   off = (fi->chk_uri == NULL) ? 0 : length;
1158   pi.status = GNUNET_FS_STATUS_PUBLISH_SUSPEND;
1159   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, sc, fi, off));
1160   *client_info = NULL;
1161   if (NULL != sc->dsh)
1162     {
1163       GNUNET_DATASTORE_disconnect (sc->dsh, GNUNET_NO);
1164       sc->dsh = NULL;
1165     }
1166   return GNUNET_OK;
1167 }
1168
1169
1170 /**
1171  * Create SUSPEND event for the given publish operation
1172  * and then clean up our state (without stop signal).
1173  *
1174  * @param cls the 'struct GNUNET_FS_PublishContext' to signal for
1175  */
1176 void
1177 GNUNET_FS_publish_signal_suspend_ (void *cls)
1178 {
1179   struct GNUNET_FS_PublishContext *pc = cls;
1180
1181   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1182     {
1183       GNUNET_SCHEDULER_cancel (pc->h->sched, pc->upload_task);
1184       pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1185     }
1186   GNUNET_FS_file_information_inspect (pc->fi,
1187                                       &fip_signal_suspend,
1188                                       pc);
1189   GNUNET_FS_end_top (pc->h, pc->top);
1190   publish_cleanup (pc, NULL);
1191 }
1192
1193
1194 /**
1195  * We have gotten a reply for our space reservation request.
1196  * Either fail (insufficient space) or start publishing for good.
1197  * 
1198  * @param cls the 'struct GNUNET_FS_PublishContext*'
1199  * @param success positive reservation ID on success
1200  * @param msg error message on error, otherwise NULL
1201  */
1202 static void
1203 finish_reserve (void *cls,
1204                 int success,
1205                 const char *msg)
1206 {
1207   struct GNUNET_FS_PublishContext *pc = cls;
1208
1209   pc->qre = NULL;
1210   if ( (msg != NULL) ||
1211        (success <= 0) )
1212     {
1213       GNUNET_asprintf (&pc->fi->emsg, 
1214                        _("Insufficient space for publishing: %s"),
1215                        msg);
1216       signal_publish_error (pc->fi,
1217                             pc,
1218                             pc->fi->emsg);
1219       return;
1220     }
1221   pc->rid = success;
1222   pc->upload_task 
1223     = GNUNET_SCHEDULER_add_with_priority (pc->h->sched,
1224                                           GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1225                                           &GNUNET_FS_publish_main_,
1226                                           pc);
1227 }
1228
1229
1230 /**
1231  * Publish a file or directory.
1232  *
1233  * @param h handle to the file sharing subsystem
1234  * @param fi information about the file or directory structure to publish
1235  * @param namespace namespace to publish the file in, NULL for no namespace
1236  * @param nid identifier to use for the publishd content in the namespace
1237  *        (can be NULL, must be NULL if namespace is NULL)
1238  * @param nuid update-identifier that will be used for future updates 
1239  *        (can be NULL, must be NULL if namespace or nid is NULL)
1240  * @param options options for the publication 
1241  * @return context that can be used to control the publish operation
1242  */
1243 struct GNUNET_FS_PublishContext *
1244 GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h,
1245                          struct GNUNET_FS_FileInformation *fi,
1246                          struct GNUNET_FS_Namespace *namespace,
1247                          const char *nid,
1248                          const char *nuid,
1249                          enum GNUNET_FS_PublishOptions options)
1250 {
1251   struct GNUNET_FS_PublishContext *ret;
1252   struct GNUNET_DATASTORE_Handle *dsh;
1253
1254   GNUNET_assert (NULL != h);
1255   if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1256     {
1257       dsh = GNUNET_DATASTORE_connect (h->cfg,
1258                                       h->sched);
1259       if (NULL == dsh)
1260         return NULL;
1261     }
1262   else
1263     {
1264       dsh = NULL;
1265     }
1266   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_PublishContext));
1267   ret->dsh = dsh;
1268   ret->h = h;
1269   ret->fi = fi;
1270   ret->namespace = namespace;
1271   if (namespace != NULL)
1272     {
1273       namespace->rc++;
1274       GNUNET_assert (NULL != nid);
1275       ret->nid = GNUNET_strdup (nid);
1276       if (NULL != nuid)
1277         ret->nuid = GNUNET_strdup (nuid);
1278     }
1279   /* signal start */
1280   GNUNET_FS_file_information_inspect (ret->fi,
1281                                       &fip_signal_start,
1282                                       ret);
1283   ret->fi_pos = ret->fi;
1284   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_publish_signal_suspend_, ret);
1285   GNUNET_FS_publish_sync_ (ret);
1286   if (NULL != ret->dsh)
1287     {
1288       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1289                   _("Reserving space for %u entries and %llu bytes for publication\n"),
1290                   (unsigned int) ret->reserve_entries,
1291                   (unsigned long long) ret->reserve_space);
1292       ret->qre = GNUNET_DATASTORE_reserve (ret->dsh,
1293                                            ret->reserve_space,
1294                                            ret->reserve_entries,
1295                                            UINT_MAX,
1296                                            UINT_MAX,
1297                                            GNUNET_TIME_UNIT_FOREVER_REL,
1298                                            &finish_reserve,
1299                                            ret);
1300     }
1301   else
1302     {
1303       ret->upload_task 
1304         = GNUNET_SCHEDULER_add_with_priority (h->sched,
1305                                               GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1306                                               &GNUNET_FS_publish_main_,
1307                                               ret);
1308     }
1309   return ret;
1310 }
1311
1312
1313 /**
1314  * Signal the FS's progress function that we are stopping
1315  * an upload.
1316  *
1317  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1318  * @param fi the entry in the publish-structure
1319  * @param length length of the file or directory
1320  * @param meta metadata for the file or directory (can be modified)
1321  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1322  * @param anonymity pointer to selected anonymity level (can be modified)
1323  * @param priority pointer to selected priority (can be modified)
1324  * @param do_index should we index?
1325  * @param expirationTime pointer to selected expiration time (can be modified)
1326  * @param client_info pointer to client context set upon creation (can be modified)
1327  * @return GNUNET_OK to continue (always)
1328  */
1329 static int
1330 fip_signal_stop(void *cls,
1331                 struct GNUNET_FS_FileInformation *fi,
1332                 uint64_t length,
1333                 struct GNUNET_CONTAINER_MetaData *meta,
1334                 struct GNUNET_FS_Uri **uri,
1335                 uint32_t *anonymity,
1336                 uint32_t *priority,
1337                 int *do_index,
1338                 struct GNUNET_TIME_Absolute *expirationTime,
1339                 void **client_info)
1340 {
1341   struct GNUNET_FS_PublishContext*sc = cls;
1342   struct GNUNET_FS_ProgressInfo pi;
1343   uint64_t off;
1344
1345   if (fi->serialization != NULL) 
1346     {
1347       GNUNET_FS_remove_sync_file_ (sc->h,
1348                                    GNUNET_FS_SYNC_PATH_FILE_INFO,
1349                                    fi->serialization);
1350       GNUNET_free (fi->serialization);
1351       fi->serialization = NULL;
1352     }
1353   off = (fi->chk_uri == NULL) ? 0 : length;
1354   pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED;
1355   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, sc, fi, off));
1356   *client_info = NULL;
1357   return GNUNET_OK;
1358 }
1359
1360
1361 /**
1362  * Stop an upload.  Will abort incomplete uploads (but 
1363  * not remove blocks that have already been publishd) or
1364  * simply clean up the state for completed uploads.
1365  * Must NOT be called from within the event callback!
1366  *
1367  * @param pc context for the upload to stop
1368  */
1369 void 
1370 GNUNET_FS_publish_stop (struct GNUNET_FS_PublishContext *pc)
1371 {
1372   GNUNET_FS_end_top (pc->h, pc->top);
1373   if (NULL != pc->qre)
1374     {
1375       GNUNET_DATASTORE_cancel (pc->qre);
1376       pc->qre = NULL;
1377     }
1378   if (NULL != pc->dsh)
1379     {
1380       GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO);
1381       pc->dsh = NULL;
1382     }
1383   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1384     {
1385       GNUNET_SCHEDULER_cancel (pc->h->sched, pc->upload_task);
1386       pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1387     }
1388   if (pc->serialization != NULL) 
1389     {
1390       GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, pc->serialization);
1391       GNUNET_free (pc->serialization);
1392       pc->serialization = NULL;
1393     }
1394   GNUNET_FS_file_information_inspect (pc->fi,
1395                                       &fip_signal_stop,
1396                                       pc);
1397   if (GNUNET_YES == pc->in_network_wait)
1398     {
1399       pc->in_network_wait = GNUNET_SYSERR;
1400       return;
1401     }
1402   publish_cleanup (pc, NULL);
1403 }
1404
1405
1406 /**
1407  * Context for the KSK publication.
1408  */
1409 struct PublishKskContext
1410 {
1411
1412   /**
1413    * Keywords to use.
1414    */
1415   struct GNUNET_FS_Uri *ksk_uri;
1416
1417   /**
1418    * Global FS context.
1419    */
1420   struct GNUNET_FS_Handle *h;
1421
1422   /**
1423    * The master block that we are sending
1424    * (in plaintext), has "mdsize+slen" more
1425    * bytes than the struct would suggest.
1426    */
1427   struct KBlock *kb;
1428
1429   /**
1430    * Buffer of the same size as "kb" for
1431    * the encrypted version.
1432    */ 
1433   struct KBlock *cpy;
1434
1435   /**
1436    * Handle to the datastore, NULL if we are just
1437    * simulating.
1438    */
1439   struct GNUNET_DATASTORE_Handle *dsh;
1440
1441   /**
1442    * Function to call once we're done.
1443    */
1444   GNUNET_FS_PublishContinuation cont;
1445
1446   /**
1447    * Closure for cont.
1448    */ 
1449   void *cont_cls;
1450
1451   /**
1452    * When should the KBlocks expire?
1453    */
1454   struct GNUNET_TIME_Absolute expirationTime;
1455
1456   /**
1457    * Size of the serialized metadata.
1458    */
1459   ssize_t mdsize;
1460
1461   /**
1462    * Size of the (CHK) URI as a string.
1463    */
1464   size_t slen;
1465
1466   /**
1467    * Keyword that we are currently processing.
1468    */
1469   unsigned int i;
1470
1471   /**
1472    * Anonymity level for the KBlocks.
1473    */
1474   uint32_t anonymity;
1475
1476   /**
1477    * Priority for the KBlocks.
1478    */
1479   uint32_t priority;
1480 };
1481
1482
1483 /**
1484  * Continuation of "GNUNET_FS_publish_ksk" that performs
1485  * the actual publishing operation (iterating over all
1486  * of the keywords).
1487  *
1488  * @param cls closure of type "struct PublishKskContext*"
1489  * @param tc unused
1490  */
1491 static void
1492 publish_ksk_cont (void *cls,
1493                   const struct GNUNET_SCHEDULER_TaskContext *tc);
1494
1495
1496 /**
1497  * Function called by the datastore API with
1498  * the result from the PUT request.
1499  *
1500  * @param cls closure of type "struct PublishKskContext*"
1501  * @param success GNUNET_OK on success
1502  * @param msg error message (or NULL)
1503  */
1504 static void
1505 kb_put_cont (void *cls,
1506              int success,
1507              const char *msg)
1508 {
1509   struct PublishKskContext *pkc = cls;
1510
1511   if (GNUNET_OK != success)
1512     {
1513       if (NULL != pkc->dsh)
1514         {
1515           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1516           pkc->dsh = NULL;
1517         }
1518       GNUNET_free (pkc->cpy);
1519       GNUNET_free (pkc->kb);
1520       pkc->cont (pkc->cont_cls,
1521                  NULL,
1522                  msg);
1523       GNUNET_FS_uri_destroy (pkc->ksk_uri);
1524       GNUNET_free (pkc);
1525       return;
1526     }
1527   GNUNET_SCHEDULER_add_continuation (pkc->h->sched,
1528                                      &publish_ksk_cont,
1529                                      pkc,
1530                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1531 }
1532
1533
1534 /**
1535  * Continuation of "GNUNET_FS_publish_ksk" that performs the actual
1536  * publishing operation (iterating over all of the keywords).
1537  *
1538  * @param cls closure of type "struct PublishKskContext*"
1539  * @param tc unused
1540  */
1541 static void
1542 publish_ksk_cont (void *cls,
1543                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1544 {
1545   struct PublishKskContext *pkc = cls;
1546   const char *keyword;
1547   GNUNET_HashCode key;
1548   GNUNET_HashCode query;
1549   struct GNUNET_CRYPTO_AesSessionKey skey;
1550   struct GNUNET_CRYPTO_AesInitializationVector iv;
1551   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1552
1553
1554   if ( (pkc->i == pkc->ksk_uri->data.ksk.keywordCount) ||
1555        (NULL == pkc->dsh) )
1556     {
1557       if (NULL != pkc->dsh)
1558         {
1559           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1560           pkc->dsh = NULL;
1561         }
1562       GNUNET_free (pkc->cpy);
1563       GNUNET_free (pkc->kb);
1564       pkc->cont (pkc->cont_cls,
1565                  pkc->ksk_uri,
1566                  NULL);
1567       GNUNET_FS_uri_destroy (pkc->ksk_uri);
1568       GNUNET_free (pkc);
1569       return;
1570     }
1571   keyword = pkc->ksk_uri->data.ksk.keywords[pkc->i++];
1572   /* first character of keyword indicates if it is
1573      mandatory or not -- ignore for hashing */
1574   GNUNET_CRYPTO_hash (&keyword[1], strlen (&keyword[1]), &key);
1575   GNUNET_CRYPTO_hash_to_aes_key (&key, &skey, &iv);
1576   GNUNET_CRYPTO_aes_encrypt (&pkc->kb[1],
1577                              pkc->slen + pkc->mdsize,
1578                              &skey,
1579                              &iv,
1580                              &pkc->cpy[1]);
1581   pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&key);
1582   GNUNET_assert (NULL != pk);
1583   GNUNET_CRYPTO_rsa_key_get_public (pk, &pkc->cpy->keyspace);
1584   GNUNET_CRYPTO_hash (&pkc->cpy->keyspace,
1585                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1586                       &query);
1587   GNUNET_assert (GNUNET_OK == 
1588                  GNUNET_CRYPTO_rsa_sign (pk,
1589                                          &pkc->cpy->purpose,
1590                                          &pkc->cpy->signature));
1591   GNUNET_CRYPTO_rsa_key_free (pk);
1592   GNUNET_DATASTORE_put (pkc->dsh,
1593                         0,
1594                         &query,
1595                         pkc->mdsize + 
1596                         sizeof (struct KBlock) + 
1597                         pkc->slen,
1598                         pkc->cpy,
1599                         GNUNET_BLOCK_TYPE_KBLOCK, 
1600                         pkc->priority,
1601                         pkc->anonymity,
1602                         pkc->expirationTime,
1603                         -2, 1,
1604                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1605                         &kb_put_cont,
1606                         pkc);
1607 }
1608
1609
1610 /**
1611  * Publish a CHK under various keywords on GNUnet.
1612  *
1613  * @param h handle to the file sharing subsystem
1614  * @param ksk_uri keywords to use
1615  * @param meta metadata to use
1616  * @param uri URI to refer to in the KBlock
1617  * @param expirationTime when the KBlock expires
1618  * @param anonymity anonymity level for the KBlock
1619  * @param priority priority for the KBlock
1620  * @param options publication options
1621  * @param cont continuation
1622  * @param cont_cls closure for cont
1623  */
1624 void
1625 GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h,
1626                        const struct GNUNET_FS_Uri *ksk_uri,
1627                        const struct GNUNET_CONTAINER_MetaData *meta,
1628                        const struct GNUNET_FS_Uri *uri,
1629                        struct GNUNET_TIME_Absolute expirationTime,
1630                        uint32_t anonymity,
1631                        uint32_t priority,
1632                        enum GNUNET_FS_PublishOptions options,
1633                        GNUNET_FS_PublishContinuation cont,
1634                        void *cont_cls)
1635 {
1636   struct PublishKskContext *pkc;
1637   char *uris;
1638   size_t size;
1639   char *kbe;
1640   char *sptr;
1641
1642   pkc = GNUNET_malloc (sizeof (struct PublishKskContext));
1643   pkc->h = h;
1644   pkc->expirationTime = expirationTime;
1645   pkc->anonymity = anonymity;
1646   pkc->priority = priority;
1647   pkc->cont = cont;
1648   pkc->cont_cls = cont_cls;
1649   if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1650     {
1651       pkc->dsh = GNUNET_DATASTORE_connect (h->cfg,
1652                                            h->sched);
1653       if (pkc->dsh == NULL)
1654         {
1655           cont (cont_cls, NULL, _("Could not connect to datastore."));
1656           GNUNET_free (pkc);
1657           return;
1658         }
1659     }
1660   if (meta == NULL)
1661     pkc->mdsize = 0;
1662   else
1663     pkc->mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (meta);
1664   GNUNET_assert (pkc->mdsize >= 0);
1665   uris = GNUNET_FS_uri_to_string (uri);
1666   pkc->slen = strlen (uris) + 1;
1667   size = pkc->mdsize + sizeof (struct KBlock) + pkc->slen;
1668   if (size > MAX_KBLOCK_SIZE)
1669     {
1670       size = MAX_KBLOCK_SIZE;
1671       pkc->mdsize = size - sizeof (struct KBlock) - pkc->slen;
1672     }
1673   pkc->kb = GNUNET_malloc (size);
1674   kbe = (char *) &pkc->kb[1];
1675   memcpy (kbe, uris, pkc->slen);
1676   GNUNET_free (uris);
1677   sptr = &kbe[pkc->slen];
1678   if (meta != NULL)
1679     pkc->mdsize = GNUNET_CONTAINER_meta_data_serialize (meta,
1680                                                         &sptr,
1681                                                         pkc->mdsize,
1682                                                         GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
1683   if (pkc->mdsize == -1)
1684     {
1685       GNUNET_break (0);
1686       GNUNET_free (pkc->kb);
1687       if (pkc->dsh != NULL)
1688         {
1689           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1690           pkc->dsh = NULL;
1691         }
1692       cont (cont_cls, NULL, _("Internal error."));
1693       GNUNET_free (pkc);
1694       return;
1695     }
1696   size = sizeof (struct KBlock) + pkc->slen + pkc->mdsize;
1697
1698   pkc->cpy = GNUNET_malloc (size);
1699   pkc->cpy->purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) + 
1700                                   sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1701                                   pkc->mdsize + 
1702                                   pkc->slen);
1703   pkc->cpy->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK);
1704   pkc->ksk_uri = GNUNET_FS_uri_dup (ksk_uri);
1705   GNUNET_SCHEDULER_add_continuation (h->sched,
1706                                      &publish_ksk_cont,
1707                                      pkc,
1708                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1709 }
1710
1711
1712 /**
1713  * Context for the SKS publication.
1714  */
1715 struct PublishSksContext
1716 {
1717
1718   /**
1719    * Global FS context.
1720    */
1721   struct GNUNET_FS_Uri *uri;
1722
1723   /**
1724    * Handle to the datastore.
1725    */
1726   struct GNUNET_DATASTORE_Handle *dsh;
1727
1728   /**
1729    * Function to call once we're done.
1730    */
1731   GNUNET_FS_PublishContinuation cont;
1732
1733   /**
1734    * Closure for cont.
1735    */ 
1736   void *cont_cls;
1737
1738 };
1739
1740
1741 /**
1742  * Function called by the datastore API with
1743  * the result from the PUT (SBlock) request.
1744  *
1745  * @param cls closure of type "struct PublishSksContext*"
1746  * @param success GNUNET_OK on success
1747  * @param msg error message (or NULL)
1748  */
1749 static void
1750 sb_put_cont (void *cls,
1751              int success,
1752              const char *msg)
1753 {
1754   struct PublishSksContext *psc = cls;
1755
1756   if (NULL != psc->dsh)
1757     {
1758       GNUNET_DATASTORE_disconnect (psc->dsh, GNUNET_NO);
1759       psc->dsh = NULL;
1760     }
1761   if (GNUNET_OK != success)
1762     psc->cont (psc->cont_cls,
1763                NULL,
1764                msg);
1765   else
1766     psc->cont (psc->cont_cls,
1767                psc->uri,
1768                NULL);
1769   GNUNET_FS_uri_destroy (psc->uri);
1770   GNUNET_free (psc);
1771 }
1772
1773
1774 /**
1775  * Publish an SBlock on GNUnet.
1776  *
1777  * @param h handle to the file sharing subsystem
1778  * @param namespace namespace to publish in
1779  * @param identifier identifier to use
1780  * @param update update identifier to use
1781  * @param meta metadata to use
1782  * @param uri URI to refer to in the SBlock
1783  * @param expirationTime when the SBlock expires
1784  * @param anonymity anonymity level for the SBlock
1785  * @param priority priority for the SBlock
1786  * @param options publication options
1787  * @param cont continuation
1788  * @param cont_cls closure for cont
1789  */
1790 void
1791 GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h,
1792                        struct GNUNET_FS_Namespace *namespace,
1793                        const char *identifier,
1794                        const char *update,
1795                        const struct GNUNET_CONTAINER_MetaData *meta,
1796                        const struct GNUNET_FS_Uri *uri,
1797                        struct GNUNET_TIME_Absolute expirationTime,
1798                        uint32_t anonymity,
1799                        uint32_t priority,
1800                        enum GNUNET_FS_PublishOptions options,
1801                        GNUNET_FS_PublishContinuation cont,
1802                        void *cont_cls)
1803 {
1804   struct PublishSksContext *psc;
1805   struct GNUNET_CRYPTO_AesSessionKey sk;
1806   struct GNUNET_CRYPTO_AesInitializationVector iv;
1807   struct GNUNET_FS_Uri *sks_uri;
1808   char *uris;
1809   size_t size;
1810   size_t slen;
1811   size_t nidlen;
1812   size_t idlen;
1813   ssize_t mdsize;
1814   struct SBlock *sb;
1815   struct SBlock *sb_enc;
1816   char *dest;
1817   struct GNUNET_CONTAINER_MetaData *mmeta;
1818   GNUNET_HashCode key;         /* hash of thisId = key */
1819   GNUNET_HashCode id;          /* hash of hc = identifier */
1820   GNUNET_HashCode query;       /* id ^ nsid = DB query */
1821
1822   if (NULL == meta)
1823     mmeta = GNUNET_CONTAINER_meta_data_create ();
1824   else
1825     mmeta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1826   uris = GNUNET_FS_uri_to_string (uri);
1827   slen = strlen (uris) + 1;
1828   idlen = strlen (identifier);
1829   if (update == NULL)
1830     update = "";
1831   nidlen = strlen (update) + 1;
1832   mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (mmeta);
1833   size = sizeof (struct SBlock) + slen + nidlen + mdsize;
1834   if (size > MAX_SBLOCK_SIZE)
1835     {
1836       size = MAX_SBLOCK_SIZE;
1837       mdsize = size - (sizeof (struct SBlock) + slen + nidlen);
1838     }
1839   sb = GNUNET_malloc (sizeof (struct SBlock) + size);
1840   dest = (char *) &sb[1];
1841   memcpy (dest, update, nidlen);
1842   dest += nidlen;
1843   memcpy (dest, uris, slen);
1844   GNUNET_free (uris);
1845   dest += slen;
1846   mdsize = GNUNET_CONTAINER_meta_data_serialize (mmeta,
1847                                                  &dest,
1848                                                  mdsize, 
1849                                                  GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
1850   GNUNET_CONTAINER_meta_data_destroy (mmeta);
1851   if (mdsize == -1)
1852     {
1853       GNUNET_break (0);
1854       GNUNET_free (sb);
1855       cont (cont_cls,
1856             NULL,
1857             _("Internal error."));
1858       return;
1859     }
1860   size = sizeof (struct SBlock) + mdsize + slen + nidlen;
1861   sb_enc = GNUNET_malloc (size);
1862   GNUNET_CRYPTO_hash (identifier, idlen, &key);
1863   GNUNET_CRYPTO_hash (&key, sizeof (GNUNET_HashCode), &id);
1864   sks_uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
1865   sks_uri->type = sks;
1866   GNUNET_CRYPTO_rsa_key_get_public (namespace->key, &sb_enc->subspace);
1867   GNUNET_CRYPTO_hash (&sb_enc->subspace,
1868                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1869                       &sks_uri->data.sks.namespace);
1870   sks_uri->data.sks.identifier = GNUNET_strdup (identifier);
1871   GNUNET_CRYPTO_hash_xor (&id, 
1872                           &sks_uri->data.sks.namespace, 
1873                           &sb_enc->identifier);
1874   GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
1875   GNUNET_CRYPTO_aes_encrypt (&sb[1],
1876                              size - sizeof (struct SBlock),
1877                              &sk,
1878                              &iv,
1879                              &sb_enc[1]);
1880   sb_enc->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK);
1881   sb_enc->purpose.size = htonl(slen + mdsize + nidlen
1882                                + sizeof(struct SBlock)
1883                                - sizeof(struct GNUNET_CRYPTO_RsaSignature));
1884   GNUNET_assert (GNUNET_OK == 
1885                  GNUNET_CRYPTO_rsa_sign (namespace->key,
1886                                          &sb_enc->purpose,
1887                                          &sb_enc->signature));
1888   psc = GNUNET_malloc (sizeof(struct PublishSksContext));
1889   psc->uri = sks_uri;
1890   psc->cont = cont;
1891   psc->cont_cls = cont_cls;
1892   if (0 != (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1893     {
1894       GNUNET_free (sb_enc);
1895       GNUNET_free (sb);
1896       sb_put_cont (psc,
1897                    GNUNET_OK,
1898                    NULL);
1899       return;
1900     }
1901   psc->dsh = GNUNET_DATASTORE_connect (h->cfg, h->sched);
1902   if (NULL == psc->dsh)
1903     {
1904       GNUNET_free (sb_enc);
1905       GNUNET_free (sb);
1906       sb_put_cont (psc,
1907                    GNUNET_NO,
1908                    _("Failed to connect to datastore."));
1909       return;
1910     }
1911   GNUNET_CRYPTO_hash_xor (&sks_uri->data.sks.namespace,
1912                           &id,
1913                           &query);  
1914   GNUNET_DATASTORE_put (psc->dsh,
1915                         0,
1916                         &sb_enc->identifier,
1917                         size,
1918                         sb_enc,
1919                         GNUNET_BLOCK_TYPE_SBLOCK, 
1920                         priority,
1921                         anonymity,
1922                         expirationTime,
1923                         -2, 1,
1924                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1925                         &sb_put_cont,
1926                         psc);
1927   GNUNET_free (sb);
1928   GNUNET_free (sb_enc);
1929 }
1930
1931 /* end of fs_publish.c */