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