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