-fix
[oweals/gnunet.git] / src / fs / fs_dirmetascan.c
1 /*
2      This file is part of GNUnet
3      (C) 2005-2012 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_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   GNUNET_SCHEDULER_TaskIdentifier stop_task;
84
85   /**
86    * Arguments for helper.
87    */
88   char *args[4];
89
90 };
91
92
93
94 /**
95  * Abort the scan.  Must not be called from within the progress_callback
96  * function.
97  *
98  * @param ds directory scanner structure
99  */
100 void
101 GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds)
102 {
103   /* terminate helper */
104   if (NULL != ds->helper)
105     GNUNET_HELPER_stop (ds->helper);
106   
107   /* free resources */
108   if (NULL != ds->toplevel)
109     GNUNET_FS_share_tree_free (ds->toplevel);
110   if (GNUNET_SCHEDULER_NO_TASK != ds->stop_task)
111     GNUNET_SCHEDULER_cancel (ds->stop_task);
112   GNUNET_free_non_null (ds->ex_arg);
113   GNUNET_free (ds->filename_expanded);
114   GNUNET_free (ds);
115 }
116
117
118 /**
119  * Obtain the result of the scan after the scan has signalled
120  * completion.  Must not be called prior to completion.  The 'ds' is
121  * freed as part of this call.
122  *
123  * @param ds directory scanner structure
124  * @return the results of the scan (a directory tree)
125  */
126 struct GNUNET_FS_ShareTreeItem *
127 GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds)
128 {
129   struct GNUNET_FS_ShareTreeItem *result;
130
131   /* check that we're actually done */
132   GNUNET_assert (NULL == ds->helper);
133   /* preserve result */
134   result = ds->toplevel;
135   ds->toplevel = NULL; 
136   GNUNET_FS_directory_scan_abort (ds);
137   return result;
138 }
139
140
141 /**
142  * Move in the directory from the given position to the next file
143  * in DFS traversal.
144  *
145  * @param pos current position
146  * @return next file, NULL for none
147  */
148 static struct GNUNET_FS_ShareTreeItem *
149 advance (struct GNUNET_FS_ShareTreeItem *pos)
150 {
151   int moved;
152   
153   GNUNET_assert (NULL != pos);
154   moved = 0; /* must not terminate, even on file, otherwise "normal" */
155   while ( (pos->is_directory) ||
156           (0 == moved) )
157   {
158     if ( (moved != -1) &&
159          (NULL != pos->children_head) )
160     {
161       pos = pos->children_head;
162       moved = 1; /* can terminate if file */
163       continue;
164     }
165     if (NULL != pos->next)
166     {
167       pos = pos->next;
168       moved = 1; /* can terminate if file */
169       continue;
170     }
171     if (NULL != pos->parent)
172     {
173       pos = pos->parent;
174       moved = -1; /* force move to 'next' or 'parent' */
175       continue;
176     }
177     /* no more options, end of traversal */
178     return NULL;
179   }
180   return pos;
181 }
182
183
184 /**
185  * Add another child node to the tree.
186  *
187  * @param parent parent of the child, NULL for top level
188  * @param filename name of the file or directory
189  * @param is_directory GNUNET_YES for directories
190  * @return new entry that was just created
191  */
192 static struct GNUNET_FS_ShareTreeItem *
193 expand_tree (struct GNUNET_FS_ShareTreeItem *parent,
194              const char *filename,
195              int is_directory)
196 {
197   struct GNUNET_FS_ShareTreeItem *chld;
198   size_t slen;
199
200   chld = GNUNET_malloc (sizeof (struct GNUNET_FS_ShareTreeItem));
201   chld->parent = parent;
202   chld->filename = GNUNET_strdup (filename);
203   GNUNET_asprintf (&chld->short_filename,
204                    "%s%s",
205                    GNUNET_STRINGS_get_short_name (filename),
206                    is_directory ? "/" : "");
207   /* make sure we do not end with '//' */
208   slen = strlen (chld->short_filename);
209   if ( (slen >= 2) &&
210        (chld->short_filename[slen-1] == '/') &&
211        (chld->short_filename[slen-2] == '/') )
212     chld->short_filename[slen-1] = '\0';
213   chld->is_directory = is_directory;
214   if (NULL != parent)
215       GNUNET_CONTAINER_DLL_insert (parent->children_head,
216                                    parent->children_tail,
217                                    chld);  
218   return chld;
219 }
220
221
222 /**
223  * Task run last to shut everything down.
224  *
225  * @param cls the 'struct GNUNET_FS_DirScanner'
226  * @param tc unused
227  */
228 static void
229 finish_scan (void *cls,
230              const struct GNUNET_SCHEDULER_TaskContext *tc)
231 {
232   struct GNUNET_FS_DirScanner *ds = cls;
233
234   ds->stop_task = GNUNET_SCHEDULER_NO_TASK;
235   GNUNET_HELPER_stop (ds->helper);
236   ds->helper = NULL;
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 void
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   left = ntohs (msg->size) - sizeof (struct GNUNET_MessageHeader);
261   filename = (const char*) &msg[1];
262   switch (ntohs (msg->type))
263   {
264   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE:
265     if (filename[left-1] != '\0')
266     {
267       GNUNET_break (0);
268       break;
269     }
270     ds->progress_callback (ds->progress_callback_cls, 
271                            filename, GNUNET_NO,
272                            GNUNET_FS_DIRSCANNER_FILE_START);
273     if (NULL == ds->toplevel)
274       ds->toplevel = expand_tree (ds->pos,
275                                   filename, GNUNET_NO);
276     else
277       (void) expand_tree (ds->pos,
278                           filename, GNUNET_NO);
279     return;
280   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY:
281     if (filename[left-1] != '\0')
282     {
283       GNUNET_break (0);
284       break;
285     }
286     if (0 == strcmp ("..", filename))
287     {
288       if (NULL == ds->pos)
289       {
290         GNUNET_break (0);
291         break;
292       }
293       ds->pos = ds->pos->parent;
294       return;
295     }
296     ds->progress_callback (ds->progress_callback_cls, 
297                            filename, GNUNET_YES,
298                            GNUNET_FS_DIRSCANNER_FILE_START);
299     ds->pos = expand_tree (ds->pos,
300                            filename, GNUNET_YES);
301     if (NULL == ds->toplevel)
302       ds->toplevel = ds->pos;
303     return;
304   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR:
305     break;
306   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE:
307     if (filename[left-1] != '\0')
308       break;
309     ds->progress_callback (ds->progress_callback_cls, 
310                            filename, GNUNET_SYSERR,
311                            GNUNET_FS_DIRSCANNER_FILE_IGNORED);
312     return;
313   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE:
314     if (0 != left)
315     {
316       GNUNET_break (0);
317       break;
318     }
319     if (NULL == ds->toplevel)
320     {
321       GNUNET_break (0);
322       break;
323     }
324     ds->progress_callback (ds->progress_callback_cls, 
325                            NULL, GNUNET_SYSERR,
326                            GNUNET_FS_DIRSCANNER_ALL_COUNTED);
327     ds->pos = ds->toplevel;
328     if (ds->pos->is_directory)
329       ds->pos = advance (ds->pos);
330     return;
331   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA:
332     {
333       size_t nlen;
334       const char *end;
335       
336       if (NULL == ds->pos)
337       {
338         GNUNET_break (0);
339         break;
340       }
341       end = memchr (filename, 0, left);
342       if (NULL == end)
343       {
344         GNUNET_break (0);
345         break;
346       }
347       end++;
348       nlen = end - filename;
349       left -= nlen;
350       if (0 != strcmp (filename,
351                        ds->pos->filename))
352       {
353         GNUNET_break (0);
354         break;
355       }
356       ds->progress_callback (ds->progress_callback_cls, 
357                              filename, GNUNET_YES,
358                              GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED);
359       if (0 < left)
360       {
361         ds->pos->meta = GNUNET_CONTAINER_meta_data_deserialize (end, left);
362         if (NULL == ds->pos->meta)
363         {
364           GNUNET_break (0);
365           break;
366         }
367         /* having full filenames is too dangerous; always make sure we clean them up */
368         GNUNET_CONTAINER_meta_data_delete (ds->pos->meta, 
369                                            EXTRACTOR_METATYPE_FILENAME,
370                                            NULL, 0);
371         /* instead, put in our 'safer' original filename */
372         GNUNET_CONTAINER_meta_data_insert (ds->pos->meta, "<libgnunetfs>",
373                                            EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
374                                            EXTRACTOR_METAFORMAT_UTF8, "text/plain",
375                                            ds->pos->short_filename, 
376                                            strlen (ds->pos->short_filename) + 1);
377       }
378       ds->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_meta_data (ds->pos->meta);
379       ds->pos = advance (ds->pos);      
380       return;
381     }
382   case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED:
383     if (NULL != ds->pos)
384     {
385       GNUNET_break (0);
386       break;
387     }
388     if (0 != left)
389     {
390       GNUNET_break (0);
391       break;
392     }   
393     if (NULL == ds->toplevel)
394     {
395       GNUNET_break (0);
396       break;
397     }
398     ds->stop_task = GNUNET_SCHEDULER_add_now (&finish_scan,
399                                               ds);
400     return;
401   default:
402     GNUNET_break (0);
403     break;
404   }
405   ds->progress_callback (ds->progress_callback_cls, 
406                          NULL, GNUNET_SYSERR,
407                          GNUNET_FS_DIRSCANNER_INTERNAL_ERROR);
408 }
409
410
411 /**
412  * Start a directory scanner thread.
413  *
414  * @param filename name of the directory to scan
415  * @param disable_extractor GNUNET_YES to not to run libextractor on files (only build a tree)
416  * @param ex if not NULL, must be a list of extra plugins for extractor
417  * @param cb the callback to call when there are scanning progress messages
418  * @param cb_cls closure for 'cb'
419  * @return directory scanner object to be used for controlling the scanner
420  */
421 struct GNUNET_FS_DirScanner *
422 GNUNET_FS_directory_scan_start (const char *filename,
423                                 int disable_extractor, const char *ex,
424                                 GNUNET_FS_DirScannerProgressCallback cb, 
425                                 void *cb_cls)
426 {
427   struct stat sbuf;
428   char *filename_expanded;
429   struct GNUNET_FS_DirScanner *ds;
430
431   if (0 != STAT (filename, &sbuf))
432     return NULL;
433   filename_expanded = GNUNET_STRINGS_filename_expand (filename);
434   if (NULL == filename_expanded)
435     return NULL;
436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
437               "Starting to scan directory `%s'\n",
438               filename_expanded);
439   ds = GNUNET_malloc (sizeof (struct GNUNET_FS_DirScanner));
440   ds->progress_callback = cb;
441   ds->progress_callback_cls = cb_cls;
442   ds->filename_expanded = filename_expanded;
443   if (disable_extractor)  
444     ds->ex_arg = GNUNET_strdup ("-");
445   else 
446     ds->ex_arg = (NULL != ex) ? GNUNET_strdup (ex) : NULL;
447   ds->args[0] = "gnunet-helper-fs-publish";
448   ds->args[1] = ds->filename_expanded;
449   ds->args[2] = ds->ex_arg;
450   ds->args[3] = NULL;
451   ds->helper = GNUNET_HELPER_start ("gnunet-helper-fs-publish",
452                                     ds->args,
453                                     &process_helper_msgs,
454                                     ds);
455   if (NULL == ds->helper)
456   {
457     GNUNET_free (filename_expanded);
458     GNUNET_free (ds);
459     return NULL;
460   }
461   return ds;
462 }
463
464
465 /* end of fs_dirmetascan.c */