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