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