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