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