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