89d1f84cb9d31ac0089313393e428c0f01b8e231
[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   /* continue with main */
491   sc->upload_task 
492     = GNUNET_SCHEDULER_add_with_priority (sc->h->sched,
493                                           GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
494                                           &GNUNET_FS_publish_main_,
495                                           sc);
496 }
497
498
499 /**
500  * Function called asking for the current (encoded)
501  * block to be processed.  After processing the
502  * client should either call "GNUNET_FS_tree_encode_next"
503  * or (on error) "GNUNET_FS_tree_encode_finish".
504  *
505  * @param cls closure
506  * @param query the query for the block (key for lookup in the datastore)
507  * @param offset offset of the block in the file
508  * @param type type of the block (IBLOCK or DBLOCK)
509  * @param block the (encrypted) block
510  * @param block_size size of block (in bytes)
511  */
512 static void 
513 block_proc (void *cls,
514             const GNUNET_HashCode *query,
515             uint64_t offset,
516             enum GNUNET_BLOCK_Type type,
517             const void *block,
518             uint16_t block_size)
519 {
520   struct GNUNET_FS_PublishContext *sc = cls;
521   struct GNUNET_FS_FileInformation *p;
522   struct PutContCtx * dpc_cls;
523   struct OnDemandBlock odb;
524
525   p = sc->fi_pos;
526   if (NULL == sc->dsh)
527     {
528 #if DEBUG_PUBLISH
529       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
530                   "Waiting for datastore connection\n");
531 #endif
532       sc->upload_task
533         = GNUNET_SCHEDULER_add_with_priority (sc->h->sched,
534                                               GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
535                                               &GNUNET_FS_publish_main_,
536                                               sc);
537       return;
538     }
539   
540   GNUNET_assert (GNUNET_NO == sc->in_network_wait);
541   sc->in_network_wait = GNUNET_YES;
542   dpc_cls = GNUNET_malloc(sizeof(struct PutContCtx));
543   dpc_cls->cont = &GNUNET_FS_publish_main_;
544   dpc_cls->cont_cls = sc;
545   dpc_cls->sc = sc;
546   dpc_cls->p = p;
547   if ( (! p->is_directory) &&
548        (GNUNET_YES == p->data.file.do_index) &&
549        (type == GNUNET_BLOCK_TYPE_DBLOCK) )
550     {
551 #if DEBUG_PUBLISH
552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
553                   "Indexing block `%s' for offset %llu with index size %u\n",
554                   GNUNET_h2s (query),
555                   (unsigned long long) offset,
556                   sizeof (struct OnDemandBlock));
557 #endif
558       odb.offset = GNUNET_htonll (offset);
559       odb.file_id = p->data.file.file_id;
560       GNUNET_DATASTORE_put (sc->dsh,
561                             sc->rid,
562                             query,
563                             sizeof(struct OnDemandBlock),
564                             &odb,
565                             GNUNET_BLOCK_TYPE_ONDEMAND,
566                             p->priority,
567                             p->anonymity,
568                             p->expirationTime,
569                             -2, 1,
570                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
571                             &ds_put_cont,
572                             dpc_cls);     
573       return;
574     }
575 #if DEBUG_PUBLISH
576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
577               "Publishing block `%s' for offset %llu with size %u\n",
578               GNUNET_h2s (query),
579               (unsigned long long) offset,
580               (unsigned int) block_size);
581 #endif
582   GNUNET_DATASTORE_put (sc->dsh,
583                         sc->rid,
584                         query,
585                         block_size,
586                         block,
587                         type,
588                         p->priority,
589                         p->anonymity,
590                         p->expirationTime,
591                         -2, 1,
592                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
593                         &ds_put_cont,
594                         dpc_cls);
595 }
596
597
598 /**
599  * Function called with information about our
600  * progress in computing the tree encoding.
601  *
602  * @param cls closure
603  * @param offset where are we in the file
604  * @param pt_block plaintext of the currently processed block
605  * @param pt_size size of pt_block
606  * @param depth depth of the block in the tree
607  */
608 static void 
609 progress_proc (void *cls,
610                uint64_t offset,
611                const void *pt_block,
612                size_t pt_size,
613                unsigned int depth)
614 {                      
615   struct GNUNET_FS_PublishContext *sc = cls;
616   struct GNUNET_FS_FileInformation *p;
617   struct GNUNET_FS_ProgressInfo pi;
618
619   p = sc->fi_pos;
620   pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS;
621   pi.value.publish.specifics.progress.data = pt_block;
622   pi.value.publish.specifics.progress.offset = offset;
623   pi.value.publish.specifics.progress.data_len = pt_size;
624   pi.value.publish.specifics.progress.depth = depth;
625   p->client_info = GNUNET_FS_publish_make_status_ (&pi, sc, p, offset);
626 }
627
628
629 /**
630  * We are uploading a file or directory; load (if necessary) the next
631  * block into memory, encrypt it and send it to the FS service.  Then
632  * continue with the main task.
633  *
634  * @param sc overall upload data
635  */
636 static void
637 publish_content (struct GNUNET_FS_PublishContext *sc) 
638 {
639   struct GNUNET_FS_FileInformation *p;
640   char *emsg;
641   struct GNUNET_FS_DirectoryBuilder *db;
642   struct GNUNET_FS_FileInformation *dirpos;
643   void *raw_data;
644   uint64_t size;
645
646   p = sc->fi_pos;
647   GNUNET_assert (p != NULL);
648   if (NULL == p->te)
649     {
650       if (p->is_directory)
651         {
652 #if DEBUG_PUBLISH
653           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
654                       "Creating directory\n");
655 #endif
656           db = GNUNET_FS_directory_builder_create (p->meta);
657           dirpos = p->data.dir.entries;
658           while (NULL != dirpos)
659             {
660               if (dirpos->is_directory)
661                 {
662                   raw_data = dirpos->data.dir.dir_data;
663                   dirpos->data.dir.dir_data = NULL;
664                 }
665               else
666                 {
667                   raw_data = NULL;
668                   if ( (dirpos->data.file.file_size < MAX_INLINE_SIZE) &&
669                        (dirpos->data.file.file_size > 0) )
670                     {
671                       raw_data = GNUNET_malloc (dirpos->data.file.file_size);
672                       emsg = NULL;
673                       if (dirpos->data.file.file_size !=
674                           dirpos->data.file.reader (dirpos->data.file.reader_cls,
675                                                     0,
676                                                     dirpos->data.file.file_size,
677                                                     raw_data,
678                                                     &emsg))
679                         {
680                           GNUNET_free_non_null (emsg);
681                           GNUNET_free (raw_data);
682                           raw_data = NULL;
683                         } 
684                     }
685                 }
686               GNUNET_FS_directory_builder_add (db,
687                                                dirpos->chk_uri,
688                                                dirpos->meta,
689                                                raw_data);
690               GNUNET_free_non_null (raw_data);
691               dirpos = dirpos->next;
692             }
693           GNUNET_FS_directory_builder_finish (db,
694                                               &p->data.dir.dir_size,
695                                               &p->data.dir.dir_data);
696           GNUNET_FS_file_information_sync_ (p);
697         }
698       size = (p->is_directory) 
699         ? p->data.dir.dir_size 
700         : p->data.file.file_size;
701 #if DEBUG_PUBLISH
702       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
703                   "Creating tree encoder\n");
704 #endif
705       p->te = GNUNET_FS_tree_encoder_create (sc->h,
706                                              size,
707                                              sc,
708                                              &block_reader,
709                                              &block_proc,
710                                              &progress_proc,
711                                              &encode_cont);
712
713     }
714 #if DEBUG_PUBLISH
715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
716               "Processing next block from tree\n");
717 #endif
718   GNUNET_FS_tree_encoder_next (p->te);
719 }
720
721
722 /**
723  * Process the response (or lack thereof) from
724  * the "fs" service to our 'start index' request.
725  *
726  * @param cls closure (of type "struct GNUNET_FS_PublishContext*"_)
727  * @param msg the response we got
728  */
729 static void
730 process_index_start_response (void *cls,
731                               const struct GNUNET_MessageHeader *msg)
732 {
733   struct GNUNET_FS_PublishContext *sc = cls;
734   struct GNUNET_FS_FileInformation *p;
735   const char *emsg;
736   uint16_t msize;
737
738   GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
739   sc->client = NULL;
740   p = sc->fi_pos;
741   if (msg == NULL)
742     {
743       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
744                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
745                   p->filename,
746                   _("timeout on index-start request to `fs' service"));
747       p->data.file.do_index = GNUNET_NO;
748       GNUNET_FS_file_information_sync_ (p);
749       publish_content (sc);
750       return;
751     }
752   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK)
753     {
754       msize = ntohs (msg->size);
755       emsg = (const char *) &msg[1];
756       if ( (msize <= sizeof (struct GNUNET_MessageHeader)) ||
757            (emsg[msize - sizeof(struct GNUNET_MessageHeader) - 1] != '\0') )
758         emsg = gettext_noop ("unknown error");
759       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
760                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
761                   p->filename,
762                   gettext (emsg));
763       p->data.file.do_index = GNUNET_NO;
764       GNUNET_FS_file_information_sync_ (p);
765       publish_content (sc);
766       return;
767     }
768   p->data.file.index_start_confirmed = GNUNET_YES;
769   /* success! continue with indexing */
770   GNUNET_FS_file_information_sync_ (p);
771   publish_content (sc);
772 }
773
774
775 /**
776  * Function called once the hash computation over an
777  * indexed file has completed.
778  *
779  * @param cls closure, our publishing context
780  * @param res resulting hash, NULL on error
781  */
782 static void 
783 hash_for_index_cb (void *cls,
784                    const GNUNET_HashCode *
785                    res)
786 {
787   struct GNUNET_FS_PublishContext *sc = cls;
788   struct GNUNET_FS_FileInformation *p;
789   struct IndexStartMessage *ism;
790   size_t slen;
791   struct GNUNET_CLIENT_Connection *client;
792   uint64_t dev;
793   uint64_t ino;
794   char *fn;
795
796   sc->fhc = NULL;
797   p = sc->fi_pos;
798   if (NULL == res) 
799     {
800       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
801                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
802                   p->filename,
803                   _("failed to compute hash"));
804       p->data.file.do_index = GNUNET_NO;
805       GNUNET_FS_file_information_sync_ (p);
806       publish_content (sc);
807       return;
808     }
809   if (GNUNET_YES == p->data.file.index_start_confirmed)
810     {
811       publish_content (sc);
812       return;
813     }
814   fn = GNUNET_STRINGS_filename_expand (p->filename);
815   GNUNET_assert (fn != NULL);
816   slen = strlen (fn) + 1;
817   if (slen >= GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof(struct IndexStartMessage))
818     {
819       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
820                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
821                   fn,
822                   _("filename too long"));
823       GNUNET_free (fn);
824       p->data.file.do_index = GNUNET_NO;
825       GNUNET_FS_file_information_sync_ (p);
826       publish_content (sc);
827       return;
828     }
829 #if DEBUG_PUBLISH
830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831               "Hash of indexed file `%s' is `%s'\n",
832               p->filename,
833               GNUNET_h2s (res));
834 #endif
835   client = GNUNET_CLIENT_connect (sc->h->sched,
836                                   "fs",
837                                   sc->h->cfg);
838   if (NULL == client)
839     {
840       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
841                   _("Can not index file `%s': %s.  Will try to insert instead.\n"),
842                   p->filename,
843                   _("could not connect to `fs' service"));
844       p->data.file.do_index = GNUNET_NO;
845       publish_content (sc);
846       GNUNET_free (fn);
847       return;
848     }
849   if (p->data.file.have_hash != GNUNET_YES)
850     {
851       p->data.file.file_id = *res;
852       p->data.file.have_hash = GNUNET_YES;
853       GNUNET_FS_file_information_sync_ (p);
854     }
855   ism = GNUNET_malloc (sizeof(struct IndexStartMessage) +
856                        slen);
857   ism->header.size = htons(sizeof(struct IndexStartMessage) +
858                            slen);
859   ism->header.type = htons(GNUNET_MESSAGE_TYPE_FS_INDEX_START);
860   if (GNUNET_OK ==
861       GNUNET_DISK_file_get_identifiers (p->filename,
862                                         &dev,
863                                         &ino))
864     {
865       ism->device = GNUNET_htonll (dev);
866       ism->inode = GNUNET_htonll(ino);
867     }
868 #if DEBUG_PUBLISH
869   else
870     {
871       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872                   _("Failed to get file identifiers for `%s'\n"),
873                   p->filename);
874     }
875 #endif
876   ism->file_id = *res;
877   memcpy (&ism[1],
878           fn,
879           slen);
880   GNUNET_free (fn);
881   sc->client = client;
882   GNUNET_break (GNUNET_YES ==
883                 GNUNET_CLIENT_transmit_and_get_response (client,
884                                                          &ism->header,
885                                                          GNUNET_TIME_UNIT_FOREVER_REL,
886                                                          GNUNET_YES,
887                                                          &process_index_start_response,
888                                                          sc));
889   GNUNET_free (ism);
890 }
891
892
893 /**
894  * Main function that performs the upload.
895  *
896  * @param cls "struct GNUNET_FS_PublishContext" identifies the upload
897  * @param tc task context
898  */
899 void
900 GNUNET_FS_publish_main_ (void *cls,
901                          const struct GNUNET_SCHEDULER_TaskContext *tc)
902 {
903   struct GNUNET_FS_PublishContext *pc = cls;
904   struct GNUNET_FS_ProgressInfo pi;
905   struct GNUNET_FS_FileInformation *p;
906   struct GNUNET_FS_Uri *loc;
907   char *fn;
908
909   pc->upload_task = GNUNET_SCHEDULER_NO_TASK;  
910   p = pc->fi_pos;
911   if (NULL == p)
912     {
913 #if DEBUG_PUBLISH
914       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915                   "Publishing complete, now publishing SKS and KSK blocks.\n");
916 #endif
917       /* upload of entire hierarchy complete,
918          publish namespace entries */
919       GNUNET_FS_publish_sync_ (pc);
920       publish_sblock (pc);
921       return;
922     }
923   /* find starting position */
924   while ( (p->is_directory) &&
925           (NULL != p->data.dir.entries) &&
926           (NULL == p->emsg) &&
927           (NULL == p->data.dir.entries->chk_uri) )
928     {
929       p = p->data.dir.entries;
930       pc->fi_pos = p;
931       GNUNET_FS_publish_sync_ (pc);
932     }
933   /* abort on error */
934   if (NULL != p->emsg)
935     {
936 #if DEBUG_PUBLISH
937       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938                   "Error uploading: %s\n",
939                   p->emsg);
940 #endif
941       /* error with current file, abort all
942          related files as well! */
943       while (NULL != p->dir)
944         {
945           fn = GNUNET_CONTAINER_meta_data_get_by_type (p->meta,
946                                                        EXTRACTOR_METATYPE_FILENAME);
947           p = p->dir;
948           if (fn != NULL)
949             {
950               GNUNET_asprintf (&p->emsg, 
951                                _("Recursive upload failed at `%s': %s"),
952                                fn,
953                                p->emsg);
954               GNUNET_free (fn);
955             }
956           else
957             {
958               GNUNET_asprintf (&p->emsg, 
959                                _("Recursive upload failed: %s"),
960                                p->emsg);              
961             }
962           pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR;
963           pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL;
964           pi.value.publish.specifics.error.message = p->emsg;
965           p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0);
966         }
967       pc->all_done = GNUNET_YES;
968       GNUNET_FS_publish_sync_ (pc);
969       return;
970     }
971   /* handle completion */
972   if (NULL != p->chk_uri)
973     {
974 #if DEBUG_PUBLISH
975       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
976                   "File upload complete, now publishing KSK blocks.\n");
977 #endif
978       if (0 == p->anonymity)
979         {
980           /* zero anonymity, box CHK URI in LOC URI */
981           loc = GNUNET_FS_uri_loc_create (p->chk_uri,
982                                           pc->h->cfg,
983                                           p->expirationTime);
984           GNUNET_FS_uri_destroy (p->chk_uri);
985           p->chk_uri = loc;
986         }
987       GNUNET_FS_publish_sync_ (pc);
988       /* upload of "p" complete, publish KBlocks! */
989       if (p->keywords != NULL)
990         {
991           GNUNET_FS_publish_ksk (pc->h,
992                                  p->keywords,
993                                  p->meta,
994                                  p->chk_uri,
995                                  p->expirationTime,
996                                  p->anonymity,
997                                  p->priority,
998                                  pc->options,
999                                  &publish_kblocks_cont,
1000                                  pc);
1001         }
1002       else
1003         {
1004           publish_kblocks_cont (pc,
1005                                 p->chk_uri,
1006                                 NULL);
1007         }
1008       return;
1009     }
1010   if ( (!p->is_directory) &&
1011        (p->data.file.do_index) )
1012     {
1013       if (NULL == p->filename)
1014         {
1015           p->data.file.do_index = GNUNET_NO;
1016           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1017                       _("Can not index file `%s': %s.  Will try to insert instead.\n"),
1018                       "<no-name>",
1019                       _("needs to be an actual file"));
1020           GNUNET_FS_file_information_sync_ (p);
1021           publish_content (pc);
1022           return;
1023         }      
1024       if (p->data.file.have_hash)
1025         {
1026           hash_for_index_cb (pc,
1027                              &p->data.file.file_id);
1028         }
1029       else
1030         {
1031           p->start_time = GNUNET_TIME_absolute_get ();
1032           pc->fhc = GNUNET_CRYPTO_hash_file (pc->h->sched,
1033                                              GNUNET_SCHEDULER_PRIORITY_IDLE,
1034                                              p->filename,
1035                                              HASHING_BLOCKSIZE,
1036                                              &hash_for_index_cb,
1037                                              pc);
1038         }
1039       return;
1040     }
1041   publish_content (pc);
1042 }
1043
1044
1045 /**
1046  * Signal the FS's progress function that we are starting
1047  * an upload.
1048  *
1049  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1050  * @param fi the entry in the publish-structure
1051  * @param length length of the file or directory
1052  * @param meta metadata for the file or directory (can be modified)
1053  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1054  * @param anonymity pointer to selected anonymity level (can be modified)
1055  * @param priority pointer to selected priority (can be modified)
1056  * @param do_index should we index?
1057  * @param expirationTime pointer to selected expiration time (can be modified)
1058  * @param client_info pointer to client context set upon creation (can be modified)
1059  * @return GNUNET_OK to continue (always)
1060  */
1061 static int
1062 fip_signal_start(void *cls,
1063                  struct GNUNET_FS_FileInformation *fi,
1064                  uint64_t length,
1065                  struct GNUNET_CONTAINER_MetaData *meta,
1066                  struct GNUNET_FS_Uri **uri,
1067                  uint32_t *anonymity,
1068                  uint32_t *priority,
1069                  int *do_index,
1070                  struct GNUNET_TIME_Absolute *expirationTime,
1071                  void **client_info)
1072 {
1073   struct GNUNET_FS_PublishContext *sc = cls;
1074   struct GNUNET_FS_ProgressInfo pi;
1075   unsigned int kc;
1076   uint64_t left;
1077
1078   if (*do_index)
1079     {
1080       /* space for on-demand blocks */
1081       sc->reserve_space += ((length + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * sizeof (struct OnDemandBlock);
1082     }
1083   else
1084     {
1085       /* space for DBlocks */
1086       sc->reserve_space += length;
1087     }
1088   /* entries for IBlocks and DBlocks, space for IBlocks */
1089   left = length;
1090   while (1)
1091     {
1092       left = (left + DBLOCK_SIZE - 1) / DBLOCK_SIZE;
1093       sc->reserve_entries += left;
1094       if (left <= 1)
1095         break;
1096       left = left * sizeof (struct ContentHashKey);
1097       sc->reserve_space += left;
1098     }
1099   /* entries and space for keywords */
1100   if (NULL != *uri)
1101     {
1102       kc = GNUNET_FS_uri_ksk_get_keyword_count (*uri);
1103       sc->reserve_entries += kc;
1104       sc->reserve_space += GNUNET_SERVER_MAX_MESSAGE_SIZE * kc;
1105     }  
1106   pi.status = GNUNET_FS_STATUS_PUBLISH_START;
1107   *client_info = GNUNET_FS_publish_make_status_ (&pi, sc, fi, 0);
1108   GNUNET_FS_file_information_sync_ (fi);
1109   return GNUNET_OK;
1110 }
1111
1112
1113 /**
1114  * Signal the FS's progress function that we are suspending
1115  * an upload.
1116  *
1117  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1118  * @param fi the entry in the publish-structure
1119  * @param length length of the file or directory
1120  * @param meta metadata for the file or directory (can be modified)
1121  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1122  * @param anonymity pointer to selected anonymity level (can be modified)
1123  * @param priority pointer to selected priority (can be modified)
1124  * @param do_index should we index?
1125  * @param expirationTime pointer to selected expiration time (can be modified)
1126  * @param client_info pointer to client context set upon creation (can be modified)
1127  * @return GNUNET_OK to continue (always)
1128  */
1129 static int
1130 fip_signal_suspend(void *cls,
1131                    struct GNUNET_FS_FileInformation *fi,
1132                    uint64_t length,
1133                    struct GNUNET_CONTAINER_MetaData *meta,
1134                    struct GNUNET_FS_Uri **uri,
1135                    uint32_t *anonymity,
1136                    uint32_t *priority,
1137                    int *do_index,
1138                    struct GNUNET_TIME_Absolute *expirationTime,
1139                    void **client_info)
1140 {
1141   struct GNUNET_FS_PublishContext*sc = cls;
1142   struct GNUNET_FS_ProgressInfo pi;
1143   uint64_t off;
1144
1145   GNUNET_free_non_null (fi->serialization);
1146   fi->serialization = NULL;    
1147   off = (fi->chk_uri == NULL) ? 0 : length;
1148   pi.status = GNUNET_FS_STATUS_PUBLISH_SUSPEND;
1149   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, sc, fi, off));
1150   *client_info = NULL;
1151   if (NULL != sc->dsh)
1152     {
1153       GNUNET_DATASTORE_disconnect (sc->dsh, GNUNET_NO);
1154       sc->dsh = NULL;
1155     }
1156   return GNUNET_OK;
1157 }
1158
1159
1160 /**
1161  * Create SUSPEND event for the given publish operation
1162  * and then clean up our state (without stop signal).
1163  *
1164  * @param cls the 'struct GNUNET_FS_PublishContext' to signal for
1165  */
1166 void
1167 GNUNET_FS_publish_signal_suspend_ (void *cls)
1168 {
1169   struct GNUNET_FS_PublishContext *pc = cls;
1170
1171   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1172     {
1173       GNUNET_SCHEDULER_cancel (pc->h->sched, pc->upload_task);
1174       pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1175     }
1176   GNUNET_FS_file_information_inspect (pc->fi,
1177                                       &fip_signal_suspend,
1178                                       pc);
1179   GNUNET_FS_end_top (pc->h, pc->top);
1180   publish_cleanup (pc, NULL);
1181 }
1182
1183
1184 /**
1185  * We have gotten a reply for our space reservation request.
1186  * Either fail (insufficient space) or start publishing for good.
1187  * 
1188  * @param cls the 'struct GNUNET_FS_PublishContext*'
1189  * @param success positive reservation ID on success
1190  * @param msg error message on error, otherwise NULL
1191  */
1192 static void
1193 finish_reserve (void *cls,
1194                 int success,
1195                 const char *msg)
1196 {
1197   struct GNUNET_FS_PublishContext *pc = cls;
1198
1199   pc->qre = NULL;
1200   if ( (msg != NULL) ||
1201        (success <= 0) )
1202     {
1203       GNUNET_asprintf (&pc->fi->emsg, 
1204                        _("Insufficient space for publishing: %s"),
1205                        msg);
1206       signal_publish_error (pc->fi,
1207                             pc,
1208                             pc->fi->emsg);
1209       return;
1210     }
1211   pc->rid = success;
1212   pc->upload_task 
1213     = GNUNET_SCHEDULER_add_with_priority (pc->h->sched,
1214                                           GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1215                                           &GNUNET_FS_publish_main_,
1216                                           pc);
1217 }
1218
1219
1220 /**
1221  * Publish a file or directory.
1222  *
1223  * @param h handle to the file sharing subsystem
1224  * @param fi information about the file or directory structure to publish
1225  * @param namespace namespace to publish the file in, NULL for no namespace
1226  * @param nid identifier to use for the publishd content in the namespace
1227  *        (can be NULL, must be NULL if namespace is NULL)
1228  * @param nuid update-identifier that will be used for future updates 
1229  *        (can be NULL, must be NULL if namespace or nid is NULL)
1230  * @param options options for the publication 
1231  * @return context that can be used to control the publish operation
1232  */
1233 struct GNUNET_FS_PublishContext *
1234 GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h,
1235                          struct GNUNET_FS_FileInformation *fi,
1236                          struct GNUNET_FS_Namespace *namespace,
1237                          const char *nid,
1238                          const char *nuid,
1239                          enum GNUNET_FS_PublishOptions options)
1240 {
1241   struct GNUNET_FS_PublishContext *ret;
1242   struct GNUNET_DATASTORE_Handle *dsh;
1243
1244   GNUNET_assert (NULL != h);
1245   if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1246     {
1247       dsh = GNUNET_DATASTORE_connect (h->cfg,
1248                                       h->sched);
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 (h->sched,
1295                                               GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1296                                               &GNUNET_FS_publish_main_,
1297                                               ret);
1298     }
1299   return ret;
1300 }
1301
1302
1303 /**
1304  * Signal the FS's progress function that we are stopping
1305  * an upload.
1306  *
1307  * @param cls closure (of type "struct GNUNET_FS_PublishContext*")
1308  * @param fi the entry in the publish-structure
1309  * @param length length of the file or directory
1310  * @param meta metadata for the file or directory (can be modified)
1311  * @param uri pointer to the keywords that will be used for this entry (can be modified)
1312  * @param anonymity pointer to selected anonymity level (can be modified)
1313  * @param priority pointer to selected priority (can be modified)
1314  * @param do_index should we index?
1315  * @param expirationTime pointer to selected expiration time (can be modified)
1316  * @param client_info pointer to client context set upon creation (can be modified)
1317  * @return GNUNET_OK to continue (always)
1318  */
1319 static int
1320 fip_signal_stop(void *cls,
1321                 struct GNUNET_FS_FileInformation *fi,
1322                 uint64_t length,
1323                 struct GNUNET_CONTAINER_MetaData *meta,
1324                 struct GNUNET_FS_Uri **uri,
1325                 uint32_t *anonymity,
1326                 uint32_t *priority,
1327                 int *do_index,
1328                 struct GNUNET_TIME_Absolute *expirationTime,
1329                 void **client_info)
1330 {
1331   struct GNUNET_FS_PublishContext*sc = cls;
1332   struct GNUNET_FS_ProgressInfo pi;
1333   uint64_t off;
1334
1335   if (fi->serialization != NULL) 
1336     {
1337       GNUNET_FS_remove_sync_file_ (sc->h,
1338                                    GNUNET_FS_SYNC_PATH_FILE_INFO,
1339                                    fi->serialization);
1340       GNUNET_free (fi->serialization);
1341       fi->serialization = NULL;
1342     }
1343   off = (fi->chk_uri == NULL) ? 0 : length;
1344   pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED;
1345   GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, sc, fi, off));
1346   *client_info = NULL;
1347   return GNUNET_OK;
1348 }
1349
1350
1351 /**
1352  * Stop an upload.  Will abort incomplete uploads (but 
1353  * not remove blocks that have already been publishd) or
1354  * simply clean up the state for completed uploads.
1355  * Must NOT be called from within the event callback!
1356  *
1357  * @param pc context for the upload to stop
1358  */
1359 void 
1360 GNUNET_FS_publish_stop (struct GNUNET_FS_PublishContext *pc)
1361 {
1362   GNUNET_FS_end_top (pc->h, pc->top);
1363   if (NULL != pc->qre)
1364     {
1365       GNUNET_DATASTORE_cancel (pc->qre);
1366       pc->qre = NULL;
1367     }
1368   if (NULL != pc->dsh)
1369     {
1370       GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO);
1371       pc->dsh = NULL;
1372     }
1373   if (GNUNET_SCHEDULER_NO_TASK != pc->upload_task)
1374     {
1375       GNUNET_SCHEDULER_cancel (pc->h->sched, pc->upload_task);
1376       pc->upload_task = GNUNET_SCHEDULER_NO_TASK;
1377     }
1378   if (pc->serialization != NULL) 
1379     {
1380       GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, pc->serialization);
1381       GNUNET_free (pc->serialization);
1382       pc->serialization = NULL;
1383     }
1384   GNUNET_FS_file_information_inspect (pc->fi,
1385                                       &fip_signal_stop,
1386                                       pc);
1387   if (GNUNET_YES == pc->in_network_wait)
1388     {
1389       pc->in_network_wait = GNUNET_SYSERR;
1390       return;
1391     }
1392   publish_cleanup (pc, NULL);
1393 }
1394
1395
1396 /**
1397  * Context for the KSK publication.
1398  */
1399 struct PublishKskContext
1400 {
1401
1402   /**
1403    * Keywords to use.
1404    */
1405   struct GNUNET_FS_Uri *ksk_uri;
1406
1407   /**
1408    * Global FS context.
1409    */
1410   struct GNUNET_FS_Handle *h;
1411
1412   /**
1413    * The master block that we are sending
1414    * (in plaintext), has "mdsize+slen" more
1415    * bytes than the struct would suggest.
1416    */
1417   struct KBlock *kb;
1418
1419   /**
1420    * Buffer of the same size as "kb" for
1421    * the encrypted version.
1422    */ 
1423   struct KBlock *cpy;
1424
1425   /**
1426    * Handle to the datastore, NULL if we are just
1427    * simulating.
1428    */
1429   struct GNUNET_DATASTORE_Handle *dsh;
1430
1431   /**
1432    * Function to call once we're done.
1433    */
1434   GNUNET_FS_PublishContinuation cont;
1435
1436   /**
1437    * Closure for cont.
1438    */ 
1439   void *cont_cls;
1440
1441   /**
1442    * When should the KBlocks expire?
1443    */
1444   struct GNUNET_TIME_Absolute expirationTime;
1445
1446   /**
1447    * Size of the serialized metadata.
1448    */
1449   ssize_t mdsize;
1450
1451   /**
1452    * Size of the (CHK) URI as a string.
1453    */
1454   size_t slen;
1455
1456   /**
1457    * Keyword that we are currently processing.
1458    */
1459   unsigned int i;
1460
1461   /**
1462    * Anonymity level for the KBlocks.
1463    */
1464   uint32_t anonymity;
1465
1466   /**
1467    * Priority for the KBlocks.
1468    */
1469   uint32_t priority;
1470 };
1471
1472
1473 /**
1474  * Continuation of "GNUNET_FS_publish_ksk" that performs
1475  * the actual publishing operation (iterating over all
1476  * of the keywords).
1477  *
1478  * @param cls closure of type "struct PublishKskContext*"
1479  * @param tc unused
1480  */
1481 static void
1482 publish_ksk_cont (void *cls,
1483                   const struct GNUNET_SCHEDULER_TaskContext *tc);
1484
1485
1486 /**
1487  * Function called by the datastore API with
1488  * the result from the PUT request.
1489  *
1490  * @param cls closure of type "struct PublishKskContext*"
1491  * @param success GNUNET_OK on success
1492  * @param msg error message (or NULL)
1493  */
1494 static void
1495 kb_put_cont (void *cls,
1496              int success,
1497              const char *msg)
1498 {
1499   struct PublishKskContext *pkc = cls;
1500
1501   if (GNUNET_OK != success)
1502     {
1503       if (NULL != pkc->dsh)
1504         {
1505           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1506           pkc->dsh = NULL;
1507         }
1508       GNUNET_free (pkc->cpy);
1509       GNUNET_free (pkc->kb);
1510       pkc->cont (pkc->cont_cls,
1511                  NULL,
1512                  msg);
1513       GNUNET_FS_uri_destroy (pkc->ksk_uri);
1514       GNUNET_free (pkc);
1515       return;
1516     }
1517   GNUNET_SCHEDULER_add_continuation (pkc->h->sched,
1518                                      &publish_ksk_cont,
1519                                      pkc,
1520                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1521 }
1522
1523
1524 /**
1525  * Continuation of "GNUNET_FS_publish_ksk" that performs the actual
1526  * publishing operation (iterating over all of the keywords).
1527  *
1528  * @param cls closure of type "struct PublishKskContext*"
1529  * @param tc unused
1530  */
1531 static void
1532 publish_ksk_cont (void *cls,
1533                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1534 {
1535   struct PublishKskContext *pkc = cls;
1536   const char *keyword;
1537   GNUNET_HashCode key;
1538   GNUNET_HashCode query;
1539   struct GNUNET_CRYPTO_AesSessionKey skey;
1540   struct GNUNET_CRYPTO_AesInitializationVector iv;
1541   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1542
1543
1544   if ( (pkc->i == pkc->ksk_uri->data.ksk.keywordCount) ||
1545        (NULL == pkc->dsh) )
1546     {
1547       if (NULL != pkc->dsh)
1548         {
1549           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1550           pkc->dsh = NULL;
1551         }
1552       GNUNET_free (pkc->cpy);
1553       GNUNET_free (pkc->kb);
1554       pkc->cont (pkc->cont_cls,
1555                  pkc->ksk_uri,
1556                  NULL);
1557       GNUNET_FS_uri_destroy (pkc->ksk_uri);
1558       GNUNET_free (pkc);
1559       return;
1560     }
1561   keyword = pkc->ksk_uri->data.ksk.keywords[pkc->i++];
1562   /* first character of keyword indicates if it is
1563      mandatory or not -- ignore for hashing */
1564   GNUNET_CRYPTO_hash (&keyword[1], strlen (&keyword[1]), &key);
1565   GNUNET_CRYPTO_hash_to_aes_key (&key, &skey, &iv);
1566   GNUNET_CRYPTO_aes_encrypt (&pkc->kb[1],
1567                              pkc->slen + pkc->mdsize,
1568                              &skey,
1569                              &iv,
1570                              &pkc->cpy[1]);
1571   pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&key);
1572   GNUNET_assert (NULL != pk);
1573   GNUNET_CRYPTO_rsa_key_get_public (pk, &pkc->cpy->keyspace);
1574   GNUNET_CRYPTO_hash (&pkc->cpy->keyspace,
1575                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1576                       &query);
1577   GNUNET_assert (GNUNET_OK == 
1578                  GNUNET_CRYPTO_rsa_sign (pk,
1579                                          &pkc->cpy->purpose,
1580                                          &pkc->cpy->signature));
1581   GNUNET_CRYPTO_rsa_key_free (pk);
1582   GNUNET_DATASTORE_put (pkc->dsh,
1583                         0,
1584                         &query,
1585                         pkc->mdsize + 
1586                         sizeof (struct KBlock) + 
1587                         pkc->slen,
1588                         pkc->cpy,
1589                         GNUNET_BLOCK_TYPE_KBLOCK, 
1590                         pkc->priority,
1591                         pkc->anonymity,
1592                         pkc->expirationTime,
1593                         -2, 1,
1594                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1595                         &kb_put_cont,
1596                         pkc);
1597 }
1598
1599
1600 /**
1601  * Publish a CHK under various keywords on GNUnet.
1602  *
1603  * @param h handle to the file sharing subsystem
1604  * @param ksk_uri keywords to use
1605  * @param meta metadata to use
1606  * @param uri URI to refer to in the KBlock
1607  * @param expirationTime when the KBlock expires
1608  * @param anonymity anonymity level for the KBlock
1609  * @param priority priority for the KBlock
1610  * @param options publication options
1611  * @param cont continuation
1612  * @param cont_cls closure for cont
1613  */
1614 void
1615 GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h,
1616                        const struct GNUNET_FS_Uri *ksk_uri,
1617                        const struct GNUNET_CONTAINER_MetaData *meta,
1618                        const struct GNUNET_FS_Uri *uri,
1619                        struct GNUNET_TIME_Absolute expirationTime,
1620                        uint32_t anonymity,
1621                        uint32_t priority,
1622                        enum GNUNET_FS_PublishOptions options,
1623                        GNUNET_FS_PublishContinuation cont,
1624                        void *cont_cls)
1625 {
1626   struct PublishKskContext *pkc;
1627   char *uris;
1628   size_t size;
1629   char *kbe;
1630   char *sptr;
1631
1632   pkc = GNUNET_malloc (sizeof (struct PublishKskContext));
1633   pkc->h = h;
1634   pkc->expirationTime = expirationTime;
1635   pkc->anonymity = anonymity;
1636   pkc->priority = priority;
1637   pkc->cont = cont;
1638   pkc->cont_cls = cont_cls;
1639   if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1640     {
1641       pkc->dsh = GNUNET_DATASTORE_connect (h->cfg,
1642                                            h->sched);
1643       if (pkc->dsh == NULL)
1644         {
1645           cont (cont_cls, NULL, _("Could not connect to datastore."));
1646           GNUNET_free (pkc);
1647           return;
1648         }
1649     }
1650   if (meta == NULL)
1651     pkc->mdsize = 0;
1652   else
1653     pkc->mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (meta);
1654   GNUNET_assert (pkc->mdsize >= 0);
1655   uris = GNUNET_FS_uri_to_string (uri);
1656   pkc->slen = strlen (uris) + 1;
1657   size = pkc->mdsize + sizeof (struct KBlock) + pkc->slen;
1658   if (size > MAX_KBLOCK_SIZE)
1659     {
1660       size = MAX_KBLOCK_SIZE;
1661       pkc->mdsize = size - sizeof (struct KBlock) - pkc->slen;
1662     }
1663   pkc->kb = GNUNET_malloc (size);
1664   kbe = (char *) &pkc->kb[1];
1665   memcpy (kbe, uris, pkc->slen);
1666   GNUNET_free (uris);
1667   sptr = &kbe[pkc->slen];
1668   if (meta != NULL)
1669     pkc->mdsize = GNUNET_CONTAINER_meta_data_serialize (meta,
1670                                                         &sptr,
1671                                                         pkc->mdsize,
1672                                                         GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
1673   if (pkc->mdsize == -1)
1674     {
1675       GNUNET_break (0);
1676       GNUNET_free (pkc->kb);
1677       if (pkc->dsh != NULL)
1678         {
1679           GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO);
1680           pkc->dsh = NULL;
1681         }
1682       cont (cont_cls, NULL, _("Internal error."));
1683       GNUNET_free (pkc);
1684       return;
1685     }
1686   size = sizeof (struct KBlock) + pkc->slen + pkc->mdsize;
1687
1688   pkc->cpy = GNUNET_malloc (size);
1689   pkc->cpy->purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) + 
1690                                   sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1691                                   pkc->mdsize + 
1692                                   pkc->slen);
1693   pkc->cpy->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK);
1694   pkc->ksk_uri = GNUNET_FS_uri_dup (ksk_uri);
1695   GNUNET_SCHEDULER_add_continuation (h->sched,
1696                                      &publish_ksk_cont,
1697                                      pkc,
1698                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1699 }
1700
1701
1702 /**
1703  * Context for the SKS publication.
1704  */
1705 struct PublishSksContext
1706 {
1707
1708   /**
1709    * Global FS context.
1710    */
1711   struct GNUNET_FS_Uri *uri;
1712
1713   /**
1714    * Handle to the datastore.
1715    */
1716   struct GNUNET_DATASTORE_Handle *dsh;
1717
1718   /**
1719    * Function to call once we're done.
1720    */
1721   GNUNET_FS_PublishContinuation cont;
1722
1723   /**
1724    * Closure for cont.
1725    */ 
1726   void *cont_cls;
1727
1728 };
1729
1730
1731 /**
1732  * Function called by the datastore API with
1733  * the result from the PUT (SBlock) request.
1734  *
1735  * @param cls closure of type "struct PublishSksContext*"
1736  * @param success GNUNET_OK on success
1737  * @param msg error message (or NULL)
1738  */
1739 static void
1740 sb_put_cont (void *cls,
1741              int success,
1742              const char *msg)
1743 {
1744   struct PublishSksContext *psc = cls;
1745
1746   if (NULL != psc->dsh)
1747     {
1748       GNUNET_DATASTORE_disconnect (psc->dsh, GNUNET_NO);
1749       psc->dsh = NULL;
1750     }
1751   if (GNUNET_OK != success)
1752     psc->cont (psc->cont_cls,
1753                NULL,
1754                msg);
1755   else
1756     psc->cont (psc->cont_cls,
1757                psc->uri,
1758                NULL);
1759   GNUNET_FS_uri_destroy (psc->uri);
1760   GNUNET_free (psc);
1761 }
1762
1763
1764 /**
1765  * Publish an SBlock on GNUnet.
1766  *
1767  * @param h handle to the file sharing subsystem
1768  * @param namespace namespace to publish in
1769  * @param identifier identifier to use
1770  * @param update update identifier to use
1771  * @param meta metadata to use
1772  * @param uri URI to refer to in the SBlock
1773  * @param expirationTime when the SBlock expires
1774  * @param anonymity anonymity level for the SBlock
1775  * @param priority priority for the SBlock
1776  * @param options publication options
1777  * @param cont continuation
1778  * @param cont_cls closure for cont
1779  */
1780 void
1781 GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h,
1782                        struct GNUNET_FS_Namespace *namespace,
1783                        const char *identifier,
1784                        const char *update,
1785                        const struct GNUNET_CONTAINER_MetaData *meta,
1786                        const struct GNUNET_FS_Uri *uri,
1787                        struct GNUNET_TIME_Absolute expirationTime,
1788                        uint32_t anonymity,
1789                        uint32_t priority,
1790                        enum GNUNET_FS_PublishOptions options,
1791                        GNUNET_FS_PublishContinuation cont,
1792                        void *cont_cls)
1793 {
1794   struct PublishSksContext *psc;
1795   struct GNUNET_CRYPTO_AesSessionKey sk;
1796   struct GNUNET_CRYPTO_AesInitializationVector iv;
1797   struct GNUNET_FS_Uri *sks_uri;
1798   char *uris;
1799   size_t size;
1800   size_t slen;
1801   size_t nidlen;
1802   size_t idlen;
1803   ssize_t mdsize;
1804   struct SBlock *sb;
1805   struct SBlock *sb_enc;
1806   char *dest;
1807   struct GNUNET_CONTAINER_MetaData *mmeta;
1808   GNUNET_HashCode key;         /* hash of thisId = key */
1809   GNUNET_HashCode id;          /* hash of hc = identifier */
1810   GNUNET_HashCode query;       /* id ^ nsid = DB query */
1811
1812   if (NULL == meta)
1813     mmeta = GNUNET_CONTAINER_meta_data_create ();
1814   else
1815     mmeta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1816   uris = GNUNET_FS_uri_to_string (uri);
1817   slen = strlen (uris) + 1;
1818   idlen = strlen (identifier);
1819   if (update == NULL)
1820     update = "";
1821   nidlen = strlen (update) + 1;
1822   mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (mmeta);
1823   size = sizeof (struct SBlock) + slen + nidlen + mdsize;
1824   if (size > MAX_SBLOCK_SIZE)
1825     {
1826       size = MAX_SBLOCK_SIZE;
1827       mdsize = size - (sizeof (struct SBlock) + slen + nidlen);
1828     }
1829   sb = GNUNET_malloc (sizeof (struct SBlock) + size);
1830   dest = (char *) &sb[1];
1831   memcpy (dest, update, nidlen);
1832   dest += nidlen;
1833   memcpy (dest, uris, slen);
1834   GNUNET_free (uris);
1835   dest += slen;
1836   mdsize = GNUNET_CONTAINER_meta_data_serialize (mmeta,
1837                                                  &dest,
1838                                                  mdsize, 
1839                                                  GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
1840   GNUNET_CONTAINER_meta_data_destroy (mmeta);
1841   if (mdsize == -1)
1842     {
1843       GNUNET_break (0);
1844       GNUNET_free (sb);
1845       cont (cont_cls,
1846             NULL,
1847             _("Internal error."));
1848       return;
1849     }
1850   size = sizeof (struct SBlock) + mdsize + slen + nidlen;
1851   sb_enc = GNUNET_malloc (size);
1852   GNUNET_CRYPTO_hash (identifier, idlen, &key);
1853   GNUNET_CRYPTO_hash (&key, sizeof (GNUNET_HashCode), &id);
1854   sks_uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
1855   sks_uri->type = sks;
1856   GNUNET_CRYPTO_rsa_key_get_public (namespace->key, &sb_enc->subspace);
1857   GNUNET_CRYPTO_hash (&sb_enc->subspace,
1858                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1859                       &sks_uri->data.sks.namespace);
1860   sks_uri->data.sks.identifier = GNUNET_strdup (identifier);
1861   GNUNET_CRYPTO_hash_xor (&id, 
1862                           &sks_uri->data.sks.namespace, 
1863                           &sb_enc->identifier);
1864   GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
1865   GNUNET_CRYPTO_aes_encrypt (&sb[1],
1866                              size - sizeof (struct SBlock),
1867                              &sk,
1868                              &iv,
1869                              &sb_enc[1]);
1870   sb_enc->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK);
1871   sb_enc->purpose.size = htonl(slen + mdsize + nidlen
1872                                + sizeof(struct SBlock)
1873                                - sizeof(struct GNUNET_CRYPTO_RsaSignature));
1874   GNUNET_assert (GNUNET_OK == 
1875                  GNUNET_CRYPTO_rsa_sign (namespace->key,
1876                                          &sb_enc->purpose,
1877                                          &sb_enc->signature));
1878   psc = GNUNET_malloc (sizeof(struct PublishSksContext));
1879   psc->uri = sks_uri;
1880   psc->cont = cont;
1881   psc->cont_cls = cont_cls;
1882   if (0 != (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
1883     {
1884       GNUNET_free (sb_enc);
1885       GNUNET_free (sb);
1886       sb_put_cont (psc,
1887                    GNUNET_OK,
1888                    NULL);
1889       return;
1890     }
1891   psc->dsh = GNUNET_DATASTORE_connect (h->cfg, h->sched);
1892   if (NULL == psc->dsh)
1893     {
1894       GNUNET_free (sb_enc);
1895       GNUNET_free (sb);
1896       sb_put_cont (psc,
1897                    GNUNET_NO,
1898                    _("Failed to connect to datastore."));
1899       return;
1900     }
1901   GNUNET_CRYPTO_hash_xor (&sks_uri->data.sks.namespace,
1902                           &id,
1903                           &query);  
1904   GNUNET_DATASTORE_put (psc->dsh,
1905                         0,
1906                         &sb_enc->identifier,
1907                         size,
1908                         sb_enc,
1909                         GNUNET_BLOCK_TYPE_SBLOCK, 
1910                         priority,
1911                         anonymity,
1912                         expirationTime,
1913                         -2, 1,
1914                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1915                         &sb_put_cont,
1916                         psc);
1917   GNUNET_free (sb);
1918   GNUNET_free (sb_enc);
1919 }
1920
1921 /* end of fs_publish.c */