68e31078892e08edcd4fc7e193b5ebdbd9ccf54f
[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_FSCK_RANGE_VIOLATION)
411                                         goto err;
412                                 ret = mark_row_invalid(t, i);
413                                 if (ret < 0)
414                                         goto err;
415                                 t->num_invalid_rows++;
416                                 break;
417                         }
418                 }
419
420         }
421         if (t->num_invalid_rows)
422                 NOTICE_LOG("ranges OK. %d invalid row(s) detected\n",
423                         t->num_invalid_rows);
424         else
425                 INFO_LOG("no invalid rows, no range violations, good\n");
426         return 1;
427 err:
428         return ret;
429 }
430
431 static int move_index_entry(struct osl_table *t, uint32_t dest, uint32_t src)
432 {
433         char *dest_ie, *src_ie;
434         int ret = get_row_index(t, dest, &dest_ie);
435
436         if (ret < 0)
437                 return ret;
438         ret = get_row_index(t, src, &src_ie);
439         if (ret < 0)
440                 return ret;
441         INFO_LOG("moving entry #%u to position %u\n", src, dest);
442         memcpy(dest_ie, src_ie, t->row_index_size);
443         return 1;
444 }
445
446 static int map_index(const struct osl_table_description *desc, struct osl_object *map)
447 {
448         char *filename = index_filename(desc);
449         int ret;
450
451         ret = mmap_full_file(filename, O_RDWR, &map->data, &map->size, NULL);
452         DEBUG_LOG("mapping index %s: ret: %d, size: %zu\n", filename, ret, map->size);
453         free(filename);
454         return ret;
455 }
456
457 static int prune_invalid_rows_from_index(struct osl_table *t)
458 {
459         uint32_t top = 0, bottom;
460         char *filename;
461         int ret;
462
463         if (!t->num_invalid_rows) {
464                 INFO_LOG("all rows are valid, good\n");
465                 return 1;
466         }
467         NOTICE_LOG("deleting %u invalid row(s) (%d bytes) from index\n",
468                 t->num_invalid_rows, t->row_index_size * t->num_invalid_rows);
469         bottom = t->num_rows - 1;
470         while (top < bottom) {
471                 if (!row_is_invalid(t, top)) {
472                         top++;
473                         continue;
474                 }
475                 while (bottom > top) {
476                         if (row_is_invalid(t, bottom)) {
477                                 bottom--;
478                                 continue;
479                         }
480                         /* move bottom index entry to top */
481                         move_index_entry(t, top, bottom);
482                         bottom--;
483                         top++;
484                         break;
485                 }
486         }
487         DEBUG_LOG("unmapping index\n");
488         osl_munmap(t->index_map.data, t->index_map.size);
489         filename = index_filename(t->desc);
490         ret = truncate_file(filename, t->row_index_size
491                 * t->num_invalid_rows);
492         free(filename);
493         if (ret < 0)
494                 return ret;
495         ret = map_index(t->desc, &t->index_map);
496         if (ret < 0)
497                 return ret;
498         t->num_rows = table_num_rows(t);
499         return 1;
500 }
501
502 static int check_for_invalid_objects(struct osl_table *t, uint32_t **lost_bytes)
503 {
504         int i, j, ret;
505         const struct osl_column_description *cd;
506         uint32_t *loss = fsck_malloc(sizeof(uint32_t) * t->desc->num_columns);
507
508         INFO_LOG("looking for mapped objects not contained in index\n");
509         /* first count used bytes */
510         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
511                 loss[i] = t->columns[i].data_map.size;
512                 for (j = 0; j < t->num_rows; j++) {
513                         struct osl_object obj;
514                         ret = get_mapped_object(t, i, j, &obj);
515                         if (ret < 0)
516                                 goto err;
517                         loss[i] -= obj.size;
518                 }
519         }
520         ret = 0;
521         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
522                 if (loss[i]) {
523                         NOTICE_LOG("column %u contains %u lost bytes\n",
524                                 i, loss[i]);
525                         ret = 1;
526                 }
527         }
528         if (!ret)
529                 INFO_LOG("all mapped objects are valid, good\n");
530         *lost_bytes = loss;
531         return ret;
532 err:
533         free(loss);
534         return ret;
535 }
536
537 /* prune_invalid_rows() must be run on the table before calling this */
538 static int prune_mapped_column(struct osl_table *t, uint32_t col_num, int fd)
539 {
540         int i, ret;
541         uint32_t written = 0;
542         struct osl_column *col = t->columns + col_num;
543
544         INFO_LOG("pruning col %u\n", col_num);
545         for (i = 0; i < t->num_rows; i++) {
546                 struct osl_object obj;
547                 char *index_entry;
548
549                 DEBUG_LOG("checking row %u/%u\n", i, t->num_rows);
550                 ret = get_mapped_object(t, col_num, i, &obj);
551                 if (ret < 0)
552                         return ret;
553                 ret = _write_all(fd, (char *)(obj.data) - 1, obj.size + 1);
554                 if (ret < 0)
555                         return ret;
556                 written += obj.size + 1;
557                 ret = get_row_index(t, i, &index_entry);
558                 if (ret < 0)
559                         return ret;
560                 update_cell_index(index_entry, col, written, obj.size);
561         }
562         return 1;
563 }
564
565 static int prune_objects(struct osl_table *t, uint32_t *lost_bytes)
566 {
567         int i, ret;
568         const struct osl_column_description *cd;
569         char **col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
570         char **new_col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
571         char *idx_filename = index_filename(t->desc);
572         char *old_idx_filename = make_message("%s.bak", idx_filename);
573         int fd;
574
575         NOTICE_LOG("removing unreferenced objects from data files\n");
576         /* first make a copy of the index */
577         ret = osl_open(old_idx_filename, O_WRONLY | O_CREAT | O_EXCL, 0644);
578         if (ret < 0)
579                 goto out_free;
580         fd = ret;
581         ret = _write_all(fd, t->index_map.data, t->index_map.size);
582         close(fd);
583         if (ret < 0)
584                 goto out_free;
585         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
586                 if (!lost_bytes[i])
587                         continue;
588                 col_filenames[i] = column_filename(t, i);
589                 new_col_filenames[i] = make_message("%s.fsck", col_filenames[i]);
590                 ret = osl_open(new_col_filenames[i], O_WRONLY | O_CREAT | O_EXCL, 0644);
591                 if (ret < 0)
592                         goto out_unlink_data;
593                 fd = ret;
594                 ret = prune_mapped_column(t, i, fd);
595                 close(fd);
596                 if (ret < 0)
597                         goto out_unlink_data;
598         }
599         ret = unmap_table(t, OSL_MARK_CLEAN);
600         if (ret < 0)
601                 goto out_unlink_data;
602         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
603                 if (!lost_bytes[i])
604                         continue;
605                 ret = osl_rename(new_col_filenames[i], col_filenames[i]);
606                 if (ret < 0) { /* we're kinda screwed here */
607                         CRIT_LOG("rename of col %i failed: %s\n", i,
608                                 osl_strerror(errno));
609                         goto out_free;
610                 }
611         }
612         unlink(old_idx_filename);
613         ret = map_table(t, 0);
614         goto out_free;
615 out_unlink_data:
616         FOR_EACH_MAPPED_COLUMN(i, t, cd)
617                 unlink(new_col_filenames[i]);
618 out_free:
619         free(old_idx_filename);
620         free(idx_filename);
621         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
622                 free(col_filenames[i]);
623                 free(new_col_filenames[i]);
624         }
625         free(col_filenames);
626         free(new_col_filenames);
627         return ret;
628 }
629
630 static struct osl_column_description hash_tree_table_cols[] = {
631         {
632                 .storage_type = OSL_NO_STORAGE,
633                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
634                 .name = "hash",
635                 .compare_function = uint32_compare,
636                 .data_size = HASH_SIZE
637         },
638 };
639
640 static const struct osl_table_description hash_tree_table_desc = {
641         .dir = "/", /* irrelevant */
642         .name = "hash_tree",
643         .num_columns = 1,
644         .flags = 0,
645         .column_descriptions = hash_tree_table_cols
646 };
647
648 /**
649  * The hash_tree table contains all hashes of the disk storage name column.
650  * of each row. It is used for checking if a disk storage file has a reference
651  * in the table.
652  */
653 static struct osl_table *hash_tree_table;
654 static HASH_TYPE *hashes;
655
656 static int check_disk_storage_column(struct osl_table *t, int row_num,
657                 int col_num, char *ds_name, unsigned *num_missing_objects)
658 {
659         int ret;
660         struct stat statbuf;
661         char *path = disk_storage_path(t, col_num, ds_name);
662         unsigned dsnc = t->disk_storage_name_column;
663         struct osl_object obj;
664
665         DEBUG_LOG("checking if %s is a regular file\n", path);
666         ret = stat(path, &statbuf);
667         if (ret < 0 && errno == ENOENT) {
668                 struct osl_row *row;
669                 (*num_missing_objects)++;
670                 ERROR_LOG("row %d: object %s is missing\n", row_num, path);
671                 NOTICE_LOG("trying to delete row %d\n", row_num);
672                 ret = osl_get_row(t, dsnc, &obj, &row);
673                 if (ret < 0) {
674                         CRIT_LOG("unable to get row %d\n", row_num);
675                         mark_row_invalid(t, row_num);
676                         CRIT_LOG("Please re-run fsck\n");
677                         goto out;
678                 }
679                 ret = osl_del_row(t, row);
680                 if (ret < 0)
681                         goto out;
682         }
683 out:
684         free(path);
685         if (ret < 0)
686                 return ret;
687         ret = -E_FSCK_NOT_A_REGULAR_FILE;
688         if (!(S_IFREG & statbuf.st_mode))
689                 return ret;
690         return 1;
691 }
692
693 static int check_disk_storage_presence(struct osl_table *t)
694 {
695         int ret, i, j;
696         struct osl_object obj, hash_obj = {.size = HASH_SIZE};
697         char *ds_name;
698         const struct osl_column_description *cd;
699         unsigned dsnc = t->disk_storage_name_column, missing_objects = 0;
700
701         if (!t->num_rows)
702                 return 1;
703         hashes = fsck_malloc(t->num_rows * HASH_SIZE);
704         INFO_LOG("looking for missing disk storage objects\n");
705         for (i = 0; i < t->num_rows; i++) {
706                 if (row_is_invalid(t, i))
707                         continue;
708                 ret = get_mapped_object(t, dsnc, i, &obj);
709                 if (ret < 0)
710                         return ret;
711                 hash_object(&obj, hashes + i * HASH_SIZE);
712                 hash_obj.data = hashes + i * HASH_SIZE;
713                 osl_add_row(hash_tree_table, &hash_obj);
714                 ds_name = disk_storage_name_of_hash(t, hashes + i * HASH_SIZE);
715                 FOR_EACH_DISK_STORAGE_COLUMN(j, t, cd) {
716                         ret = check_disk_storage_column(t, i, j, ds_name,
717                                 &missing_objects);
718                         if (ret < 0)
719                                 goto err;
720                 }
721                 free(ds_name);
722         }
723         if (!missing_objects)
724                 INFO_LOG("all referenced disk storage objects exist, good\n");
725         else
726                 NOTICE_LOG("%d missing object(s)\n", missing_objects);
727         return missing_objects;
728 err:
729         free(ds_name);
730         return ret;
731 }
732
733 static int dummy_compare(const struct osl_object *obj1, const struct osl_object *obj2)
734 {
735         if (obj1 < obj2)
736                 return -1;
737         if (obj1 > obj2)
738                 return 1;
739         return 0;
740 }
741
742 static unsigned files_pruned;
743
744 int prune_disk_storage_file(const char *path, void *private_data)
745 {
746         HASH_TYPE hash[HASH_SIZE];
747         uint8_t flags = *(uint8_t *)private_data;
748         struct osl_object obj = {.data = hash, .size = HASH_SIZE};
749         struct osl_row *row;
750         int ret = -1;
751         size_t len = strlen(path);
752
753
754         DEBUG_LOG("path: %s\n", path);
755         if (flags & OSL_LARGE_TABLE) {
756                 if (len < HASH_SIZE * 2 + 2)
757                         goto invalid;
758 //              NOTICE_LOG("p: %s\n", path + len - 2 * HASH_SIZE - 1);
759                 ret = asc_to_hash(path + len - 2 * HASH_SIZE - 1, 1, hash);
760                 if (ret < 0)
761                         goto invalid;
762                 ret = asc_to_hash(path + len - 2 * HASH_SIZE + 2, HASH_SIZE - 1,
763                         hash + 1);
764                 if (ret < 0)
765                         goto invalid;
766 //              INFO_LOG("high: %x, low: %x, hash: %x\n", high, low, hash);
767         } else {
768                 if (len < 2 * HASH_SIZE + 1)
769                         goto invalid;
770                 ret = asc_to_hash(path + len - 2 * HASH_SIZE, 2 * HASH_SIZE, hash);
771                 if (ret < 0)
772                         goto invalid;
773 //              INFO_LOG("hash: %x\n", hash);
774         }
775 #if 0
776 {
777         char asc[2 * HASH_SIZE + 1];
778         hash_to_asc(hash, asc);
779         NOTICE_LOG("before: %s\nafter: %s\n", path, asc);
780 }
781 #endif
782         ret = osl_get_row(hash_tree_table, 0, &obj, &row);
783         if (ret >= 0)
784                 return 1;
785         NOTICE_LOG("unreferenced file in hash dir: %s\n", path);
786         goto remove;
787 invalid:
788         ERROR_LOG("could not read hash value of %s\n", path);
789 remove:
790         NOTICE_LOG("removing %s\n", path);
791         unlink(path);
792         files_pruned++;
793         return 1;
794 }
795
796 static int prune_disk_storage_files(struct osl_table *t)
797 {
798         int i, ret = 1;
799         const struct osl_column_description *cd;
800
801         INFO_LOG("looking for unreferenced disk storage files\n");
802         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
803                 char *dirname = column_filename(t, i);
804                 uint8_t flags = t->desc->flags;
805                 ret = for_each_file_in_dir(dirname, prune_disk_storage_file,
806                         &flags);
807                 free(dirname);
808         }
809         if (files_pruned)
810                 NOTICE_LOG("%u disk storage files deleted\n",
811                         files_pruned);
812         else
813                 INFO_LOG("all files are are referenced, good\n");
814         return ret;
815 }
816
817 static int check_disk_storage_columns(struct osl_table *t)
818 {
819         int ret, i;
820         const struct osl_column_description *cd;
821
822         if (!t->num_disk_storage_columns) {
823                 INFO_LOG("no disk storage columns in table '%s', "
824                         "skipping checks\n", t->desc->name);
825                 return 1;
826         }
827         FOR_EACH_COLUMN(i, t->desc, cd)
828                 t->desc->column_descriptions[i].compare_function = dummy_compare;
829         ret = init_rbtrees(t);
830         if (ret < 0)
831                 return ret;
832         INFO_LOG("creating rbtree for disk storage hash values\n");
833         ret = osl_open_table(&hash_tree_table_desc, &hash_tree_table);
834         if (ret < 0)
835                 goto out;
836         ret = check_disk_storage_presence(t);
837         if (ret < 0)
838                 goto out_close_hash_tree;
839         ret = prune_disk_storage_files(t);
840 out_close_hash_tree:
841         osl_close_table(hash_tree_table, 0);
842         free(hashes);
843         hashes = NULL;
844 out:
845         clear_rbtrees(t); /* TODO why are we doing that here? Seems odd */
846         return ret;
847 }
848
849 static void set_dummy_contents(struct osl_table_description *desc)
850 {
851         int i;
852         struct osl_column_description *cd;
853
854         for (i = 0; i < desc->num_columns; i++) {
855                 cd = get_column_description(desc, i);
856                 cd->compare_function = dummy_compare;
857         }
858 }
859
860 static int fsck_init(struct osl_table_description *desc, struct osl_table **t)
861 {
862         struct osl_object map;
863         int ret = map_index(desc, &map);
864
865         if (ret < 0)
866                 goto out;
867         ret = read_table_desc(&map, desc);
868         if (ret < 0) {
869                 osl_munmap(map.data, map.size);
870                 goto out;
871         }
872         set_dummy_contents(desc);
873         ret = init_table_structure(desc, t);
874         if (ret < 0) {
875                 osl_munmap(map.data, map.size);
876                 goto out;
877         }
878         DEBUG_LOG("unmapping index\n");
879         osl_munmap(map.data, map.size);
880         if (conf.force_given)
881                 ret = map_table(*t, (MAP_TBL_FL_IGNORE_DIRTY));
882         else
883                 ret = map_table(*t, 0);
884         if (ret >= 0)
885                 (*t)->num_rows = table_num_rows(*t);
886 out:
887         return ret;
888 }
889
890 static void fsck_cleanup(struct osl_table *t)
891 {
892         int i;
893
894         if (!t)
895                 return;
896         if (t->desc->column_descriptions) {
897                 struct osl_column_description *cd;
898                 for (i = 0; i < t->desc->num_columns; i++) {
899                         cd = get_column_description(t->desc, i);
900                         free((char*)cd->name);
901                 }
902                 free(t->desc->column_descriptions);
903         }
904         free(t->columns);
905         free(t);
906
907 }
908
909 #define ST_CASE(st) case st: return #st
910
911 const char *get_asc_storage_type(enum osl_storage_type st)
912 {
913         switch (st) {
914                 ST_CASE(OSL_MAPPED_STORAGE);
915                 ST_CASE(OSL_DISK_STORAGE);
916                 ST_CASE(OSL_NO_STORAGE);
917         }
918         return NULL;
919 }
920
921 #define APPEND_ASC_SF(sf, flag, str) do { if (sf & flag) { \
922         if (str) str = make_message("%s%s", str, " | " # flag); \
923         else str = fsck_strdup(#flag); }} while (0)
924
925
926 char *get_asc_storage_flags(enum osl_storage_type sf)
927 {
928         char *asc_sf = NULL;
929
930         APPEND_ASC_SF(sf, OSL_RBTREE, asc_sf);
931         APPEND_ASC_SF(sf, OSL_FIXED_SIZE, asc_sf);
932         APPEND_ASC_SF(sf, OSL_UNIQUE, asc_sf);
933         return asc_sf;
934 }
935
936 static int dump_table_desc(struct osl_table *t, int fd)
937 {
938         const struct osl_table_description *desc = t->desc;
939         int ret, i;
940         struct osl_column_description *cd;
941         char *msg = make_message("static struct osl_column_description cols[] = {\n");
942         ret = _write_all(fd, msg, strlen(msg));
943         if (ret < 0)
944                 return ret;
945         free(msg);
946         FOR_EACH_COLUMN(i, desc, cd) {
947                 const char *asc_st;
948                 msg = make_message("\t[%d] = {\n", i);
949                 ret = _write_all(fd, msg, strlen(msg));
950                 if (ret < 0)
951                         return ret;
952                 free(msg);
953                 asc_st = get_asc_storage_type(cd->storage_type);
954                 msg = make_message("\t\t.storage_type = %s,\n", asc_st);
955                 ret = _write_all(fd, msg, strlen(msg));
956                 if (ret < 0)
957                         return ret;
958                 free(msg);
959                 if (cd->storage_flags) {
960                         char *asc_sf = get_asc_storage_flags(cd->storage_flags);
961                         msg = make_message("\t\t,storage_flags = %s,\n", asc_sf);
962                         free(asc_sf);
963                         ret = _write_all(fd, msg, strlen(msg));
964                         if (ret < 0)
965                                 return ret;
966                         free(msg);
967                 }
968                 if (cd->storage_flags & OSL_FIXED_SIZE) {
969                         msg = make_message("\t\t.data_size = %u,\n", cd->data_size);
970                         ret = _write_all(fd, msg, strlen(msg));
971                         if (ret < 0)
972                                 return ret;
973                         free(msg);
974                 }
975                 msg = make_message("\t\t.name = \"%s\",\n", cd->name);
976                 ret = _write_all(fd, msg, strlen(msg));
977                 if (ret < 0)
978                         return ret;
979                 free(msg);
980                 if (cd->storage_flags & OSL_RBTREE) {
981                         msg = make_message("\t\t.compare_function = compare_func,\n");
982                         ret = _write_all(fd, msg, strlen(msg));
983                         if (ret < 0)
984                                 return ret;
985                         free(msg);
986                 }
987                 msg = make_message("\t},\n");
988                 ret = _write_all(fd, msg, strlen(msg));
989                 if (ret < 0)
990                         return ret;
991                 free(msg);
992         }
993         msg = make_message("};\n");
994         ret = _write_all(fd, msg, strlen(msg));
995         if (ret < 0)
996                 return ret;
997         free(msg);
998         return 1;
999 }
1000
1001 static int dump_row(struct osl_table *t, unsigned row_num, const char *row_dir)
1002 {
1003         int ret, i;
1004         const struct osl_column_description *cd;
1005         unsigned dsnc;
1006         struct osl_object obj;
1007         char *ds_name;
1008         HASH_TYPE hash[HASH_SIZE];
1009         char *filename;
1010
1011         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
1012                 ret = get_mapped_object(t, i, row_num, &obj);
1013                 if (ret < 0)
1014                         return ret;
1015                 filename = make_message("%s/col_%03u", row_dir, i);
1016                 ret = write_file(filename, obj.data, obj.size);
1017                 free(filename);
1018                 if (ret < 0)
1019                         return ret;
1020         }
1021         if (!t->num_disk_storage_columns)
1022                 return 1;
1023         dsnc = t->disk_storage_name_column;
1024         ret = get_mapped_object(t, dsnc, row_num, &obj);
1025         if (ret < 0)
1026                 return ret;
1027         hash_object(&obj, hash);
1028         ds_name = disk_storage_name_of_hash(t, hash);
1029         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
1030                 filename = disk_storage_path(t, i, ds_name);
1031                 ret = mmap_full_file(filename, O_RDONLY, &obj.data, &obj.size, NULL);
1032                 free(filename);
1033                 if (ret < 0)
1034                         goto out;
1035                 filename = make_message("%s/col_%03u", row_dir, i);
1036                 ret = write_file(filename, obj.data, obj.size);
1037                 free(filename);
1038                 if (ret < 0)
1039                         goto out;
1040         }
1041         ret = 1;
1042 out:
1043         free(ds_name);
1044         return ret;
1045 }
1046
1047 static int dump_rows(char *dump_dir, struct osl_table *t)
1048 {
1049         unsigned i;
1050         char *current_dir = NULL;
1051         int ret = 0;
1052
1053         for (i = 0; i < t->num_rows; i++) {
1054                 char *row_dir;
1055                 if (row_is_invalid(t, i))
1056                         continue;
1057                 if (!(i % 1000)) {
1058                         free(current_dir);
1059                         current_dir = make_message("%s/rows_%u-%u", dump_dir, i, i + 999);
1060                         NOTICE_LOG("dumping rows %u - %u\n", i, i + 999);
1061                         ret = osl_mkdir(current_dir, 0777);
1062                         if (ret < 0 && !is_errno(-ret, EEXIST))
1063                                 goto out;
1064                 }
1065                 row_dir = make_message("%s/row_%03u", current_dir, i);
1066                 ret = osl_mkdir(row_dir, 0777);
1067                 if (ret < 0 && !is_errno(-ret, EEXIST)) {
1068                         free(row_dir);
1069                         goto out;
1070                 }
1071                 ret = dump_row(t, i, row_dir);
1072                 free(row_dir);
1073                 if (ret < 0)
1074                         goto out;
1075         }
1076 out:
1077         free(current_dir);
1078         return ret;
1079 }
1080
1081 static int dump_table(char *dump_dir, struct osl_table_description *desc)
1082 {
1083         struct osl_table *t = NULL;
1084         int fd, ret = fsck_init(desc, &t);
1085         char *desc_file;
1086         char *table_dump_dir = NULL;
1087
1088         if (ret < 0)
1089                 goto out;
1090         ret = osl_mkdir(dump_dir, 0777);
1091         if (ret < 0 && !is_errno(-ret, EEXIST))
1092                 goto out;
1093         table_dump_dir = make_message("%s/%s", dump_dir, desc->name);
1094         ret = osl_mkdir(table_dump_dir, 0777);
1095         if (ret < 0 && !is_errno(-ret, EEXIST))
1096                 goto out;
1097         desc_file = make_message("%s/table_description.c", table_dump_dir);
1098         ret = osl_open(desc_file, O_WRONLY | O_CREAT | O_EXCL, 0644);
1099         free(desc_file);
1100         if (ret < 0)
1101                 goto out;
1102         fd = ret;
1103         ret = dump_table_desc(t, fd);
1104         close(fd);
1105         if (ret < 0)
1106                 goto out;
1107         ret = dump_rows(table_dump_dir, t);
1108 out:
1109         free(table_dump_dir);
1110         fsck_cleanup(t);
1111         return ret;
1112 }
1113
1114 static int fsck(struct osl_table_description *desc)
1115 {
1116         int ret;
1117         struct osl_table *t = NULL;
1118         uint32_t *lost_bytes = NULL;
1119
1120         ret = fsck_init(desc, &t);
1121         if (ret < 0)
1122                 goto out;
1123         ret = check_index_ranges(t);
1124         if (ret < 0)
1125                 goto out_unmap;
1126         ret = check_disk_storage_columns(t);
1127         if (ret < 0)
1128                 goto out_unmap;
1129         ret = prune_invalid_rows_from_index(t);
1130         if (ret < 0)
1131                 goto out_unmap;
1132         ret = check_for_invalid_objects(t, &lost_bytes);
1133         if (ret < 0)
1134                 goto out_unmap;
1135         if (ret > 0) { /* at least one mapped data file needs pruning */
1136                 ret = prune_objects(t, lost_bytes);
1137                 if (ret < 0)
1138                         goto out_unmap;
1139         }
1140         free(lost_bytes);
1141 out_unmap:
1142         unmap_table(t, OSL_MARK_CLEAN);
1143 out:
1144         fsck_cleanup(t);
1145         return ret;
1146 }
1147
1148 static int check_table(char *db_dir, char *table_name)
1149 {
1150         struct osl_table_description desc = {
1151                 .column_descriptions = NULL,
1152                 .dir = db_dir,
1153                 .name = table_name
1154         };
1155         int ret;
1156
1157         INFO_LOG("checking table %s\n", table_name);
1158         if (!conf.no_fsck_given) {
1159                 ret = fsck(&desc);
1160                 if (ret < 0)
1161                         goto out;
1162         }
1163         ret = 1;
1164         if (!conf.dump_dir_given || !*conf.dump_dir_arg)
1165                 goto out;
1166         ret = dump_table(conf.dump_dir_arg, &desc);
1167 out:
1168         if (ret < 0)
1169                 ERROR_LOG("failed to check table %s\n", table_name);
1170         else
1171                 NOTICE_LOG("successfully checked table %s\n", table_name);
1172         return ret;
1173 }
1174
1175 static int check_all_tables(char *db_dir)
1176 {
1177         DIR *dir;
1178         struct dirent *entry;
1179         int cwd_fd, ret2, ret = fsck_opendir(db_dir, &dir, &cwd_fd);
1180
1181         if (ret < 0)
1182                 return ret;
1183         while ((entry = readdir(dir))) {
1184                 mode_t m;
1185                 struct stat s;
1186                 if (!strcmp(entry->d_name, "."))
1187                         continue;
1188                 if (!strcmp(entry->d_name, ".."))
1189                         continue;
1190                 if (lstat(entry->d_name, &s) == -1)
1191                         continue;
1192                 m = s.st_mode;
1193                 if (!S_ISDIR(m))
1194                         continue;
1195                 ret = check_table(db_dir, entry->d_name);
1196                 if (ret < 0)
1197                         break;
1198         }
1199         closedir(dir);
1200         ret2 = __fchdir(cwd_fd);
1201         if (ret2 < 0 && ret >= 0)
1202                 ret = ret2;
1203         close(cwd_fd);
1204         return ret;
1205 }
1206
1207 int main(int argc, char **argv)
1208 {
1209         int i, ret;
1210         struct fsck_cmdline_parser_params params = {
1211                 .override = 0,
1212                 .initialize = 1,
1213                 .check_required = 1,
1214                 .check_ambiguity = 1,
1215                 .print_errors = 1
1216         };
1217         ret = fsck_cmdline_parser_ext(argc, argv, &conf, &params);
1218         if (ret < 0) {
1219                 loglevel = EMERG;
1220                 ret = -E_FSCK_SYNTAX;
1221                 goto out;
1222         }
1223         loglevel = conf.loglevel_arg;
1224         HANDLE_VERSION_FLAG("fsck", conf);
1225         INFO_LOG("database dir: %s\n", conf.database_dir_arg);
1226         if (!conf.inputs_num) {
1227                 ret = check_all_tables(conf.database_dir_arg);
1228                 goto out;
1229         }
1230         for (i = 0; i < conf.inputs_num; i++) {
1231                 ret = check_table(conf.database_dir_arg, conf.inputs[i]);
1232                 if (ret < 0)
1233                         break;
1234         }
1235 out:
1236         if (ret < 0) {
1237                 ERROR_LOG("%s\n", fsck_strerror(-ret));
1238                 if (conf.loglevel_arg > 1)
1239                         EMERG_LOG("re-run with \"--loglevel %d\" to increase verbosity\n",
1240                                 conf.loglevel_arg - 1);
1241         } else
1242                 NOTICE_LOG("success\n");
1243         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1244 }