small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[oweals/gnunet.git] / src / fs / fs_dirmetascan.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2005-2012 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file fs/fs_dirmetascan.c
23  * @brief code to asynchronously build a 'struct GNUNET_FS_ShareTreeItem'
24  *        from an on-disk directory for publishing; use the 'gnunet-helper-fs-publish'.
25  * @author LRN
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_fs_service.h"
30 #include "gnunet_scheduler_lib.h"
31 #include <pthread.h>
32
33
34 /**
35  * An opaque structure a pointer to which is returned to the
36  * caller to be used to control the scanner.
37  */
38 struct GNUNET_FS_DirScanner
39 {
40
41   /**
42    * Helper process.
43    */
44   struct GNUNET_HELPER_Handle *helper;
45
46   /**
47    * Expanded filename (as given by the scan initiator).
48    * The scanner thread stores a copy here, and frees it when it finishes.
49    */
50   char *filename_expanded;
51
52   /**
53    * Second argument to helper process.
54    */
55   char *ex_arg;
56
57   /**
58    * The function that will be called every time there's a progress
59    * message.
60    */
61   GNUNET_FS_DirScannerProgressCallback progress_callback;
62
63   /**
64    * A closure for progress_callback.
65    */
66   void *progress_callback_cls;
67
68   /**
69    * After the scan is finished, it will contain a pointer to the
70    * top-level directory entry in the directory tree built by the
71    * scanner.
72    */
73   struct GNUNET_FS_ShareTreeItem *toplevel;
74
75   /**
76    * Current position during processing.
77    */
78   struct GNUNET_FS_ShareTreeItem *pos;
79
80   /**
81    * Task scheduled when we are done.
82    */
83   struct GNUNET_SCHEDULER_Task * stop_task;
84
85   /**
86    * Arguments for helper.
87    */
88   char *args[4];
89
90 };
91
92
93 /**
94  * Abort the scan.  Must not be called from within the progress_callback
95  * function.
96  *
97  * @param ds directory scanner structure
98  */
99 void
100 GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds)
101 {
102   /* terminate helper */
103   if (NULL != ds->helper)
104     GNUNET_HELPER_stop (ds->helper, GNUNET_NO);
105
106   /* free resources */
107   if (NULL != ds->toplevel)
108     GNUNET_FS_share_tree_free (ds->toplevel);
109   if (NULL != ds->stop_task)
110     GNUNET_SCHEDULER_cancel (ds->stop_task);
111   GNUNET_free_non_null (ds->ex_arg);
112   GNUNET_free (ds->filename_expanded);
113   GNUNET_free (ds);
114 }
115
116
117 /**
118  * Obtain the result of the scan after the scan has signalled
119  * completion.  Must not be called prior to completion.  The 'ds' is
120  * freed as part of this call.
121  *
122  * @param ds directory scanner structure
123  * @return the results of the scan (a directory tree)
124  */
125 struct GNUNET_FS_ShareTreeItem *
126 GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds)
127 {
128   struct GNUNET_FS_ShareTreeItem *result;
129
130   /* check that we're actually done */
131   GNUNET_assert (NULL == ds->helper);
132   /* preserve result */
133   result = ds->toplevel;
134   ds->toplevel = NULL;
135   GNUNET_FS_directory_scan_abort (ds);
136   return result;
137 }
138
139
140 /**
141  * Move in the directory from the given position to the next file
142  * in DFS traversal.
143  *
144  * @param pos current position
145  * @return next file, NULL for none
146  */
147 static struct GNUNET_FS_ShareTreeItem *
148 advance (struct GNUNET_FS_ShareTreeItem *pos)
149 {
150   int moved;
151
152   GNUNET_assert (NULL != pos);
153   moved = 0; /* must not terminate, even on file, otherwise "normal" */
154   while ( (pos->is_directory == GNUNET_YES) ||
155           (0 == moved) )
156   {
157     if ( (moved != -1) &&
158          (NULL != pos->children_head) )
159     {
160       pos = pos->children_head;
161       moved = 1; /* can terminate if file */
162       continue;
163     }
164     if (NULL != pos->next)
165     {
166       pos = pos->next;
167       moved = 1; /* can terminate if file */
168       continue;
169     }
170     if (NULL != pos->parent)
171     {
172       pos = pos->parent;
173       moved = -1; /* force move to 'next' or 'parent' */
174       continue;
175     }
176     /* no more options, end of traversal */
177     return NULL;
178   }
179   return pos;
180 }
181
182
183 /**
184  * Add another child node to the tree.
185  *
186  * @param parent parent of the child, NULL for top level
187  * @param filename name of the file or directory
188  * @param is_directory GNUNET_YES for directories
189  * @return new entry that was just created
190  */
191 static struct GNUNET_FS_ShareTreeItem *
192 expand_tree (struct GNUNET_FS_ShareTreeItem *parent,
193              const char *filename,
194              int is_directory)
195 {
196   struct GNUNET_FS_ShareTreeItem *chld;
197   size_t slen;
198
199   chld = GNUNET_new (struct GNUNET_FS_ShareTreeItem);
200   chld->parent = parent;
201   chld->filename = GNUNET_strdup (filename);
202   GNUNET_asprintf (&chld->short_filename,
203                    "%s%s",
204                    GNUNET_STRINGS_get_short_name (filename),
205                    is_directory == GNUNET_YES ? "/" : "");
206   /* make sure we do not end with '//' */
207   slen = strlen (chld->short_filename);
208   if ( (slen >= 2) &&
209        (chld->short_filename[slen-1] == '/') &&
210        (chld->short_filename[slen-2] == '/') )
211     chld->short_filename[slen-1] = '\0';
212   chld->is_directory = is_directory;
213   if (NULL != parent)
214       GNUNET_CONTAINER_DLL_insert (parent->children_head,
215                                    parent->children_tail,
216                                    chld);
217   return chld;
218 }
219
220
221 /**
222  * Task run last to shut everything down.
223  *
224  * @param cls the 'struct GNUNET_FS_DirScanner'
225  */
226 static void
227 finish_scan (void *cls)
228 {
229   struct GNUNET_FS_DirScanner *ds = cls;
230
231   ds->stop_task = NULL;
232   if (NULL != ds->helper)
233   {
234     GNUNET_HELPER_stop (ds->helper, GNUNET_NO);
235     ds->helper = NULL;
236   }
237   ds->progress_callback (ds->progress_callback_cls,
238                          NULL, GNUNET_SYSERR,
239                          GNUNET_FS_DIRSCANNER_FINISHED);
240 }
241
242
243 /**
244  * Called every time there is data to read from the scanner.
245  * Calls the scanner progress handler.
246  *
247  * @param cls the closure (directory scanner object)
248  * @param client always NULL
249  * @param msg message from the helper process
250  */
251 static int
252 process_helper_msgs (void *cls,
253                      void *client,
254                      const struct GNUNET_MessageHeader *msg)
255 {
256   struct GNUNET_FS_DirScanner *ds = cls;
257   const char *filename;
258   size_t left;
259
260 #if 0
261   fprintf (stderr, "DMS parses %u-byte message of type %u\n",
262            (unsigned int) ntohs (msg->size),
263            (unsigned int) ntohs (msg->type));
264 #endif
265   left = ntohs (msg->size) - sizeof (struct GNUNET_MessageHeader);
266   filename = (const char*) &msg[1];
267   switch (ntohs (msg->type))
268   {
269   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE:
270     if (filename[left-1] != '\0')
271     {
272       GNUNET_break (0);
273       break;
274     }
275     ds->progress_callback (ds->progress_callback_cls,
276                            filename, GNUNET_NO,
277                            GNUNET_FS_DIRSCANNER_FILE_START);
278     if (NULL == ds->toplevel)
279       ds->toplevel = expand_tree (ds->pos,
280                                   filename, GNUNET_NO);
281     else
282       (void) expand_tree (ds->pos,
283                           filename, GNUNET_NO);
284     return GNUNET_OK;
285   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY:
286     if (filename[left-1] != '\0')
287     {
288       GNUNET_break (0);
289       break;
290     }
291     if (0 == strcmp ("..", filename))
292     {
293       if (NULL == ds->pos)
294       {
295         GNUNET_break (0);
296         break;
297       }
298       ds->pos = ds->pos->parent;
299       return GNUNET_OK;
300     }
301     ds->progress_callback (ds->progress_callback_cls,
302                            filename, GNUNET_YES,
303                            GNUNET_FS_DIRSCANNER_FILE_START);
304     ds->pos = expand_tree (ds->pos,
305                            filename, GNUNET_YES);
306     if (NULL == ds->toplevel)
307       ds->toplevel = ds->pos;
308     return GNUNET_OK;
309   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR:
310     break;
311   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE:
312     if ('\0' != filename[left-1])
313       break;
314     ds->progress_callback (ds->progress_callback_cls,
315                            filename, GNUNET_SYSERR,
316                            GNUNET_FS_DIRSCANNER_FILE_IGNORED);
317     return GNUNET_OK;
318   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE:
319     if (0 != left)
320     {
321       GNUNET_break (0);
322       break;
323     }
324     if (NULL == ds->toplevel)
325     {
326       GNUNET_break (0);
327       break;
328     }
329     ds->progress_callback (ds->progress_callback_cls,
330                            NULL, GNUNET_SYSERR,
331                            GNUNET_FS_DIRSCANNER_ALL_COUNTED);
332     ds->pos = ds->toplevel;
333     if (GNUNET_YES == ds->pos->is_directory)
334       ds->pos = advance (ds->pos);
335     return GNUNET_OK;
336   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA:
337     {
338       size_t nlen;
339       const char *end;
340
341       if (NULL == ds->pos)
342       {
343         GNUNET_break (0);
344         break;
345       }
346       end = memchr (filename, 0, left);
347       if (NULL == end)
348       {
349         GNUNET_break (0);
350         break;
351       }
352       end++;
353       nlen = end - filename;
354       left -= nlen;
355       if (0 != strcmp (filename,
356                        ds->pos->filename))
357       {
358         GNUNET_break (0);
359         break;
360       }
361       ds->progress_callback (ds->progress_callback_cls,
362                              filename, GNUNET_YES,
363                              GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED);
364       if (0 < left)
365       {
366         ds->pos->meta = GNUNET_CONTAINER_meta_data_deserialize (end, left);
367         if (NULL == ds->pos->meta)
368         {
369           GNUNET_break (0);
370           break;
371         }
372         /* having full filenames is too dangerous; always make sure we clean them up */
373         GNUNET_CONTAINER_meta_data_delete (ds->pos->meta,
374                                            EXTRACTOR_METATYPE_FILENAME,
375                                            NULL, 0);
376         /* instead, put in our 'safer' original filename */
377         GNUNET_CONTAINER_meta_data_insert (ds->pos->meta, "<libgnunetfs>",
378                                            EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
379                                            EXTRACTOR_METAFORMAT_UTF8, "text/plain",
380                                            ds->pos->short_filename,
381                                            strlen (ds->pos->short_filename) + 1);
382       }
383       ds->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_meta_data (ds->pos->meta);
384       ds->pos = advance (ds->pos);
385       return GNUNET_OK;
386     }
387   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED:
388     if (NULL != ds->pos)
389     {
390       GNUNET_break (0);
391       break;
392     }
393     if (0 != left)
394     {
395       GNUNET_break (0);
396       break;
397     }
398     if (NULL == ds->toplevel)
399     {
400       GNUNET_break (0);
401       break;
402     }
403     ds->stop_task = GNUNET_SCHEDULER_add_now (&finish_scan,
404                                               ds);
405     return GNUNET_OK;
406   default:
407     GNUNET_break (0);
408     break;
409   }
410   ds->progress_callback (ds->progress_callback_cls,
411                          NULL, GNUNET_SYSERR,
412                          GNUNET_FS_DIRSCANNER_INTERNAL_ERROR);
413   return GNUNET_OK;
414 }
415
416
417 /**
418  * Function called if our helper process died.
419  *
420  * @param cls the 'struct GNUNET_FS_DirScanner' callback.
421  */
422 static void
423 helper_died_cb (void *cls)
424 {
425   struct GNUNET_FS_DirScanner *ds = cls;
426
427   ds->helper = NULL;
428   if (NULL != ds->stop_task)
429     return; /* normal death, was finished */
430   ds->progress_callback (ds->progress_callback_cls,
431                          NULL, GNUNET_SYSERR,
432                          GNUNET_FS_DIRSCANNER_INTERNAL_ERROR);
433 }
434
435
436 /**
437  * Start a directory scanner thread.
438  *
439  * @param filename name of the directory to scan
440  * @param disable_extractor #GNUNET_YES to not run libextractor on files (only
441  *        build a tree)
442  * @param ex if not NULL, must be a list of extra plugins for extractor
443  * @param cb the callback to call when there are scanning progress messages
444  * @param cb_cls closure for 'cb'
445  * @return directory scanner object to be used for controlling the scanner
446  */
447 struct GNUNET_FS_DirScanner *
448 GNUNET_FS_directory_scan_start (const char *filename,
449                                 int disable_extractor, const char *ex,
450                                 GNUNET_FS_DirScannerProgressCallback cb,
451                                 void *cb_cls)
452 {
453   struct stat sbuf;
454   char *filename_expanded;
455   struct GNUNET_FS_DirScanner *ds;
456
457   if (0 != STAT (filename, &sbuf))
458     return NULL;
459   filename_expanded = GNUNET_STRINGS_filename_expand (filename);
460   if (NULL == filename_expanded)
461     return NULL;
462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
463               "Starting to scan directory `%s'\n",
464               filename_expanded);
465   ds = GNUNET_new (struct GNUNET_FS_DirScanner);
466   ds->progress_callback = cb;
467   ds->progress_callback_cls = cb_cls;
468   ds->filename_expanded = filename_expanded;
469   if (disable_extractor)
470     ds->ex_arg = GNUNET_strdup ("-");
471   else
472     ds->ex_arg = (NULL != ex) ? GNUNET_strdup (ex) : NULL;
473   ds->args[0] = "gnunet-helper-fs-publish";
474   ds->args[1] = ds->filename_expanded;
475   ds->args[2] = ds->ex_arg;
476   ds->args[3] = NULL;
477   ds->helper = GNUNET_HELPER_start (GNUNET_NO,
478                                     "gnunet-helper-fs-publish",
479                                     ds->args,
480                                     &process_helper_msgs,
481                                     &helper_died_cb, ds);
482   if (NULL == ds->helper)
483     {
484     GNUNET_free (filename_expanded);
485     GNUNET_free (ds);
486     return NULL;
487   }
488   return ds;
489 }
490
491
492 /* end of fs_dirmetascan.c */