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