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