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