]> git.tuebingen.mpg.de Git - osl.git/blob - fsck.c
b5e4fdbe16e0fc593e303de69de8e521b845ed31
[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 "fd.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  * Traverse the given directory recursively.
227  *
228  * \param dirname The directory to traverse.
229  * \param func The function to call for each entry.
230  * \param private_data Pointer to an arbitrary data structure.
231  *
232  * For each regular file under \a dirname, the supplied function \a func is
233  * called.  The full path of the regular file and the \a private_data pointer
234  * are passed to \a func. Directories for which the calling process has no
235  * permissions to change to are silently ignored.
236  *
237  * \return Standard.
238  */
239 static int for_each_file_in_dir(const char *dirname,
240                 int (*func)(const char *, void *), void *private_data)
241 {
242         DIR *dir;
243         struct dirent *entry;
244         int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
245
246         if (ret < 0)
247                 return ret == -ERRNO_TO_ERROR(EACCES)? 1 : ret;
248         /* scan cwd recursively */
249         while ((entry = readdir(dir))) {
250                 mode_t m;
251                 char *tmp;
252                 struct stat s;
253
254                 if (!strcmp(entry->d_name, "."))
255                         continue;
256                 if (!strcmp(entry->d_name, ".."))
257                         continue;
258                 if (lstat(entry->d_name, &s) == -1)
259                         continue;
260                 m = s.st_mode;
261                 if (!S_ISREG(m) && !S_ISDIR(m))
262                         continue;
263                 tmp = make_message("%s/%s", dirname, entry->d_name);
264                 if (!S_ISDIR(m)) {
265                         ret = func(tmp, private_data);
266                         free(tmp);
267                         if (ret < 0)
268                                 goto out;
269                         continue;
270                 }
271                 /* directory */
272                 ret = for_each_file_in_dir(tmp, func, private_data);
273                 free(tmp);
274                 if (ret < 0)
275                         goto out;
276         }
277         ret = 1;
278 out:
279         closedir(dir);
280         ret2 = __fchdir(cwd_fd);
281         if (ret2 < 0 && ret >= 0)
282                 ret = ret2;
283         close(cwd_fd);
284         return ret;
285 }
286
287 /*
288  * check for object boundary violations
289  *
290  * test whether the range pointed to by the index entry for a given cell is
291  * contained in mapped data file. This should always be the case. Otherwise
292  * we are in real trouble.
293  */
294 static int check_range(struct osl_table *t, uint32_t row_num, uint32_t col_num)
295 {
296         char *index_entry;
297         struct osl_object obj;
298         struct osl_column *col;
299         int ret;
300         char *map_start, *obj_start;
301
302         ret = get_cell_index(t, row_num, col_num, &index_entry);
303         if (ret < 0)
304                 return ret;
305         ret = get_mapped_object(t, col_num, row_num, &obj);
306         if (ret < 0)
307                 return ret;
308         col = t->columns + col_num;
309         obj_start = obj.data;
310         map_start = col->data_map.data;
311 //      INFO_LOG("obj: %p..%p\n", obj_start, obj_start + obj.size);
312 //      INFO_LOG("map: %p..%p\n", map_start, map_start + col->data_map.size);
313         if (obj_start < map_start || obj_start + obj.size > map_start + col->data_map.size) {
314                 CRIT_LOG("range violation in row %u, col %u\n", row_num,
315                         col_num);
316                 return -E_FSCK_RANGE_VIOLATION;
317         }
318         DEBUG_LOG("col %u: ok\n", col_num);
319         return 1;
320 }
321
322 /*
323  * check all cells of the given table for boundary violations
324  */
325 static int check_index_ranges(struct osl_table *t)
326 {
327         int i, j, ret;
328
329         INFO_LOG("checking for range violations in index\n");
330         //DEBUG_LOG("%d rows. %d columns\n", t->num_rows, t->desc->num_columns);
331         t->num_invalid_rows = 0;
332         for (i = 0; i < t->num_rows; i++) {
333                 if (row_is_invalid(t, i)) {
334                         t->num_invalid_rows++;
335                         continue;
336                 }
337                 for (j = 0; j < t->desc->num_columns; j++) { /* FXIME */
338                         const struct osl_column_description *cd =
339                                 get_column_description(t->desc, j);
340                         if (cd->storage_type != OSL_MAPPED_STORAGE)
341                                 continue;
342                         ret = check_range(t, i, j);
343                         if (ret < 0) {
344                                 if (ret != -E_OSL_INVALID_OBJECT &&
345                                                 ret != -E_FSCK_RANGE_VIOLATION)
346                                         goto err;
347                                 if (ret == -E_OSL_INVALID_OBJECT) {
348                                         CRIT_LOG("row %d, col %d maps to an "
349                                                 "invalid object\n", i, j);
350                                 }
351                                 ret = mark_row_invalid(t, i);
352                                 if (ret < 0)
353                                         goto err;
354                                 t->num_invalid_rows++;
355                                 break;
356                         }
357                 }
358
359         }
360         if (t->num_invalid_rows)
361                 NOTICE_LOG("ranges OK. %d invalid row(s) detected\n",
362                         t->num_invalid_rows);
363         else
364                 INFO_LOG("no invalid rows, no range violations, good\n");
365         return 1;
366 err:
367         return ret;
368 }
369
370 static int move_index_entry(struct osl_table *t, uint32_t dest, uint32_t src)
371 {
372         char *dest_ie, *src_ie;
373         int ret = get_row_index(t, dest, &dest_ie);
374
375         if (ret < 0)
376                 return ret;
377         ret = get_row_index(t, src, &src_ie);
378         if (ret < 0)
379                 return ret;
380         INFO_LOG("moving entry #%u to position %u\n", src, dest);
381         memcpy(dest_ie, src_ie, t->row_index_size);
382         return 1;
383 }
384
385 static int map_index(const struct osl_table_description *desc, struct osl_object *map)
386 {
387         char *filename = index_filename(desc);
388         int ret;
389
390         ret = mmap_full_file(filename, O_RDWR, &map->data, &map->size, NULL);
391         DEBUG_LOG("mapping index %s: ret: %d, size: %zu\n", filename, ret, map->size);
392         free(filename);
393         return ret;
394 }
395
396 static int prune_invalid_rows_from_index(struct osl_table *t)
397 {
398         uint32_t top = 0, bottom;
399         char *filename;
400         int ret;
401
402         if (!t->num_invalid_rows) {
403                 INFO_LOG("all rows are valid, good\n");
404                 return 1;
405         }
406         NOTICE_LOG("deleting %u invalid row(s) (%d bytes) from index\n",
407                 t->num_invalid_rows, t->row_index_size * t->num_invalid_rows);
408         bottom = t->num_rows - 1;
409         while (top < bottom) {
410                 if (!row_is_invalid(t, top)) {
411                         top++;
412                         continue;
413                 }
414                 while (bottom > top) {
415                         if (row_is_invalid(t, bottom)) {
416                                 bottom--;
417                                 continue;
418                         }
419                         /* move bottom index entry to top */
420                         move_index_entry(t, top, bottom);
421                         bottom--;
422                         top++;
423                         break;
424                 }
425         }
426         DEBUG_LOG("unmapping index\n");
427         osl_munmap(t->index_map.data, t->index_map.size);
428         filename = index_filename(t->desc);
429         ret = truncate_file(filename, t->row_index_size
430                 * t->num_invalid_rows);
431         free(filename);
432         if (ret < 0)
433                 return ret;
434         ret = map_index(t->desc, &t->index_map);
435         if (ret < 0)
436                 return ret;
437         t->num_rows = table_num_rows(t);
438         return 1;
439 }
440
441 static int check_for_invalid_objects(struct osl_table *t, uint32_t **lost_bytes)
442 {
443         int i, j, ret;
444         const struct osl_column_description *cd;
445         uint32_t *loss = fsck_malloc(sizeof(uint32_t) * t->desc->num_columns);
446
447         INFO_LOG("looking for mapped objects not contained in index\n");
448         /* first count used bytes */
449         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
450                 loss[i] = t->columns[i].data_map.size;
451                 for (j = 0; j < t->num_rows; j++) {
452                         struct osl_object obj;
453                         ret = get_mapped_object(t, i, j, &obj);
454                         if (ret >= 0) {
455                                 loss[i] -= obj.size + 1; /* add one for header byte */
456                                 continue;
457                         }
458                         if (ret != -E_OSL_INVALID_OBJECT)
459                                 goto err;
460                         CRIT_LOG("row %d, col %d points to an invalid "
461                                 "mapped object, bad\n", j, i);
462                 }
463         }
464         ret = 0;
465         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
466                 if (loss[i]) {
467                         NOTICE_LOG("column %u contains %u lost bytes\n",
468                                 i, loss[i]);
469                         ret = 1;
470                 }
471         }
472         if (!ret)
473                 INFO_LOG("all mapped objects are valid, good\n");
474         *lost_bytes = loss;
475         return ret;
476 err:
477         free(loss);
478         return ret;
479 }
480
481 /* prune_invalid_rows() must be run on the table before calling this */
482 static int prune_mapped_column(struct osl_table *t, uint32_t col_num, int fd)
483 {
484         int i, ret;
485         uint32_t written = 0;
486         struct osl_column *col = t->columns + col_num;
487
488         INFO_LOG("pruning col %u\n", col_num);
489         for (i = 0; i < t->num_rows; i++) {
490                 struct osl_object obj;
491                 char *index_entry;
492
493                 DEBUG_LOG("checking row %u/%u\n", i, t->num_rows);
494                 ret = get_mapped_object(t, col_num, i, &obj);
495                 if (ret < 0)
496                         return ret;
497                 ret = _write_all(fd, (char *)(obj.data) - 1, obj.size + 1);
498                 if (ret < 0)
499                         return ret;
500                 written += obj.size + 1;
501                 ret = get_row_index(t, i, &index_entry);
502                 if (ret < 0)
503                         return ret;
504                 update_cell_index(index_entry, col, written, obj.size);
505         }
506         return 1;
507 }
508
509 static int prune_objects(struct osl_table *t, uint32_t *lost_bytes)
510 {
511         int i, ret;
512         const struct osl_column_description *cd;
513         char **col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
514         char **new_col_filenames = fsck_calloc(t->desc->num_columns * sizeof(char *));
515         char *idx_filename = index_filename(t->desc);
516         char *old_idx_filename = make_message("%s.bak", idx_filename);
517         int fd;
518
519         NOTICE_LOG("removing unreferenced objects from data files\n");
520         /* first make a copy of the index */
521         ret = osl_open(old_idx_filename, O_WRONLY | O_CREAT | O_EXCL, 0644);
522         if (ret < 0)
523                 goto out_free;
524         fd = ret;
525         ret = _write_all(fd, t->index_map.data, t->index_map.size);
526         close(fd);
527         if (ret < 0)
528                 goto out_free;
529         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
530                 if (!lost_bytes[i])
531                         continue;
532                 col_filenames[i] = column_filename(t, i);
533                 new_col_filenames[i] = make_message("%s.fsck", col_filenames[i]);
534                 ret = osl_open(new_col_filenames[i], O_WRONLY | O_CREAT | O_EXCL, 0644);
535                 if (ret < 0)
536                         goto out_unlink_data;
537                 fd = ret;
538                 ret = prune_mapped_column(t, i, fd);
539                 close(fd);
540                 if (ret < 0)
541                         goto out_unlink_data;
542         }
543         ret = unmap_table(t, OSL_MARK_CLEAN);
544         if (ret < 0)
545                 goto out_unlink_data;
546         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
547                 if (!lost_bytes[i])
548                         continue;
549                 ret = osl_rename(new_col_filenames[i], col_filenames[i]);
550                 if (ret < 0) { /* we're kinda screwed here */
551                         CRIT_LOG("rename of col %i failed: %s\n", i,
552                                 osl_strerror(errno));
553                         goto out_free;
554                 }
555         }
556         unlink(old_idx_filename);
557         ret = map_table(t, 0);
558         goto out_free;
559 out_unlink_data:
560         FOR_EACH_MAPPED_COLUMN(i, t, cd)
561                 unlink(new_col_filenames[i]);
562 out_free:
563         free(old_idx_filename);
564         free(idx_filename);
565         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
566                 free(col_filenames[i]);
567                 free(new_col_filenames[i]);
568         }
569         free(col_filenames);
570         free(new_col_filenames);
571         return ret;
572 }
573
574 static struct osl_column_description hash_tree_table_cols[] = {
575         {
576                 .storage_type = OSL_NO_STORAGE,
577                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
578                 .name = "hash",
579                 .compare_function = uint32_compare,
580                 .data_size = HASH_SIZE
581         },
582 };
583
584 static const struct osl_table_description hash_tree_table_desc = {
585         .dir = "/", /* irrelevant */
586         .name = "hash_tree",
587         .num_columns = 1,
588         .flags = 0,
589         .column_descriptions = hash_tree_table_cols
590 };
591
592 /**
593  * The hash_tree table contains all hashes of the disk storage name column.
594  * of each row. It is used for checking if a disk storage file has a reference
595  * in the table.
596  */
597 static struct osl_table *hash_tree_table;
598 static HASH_TYPE *hashes;
599
600 static int check_disk_storage_column(struct osl_table *t, int row_num,
601                 int col_num, char *ds_name, unsigned *num_missing_objects)
602 {
603         int ret;
604         struct stat statbuf;
605         char *path = disk_storage_path(t, col_num, ds_name);
606         unsigned dsnc = t->disk_storage_name_column;
607         struct osl_object obj;
608
609         DEBUG_LOG("checking if %s is a regular file\n", path);
610         ret = stat(path, &statbuf);
611         if (ret < 0 && errno == ENOENT) {
612                 struct osl_row *row;
613                 (*num_missing_objects)++;
614                 ERROR_LOG("row %d: object %s is missing\n", row_num, path);
615                 NOTICE_LOG("trying to delete row %d\n", row_num);
616                 ret = osl_get_row(t, dsnc, &obj, &row);
617                 if (ret < 0) {
618                         CRIT_LOG("unable to get row %d\n", row_num);
619                         mark_row_invalid(t, row_num);
620                         CRIT_LOG("Please re-run fsck\n");
621                         goto out;
622                 }
623                 ret = osl_del_row(t, row);
624                 if (ret < 0)
625                         goto out;
626         }
627 out:
628         free(path);
629         if (ret < 0)
630                 return ret;
631         ret = -E_FSCK_NOT_A_REGULAR_FILE;
632         if (!(S_IFREG & statbuf.st_mode))
633                 return ret;
634         return 1;
635 }
636
637 static int check_disk_storage_presence(struct osl_table *t)
638 {
639         int ret, i, j;
640         struct osl_object obj, hash_obj = {.size = HASH_SIZE};
641         char *ds_name;
642         const struct osl_column_description *cd;
643         unsigned dsnc = t->disk_storage_name_column, missing_objects = 0;
644
645         if (!t->num_rows)
646                 return 1;
647         hashes = fsck_malloc(t->num_rows * HASH_SIZE);
648         INFO_LOG("looking for missing disk storage objects\n");
649         for (i = 0; i < t->num_rows; i++) {
650                 if (row_is_invalid(t, i))
651                         continue;
652                 ret = get_mapped_object(t, dsnc, i, &obj);
653                 if (ret < 0)
654                         return ret;
655                 hash_object(&obj, hashes + i * HASH_SIZE);
656                 hash_obj.data = hashes + i * HASH_SIZE;
657                 osl_add_row(hash_tree_table, &hash_obj);
658                 ds_name = disk_storage_name_of_hash(t, hashes + i * HASH_SIZE);
659                 FOR_EACH_DISK_STORAGE_COLUMN(j, t, cd) {
660                         ret = check_disk_storage_column(t, i, j, ds_name,
661                                 &missing_objects);
662                         if (ret < 0)
663                                 goto err;
664                 }
665                 free(ds_name);
666         }
667         if (!missing_objects)
668                 INFO_LOG("all referenced disk storage objects exist, good\n");
669         else
670                 NOTICE_LOG("%d missing object(s)\n", missing_objects);
671         return missing_objects;
672 err:
673         free(ds_name);
674         return ret;
675 }
676
677 static int dummy_compare(const struct osl_object *obj1, const struct osl_object *obj2)
678 {
679         if (obj1 < obj2)
680                 return -1;
681         if (obj1 > obj2)
682                 return 1;
683         return 0;
684 }
685
686 static unsigned files_pruned;
687
688 int prune_disk_storage_file(const char *path, void *private_data)
689 {
690         HASH_TYPE hash[HASH_SIZE];
691         unsigned flags = *(unsigned *)private_data;
692         struct osl_object obj = {.data = hash, .size = HASH_SIZE};
693         struct osl_row *row;
694         int ret = -1;
695         size_t len = strlen(path);
696
697
698         DEBUG_LOG("path: %s\n", path);
699         if (flags & OSL_LARGE_TABLE) {
700                 if (len < HASH_SIZE * 2 + 2)
701                         goto invalid;
702 //              NOTICE_LOG("p: %s\n", path + len - 2 * HASH_SIZE - 1);
703                 ret = asc_to_hash(path + len - 2 * HASH_SIZE - 1, 1, hash);
704                 if (ret < 0)
705                         goto invalid;
706                 ret = asc_to_hash(path + len - 2 * HASH_SIZE + 2, HASH_SIZE - 1,
707                         hash + 1);
708                 if (ret < 0)
709                         goto invalid;
710 //              INFO_LOG("high: %x, low: %x, hash: %x\n", high, low, hash);
711         } else {
712                 if (len < 2 * HASH_SIZE + 1)
713                         goto invalid;
714                 ret = asc_to_hash(path + len - 2 * HASH_SIZE, 2 * HASH_SIZE, hash);
715                 if (ret < 0)
716                         goto invalid;
717 //              INFO_LOG("hash: %x\n", hash);
718         }
719 #if 0
720 {
721         char asc[2 * HASH_SIZE + 1];
722         hash_to_asc(hash, asc);
723         NOTICE_LOG("before: %s\nafter: %s\n", path, asc);
724 }
725 #endif
726         ret = osl_get_row(hash_tree_table, 0, &obj, &row);
727         if (ret >= 0)
728                 return 1;
729         NOTICE_LOG("unreferenced file in hash dir: %s\n", path);
730         goto remove;
731 invalid:
732         ERROR_LOG("could not read hash value of %s\n", path);
733 remove:
734         NOTICE_LOG("removing %s\n", path);
735         unlink(path);
736         files_pruned++;
737         return 1;
738 }
739
740 static int prune_disk_storage_files(struct osl_table *t)
741 {
742         int i, ret = 1;
743         const struct osl_column_description *cd;
744
745         INFO_LOG("looking for unreferenced disk storage files\n");
746         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
747                 char *dirname = column_filename(t, i);
748                 ret = for_each_file_in_dir(dirname, prune_disk_storage_file,
749                         (unsigned *)&t->desc->flags);
750                 free(dirname);
751         }
752         if (files_pruned)
753                 NOTICE_LOG("%u disk storage files deleted\n",
754                         files_pruned);
755         else
756                 INFO_LOG("all files are are referenced, good\n");
757         return ret;
758 }
759
760 static int check_disk_storage_columns(struct osl_table *t)
761 {
762         int ret, i;
763         const struct osl_column_description *cd;
764
765         if (!t->num_disk_storage_columns) {
766                 INFO_LOG("no disk storage columns in table '%s', "
767                         "skipping checks\n", t->desc->name);
768                 return 1;
769         }
770         FOR_EACH_COLUMN(i, t->desc, cd)
771                 t->desc->column_descriptions[i].compare_function = dummy_compare;
772         ret = init_rbtrees(t);
773         if (ret < 0)
774                 return ret;
775         INFO_LOG("creating rbtree for disk storage hash values\n");
776         ret = osl_open_table(&hash_tree_table_desc, &hash_tree_table);
777         if (ret < 0)
778                 goto out;
779         ret = check_disk_storage_presence(t);
780         if (ret < 0)
781                 goto out_close_hash_tree;
782         ret = prune_disk_storage_files(t);
783 out_close_hash_tree:
784         osl_close_table(hash_tree_table, 0);
785         free(hashes);
786         hashes = NULL;
787 out:
788         clear_rbtrees(t); /* TODO why are we doing that here? Seems odd */
789         return ret;
790 }
791
792 static void set_dummy_contents(struct osl_table_description *desc)
793 {
794         int i;
795         struct osl_column_description *cd;
796
797         for (i = 0; i < desc->num_columns; i++) {
798                 cd = get_column_description(desc, i);
799                 cd->compare_function = dummy_compare;
800         }
801 }
802
803 static int fsck_init(struct osl_table_description *desc, struct osl_table **t)
804 {
805         struct osl_object map;
806         int ret = map_index(desc, &map);
807
808         if (ret < 0)
809                 goto out;
810         ret = read_table_desc(&map, desc);
811         if (ret < 0) {
812                 osl_munmap(map.data, map.size);
813                 goto out;
814         }
815         set_dummy_contents(desc);
816         ret = init_table_structure(desc, t);
817         if (ret < 0) {
818                 osl_munmap(map.data, map.size);
819                 goto out;
820         }
821         DEBUG_LOG("unmapping index\n");
822         osl_munmap(map.data, map.size);
823         if (conf.force_given)
824                 ret = map_table(*t, (MAP_TBL_FL_IGNORE_DIRTY));
825         else
826                 ret = map_table(*t, 0);
827         if (ret >= 0)
828                 (*t)->num_rows = table_num_rows(*t);
829 out:
830         return ret;
831 }
832
833 static void fsck_cleanup(struct osl_table *t)
834 {
835         int i;
836
837         if (!t)
838                 return;
839         if (t->desc->column_descriptions) {
840                 struct osl_column_description *cd;
841                 for (i = 0; i < t->desc->num_columns; i++) {
842                         cd = get_column_description(t->desc, i);
843                         free((char*)cd->name);
844                 }
845                 free(t->desc->column_descriptions);
846         }
847         free(t->columns);
848         free(t);
849
850 }
851
852 #define ST_CASE(st) case st: return #st
853
854 const char *get_asc_storage_type(enum osl_storage_type st)
855 {
856         switch (st) {
857                 ST_CASE(OSL_MAPPED_STORAGE);
858                 ST_CASE(OSL_DISK_STORAGE);
859                 ST_CASE(OSL_NO_STORAGE);
860         }
861         return NULL;
862 }
863
864 #define APPEND_ASC_SF(sf, flag, str) do { if (sf & flag) { \
865         if (str) str = make_message("%s%s", str, " | " # flag); \
866         else str = fsck_strdup(#flag); }} while (0)
867
868
869 char *get_asc_storage_flags(enum osl_storage_type sf)
870 {
871         char *asc_sf = NULL;
872
873         APPEND_ASC_SF(sf, OSL_RBTREE, asc_sf);
874         APPEND_ASC_SF(sf, OSL_FIXED_SIZE, asc_sf);
875         APPEND_ASC_SF(sf, OSL_UNIQUE, asc_sf);
876         return asc_sf;
877 }
878
879 static int dump_table_desc(struct osl_table *t, int fd)
880 {
881         const struct osl_table_description *desc = t->desc;
882         int ret, i;
883         struct osl_column_description *cd;
884         char *msg = make_message("static struct osl_column_description cols[] = {\n");
885         ret = _write_all(fd, msg, strlen(msg));
886         if (ret < 0)
887                 return ret;
888         free(msg);
889         FOR_EACH_COLUMN(i, desc, cd) {
890                 const char *asc_st;
891                 msg = make_message("\t[%d] = {\n", i);
892                 ret = _write_all(fd, msg, strlen(msg));
893                 if (ret < 0)
894                         return ret;
895                 free(msg);
896                 asc_st = get_asc_storage_type(cd->storage_type);
897                 msg = make_message("\t\t.storage_type = %s,\n", asc_st);
898                 ret = _write_all(fd, msg, strlen(msg));
899                 if (ret < 0)
900                         return ret;
901                 free(msg);
902                 if (cd->storage_flags) {
903                         char *asc_sf = get_asc_storage_flags(cd->storage_flags);
904                         msg = make_message("\t\t,storage_flags = %s,\n", asc_sf);
905                         free(asc_sf);
906                         ret = _write_all(fd, msg, strlen(msg));
907                         if (ret < 0)
908                                 return ret;
909                         free(msg);
910                 }
911                 if (cd->storage_flags & OSL_FIXED_SIZE) {
912                         msg = make_message("\t\t.data_size = %u,\n", cd->data_size);
913                         ret = _write_all(fd, msg, strlen(msg));
914                         if (ret < 0)
915                                 return ret;
916                         free(msg);
917                 }
918                 msg = make_message("\t\t.name = \"%s\",\n", cd->name);
919                 ret = _write_all(fd, msg, strlen(msg));
920                 if (ret < 0)
921                         return ret;
922                 free(msg);
923                 if (cd->storage_flags & OSL_RBTREE) {
924                         msg = make_message("\t\t.compare_function = compare_func,\n");
925                         ret = _write_all(fd, msg, strlen(msg));
926                         if (ret < 0)
927                                 return ret;
928                         free(msg);
929                 }
930                 msg = make_message("\t},\n");
931                 ret = _write_all(fd, msg, strlen(msg));
932                 if (ret < 0)
933                         return ret;
934                 free(msg);
935         }
936         msg = make_message("};\n");
937         ret = _write_all(fd, msg, strlen(msg));
938         if (ret < 0)
939                 return ret;
940         free(msg);
941         return 1;
942 }
943
944 static int dump_row(struct osl_table *t, unsigned row_num, const char *row_dir)
945 {
946         int ret, i;
947         const struct osl_column_description *cd;
948         unsigned dsnc;
949         struct osl_object obj;
950         char *ds_name;
951         HASH_TYPE hash[HASH_SIZE];
952         char *filename;
953
954         FOR_EACH_MAPPED_COLUMN(i, t, cd) {
955                 ret = get_mapped_object(t, i, row_num, &obj);
956                 if (ret < 0)
957                         return ret;
958                 filename = make_message("%s/col_%03u", row_dir, i);
959                 ret = write_file(filename, obj.data, obj.size);
960                 free(filename);
961                 if (ret < 0)
962                         return ret;
963         }
964         if (!t->num_disk_storage_columns)
965                 return 1;
966         dsnc = t->disk_storage_name_column;
967         ret = get_mapped_object(t, dsnc, row_num, &obj);
968         if (ret < 0)
969                 return ret;
970         hash_object(&obj, hash);
971         ds_name = disk_storage_name_of_hash(t, hash);
972         FOR_EACH_DISK_STORAGE_COLUMN(i, t, cd) {
973                 filename = disk_storage_path(t, i, ds_name);
974                 ret = mmap_full_file(filename, O_RDONLY, &obj.data, &obj.size, NULL);
975                 free(filename);
976                 if (ret < 0)
977                         goto out;
978                 filename = make_message("%s/col_%03u", row_dir, i);
979                 ret = write_file(filename, obj.data, obj.size);
980                 free(filename);
981                 if (ret < 0)
982                         goto out;
983         }
984         ret = 1;
985 out:
986         free(ds_name);
987         return ret;
988 }
989
990 static int dump_rows(char *dump_dir, struct osl_table *t)
991 {
992         unsigned i;
993         char *current_dir = NULL;
994         int ret = 0;
995
996         for (i = 0; i < t->num_rows; i++) {
997                 char *row_dir;
998                 if (row_is_invalid(t, i))
999                         continue;
1000                 if (!(i % 1000)) {
1001                         free(current_dir);
1002                         current_dir = make_message("%s/rows_%u-%u", dump_dir, i, i + 999);
1003                         NOTICE_LOG("dumping rows %u - %u\n", i, i + 999);
1004                         ret = osl_mkdir(current_dir, 0777);
1005                         if (ret < 0 && !is_errno(-ret, EEXIST))
1006                                 goto out;
1007                 }
1008                 row_dir = make_message("%s/row_%03u", current_dir, i);
1009                 ret = osl_mkdir(row_dir, 0777);
1010                 if (ret < 0 && !is_errno(-ret, EEXIST)) {
1011                         free(row_dir);
1012                         goto out;
1013                 }
1014                 ret = dump_row(t, i, row_dir);
1015                 free(row_dir);
1016                 if (ret < 0)
1017                         goto out;
1018         }
1019 out:
1020         free(current_dir);
1021         return ret;
1022 }
1023
1024 static int dump_table(char *dump_dir, struct osl_table_description *desc)
1025 {
1026         struct osl_table *t = NULL;
1027         int fd, ret = fsck_init(desc, &t);
1028         char *desc_file;
1029         char *table_dump_dir = NULL;
1030
1031         if (ret < 0)
1032                 goto out;
1033         ret = osl_mkdir(dump_dir, 0777);
1034         if (ret < 0 && !is_errno(-ret, EEXIST))
1035                 goto out;
1036         table_dump_dir = make_message("%s/%s", dump_dir, desc->name);
1037         ret = osl_mkdir(table_dump_dir, 0777);
1038         if (ret < 0 && !is_errno(-ret, EEXIST))
1039                 goto out;
1040         desc_file = make_message("%s/table_description.c", table_dump_dir);
1041         ret = osl_open(desc_file, O_WRONLY | O_CREAT | O_EXCL, 0644);
1042         free(desc_file);
1043         if (ret < 0)
1044                 goto out;
1045         fd = ret;
1046         ret = dump_table_desc(t, fd);
1047         close(fd);
1048         if (ret < 0)
1049                 goto out;
1050         ret = dump_rows(table_dump_dir, t);
1051 out:
1052         free(table_dump_dir);
1053         fsck_cleanup(t);
1054         return ret;
1055 }
1056
1057 static int fsck(struct osl_table_description *desc)
1058 {
1059         int ret;
1060         struct osl_table *t = NULL;
1061         uint32_t *lost_bytes = NULL;
1062
1063         ret = fsck_init(desc, &t);
1064         if (ret < 0)
1065                 goto out;
1066         ret = check_index_ranges(t);
1067         if (ret < 0)
1068                 goto out_unmap;
1069         ret = check_disk_storage_columns(t);
1070         if (ret < 0)
1071                 goto out_unmap;
1072         ret = prune_invalid_rows_from_index(t);
1073         if (ret < 0)
1074                 goto out_unmap;
1075         ret = check_for_invalid_objects(t, &lost_bytes);
1076         if (ret < 0)
1077                 goto out_unmap;
1078         if (ret > 0) { /* at least one mapped data file needs pruning */
1079                 ret = prune_objects(t, lost_bytes);
1080                 if (ret < 0)
1081                         goto out_unmap;
1082         }
1083         free(lost_bytes);
1084 out_unmap:
1085         unmap_table(t, OSL_MARK_CLEAN);
1086 out:
1087         fsck_cleanup(t);
1088         return ret;
1089 }
1090
1091 static int check_table(char *db_dir, char *table_name)
1092 {
1093         struct osl_table_description desc = {
1094                 .column_descriptions = NULL,
1095                 .dir = db_dir,
1096                 .name = table_name
1097         };
1098         int ret;
1099
1100         INFO_LOG("checking table %s\n", table_name);
1101         if (!conf.no_fsck_given) {
1102                 ret = fsck(&desc);
1103                 if (ret < 0)
1104                         goto out;
1105         }
1106         ret = 1;
1107         if (!conf.dump_dir_given || !*conf.dump_dir_arg)
1108                 goto out;
1109         ret = dump_table(conf.dump_dir_arg, &desc);
1110 out:
1111         if (ret < 0)
1112                 ERROR_LOG("failed to check table %s\n", table_name);
1113         else
1114                 NOTICE_LOG("successfully checked table %s\n", table_name);
1115         return ret;
1116 }
1117
1118 static int check_all_tables(char *db_dir)
1119 {
1120         DIR *dir;
1121         struct dirent *entry;
1122         int cwd_fd, ret2, ret = para_opendir(db_dir, &dir, &cwd_fd);
1123
1124         if (ret < 0)
1125                 return ret;
1126         while ((entry = readdir(dir))) {
1127                 mode_t m;
1128                 struct stat s;
1129                 if (!strcmp(entry->d_name, "."))
1130                         continue;
1131                 if (!strcmp(entry->d_name, ".."))
1132                         continue;
1133                 if (lstat(entry->d_name, &s) == -1)
1134                         continue;
1135                 m = s.st_mode;
1136                 if (!S_ISDIR(m))
1137                         continue;
1138                 ret = check_table(db_dir, entry->d_name);
1139                 if (ret < 0)
1140                         break;
1141         }
1142         closedir(dir);
1143         ret2 = __fchdir(cwd_fd);
1144         if (ret2 < 0 && ret >= 0)
1145                 ret = ret2;
1146         close(cwd_fd);
1147         return ret;
1148 }
1149
1150 int main(int argc, char **argv)
1151 {
1152         int i, ret;
1153         struct fsck_cmdline_parser_params params = {
1154                 .override = 0,
1155                 .initialize = 1,
1156                 .check_required = 1,
1157                 .check_ambiguity = 1,
1158                 .print_errors = 1
1159         };
1160         ret = fsck_cmdline_parser_ext(argc, argv, &conf, &params);
1161         if (ret < 0) {
1162                 loglevel = EMERG;
1163                 ret = -E_FSCK_SYNTAX;
1164                 goto out;
1165         }
1166         loglevel = conf.loglevel_arg;
1167         HANDLE_VERSION_FLAG("fsck", conf);
1168         INFO_LOG("database dir: %s\n", conf.database_dir_arg);
1169         if (!conf.inputs_num) {
1170                 ret = check_all_tables(conf.database_dir_arg);
1171                 goto out;
1172         }
1173         for (i = 0; i < conf.inputs_num; i++) {
1174                 ret = check_table(conf.database_dir_arg, conf.inputs[i]);
1175                 if (ret < 0)
1176                         break;
1177         }
1178 out:
1179         if (ret < 0) {
1180                 ERROR_LOG("%s\n", fsck_strerror(-ret));
1181                 if (conf.loglevel_arg > 1)
1182                         EMERG_LOG("re-run with \"--loglevel %d\" to increase verbosity\n",
1183                                 conf.loglevel_arg - 1);
1184         } else
1185                 NOTICE_LOG("success\n");
1186         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1187 }