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