Change type of struct osl_table_description->flags to uint8_t.
[osl.git] / fsck.c
1 /*
2  * Copyright (C) 2007-2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file fsck.c The program used to check an osl table. */
8
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <dirent.h>
12 #include <assert.h>
13 #include <pwd.h>
14
15 #include "log.h"
16 #include "osl.h"
17 #include "error.h"
18 #include "util.h"
19 #include "osl_core.h"
20 #include "fsck.cmdline.h"
21
22 /** version text used by various commands if -V switch was given */
23 #define VERSION_TEXT(prefix) "osl_" prefix " " VERSION " " "\n" \
24         "Copyright (C) 2008 Andre Noll\n" \
25         "This is free software with ABSOLUTELY NO WARRANTY." \
26         " See COPYING for details.\n" \
27         "Written by Andre Noll.\n" \
28         "Report bugs to <maan@systemlinux.org>.\n"
29
30 /** print out \p VERSION_TEXT and exit if version flag was given */
31 #define HANDLE_VERSION_FLAG(_prefix, _args_info_struct) \
32         if (_args_info_struct.version_given) { \
33                 printf("%s", VERSION_TEXT(_prefix)); \
34                 exit(EXIT_SUCCESS); \
35         }
36
37 static struct fsck_args_info conf;
38
39 #define FSCK_ERRORS \
40         FSCK_ERROR(RANGE_VIOLATION, "range violation detected, very bad"), \
41         FSCK_ERROR(NOT_A_REGULAR_FILE, "not a regular file"), \
42         FSCK_ERROR(SYNTAX, "fsck syntax error"),
43
44 #define FSCK_ERROR(num, txt) E_FSCK_ ## num
45 enum {
46         FSCK_DUMMY = (1 << FSCK_ERROR_BIT) - 1,
47         FSCK_ERRORS
48 };
49 #undef FSCK_ERROR
50 #define FSCK_ERROR(num, txt) txt
51 const char const *fsck_errors[] = {
52         FSCK_ERRORS
53 };
54
55 static const char *fsck_strerror(int num)
56 {
57         if (num & (1 << FSCK_ERROR_BIT))
58                 return fsck_errors[num & ((1 << FSCK_ERROR_BIT) - 1)];
59         return osl_strerror(num);
60 }
61
62 extern int loglevel;
63
64 /* taken from git */
65 signed char hexval_table[256] = {
66          -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
67          -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
68          -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
69          -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
70          -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
71          -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
72           0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
73           8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
74          -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
75          -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
76          -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
77          -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
78          -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
79          -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
80          -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
81          -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
82          -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
83          -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
84          -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
85          -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
86          -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
87          -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
88          -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
89          -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
90          -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
91          -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
92          -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
93          -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
94          -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
95          -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
96          -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
97          -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
98 };
99
100 int asc_to_hash(const char *asc_hash, int len, HASH_TYPE *hash)
101 {
102         int i = 0;
103         const unsigned char *asc = (const unsigned char *) asc_hash;
104
105         while (*asc && i++ < len) {
106                 unsigned int val = (hexval_table[asc[0]] << 4) | hexval_table[asc[1]];
107                 if (val & ~0xff)
108                         return -1;
109                 *hash++ = val;
110                 asc += 2;
111
112         }
113         return 1;
114 }
115
116 static int _write_all(int fd, const char *buf, size_t len)
117 {
118         return write_all(fd, buf, &len);
119 }
120
121 /**
122  * Paraslash's version of malloc().
123  *
124  * \param size The desired new size.
125  *
126  * A wrapper for malloc(3) which exits on errors.
127  *
128  * \return A pointer to the allocated memory, which is suitably aligned for any
129  * kind of variable.
130  *
131  * \sa malloc(3).
132  */
133 __must_check __malloc static void *fsck_malloc(size_t size)
134 {
135         assert(size);
136         void *p = malloc(size);
137
138         if (!p) {
139                 EMERG_LOG("malloc failed (size = %zu),  aborting\n",
140                         size);
141                 exit(EXIT_FAILURE);
142         }
143         return p;
144 }
145
146 /**
147  * Paraslash's version of calloc().
148  *
149  * \param size The desired new size.
150  *
151  * A wrapper for calloc(3) which exits on errors.
152  *
153  * \return A pointer to the allocated and zeroed-out memory, which is suitably
154  * aligned for any kind of variable.
155  *
156  * \sa calloc(3)
157  */
158 __must_check __malloc static void *fsck_calloc(size_t size)
159 {
160         void *ret = fsck_malloc(size);
161
162         memset(ret, 0, size);
163         return ret;
164 }
165
166 /**
167  * Paraslash's version of strdup().
168  *
169  * \param s The string to be duplicated.
170  *
171  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
172  * there is no need to check the return value in the caller.
173  *
174  * \return A pointer to the duplicated string. If \p s was the NULL pointer,
175  * an pointer to an empty string is returned.
176  *
177  * \sa strdup(3)
178  */
179 __must_check __malloc static char *fsck_strdup(const char *s)
180 {
181         char *ret;
182
183         if ((ret = strdup(s? s: "")))
184                 return ret;
185         EMERG_LOG("strdup failed, aborting\n");
186         exit(EXIT_FAILURE);
187 }
188
189 /**
190  * Compare two osl objects pointing to unsigned integers of 32 bit size.
191  *
192  * \param obj1 Pointer to the first integer.
193  * \param obj2 Pointer to the second integer.
194  *
195  * \return The values required for an osl compare function.
196  *
197  * \sa osl_compare_func, osl_hash_compare().
198  */
199 static int uint32_compare(const struct osl_object *obj1, const struct osl_object *obj2)
200 {
201         uint32_t d1 = read_u32((const char *)obj1->data);
202         uint32_t d2 = read_u32((const char *)obj2->data);
203
204         if (d1 < d2)
205                 return 1;
206         if (d1 > d2)
207                 return -1;
208         return 0;
209 }
210
211 /**
212  * A wrapper for fchdir().
213  *
214  * \param fd An open file descriptor.
215  *
216  * \return Standard.
217  */
218 static inline int __fchdir(int fd)
219 {
220         if (fchdir(fd) < 0)
221                 return -ERRNO_TO_ERROR(errno);
222         return 1;
223 }
224
225 /**
226  * Wrapper for chdir(2).
227  *
228  * \param path The specified directory.
229  *
230  * \return Standard.
231  */
232 _static_inline_ int __chdir(const char *path)
233 {
234         if (chdir(path) >= 0)
235                 return 1;
236         return -ERRNO_TO_ERROR(errno);
237 }
238
239 /**
240  * Save the cwd and open a given directory.
241  *
242  * \param dirname Path to the directory to open.
243  * \param dir Result pointer.
244  * \param cwd File descriptor of the current working directory.
245  *
246  * \return Standard.
247  *
248  * Opening the current directory (".") and calling fchdir() to return is
249  * usually faster and more reliable than saving cwd in some buffer and calling
250  * chdir() afterwards.
251  *
252  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
253  * stored in \a cwd. If the function returns success, and \a cwd is not \p
254  * NULL, the caller must close this file descriptor (probably after calling
255  * fchdir(*cwd)).
256  *
257  * On errors, the function undos everything, so the caller needs neither close
258  * any files, nor change back to the original working directory.
259  *
260  * \sa getcwd(3).
261  *
262  */
263 static int fsck_opendir(const char *dirname, DIR **dir, int *cwd)
264 {
265         int ret;
266
267         if (cwd) {
268                 ret = osl_open(".", O_RDONLY, 0);
269                 if (ret < 0)
270                         return ret;
271                 *cwd = ret;
272         }
273         ret = __chdir(dirname);
274         if (ret < 0)
275                 goto close_cwd;
276         *dir = opendir(".");
277         if (*dir)
278                 return 1;
279         ret = -ERRNO_TO_ERROR(errno);
280 /* Ignore return value of fchdir() and close(). We're busted anyway. */
281         if (cwd)
282                 fchdir(*cwd);
283 close_cwd:
284         if (cwd)
285                 close(*cwd);
286         return ret;
287 }
288
289
290
291 /**
292  * Traverse the given directory recursively.
293  *
294  * \param dirname The directory to traverse.
295  * \param func The function to call for each entry.
296  * \param private_data Pointer to an arbitrary data structure.
297  *
298  * For each regular file under \a dirname, the supplied function \a func is
299  * called.  The full path of the regular file and the \a private_data pointer
300  * are passed to \a func. Directories for which the calling process has no
301  * permissions to change to are silently ignored.
302  *
303  * \return Standard.
304  */
305 static int for_each_file_in_dir(const char *dirname,
306                 int (*func)(const char *, void *), void *private_data)
307 {
308         DIR *dir;
309         struct dirent *entry;
310         int cwd_fd, ret2, ret = fsck_opendir(dirname, &dir, &cwd_fd);
311
312         if (ret < 0)
313                 return ret == -ERRNO_TO_ERROR(EACCES)? 1 : ret;
314         /* scan cwd recursively */
315         while ((entry = readdir(dir))) {
316                 mode_t m;
317                 char *tmp;
318                 struct stat s;
319
320                 if (!strcmp(entry->d_name, "."))
321                         continue;
322                 if (!strcmp(entry->d_name, ".."))
323                         continue;
324                 if (lstat(entry->d_name, &s) == -1)
325                         continue;
326                 m = s.st_mode;
327                 if (!S_ISREG(m) && !S_ISDIR(m))
328                         continue;
329                 tmp = make_message("%s/%s", dirname, entry->d_name);
330                 if (!S_ISDIR(m)) {
331                         ret = func(tmp, private_data);
332                         free(tmp);
333                         if (ret < 0)
334                                 goto out;
335                         continue;
336                 }
337                 /* directory */
338                 ret = for_each_file_in_dir(tmp, func, private_data);
339                 free(tmp);
340                 if (ret < 0)
341                         goto out;
342         }
343         ret = 1;
344 out:
345         closedir(dir);
346         ret2 = __fchdir(cwd_fd);
347         if (ret2 < 0 && ret >= 0)
348                 ret = ret2;
349         close(cwd_fd);
350         return ret;
351 }
352
353 /*
354  * check for object boundary violations
355  *
356  * test whether the range pointed to by the index entry for a given cell is
357  * contained in mapped data file. This should always be the case. Otherwise
358  * we are in real trouble.
359  */
360 static int check_range(struct osl_table *t, uint32_t row_num, uint32_t col_num)
361 {
362         char *index_entry;
363         struct osl_object obj;
364         struct osl_column *col;
365         int ret;
366         char *map_start, *obj_start;
367
368         ret = get_cell_index(t, row_num, col_num, &index_entry);
369         if (ret < 0)
370                 return ret;
371         ret = get_mapped_object(t, col_num, row_num, &obj);
372         if (ret < 0)
373                 return ret;
374         col = t->columns + col_num;
375         obj_start = obj.data;
376         map_start = col->data_map.data;
377 //      INFO_LOG("obj: %p..%p\n", obj_start, obj_start + obj.size);
378 //      INFO_LOG("map: %p..%p\n", map_start, map_start + col->data_map.size);
379         if (obj_start < map_start || obj_start + obj.size > map_start + col->data_map.size) {
380                 CRIT_LOG("range violation in row %u, col %u\n", row_num,
381                         col_num);
382                 return -E_FSCK_RANGE_VIOLATION;
383         }
384         DEBUG_LOG("col %u: ok\n", col_num);
385         return 1;
386 }
387
388 /*
389  * check all cells of the given table for boundary violations
390  */
391 static int check_index_ranges(struct osl_table *t)
392 {
393         int i, j, ret;
394
395         INFO_LOG("checking for range violations in index\n");
396         //DEBUG_LOG("%d rows. %d columns\n", t->num_rows, t->desc->num_columns);
397         t->num_invalid_rows = 0;
398         for (i = 0; i < t->num_rows; i++) {
399                 if (row_is_invalid(t, i)) {
400                         t->num_invalid_rows++;
401                         continue;
402                 }
403                 for (j = 0; j < t->desc->num_columns; j++) { /* FXIME */
404                         const struct osl_column_description *cd =
405                                 get_column_description(t->desc, j);
406                         if (cd->storage_type != OSL_MAPPED_STORAGE)
407                                 continue;
408                         ret = check_range(t, i, j);
409                         if (ret < 0) {
410                                 if (ret != -E_OSL_INVALID_OBJECT &&
411                                                 ret != -E_FSCK_RANGE_VIOLATION)
412                                         goto err;
413                                 if (ret == -E_OSL_INVALID_OBJECT) {
414                                         CRIT_LOG("row %d, col %d maps to an "
415                                                 "invalid object\n", i, j);
416                                 }
417                                 ret = mark_row_invalid(t, i);
418                                 if (ret < 0)
419                                         goto err;
420                                 t->num_invalid_rows++;
421                                 break;
422                         }
423                 }
424
425         }
426         if (t->num_invalid_rows)
427                 NOTICE_LOG("ranges OK. %d invalid row(s) detected\n",
428                         t->num_invalid_rows);
429         else
430                 INFO_LOG("no invalid rows, no range violations, good\n");
431         return 1;
432 err:
433         return ret;
434 }
435
436 static int move_index_entry(struct osl_table *t, uint32_t dest, uint32_t src)
437 {
438         char *dest_ie, *src_ie;
439         int ret = get_row_index(t, dest, &dest_ie);
440
441         if (ret < 0)
442                 return ret;
443         ret = get_row_index(t, src, &src_ie);
444         if (ret < 0)
445                 return ret;
446         INFO_LOG("moving entry #%u to position %u\n", src, dest);
447         memcpy(dest_ie, src_ie, t->row_index_size);
448         return 1;
449 }
450
451 static int map_index(const struct osl_table_description *desc, struct osl_object *map)
452 {
453         char *filename = index_filename(desc);
454         int ret;
455
456         ret = mmap_full_file(filename, O_RDWR, &map->data, &map->size, NULL);
457         DEBUG_LOG("mapping index %s: ret: %d, size: %zu\n", filename, ret, map->size);
458         free(filename);
459         return ret;
460 }
461
462 static int prune_invalid_rows_from_index(struct osl_table *t)
463 {
464         uint32_t top = 0, bottom;
465         char *filename;
466         int ret;
467
468         if (!t->num_invalid_rows) {
469                 INFO_LOG("all rows are valid, good\n");
470                 return 1;
471         }
472         NOTICE_LOG("deleting %u invalid row(s) (%d bytes) from index\n",
473                 t->num_invalid_rows, t->row_index_size * t->num_invalid_rows);
474         bottom = t->num_rows - 1;
475         while (top < bottom) {
476                 if (!row_is_invalid(t, top)) {
477                         top++;
478                         continue;
479                 }
480                 while (bottom > top) {
481                         if (row_is_invalid(t, bottom)) {
482                                 bottom--;
483                                 continue;
484                         }
485                         /* move bottom index entry to top */
486                         move_index_entry(t, top, bottom);
487                         bottom--;
488                         top++;
489                         break;
490                 }
491         }
492         DEBUG_LOG("unmapping index\n");
493         osl_munmap(t->index_map.data, t->index_map.size);
494         filename = index_filename(t->desc);
495         ret = truncate_file(filename, t->row_index_size
496                 * t->num_invalid_rows);
497         free(filename);
498         if (ret < 0)
499                 return ret;
500         ret = map_index(t->desc, &t->index_map);
501         if (ret < 0)
502                 return ret;
503         t->num_rows = table_num_rows(t);
504         return 1;
505 }
506
507 static int check_for_invalid_objects(struct osl_table *t, uint32_t **lost_bytes)
508 {
509         int i, j, ret;
510         const struct osl_column_description *cd;
511         uint32_t *loss = fsck_malloc(sizeof(uint32_t) * t->desc->num_columns);
512
513         INFO_LOG("looking for mapped objects not contained in index\n");
514         /* first count used bytes */
515         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
516                 loss[i] = t->columns[i].data_map.size;
517                 for (j = 0; j < t->num_rows; j++) {
518                         struct osl_object obj;
519                         ret = get_mapped_object(t, i, j, &obj);
520                         if (ret >= 0) {
521                                 loss[i] -= obj.size + 1; /* add one for header byte */
522                                 continue;
523                         }
524                         if (ret != -E_OSL_INVALID_OBJECT)
525                                 goto err;
526                         CRIT_LOG("row %d, col %d points to an invalid "
527                                 "mapped object, bad\n", j, i);
528                 }
529         }
530         ret = 0;
531         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
532                 if (loss[i]) {
533                         NOTICE_LOG("column %u contains %u lost bytes\n",
534                                 i, loss[i]);
535                         ret = 1;
536                 }
537         }
538         if (!ret)
539                 INFO_LOG("all mapped objects are valid, good\n");
540         *lost_bytes = loss;
541         return ret;
542 err:
543         free(loss);
544         return ret;
545 }
546
547 /* prune_invalid_rows() must be run on the table before calling this */
548 static int prune_mapped_column(struct osl_table *t, uint32_t col_num, int fd)
549 {
550         int i, ret;
551         uint32_t written = 0;
552         struct osl_column *col = t->columns + col_num;
553
554         INFO_LOG("pruning col %u\n", col_num);
555         for (i = 0; i < t->num_rows; i++) {
556                 struct osl_object obj;
557                 char *index_entry;
558
559                 DEBUG_LOG("checking row %u/%u\n", i, t->num_rows);
560                 ret = get_mapped_object(t, col_num, i, &obj);
561                 if (ret < 0)
562                         return ret;
563                 ret = _write_all(fd, (char *)(obj.data) - 1, obj.size + 1);
564                 if (ret < 0)
565                         return ret;
566                 written += obj.size + 1;
567                 ret = get_row_index(t, i, &index_entry);
568                 if (ret < 0)
569                         return ret;
570                 update_cell_index(index_entry, col, written, obj.size);
571         }
572         return 1;
573 }
574
575 static int prune_objects(struct osl_table *t, uint32_t *lost_bytes)
576 {
577         int i, ret;
578         const struct osl_column_description *cd;
579         char **col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
580         char **new_col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
581         char *idx_filename = index_filename(t->desc);
582         char *old_idx_filename = make_message("%s.bak", idx_filename);
583         int fd;
584
585         NOTICE_LOG("removing unreferenced objects from data files\n");
586         /* first make a copy of the index */
587         ret = osl_open(old_idx_filename, O_WRONLY | O_CREAT | O_EXCL, 0644);
588         if (ret < 0)
589                 goto out_free;
590         fd = ret;
591         ret = _write_all(fd, t->index_map.data, t->index_map.size);
592         close(fd);
593         if (ret < 0)
594                 goto out_free;
595         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
596                 if (!lost_bytes[i])
597                         continue;
598                 col_filenames[i] = column_filename(t, i);
599                 new_col_filenames[i] = make_message("%s.fsck", col_filenames[i]);
600                 ret = osl_open(new_col_filenames[i], O_WRONLY | O_CREAT | O_EXCL, 0644);
601                 if (ret < 0)
602                         goto out_unlink_data;
603                 fd = ret;
604                 ret = prune_mapped_column(t, i, fd);
605                 close(fd);
606                 if (ret < 0)
607                         goto out_unlink_data;
608         }
609         ret = unmap_table(t, OSL_MARK_CLEAN);
610         if (ret < 0)
611                 goto out_unlink_data;
612         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
613                 if (!lost_bytes[i])
614                         continue;
615                 ret = osl_rename(new_col_filenames[i], col_filenames[i]);
616                 if (ret < 0) { /* we're kinda screwed here */
617                         CRIT_LOG("rename of col %i failed: %s\n", i,
618                                 osl_strerror(errno));
619                         goto out_free;
620                 }
621         }
622         unlink(old_idx_filename);
623         ret = map_table(t, 0);
624         goto out_free;
625 out_unlink_data:
626         FOR_EACH_MAPPED_COLUMN(i, t, cd)
627                 unlink(new_col_filenames[i]);
628 out_free:
629         free(old_idx_filename);
630         free(idx_filename);
631         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
632                 free(col_filenames[i]);
633                 free(new_col_filenames[i]);
634         }
635         free(col_filenames);
636         free(new_col_filenames);
637         return ret;
638 }
639
640 static struct osl_column_description hash_tree_table_cols[] = {
641         {
642                 .storage_type = OSL_NO_STORAGE,
643                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
644                 .name = "hash",
645                 .compare_function = uint32_compare,
646                 .data_size = HASH_SIZE
647         },
648 };
649
650 static const struct osl_table_description hash_tree_table_desc = {
651         .dir = "/", /* irrelevant */
652         .name = "hash_tree",
653         .num_columns = 1,
654         .flags = 0,
655         .column_descriptions = hash_tree_table_cols
656 };
657
658 /**
659  * The hash_tree table contains all hashes of the disk storage name column.
660  * of each row. It is used for checking if a disk storage file has a reference
661  * in the table.
662  */
663 static struct osl_table *hash_tree_table;
664 static HASH_TYPE *hashes;
665
666 static int check_disk_storage_column(struct osl_table *t, int row_num,
667                 int col_num, char *ds_name, unsigned *num_missing_objects)
668 {
669         int ret;
670         struct stat statbuf;
671         char *path = disk_storage_path(t, col_num, ds_name);
672         unsigned dsnc = t->disk_storage_name_column;
673         struct osl_object obj;
674
675         DEBUG_LOG("checking if %s is a regular file\n", path);
676         ret = stat(path, &statbuf);
677         if (ret < 0 && errno == ENOENT) {
678                 struct osl_row *row;
679                 (*num_missing_objects)++;
680                 ERROR_LOG("row %d: object %s is missing\n", row_num, path);
681                 NOTICE_LOG("trying to delete row %d\n", row_num);
682                 ret = osl_get_row(t, dsnc, &obj, &row);
683                 if (ret < 0) {
684                         CRIT_LOG("unable to get row %d\n", row_num);
685                         mark_row_invalid(t, row_num);
686                         CRIT_LOG("Please re-run fsck\n");
687                         goto out;
688                 }
689                 ret = osl_del_row(t, row);
690                 if (ret < 0)
691                         goto out;
692         }
693 out:
694         free(path);
695         if (ret < 0)
696                 return ret;
697         ret = -E_FSCK_NOT_A_REGULAR_FILE;
698         if (!(S_IFREG & statbuf.st_mode))
699                 return ret;
700         return 1;
701 }
702
703 static int check_disk_storage_presence(struct osl_table *t)
704 {
705         int ret, i, j;
706         struct osl_object obj, hash_obj = {.size = HASH_SIZE};
707         char *ds_name;
708         const struct osl_column_description *cd;
709         unsigned dsnc = t->disk_storage_name_column, missing_objects = 0;
710
711         if (!t->num_rows)
712                 return 1;
713         hashes = fsck_malloc(t->num_rows * HASH_SIZE);
714         INFO_LOG("looking for missing disk storage objects\n");
715         for (i = 0; i < t->num_rows; i++) {
716                 if (row_is_invalid(t, i))
717                         continue;
718                 ret = get_mapped_object(t, dsnc, i, &obj);
719                 if (ret < 0)
720                         return ret;
721                 hash_object(&obj, hashes + i * HASH_SIZE);
722                 hash_obj.data = hashes + i * HASH_SIZE;
723                 osl_add_row(hash_tree_table, &hash_obj);
724                 ds_name = disk_storage_name_of_hash(t, hashes + i * HASH_SIZE);
725                 FOR_EACH_DISK_STORAGE_COLUMN(j, t, cd) {
726                         ret = check_disk_storage_column(t, i, j, ds_name,
727                                 &missing_objects);
728                         if (ret < 0)
729                                 goto err;
730                 }
731                 free(ds_name);
732         }
733         if (!missing_objects)
734                 INFO_LOG("all referenced disk storage objects exist, good\n");
735         else
736                 NOTICE_LOG("%d missing object(s)\n", missing_objects);
737         return missing_objects;
738 err:
739         free(ds_name);
740         return ret;
741 }
742
743 static int dummy_compare(const struct osl_object *obj1, const struct osl_object *obj2)
744 {
745         if (obj1 < obj2)
746                 return -1;
747         if (obj1 > obj2)
748                 return 1;
749         return 0;
750 }
751
752 static unsigned files_pruned;
753
754 int prune_disk_storage_file(const char *path, void *private_data)
755 {
756         HASH_TYPE hash[HASH_SIZE];
757         uint8_t flags = *(uint8_t *)private_data;
758         struct osl_object obj = {.data = hash, .size = HASH_SIZE};
759         struct osl_row *row;
760         int ret = -1;
761         size_t len = strlen(path);
762
763
764         DEBUG_LOG("path: %s\n", path);
765         if (flags & OSL_LARGE_TABLE) {
766                 if (len < HASH_SIZE * 2 + 2)
767                         goto invalid;
768 //              NOTICE_LOG("p: %s\n", path + len - 2 * HASH_SIZE - 1);
769                 ret = asc_to_hash(path + len - 2 * HASH_SIZE - 1, 1, hash);
770                 if (ret < 0)
771                         goto invalid;
772                 ret = asc_to_hash(path + len - 2 * HASH_SIZE + 2, HASH_SIZE - 1,
773                         hash + 1);
774                 if (ret < 0)
775                         goto invalid;
776 //              INFO_LOG("high: %x, low: %x, hash: %x\n", high, low, hash);
777         } else {
778                 if (len < 2 * HASH_SIZE + 1)
779                         goto invalid;
780                 ret = asc_to_hash(path + len - 2 * HASH_SIZE, 2 * HASH_SIZE, hash);
781                 if (ret < 0)
782                         goto invalid;
783 //              INFO_LOG("hash: %x\n", hash);
784         }
785 #if 0
786 {
787         char asc[2 * HASH_SIZE + 1];
788         hash_to_asc(hash, asc);
789         NOTICE_LOG("before: %s\nafter: %s\n", path, asc);
790 }
791 #endif
792         ret = osl_get_row(hash_tree_table, 0, &obj, &row);
793         if (ret >= 0)
794                 return 1;
795         NOTICE_LOG("unreferenced file in hash dir: %s\n", path);
796         goto remove;
797 invalid:
798         ERROR_LOG("could not read hash value of %s\n", path);
799 remove:
800         NOTICE_LOG("removing %s\n", path);
801         unlink(path);
802         files_pruned++;
803         return 1;
804 }
805
806 static int prune_disk_storage_files(struct osl_table *t)
807 {
808         int i, ret = 1;
809         const struct osl_column_description *cd;
810
811         INFO_LOG("looking for unreferenced disk storage files\n");
812         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
813                 char *dirname = column_filename(t, i);
814                 uint8_t flags = t->desc->flags;
815                 ret = for_each_file_in_dir(dirname, prune_disk_storage_file,
816                         &flags);
817                 free(dirname);
818         }
819         if (files_pruned)
820                 NOTICE_LOG("%u disk storage files deleted\n",
821                         files_pruned);
822         else
823                 INFO_LOG("all files are are referenced, good\n");
824         return ret;
825 }
826
827 static int check_disk_storage_columns(struct osl_table *t)
828 {
829         int ret, i;
830         const struct osl_column_description *cd;
831
832         if (!t->num_disk_storage_columns) {
833                 INFO_LOG("no disk storage columns in table '%s', "
834                         "skipping checks\n", t->desc->name);
835                 return 1;
836         }
837         FOR_EACH_COLUMN(i, t->desc, cd)
838                 t->desc->column_descriptions[i].compare_function = dummy_compare;
839         ret = init_rbtrees(t);
840         if (ret < 0)
841                 return ret;
842         INFO_LOG("creating rbtree for disk storage hash values\n");
843         ret = osl_open_table(&hash_tree_table_desc, &hash_tree_table);
844         if (ret < 0)
845                 goto out;
846         ret = check_disk_storage_presence(t);
847         if (ret < 0)
848                 goto out_close_hash_tree;
849         ret = prune_disk_storage_files(t);
850 out_close_hash_tree:
851         osl_close_table(hash_tree_table, 0);
852         free(hashes);
853         hashes = NULL;
854 out:
855         clear_rbtrees(t); /* TODO why are we doing that here? Seems odd */
856         return ret;
857 }
858
859 static void set_dummy_contents(struct osl_table_description *desc)
860 {
861         int i;
862         struct osl_column_description *cd;
863
864         for (i = 0; i < desc->num_columns; i++) {
865                 cd = get_column_description(desc, i);
866                 cd->compare_function = dummy_compare;
867         }
868 }
869
870 static int fsck_init(struct osl_table_description *desc, struct osl_table **t)
871 {
872         struct osl_object map;
873         int ret = map_index(desc, &map);
874
875         if (ret < 0)
876                 goto out;
877         ret = read_table_desc(&map, desc);
878         if (ret < 0) {
879                 osl_munmap(map.data, map.size);
880                 goto out;
881         }
882         set_dummy_contents(desc);
883         ret = init_table_structure(desc, t);
884         if (ret < 0) {
885                 osl_munmap(map.data, map.size);
886                 goto out;
887         }
888         DEBUG_LOG("unmapping index\n");
889         osl_munmap(map.data, map.size);
890         if (conf.force_given)
891                 ret = map_table(*t, (MAP_TBL_FL_IGNORE_DIRTY));
892         else
893                 ret = map_table(*t, 0);
894         if (ret >= 0)
895                 (*t)->num_rows = table_num_rows(*t);
896 out:
897         return ret;
898 }
899
900 static void fsck_cleanup(struct osl_table *t)
901 {
902         int i;
903
904         if (!t)
905                 return;
906         if (t->desc->column_descriptions) {
907                 struct osl_column_description *cd;
908                 for (i = 0; i < t->desc->num_columns; i++) {
909                         cd = get_column_description(t->desc, i);
910                         free((char*)cd->name);
911                 }
912                 free(t->desc->column_descriptions);
913         }
914         free(t->columns);
915         free(t);
916
917 }
918
919 #define ST_CASE(st) case st: return #st
920
921 const char *get_asc_storage_type(enum osl_storage_type st)
922 {
923         switch (st) {
924                 ST_CASE(OSL_MAPPED_STORAGE);
925                 ST_CASE(OSL_DISK_STORAGE);
926                 ST_CASE(OSL_NO_STORAGE);
927         }
928         return NULL;
929 }
930
931 #define APPEND_ASC_SF(sf, flag, str) do { if (sf & flag) { \
932         if (str) str = make_message("%s%s", str, " | " # flag); \
933         else str = fsck_strdup(#flag); }} while (0)
934
935
936 char *get_asc_storage_flags(enum osl_storage_type sf)
937 {
938         char *asc_sf = NULL;
939
940         APPEND_ASC_SF(sf, OSL_RBTREE, asc_sf);
941         APPEND_ASC_SF(sf, OSL_FIXED_SIZE, asc_sf);
942         APPEND_ASC_SF(sf, OSL_UNIQUE, asc_sf);
943         return asc_sf;
944 }
945
946 static int dump_table_desc(struct osl_table *t, int fd)
947 {
948         const struct osl_table_description *desc = t->desc;
949         int ret, i;
950         struct osl_column_description *cd;
951         char *msg = make_message("static struct osl_column_description cols[] = {\n");
952         ret = _write_all(fd, msg, strlen(msg));
953         if (ret < 0)
954                 return ret;
955         free(msg);
956         FOR_EACH_COLUMN(i, desc, cd) {
957                 const char *asc_st;
958                 msg = make_message("\t[%d] = {\n", i);
959                 ret = _write_all(fd, msg, strlen(msg));
960                 if (ret < 0)
961                         return ret;
962                 free(msg);
963                 asc_st = get_asc_storage_type(cd->storage_type);
964                 msg = make_message("\t\t.storage_type = %s,\n", asc_st);
965                 ret = _write_all(fd, msg, strlen(msg));
966                 if (ret < 0)
967                         return ret;
968                 free(msg);
969                 if (cd->storage_flags) {
970                         char *asc_sf = get_asc_storage_flags(cd->storage_flags);
971                         msg = make_message("\t\t,storage_flags = %s,\n", asc_sf);
972                         free(asc_sf);
973                         ret = _write_all(fd, msg, strlen(msg));
974                         if (ret < 0)
975                                 return ret;
976                         free(msg);
977                 }
978                 if (cd->storage_flags & OSL_FIXED_SIZE) {
979                         msg = make_message("\t\t.data_size = %u,\n", cd->data_size);
980                         ret = _write_all(fd, msg, strlen(msg));
981                         if (ret < 0)
982                                 return ret;
983                         free(msg);
984                 }
985                 msg = make_message("\t\t.name = \"%s\",\n", cd->name);
986                 ret = _write_all(fd, msg, strlen(msg));
987                 if (ret < 0)
988                         return ret;
989                 free(msg);
990                 if (cd->storage_flags & OSL_RBTREE) {
991                         msg = make_message("\t\t.compare_function = compare_func,\n");
992                         ret = _write_all(fd, msg, strlen(msg));
993                         if (ret < 0)
994                                 return ret;
995                         free(msg);
996                 }
997                 msg = make_message("\t},\n");
998                 ret = _write_all(fd, msg, strlen(msg));
999                 if (ret < 0)
1000                         return ret;
1001                 free(msg);
1002         }
1003         msg = make_message("};\n");
1004         ret = _write_all(fd, msg, strlen(msg));
1005         if (ret < 0)
1006                 return ret;
1007         free(msg);
1008         return 1;
1009 }
1010
1011 static int dump_row(struct osl_table *t, unsigned row_num, const char *row_dir)
1012 {
1013         int ret, i;
1014         const struct osl_column_description *cd;
1015         unsigned dsnc;
1016         struct osl_object obj;
1017         char *ds_name;
1018         HASH_TYPE hash[HASH_SIZE];
1019         char *filename;
1020
1021         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
1022                 ret = get_mapped_object(t, i, row_num, &obj);
1023                 if (ret < 0)
1024                         return ret;
1025                 filename = make_message("%s/col_%03u", row_dir, i);
1026                 ret = write_file(filename, obj.data, obj.size);
1027                 free(filename);
1028                 if (ret < 0)
1029                         return ret;
1030         }
1031         if (!t->num_disk_storage_columns)
1032                 return 1;
1033         dsnc = t->disk_storage_name_column;
1034         ret = get_mapped_object(t, dsnc, row_num, &obj);
1035         if (ret < 0)
1036                 return ret;
1037         hash_object(&obj, hash);
1038         ds_name = disk_storage_name_of_hash(t, hash);
1039         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1040                 filename = disk_storage_path(t, i, ds_name);
1041                 ret = mmap_full_file(filename, O_RDONLY, &obj.data, &obj.size, NULL);
1042                 free(filename);
1043                 if (ret < 0)
1044                         goto out;
1045                 filename = make_message("%s/col_%03u", row_dir, i);
1046                 ret = write_file(filename, obj.data, obj.size);
1047                 free(filename);
1048                 if (ret < 0)
1049                         goto out;
1050         }
1051         ret = 1;
1052 out:
1053         free(ds_name);
1054         return ret;
1055 }
1056
1057 static int dump_rows(char *dump_dir, struct osl_table *t)
1058 {
1059         unsigned i;
1060         char *current_dir = NULL;
1061         int ret = 0;
1062
1063         for (i = 0; i < t->num_rows; i++) {
1064                 char *row_dir;
1065                 if (row_is_invalid(t, i))
1066                         continue;
1067                 if (!(i % 1000)) {
1068                         free(current_dir);
1069                         current_dir = make_message("%s/rows_%u-%u", dump_dir, i, i + 999);
1070                         NOTICE_LOG("dumping rows %u - %u\n", i, i + 999);
1071                         ret = osl_mkdir(current_dir, 0777);
1072                         if (ret < 0 && !is_errno(-ret, EEXIST))
1073                                 goto out;
1074                 }
1075                 row_dir = make_message("%s/row_%03u", current_dir, i);
1076                 ret = osl_mkdir(row_dir, 0777);
1077                 if (ret < 0 && !is_errno(-ret, EEXIST)) {
1078                         free(row_dir);
1079                         goto out;
1080                 }
1081                 ret = dump_row(t, i, row_dir);
1082                 free(row_dir);
1083                 if (ret < 0)
1084                         goto out;
1085         }
1086 out:
1087         free(current_dir);
1088         return ret;
1089 }
1090
1091 static int dump_table(char *dump_dir, struct osl_table_description *desc)
1092 {
1093         struct osl_table *t = NULL;
1094         int fd, ret = fsck_init(desc, &t);
1095         char *desc_file;
1096         char *table_dump_dir = NULL;
1097
1098         if (ret < 0)
1099                 goto out;
1100         ret = osl_mkdir(dump_dir, 0777);
1101         if (ret < 0 && !is_errno(-ret, EEXIST))
1102                 goto out;
1103         table_dump_dir = make_message("%s/%s", dump_dir, desc->name);
1104         ret = osl_mkdir(table_dump_dir, 0777);
1105         if (ret < 0 && !is_errno(-ret, EEXIST))
1106                 goto out;
1107         desc_file = make_message("%s/table_description.c", table_dump_dir);
1108         ret = osl_open(desc_file, O_WRONLY | O_CREAT | O_EXCL, 0644);
1109         free(desc_file);
1110         if (ret < 0)
1111                 goto out;
1112         fd = ret;
1113         ret = dump_table_desc(t, fd);
1114         close(fd);
1115         if (ret < 0)
1116                 goto out;
1117         ret = dump_rows(table_dump_dir, t);
1118 out:
1119         free(table_dump_dir);
1120         fsck_cleanup(t);
1121         return ret;
1122 }
1123
1124 static int fsck(struct osl_table_description *desc)
1125 {
1126         int ret;
1127         struct osl_table *t = NULL;
1128         uint32_t *lost_bytes = NULL;
1129
1130         ret = fsck_init(desc, &t);
1131         if (ret < 0)
1132                 goto out;
1133         ret = check_index_ranges(t);
1134         if (ret < 0)
1135                 goto out_unmap;
1136         ret = check_disk_storage_columns(t);
1137         if (ret < 0)
1138                 goto out_unmap;
1139         ret = prune_invalid_rows_from_index(t);
1140         if (ret < 0)
1141                 goto out_unmap;
1142         ret = check_for_invalid_objects(t, &lost_bytes);
1143         if (ret < 0)
1144                 goto out_unmap;
1145         if (ret > 0) { /* at least one mapped data file needs pruning */
1146                 ret = prune_objects(t, lost_bytes);
1147                 if (ret < 0)
1148                         goto out_unmap;
1149         }
1150         free(lost_bytes);
1151 out_unmap:
1152         unmap_table(t, OSL_MARK_CLEAN);
1153 out:
1154         fsck_cleanup(t);
1155         return ret;
1156 }
1157
1158 static int check_table(char *db_dir, char *table_name)
1159 {
1160         struct osl_table_description desc = {
1161                 .column_descriptions = NULL,
1162                 .dir = db_dir,
1163                 .name = table_name
1164         };
1165         int ret;
1166
1167         INFO_LOG("checking table %s\n", table_name);
1168         if (!conf.no_fsck_given) {
1169                 ret = fsck(&desc);
1170                 if (ret < 0)
1171                         goto out;
1172         }
1173         ret = 1;
1174         if (!conf.dump_dir_given || !*conf.dump_dir_arg)
1175                 goto out;
1176         ret = dump_table(conf.dump_dir_arg, &desc);
1177 out:
1178         if (ret < 0)
1179                 ERROR_LOG("failed to check table %s\n", table_name);
1180         else
1181                 NOTICE_LOG("successfully checked table %s\n", table_name);
1182         return ret;
1183 }
1184
1185 static int check_all_tables(char *db_dir)
1186 {
1187         DIR *dir;
1188         struct dirent *entry;
1189         int cwd_fd, ret2, ret = fsck_opendir(db_dir, &dir, &cwd_fd);
1190
1191         if (ret < 0)
1192                 return ret;
1193         while ((entry = readdir(dir))) {
1194                 mode_t m;
1195                 struct stat s;
1196                 if (!strcmp(entry->d_name, "."))
1197                         continue;
1198                 if (!strcmp(entry->d_name, ".."))
1199                         continue;
1200                 if (lstat(entry->d_name, &s) == -1)
1201                         continue;
1202                 m = s.st_mode;
1203                 if (!S_ISDIR(m))
1204                         continue;
1205                 ret = check_table(db_dir, entry->d_name);
1206                 if (ret < 0)
1207                         break;
1208         }
1209         closedir(dir);
1210         ret2 = __fchdir(cwd_fd);
1211         if (ret2 < 0 && ret >= 0)
1212                 ret = ret2;
1213         close(cwd_fd);
1214         return ret;
1215 }
1216
1217 int main(int argc, char **argv)
1218 {
1219         int i, ret;
1220         struct fsck_cmdline_parser_params params = {
1221                 .override = 0,
1222                 .initialize = 1,
1223                 .check_required = 1,
1224                 .check_ambiguity = 1,
1225                 .print_errors = 1
1226         };
1227         ret = fsck_cmdline_parser_ext(argc, argv, &conf, &params);
1228         if (ret < 0) {
1229                 loglevel = EMERG;
1230                 ret = -E_FSCK_SYNTAX;
1231                 goto out;
1232         }
1233         loglevel = conf.loglevel_arg;
1234         HANDLE_VERSION_FLAG("fsck", conf);
1235         INFO_LOG("database dir: %s\n", conf.database_dir_arg);
1236         if (!conf.inputs_num) {
1237                 ret = check_all_tables(conf.database_dir_arg);
1238                 goto out;
1239         }
1240         for (i = 0; i < conf.inputs_num; i++) {
1241                 ret = check_table(conf.database_dir_arg, conf.inputs[i]);
1242                 if (ret < 0)
1243                         break;
1244         }
1245 out:
1246         if (ret < 0) {
1247                 ERROR_LOG("%s\n", fsck_strerror(-ret));
1248                 if (conf.loglevel_arg > 1)
1249                         EMERG_LOG("re-run with \"--loglevel %d\" to increase verbosity\n",
1250                                 conf.loglevel_arg - 1);
1251         } else
1252                 NOTICE_LOG("success\n");
1253         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1254 }