The eighth batch
[git.git] / fsck.c
blob3756f52459e7710e511adf1fe029526741e34137
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "date.h"
5 #include "dir.h"
6 #include "hex.h"
7 #include "object-store-ll.h"
8 #include "path.h"
9 #include "repository.h"
10 #include "object.h"
11 #include "attr.h"
12 #include "blob.h"
13 #include "tree.h"
14 #include "tree-walk.h"
15 #include "commit.h"
16 #include "tag.h"
17 #include "fsck.h"
18 #include "refs.h"
19 #include "url.h"
20 #include "utf8.h"
21 #include "oidset.h"
22 #include "packfile.h"
23 #include "submodule-config.h"
24 #include "config.h"
25 #include "help.h"
27 static ssize_t max_tree_entry_len = 4096;
29 #define STR(x) #x
30 #define MSG_ID(id, msg_type) { STR(id), NULL, NULL, FSCK_##msg_type },
31 static struct {
32 const char *id_string;
33 const char *downcased;
34 const char *camelcased;
35 enum fsck_msg_type msg_type;
36 } msg_id_info[FSCK_MSG_MAX + 1] = {
37 FOREACH_FSCK_MSG_ID(MSG_ID)
38 { NULL, NULL, NULL, -1 }
40 #undef MSG_ID
41 #undef STR
43 static void prepare_msg_ids(void)
45 int i;
47 if (msg_id_info[0].downcased)
48 return;
50 /* convert id_string to lower case, without underscores. */
51 for (i = 0; i < FSCK_MSG_MAX; i++) {
52 const char *p = msg_id_info[i].id_string;
53 int len = strlen(p);
54 char *q = xmalloc(len);
56 msg_id_info[i].downcased = q;
57 while (*p)
58 if (*p == '_')
59 p++;
60 else
61 *(q)++ = tolower(*(p)++);
62 *q = '\0';
64 p = msg_id_info[i].id_string;
65 q = xmalloc(len);
66 msg_id_info[i].camelcased = q;
67 while (*p) {
68 if (*p == '_') {
69 p++;
70 if (*p)
71 *q++ = *p++;
72 } else {
73 *q++ = tolower(*p++);
76 *q = '\0';
80 static int parse_msg_id(const char *text)
82 int i;
84 prepare_msg_ids();
86 for (i = 0; i < FSCK_MSG_MAX; i++)
87 if (!strcmp(text, msg_id_info[i].downcased))
88 return i;
90 return -1;
93 void list_config_fsck_msg_ids(struct string_list *list, const char *prefix)
95 int i;
97 prepare_msg_ids();
99 for (i = 0; i < FSCK_MSG_MAX; i++)
100 list_config_item(list, prefix, msg_id_info[i].camelcased);
103 static enum fsck_msg_type fsck_msg_type(enum fsck_msg_id msg_id,
104 struct fsck_options *options)
106 assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX);
108 if (!options->msg_type) {
109 enum fsck_msg_type msg_type = msg_id_info[msg_id].msg_type;
111 if (options->strict && msg_type == FSCK_WARN)
112 msg_type = FSCK_ERROR;
113 return msg_type;
116 return options->msg_type[msg_id];
119 static enum fsck_msg_type parse_msg_type(const char *str)
121 if (!strcmp(str, "error"))
122 return FSCK_ERROR;
123 else if (!strcmp(str, "warn"))
124 return FSCK_WARN;
125 else if (!strcmp(str, "ignore"))
126 return FSCK_IGNORE;
127 else
128 die("Unknown fsck message type: '%s'", str);
131 int is_valid_msg_type(const char *msg_id, const char *msg_type)
133 if (parse_msg_id(msg_id) < 0)
134 return 0;
135 parse_msg_type(msg_type);
136 return 1;
139 void fsck_set_msg_type_from_ids(struct fsck_options *options,
140 enum fsck_msg_id msg_id,
141 enum fsck_msg_type msg_type)
143 if (!options->msg_type) {
144 int i;
145 enum fsck_msg_type *severity;
146 ALLOC_ARRAY(severity, FSCK_MSG_MAX);
147 for (i = 0; i < FSCK_MSG_MAX; i++)
148 severity[i] = fsck_msg_type(i, options);
149 options->msg_type = severity;
152 options->msg_type[msg_id] = msg_type;
155 void fsck_set_msg_type(struct fsck_options *options,
156 const char *msg_id_str, const char *msg_type_str)
158 int msg_id = parse_msg_id(msg_id_str);
159 char *to_free = NULL;
160 enum fsck_msg_type msg_type;
162 if (msg_id < 0)
163 die("Unhandled message id: %s", msg_id_str);
165 if (msg_id == FSCK_MSG_LARGE_PATHNAME) {
166 const char *colon = strchr(msg_type_str, ':');
167 if (colon) {
168 msg_type_str = to_free =
169 xmemdupz(msg_type_str, colon - msg_type_str);
170 colon++;
171 if (!git_parse_ssize_t(colon, &max_tree_entry_len))
172 die("unable to parse max tree entry len: %s", colon);
175 msg_type = parse_msg_type(msg_type_str);
177 if (msg_type != FSCK_ERROR && msg_id_info[msg_id].msg_type == FSCK_FATAL)
178 die("Cannot demote %s to %s", msg_id_str, msg_type_str);
180 fsck_set_msg_type_from_ids(options, msg_id, msg_type);
181 free(to_free);
184 void fsck_set_msg_types(struct fsck_options *options, const char *values)
186 char *buf = xstrdup(values), *to_free = buf;
187 int done = 0;
189 while (!done) {
190 int len = strcspn(buf, " ,|"), equal;
192 done = !buf[len];
193 if (!len) {
194 buf++;
195 continue;
197 buf[len] = '\0';
199 for (equal = 0;
200 equal < len && buf[equal] != '=' && buf[equal] != ':';
201 equal++)
202 buf[equal] = tolower(buf[equal]);
203 buf[equal] = '\0';
205 if (!strcmp(buf, "skiplist")) {
206 if (equal == len)
207 die("skiplist requires a path");
208 oidset_parse_file(&options->skip_oids, buf + equal + 1,
209 the_repository->hash_algo);
210 buf += len + 1;
211 continue;
214 if (equal == len)
215 die("Missing '=': '%s'", buf);
217 fsck_set_msg_type(options, buf, buf + equal + 1);
218 buf += len + 1;
220 free(to_free);
223 static int object_on_skiplist(struct fsck_options *opts,
224 const struct object_id *oid)
226 return opts && oid && oidset_contains(&opts->skip_oids, oid);
230 * Provide the common functionality for either fscking refs or objects.
231 * It will get the current msg error type and call the error_func callback
232 * which is registered in the "fsck_options" struct.
234 static int fsck_vreport(struct fsck_options *options,
235 void *fsck_report,
236 enum fsck_msg_id msg_id, const char *fmt, va_list ap)
238 struct strbuf sb = STRBUF_INIT;
239 enum fsck_msg_type msg_type = fsck_msg_type(msg_id, options);
240 int result;
242 if (msg_type == FSCK_IGNORE)
243 return 0;
245 if (msg_type == FSCK_FATAL)
246 msg_type = FSCK_ERROR;
247 else if (msg_type == FSCK_INFO)
248 msg_type = FSCK_WARN;
250 prepare_msg_ids();
251 strbuf_addf(&sb, "%s: ", msg_id_info[msg_id].camelcased);
253 strbuf_vaddf(&sb, fmt, ap);
254 result = options->error_func(options, fsck_report,
255 msg_type, msg_id, sb.buf);
256 strbuf_release(&sb);
258 return result;
261 __attribute__((format (printf, 5, 6)))
262 static int report(struct fsck_options *options,
263 const struct object_id *oid, enum object_type object_type,
264 enum fsck_msg_id msg_id, const char *fmt, ...)
266 va_list ap;
267 struct fsck_object_report report = {
268 .oid = oid,
269 .object_type = object_type
271 int result;
273 if (object_on_skiplist(options, oid))
274 return 0;
276 va_start(ap, fmt);
277 result = fsck_vreport(options, &report, msg_id, fmt, ap);
278 va_end(ap);
280 return result;
283 int fsck_report_ref(struct fsck_options *options,
284 struct fsck_ref_report *report,
285 enum fsck_msg_id msg_id,
286 const char *fmt, ...)
288 va_list ap;
289 int result;
290 va_start(ap, fmt);
291 result = fsck_vreport(options, report, msg_id, fmt, ap);
292 va_end(ap);
293 return result;
296 void fsck_enable_object_names(struct fsck_options *options)
298 if (!options->object_names)
299 options->object_names = kh_init_oid_map();
302 const char *fsck_get_object_name(struct fsck_options *options,
303 const struct object_id *oid)
305 khiter_t pos;
306 if (!options->object_names)
307 return NULL;
308 pos = kh_get_oid_map(options->object_names, *oid);
309 if (pos >= kh_end(options->object_names))
310 return NULL;
311 return kh_value(options->object_names, pos);
314 void fsck_put_object_name(struct fsck_options *options,
315 const struct object_id *oid,
316 const char *fmt, ...)
318 va_list ap;
319 struct strbuf buf = STRBUF_INIT;
320 khiter_t pos;
321 int hashret;
323 if (!options->object_names)
324 return;
326 pos = kh_put_oid_map(options->object_names, *oid, &hashret);
327 if (!hashret)
328 return;
329 va_start(ap, fmt);
330 strbuf_vaddf(&buf, fmt, ap);
331 kh_value(options->object_names, pos) = strbuf_detach(&buf, NULL);
332 va_end(ap);
335 const char *fsck_describe_object(struct fsck_options *options,
336 const struct object_id *oid)
338 static struct strbuf bufs[] = {
339 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
341 static int b = 0;
342 struct strbuf *buf;
343 const char *name = fsck_get_object_name(options, oid);
345 buf = bufs + b;
346 b = (b + 1) % ARRAY_SIZE(bufs);
347 strbuf_reset(buf);
348 strbuf_addstr(buf, oid_to_hex(oid));
349 if (name)
350 strbuf_addf(buf, " (%s)", name);
352 return buf->buf;
355 static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options)
357 struct tree_desc desc;
358 struct name_entry entry;
359 int res = 0;
360 const char *name;
362 if (parse_tree(tree))
363 return -1;
365 name = fsck_get_object_name(options, &tree->object.oid);
366 if (init_tree_desc_gently(&desc, &tree->object.oid,
367 tree->buffer, tree->size, 0))
368 return -1;
369 while (tree_entry_gently(&desc, &entry)) {
370 struct object *obj;
371 int result;
373 if (S_ISGITLINK(entry.mode))
374 continue;
376 if (S_ISDIR(entry.mode)) {
377 obj = (struct object *)lookup_tree(the_repository, &entry.oid);
378 if (name && obj)
379 fsck_put_object_name(options, &entry.oid, "%s%s/",
380 name, entry.path);
381 result = options->walk(obj, OBJ_TREE, data, options);
383 else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) {
384 obj = (struct object *)lookup_blob(the_repository, &entry.oid);
385 if (name && obj)
386 fsck_put_object_name(options, &entry.oid, "%s%s",
387 name, entry.path);
388 result = options->walk(obj, OBJ_BLOB, data, options);
390 else {
391 result = error("in tree %s: entry %s has bad mode %.6o",
392 fsck_describe_object(options, &tree->object.oid),
393 entry.path, entry.mode);
395 if (result < 0)
396 return result;
397 if (!res)
398 res = result;
400 return res;
403 static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options)
405 int counter = 0, generation = 0, name_prefix_len = 0;
406 struct commit_list *parents;
407 int res;
408 int result;
409 const char *name;
411 if (repo_parse_commit(the_repository, commit))
412 return -1;
414 name = fsck_get_object_name(options, &commit->object.oid);
415 if (name)
416 fsck_put_object_name(options, get_commit_tree_oid(commit),
417 "%s:", name);
419 result = options->walk((struct object *) repo_get_commit_tree(the_repository, commit),
420 OBJ_TREE, data, options);
421 if (result < 0)
422 return result;
423 res = result;
425 parents = commit->parents;
426 if (name && parents) {
427 int len = strlen(name), power;
429 if (len && name[len - 1] == '^') {
430 generation = 1;
431 name_prefix_len = len - 1;
433 else { /* parse ~<generation> suffix */
434 for (generation = 0, power = 1;
435 len && isdigit(name[len - 1]);
436 power *= 10)
437 generation += power * (name[--len] - '0');
438 if (power > 1 && len && name[len - 1] == '~')
439 name_prefix_len = len - 1;
440 else {
441 /* Maybe a non-first parent, e.g. HEAD^2 */
442 generation = 0;
443 name_prefix_len = len;
448 while (parents) {
449 if (name) {
450 struct object_id *oid = &parents->item->object.oid;
452 if (counter++)
453 fsck_put_object_name(options, oid, "%s^%d",
454 name, counter);
455 else if (generation > 0)
456 fsck_put_object_name(options, oid, "%.*s~%d",
457 name_prefix_len, name,
458 generation + 1);
459 else
460 fsck_put_object_name(options, oid, "%s^", name);
462 result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options);
463 if (result < 0)
464 return result;
465 if (!res)
466 res = result;
467 parents = parents->next;
469 return res;
472 static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options)
474 const char *name = fsck_get_object_name(options, &tag->object.oid);
476 if (parse_tag(tag))
477 return -1;
478 if (name)
479 fsck_put_object_name(options, &tag->tagged->oid, "%s", name);
480 return options->walk(tag->tagged, OBJ_ANY, data, options);
483 int fsck_walk(struct object *obj, void *data, struct fsck_options *options)
485 if (!obj)
486 return -1;
488 if (obj->type == OBJ_NONE)
489 parse_object(the_repository, &obj->oid);
491 switch (obj->type) {
492 case OBJ_BLOB:
493 return 0;
494 case OBJ_TREE:
495 return fsck_walk_tree((struct tree *)obj, data, options);
496 case OBJ_COMMIT:
497 return fsck_walk_commit((struct commit *)obj, data, options);
498 case OBJ_TAG:
499 return fsck_walk_tag((struct tag *)obj, data, options);
500 default:
501 error("Unknown object type for %s",
502 fsck_describe_object(options, &obj->oid));
503 return -1;
507 struct name_stack {
508 const char **names;
509 size_t nr, alloc;
512 static void name_stack_push(struct name_stack *stack, const char *name)
514 ALLOC_GROW(stack->names, stack->nr + 1, stack->alloc);
515 stack->names[stack->nr++] = name;
518 static const char *name_stack_pop(struct name_stack *stack)
520 return stack->nr ? stack->names[--stack->nr] : NULL;
523 static void name_stack_clear(struct name_stack *stack)
525 FREE_AND_NULL(stack->names);
526 stack->nr = stack->alloc = 0;
530 * The entries in a tree are ordered in the _path_ order,
531 * which means that a directory entry is ordered by adding
532 * a slash to the end of it.
534 * So a directory called "a" is ordered _after_ a file
535 * called "a.c", because "a/" sorts after "a.c".
537 #define TREE_UNORDERED (-1)
538 #define TREE_HAS_DUPS (-2)
540 static int is_less_than_slash(unsigned char c)
542 return '\0' < c && c < '/';
545 static int verify_ordered(unsigned mode1, const char *name1,
546 unsigned mode2, const char *name2,
547 struct name_stack *candidates)
549 int len1 = strlen(name1);
550 int len2 = strlen(name2);
551 int len = len1 < len2 ? len1 : len2;
552 unsigned char c1, c2;
553 int cmp;
555 cmp = memcmp(name1, name2, len);
556 if (cmp < 0)
557 return 0;
558 if (cmp > 0)
559 return TREE_UNORDERED;
562 * Ok, the first <len> characters are the same.
563 * Now we need to order the next one, but turn
564 * a '\0' into a '/' for a directory entry.
566 c1 = name1[len];
567 c2 = name2[len];
568 if (!c1 && !c2)
570 * git-write-tree used to write out a nonsense tree that has
571 * entries with the same name, one blob and one tree. Make
572 * sure we do not have duplicate entries.
574 return TREE_HAS_DUPS;
575 if (!c1 && S_ISDIR(mode1))
576 c1 = '/';
577 if (!c2 && S_ISDIR(mode2))
578 c2 = '/';
581 * There can be non-consecutive duplicates due to the implicitly
582 * added slash, e.g.:
584 * foo
585 * foo.bar
586 * foo.bar.baz
587 * foo.bar/
588 * foo/
590 * Record non-directory candidates (like "foo" and "foo.bar" in
591 * the example) on a stack and check directory candidates (like
592 * foo/" and "foo.bar/") against that stack.
594 if (!c1 && is_less_than_slash(c2)) {
595 name_stack_push(candidates, name1);
596 } else if (c2 == '/' && is_less_than_slash(c1)) {
597 for (;;) {
598 const char *p;
599 const char *f_name = name_stack_pop(candidates);
601 if (!f_name)
602 break;
603 if (!skip_prefix(name2, f_name, &p))
604 continue;
605 if (!*p)
606 return TREE_HAS_DUPS;
607 if (is_less_than_slash(*p)) {
608 name_stack_push(candidates, f_name);
609 break;
614 return c1 < c2 ? 0 : TREE_UNORDERED;
617 static int fsck_tree(const struct object_id *tree_oid,
618 const char *buffer, unsigned long size,
619 struct fsck_options *options)
621 int retval = 0;
622 int has_null_sha1 = 0;
623 int has_full_path = 0;
624 int has_empty_name = 0;
625 int has_dot = 0;
626 int has_dotdot = 0;
627 int has_dotgit = 0;
628 int has_zero_pad = 0;
629 int has_bad_modes = 0;
630 int has_dup_entries = 0;
631 int not_properly_sorted = 0;
632 int has_large_name = 0;
633 struct tree_desc desc;
634 unsigned o_mode;
635 const char *o_name;
636 struct name_stack df_dup_candidates = { NULL };
638 if (init_tree_desc_gently(&desc, tree_oid, buffer, size,
639 TREE_DESC_RAW_MODES)) {
640 retval += report(options, tree_oid, OBJ_TREE,
641 FSCK_MSG_BAD_TREE,
642 "cannot be parsed as a tree");
643 return retval;
646 o_mode = 0;
647 o_name = NULL;
649 while (desc.size) {
650 unsigned short mode;
651 const char *name, *backslash;
652 const struct object_id *entry_oid;
654 entry_oid = tree_entry_extract(&desc, &name, &mode);
656 has_null_sha1 |= is_null_oid(entry_oid);
657 has_full_path |= !!strchr(name, '/');
658 has_empty_name |= !*name;
659 has_dot |= !strcmp(name, ".");
660 has_dotdot |= !strcmp(name, "..");
661 has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
662 has_zero_pad |= *(char *)desc.buffer == '0';
663 has_large_name |= tree_entry_len(&desc.entry) > max_tree_entry_len;
665 if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
666 if (!S_ISLNK(mode))
667 oidset_insert(&options->gitmodules_found,
668 entry_oid);
669 else
670 retval += report(options,
671 tree_oid, OBJ_TREE,
672 FSCK_MSG_GITMODULES_SYMLINK,
673 ".gitmodules is a symbolic link");
676 if (is_hfs_dotgitattributes(name) || is_ntfs_dotgitattributes(name)) {
677 if (!S_ISLNK(mode))
678 oidset_insert(&options->gitattributes_found,
679 entry_oid);
680 else
681 retval += report(options, tree_oid, OBJ_TREE,
682 FSCK_MSG_GITATTRIBUTES_SYMLINK,
683 ".gitattributes is a symlink");
686 if (S_ISLNK(mode)) {
687 if (is_hfs_dotgitignore(name) ||
688 is_ntfs_dotgitignore(name))
689 retval += report(options, tree_oid, OBJ_TREE,
690 FSCK_MSG_GITIGNORE_SYMLINK,
691 ".gitignore is a symlink");
692 if (is_hfs_dotmailmap(name) ||
693 is_ntfs_dotmailmap(name))
694 retval += report(options, tree_oid, OBJ_TREE,
695 FSCK_MSG_MAILMAP_SYMLINK,
696 ".mailmap is a symlink");
699 if ((backslash = strchr(name, '\\'))) {
700 while (backslash) {
701 backslash++;
702 has_dotgit |= is_ntfs_dotgit(backslash);
703 if (is_ntfs_dotgitmodules(backslash)) {
704 if (!S_ISLNK(mode))
705 oidset_insert(&options->gitmodules_found,
706 entry_oid);
707 else
708 retval += report(options, tree_oid, OBJ_TREE,
709 FSCK_MSG_GITMODULES_SYMLINK,
710 ".gitmodules is a symbolic link");
712 backslash = strchr(backslash, '\\');
716 if (update_tree_entry_gently(&desc)) {
717 retval += report(options, tree_oid, OBJ_TREE,
718 FSCK_MSG_BAD_TREE,
719 "cannot be parsed as a tree");
720 break;
723 switch (mode) {
725 * Standard modes..
727 case S_IFREG | 0755:
728 case S_IFREG | 0644:
729 case S_IFLNK:
730 case S_IFDIR:
731 case S_IFGITLINK:
732 break;
734 * This is nonstandard, but we had a few of these
735 * early on when we honored the full set of mode
736 * bits..
738 case S_IFREG | 0664:
739 if (!options->strict)
740 break;
741 /* fallthrough */
742 default:
743 has_bad_modes = 1;
746 if (o_name) {
747 switch (verify_ordered(o_mode, o_name, mode, name,
748 &df_dup_candidates)) {
749 case TREE_UNORDERED:
750 not_properly_sorted = 1;
751 break;
752 case TREE_HAS_DUPS:
753 has_dup_entries = 1;
754 break;
755 default:
756 break;
760 o_mode = mode;
761 o_name = name;
764 name_stack_clear(&df_dup_candidates);
766 if (has_null_sha1)
767 retval += report(options, tree_oid, OBJ_TREE,
768 FSCK_MSG_NULL_SHA1,
769 "contains entries pointing to null sha1");
770 if (has_full_path)
771 retval += report(options, tree_oid, OBJ_TREE,
772 FSCK_MSG_FULL_PATHNAME,
773 "contains full pathnames");
774 if (has_empty_name)
775 retval += report(options, tree_oid, OBJ_TREE,
776 FSCK_MSG_EMPTY_NAME,
777 "contains empty pathname");
778 if (has_dot)
779 retval += report(options, tree_oid, OBJ_TREE,
780 FSCK_MSG_HAS_DOT,
781 "contains '.'");
782 if (has_dotdot)
783 retval += report(options, tree_oid, OBJ_TREE,
784 FSCK_MSG_HAS_DOTDOT,
785 "contains '..'");
786 if (has_dotgit)
787 retval += report(options, tree_oid, OBJ_TREE,
788 FSCK_MSG_HAS_DOTGIT,
789 "contains '.git'");
790 if (has_zero_pad)
791 retval += report(options, tree_oid, OBJ_TREE,
792 FSCK_MSG_ZERO_PADDED_FILEMODE,
793 "contains zero-padded file modes");
794 if (has_bad_modes)
795 retval += report(options, tree_oid, OBJ_TREE,
796 FSCK_MSG_BAD_FILEMODE,
797 "contains bad file modes");
798 if (has_dup_entries)
799 retval += report(options, tree_oid, OBJ_TREE,
800 FSCK_MSG_DUPLICATE_ENTRIES,
801 "contains duplicate file entries");
802 if (not_properly_sorted)
803 retval += report(options, tree_oid, OBJ_TREE,
804 FSCK_MSG_TREE_NOT_SORTED,
805 "not properly sorted");
806 if (has_large_name)
807 retval += report(options, tree_oid, OBJ_TREE,
808 FSCK_MSG_LARGE_PATHNAME,
809 "contains excessively large pathname");
810 return retval;
814 * Confirm that the headers of a commit or tag object end in a reasonable way,
815 * either with the usual "\n\n" separator, or at least with a trailing newline
816 * on the final header line.
818 * This property is important for the memory safety of our callers. It allows
819 * them to scan the buffer linewise without constantly checking the remaining
820 * size as long as:
822 * - they check that there are bytes left in the buffer at the start of any
823 * line (i.e., that the last newline they saw was not the final one we
824 * found here)
826 * - any intra-line scanning they do will stop at a newline, which will worst
827 * case hit the newline we found here as the end-of-header. This makes it
828 * OK for them to use helpers like parse_oid_hex(), or even skip_prefix().
830 static int verify_headers(const void *data, unsigned long size,
831 const struct object_id *oid, enum object_type type,
832 struct fsck_options *options)
834 const char *buffer = (const char *)data;
835 unsigned long i;
837 for (i = 0; i < size; i++) {
838 switch (buffer[i]) {
839 case '\0':
840 return report(options, oid, type,
841 FSCK_MSG_NUL_IN_HEADER,
842 "unterminated header: NUL at offset %ld", i);
843 case '\n':
844 if (i + 1 < size && buffer[i + 1] == '\n')
845 return 0;
850 * We did not find double-LF that separates the header
851 * and the body. Not having a body is not a crime but
852 * we do want to see the terminating LF for the last header
853 * line.
855 if (size && buffer[size - 1] == '\n')
856 return 0;
858 return report(options, oid, type,
859 FSCK_MSG_UNTERMINATED_HEADER, "unterminated header");
862 static int fsck_ident(const char **ident,
863 const struct object_id *oid, enum object_type type,
864 struct fsck_options *options)
866 const char *p = *ident;
867 char *end;
869 *ident = strchrnul(*ident, '\n');
870 if (**ident == '\n')
871 (*ident)++;
873 if (*p == '<')
874 return report(options, oid, type, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
875 p += strcspn(p, "<>\n");
876 if (*p == '>')
877 return report(options, oid, type, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name");
878 if (*p != '<')
879 return report(options, oid, type, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email");
880 if (p[-1] != ' ')
881 return report(options, oid, type, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
882 p++;
883 p += strcspn(p, "<>\n");
884 if (*p != '>')
885 return report(options, oid, type, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email");
886 p++;
887 if (*p != ' ')
888 return report(options, oid, type, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date");
889 p++;
891 * Our timestamp parser is based on the C strto*() functions, which
892 * will happily eat whitespace, including the newline that is supposed
893 * to prevent us walking past the end of the buffer. So do our own
894 * scan, skipping linear whitespace but not newlines, and then
895 * confirming we found a digit. We _could_ be even more strict here,
896 * as we really expect only a single space, but since we have
897 * traditionally allowed extra whitespace, we'll continue to do so.
899 while (*p == ' ' || *p == '\t')
900 p++;
901 if (!isdigit(*p))
902 return report(options, oid, type, FSCK_MSG_BAD_DATE,
903 "invalid author/committer line - bad date");
904 if (*p == '0' && p[1] != ' ')
905 return report(options, oid, type, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date");
906 if (date_overflows(parse_timestamp(p, &end, 10)))
907 return report(options, oid, type, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow");
908 if ((end == p || *end != ' '))
909 return report(options, oid, type, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date");
910 p = end + 1;
911 if ((*p != '+' && *p != '-') ||
912 !isdigit(p[1]) ||
913 !isdigit(p[2]) ||
914 !isdigit(p[3]) ||
915 !isdigit(p[4]) ||
916 (p[5] != '\n'))
917 return report(options, oid, type, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone");
918 p += 6;
919 return 0;
922 static int fsck_commit(const struct object_id *oid,
923 const char *buffer, unsigned long size,
924 struct fsck_options *options)
926 struct object_id tree_oid, parent_oid;
927 unsigned author_count;
928 int err;
929 const char *buffer_begin = buffer;
930 const char *buffer_end = buffer + size;
931 const char *p;
934 * We _must_ stop parsing immediately if this reports failure, as the
935 * memory safety of the rest of the function depends on it. See the
936 * comment above the definition of verify_headers() for more details.
938 if (verify_headers(buffer, size, oid, OBJ_COMMIT, options))
939 return -1;
941 if (buffer >= buffer_end || !skip_prefix(buffer, "tree ", &buffer))
942 return report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
943 if (parse_oid_hex(buffer, &tree_oid, &p) || *p != '\n') {
944 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
945 if (err)
946 return err;
948 buffer = p + 1;
949 while (buffer < buffer_end && skip_prefix(buffer, "parent ", &buffer)) {
950 if (parse_oid_hex(buffer, &parent_oid, &p) || *p != '\n') {
951 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
952 if (err)
953 return err;
955 buffer = p + 1;
957 author_count = 0;
958 while (buffer < buffer_end && skip_prefix(buffer, "author ", &buffer)) {
959 author_count++;
960 err = fsck_ident(&buffer, oid, OBJ_COMMIT, options);
961 if (err)
962 return err;
964 if (author_count < 1)
965 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line");
966 else if (author_count > 1)
967 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines");
968 if (err)
969 return err;
970 if (buffer >= buffer_end || !skip_prefix(buffer, "committer ", &buffer))
971 return report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line");
972 err = fsck_ident(&buffer, oid, OBJ_COMMIT, options);
973 if (err)
974 return err;
975 if (memchr(buffer_begin, '\0', size)) {
976 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_NUL_IN_COMMIT,
977 "NUL byte in the commit object body");
978 if (err)
979 return err;
981 return 0;
984 static int fsck_tag(const struct object_id *oid, const char *buffer,
985 unsigned long size, struct fsck_options *options)
987 struct object_id tagged_oid;
988 int tagged_type;
989 return fsck_tag_standalone(oid, buffer, size, options, &tagged_oid,
990 &tagged_type);
993 int fsck_tag_standalone(const struct object_id *oid, const char *buffer,
994 unsigned long size, struct fsck_options *options,
995 struct object_id *tagged_oid,
996 int *tagged_type)
998 int ret = 0;
999 char *eol;
1000 struct strbuf sb = STRBUF_INIT;
1001 const char *buffer_end = buffer + size;
1002 const char *p;
1005 * We _must_ stop parsing immediately if this reports failure, as the
1006 * memory safety of the rest of the function depends on it. See the
1007 * comment above the definition of verify_headers() for more details.
1009 ret = verify_headers(buffer, size, oid, OBJ_TAG, options);
1010 if (ret)
1011 goto done;
1013 if (buffer >= buffer_end || !skip_prefix(buffer, "object ", &buffer)) {
1014 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
1015 goto done;
1017 if (parse_oid_hex(buffer, tagged_oid, &p) || *p != '\n') {
1018 ret = report(options, oid, OBJ_TAG, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
1019 if (ret)
1020 goto done;
1022 buffer = p + 1;
1024 if (buffer >= buffer_end || !skip_prefix(buffer, "type ", &buffer)) {
1025 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
1026 goto done;
1028 eol = memchr(buffer, '\n', buffer_end - buffer);
1029 if (!eol) {
1030 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line");
1031 goto done;
1033 *tagged_type = type_from_string_gently(buffer, eol - buffer, 1);
1034 if (*tagged_type < 0)
1035 ret = report(options, oid, OBJ_TAG, FSCK_MSG_BAD_TYPE, "invalid 'type' value");
1036 if (ret)
1037 goto done;
1038 buffer = eol + 1;
1040 if (buffer >= buffer_end || !skip_prefix(buffer, "tag ", &buffer)) {
1041 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line");
1042 goto done;
1044 eol = memchr(buffer, '\n', buffer_end - buffer);
1045 if (!eol) {
1046 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line");
1047 goto done;
1049 strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
1050 if (check_refname_format(sb.buf, 0)) {
1051 ret = report(options, oid, OBJ_TAG,
1052 FSCK_MSG_BAD_TAG_NAME,
1053 "invalid 'tag' name: %.*s",
1054 (int)(eol - buffer), buffer);
1055 if (ret)
1056 goto done;
1058 buffer = eol + 1;
1060 if (buffer >= buffer_end || !skip_prefix(buffer, "tagger ", &buffer)) {
1061 /* early tags do not contain 'tagger' lines; warn only */
1062 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line");
1063 if (ret)
1064 goto done;
1066 else
1067 ret = fsck_ident(&buffer, oid, OBJ_TAG, options);
1069 if (buffer < buffer_end && !starts_with(buffer, "\n")) {
1071 * The verify_headers() check will allow
1072 * e.g. "[...]tagger <tagger>\nsome
1073 * garbage\n\nmessage" to pass, thinking "some
1074 * garbage" could be a custom header. E.g. "mktag"
1075 * doesn't want any unknown headers.
1077 ret = report(options, oid, OBJ_TAG, FSCK_MSG_EXTRA_HEADER_ENTRY, "invalid format - extra header(s) after 'tagger'");
1078 if (ret)
1079 goto done;
1082 done:
1083 strbuf_release(&sb);
1084 return ret;
1087 struct fsck_gitmodules_data {
1088 const struct object_id *oid;
1089 struct fsck_options *options;
1090 int ret;
1093 static int fsck_gitmodules_fn(const char *var, const char *value,
1094 const struct config_context *ctx UNUSED,
1095 void *vdata)
1097 struct fsck_gitmodules_data *data = vdata;
1098 const char *subsection, *key;
1099 size_t subsection_len;
1100 char *name;
1102 if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
1103 !subsection)
1104 return 0;
1106 name = xmemdupz(subsection, subsection_len);
1107 if (check_submodule_name(name) < 0)
1108 data->ret |= report(data->options,
1109 data->oid, OBJ_BLOB,
1110 FSCK_MSG_GITMODULES_NAME,
1111 "disallowed submodule name: %s",
1112 name);
1113 if (!strcmp(key, "url") && value &&
1114 check_submodule_url(value) < 0)
1115 data->ret |= report(data->options,
1116 data->oid, OBJ_BLOB,
1117 FSCK_MSG_GITMODULES_URL,
1118 "disallowed submodule url: %s",
1119 value);
1120 if (!strcmp(key, "path") && value &&
1121 looks_like_command_line_option(value))
1122 data->ret |= report(data->options,
1123 data->oid, OBJ_BLOB,
1124 FSCK_MSG_GITMODULES_PATH,
1125 "disallowed submodule path: %s",
1126 value);
1127 if (!strcmp(key, "update") && value &&
1128 parse_submodule_update_type(value) == SM_UPDATE_COMMAND)
1129 data->ret |= report(data->options, data->oid, OBJ_BLOB,
1130 FSCK_MSG_GITMODULES_UPDATE,
1131 "disallowed submodule update setting: %s",
1132 value);
1133 free(name);
1135 return 0;
1138 static int fsck_blob(const struct object_id *oid, const char *buf,
1139 unsigned long size, struct fsck_options *options)
1141 int ret = 0;
1143 if (object_on_skiplist(options, oid))
1144 return 0;
1146 if (oidset_contains(&options->gitmodules_found, oid)) {
1147 struct config_options config_opts = { 0 };
1148 struct fsck_gitmodules_data data;
1150 oidset_insert(&options->gitmodules_done, oid);
1152 if (!buf) {
1154 * A missing buffer here is a sign that the caller found the
1155 * blob too gigantic to load into memory. Let's just consider
1156 * that an error.
1158 return report(options, oid, OBJ_BLOB,
1159 FSCK_MSG_GITMODULES_LARGE,
1160 ".gitmodules too large to parse");
1163 data.oid = oid;
1164 data.options = options;
1165 data.ret = 0;
1166 config_opts.error_action = CONFIG_ERROR_SILENT;
1167 if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
1168 ".gitmodules", buf, size, &data,
1169 CONFIG_SCOPE_UNKNOWN, &config_opts))
1170 data.ret |= report(options, oid, OBJ_BLOB,
1171 FSCK_MSG_GITMODULES_PARSE,
1172 "could not parse gitmodules blob");
1173 ret |= data.ret;
1176 if (oidset_contains(&options->gitattributes_found, oid)) {
1177 const char *ptr;
1179 oidset_insert(&options->gitattributes_done, oid);
1181 if (!buf || size > ATTR_MAX_FILE_SIZE) {
1183 * A missing buffer here is a sign that the caller found the
1184 * blob too gigantic to load into memory. Let's just consider
1185 * that an error.
1187 return report(options, oid, OBJ_BLOB,
1188 FSCK_MSG_GITATTRIBUTES_LARGE,
1189 ".gitattributes too large to parse");
1192 for (ptr = buf; *ptr; ) {
1193 const char *eol = strchrnul(ptr, '\n');
1194 if (eol - ptr >= ATTR_MAX_LINE_LENGTH) {
1195 ret |= report(options, oid, OBJ_BLOB,
1196 FSCK_MSG_GITATTRIBUTES_LINE_LENGTH,
1197 ".gitattributes has too long lines to parse");
1198 break;
1201 ptr = *eol ? eol + 1 : eol;
1205 return ret;
1208 int fsck_object(struct object *obj, void *data, unsigned long size,
1209 struct fsck_options *options)
1211 if (!obj)
1212 return report(options, NULL, OBJ_NONE, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
1214 return fsck_buffer(&obj->oid, obj->type, data, size, options);
1217 int fsck_buffer(const struct object_id *oid, enum object_type type,
1218 const void *data, unsigned long size,
1219 struct fsck_options *options)
1221 if (type == OBJ_BLOB)
1222 return fsck_blob(oid, data, size, options);
1223 if (type == OBJ_TREE)
1224 return fsck_tree(oid, data, size, options);
1225 if (type == OBJ_COMMIT)
1226 return fsck_commit(oid, data, size, options);
1227 if (type == OBJ_TAG)
1228 return fsck_tag(oid, data, size, options);
1230 return report(options, oid, type,
1231 FSCK_MSG_UNKNOWN_TYPE,
1232 "unknown type '%d' (internal fsck error)",
1233 type);
1236 int fsck_objects_error_function(struct fsck_options *o,
1237 void *fsck_report,
1238 enum fsck_msg_type msg_type,
1239 enum fsck_msg_id msg_id UNUSED,
1240 const char *message)
1242 struct fsck_object_report *report = fsck_report;
1243 const struct object_id *oid = report->oid;
1245 if (msg_type == FSCK_WARN) {
1246 warning("object %s: %s", fsck_describe_object(o, oid), message);
1247 return 0;
1249 error("object %s: %s", fsck_describe_object(o, oid), message);
1250 return 1;
1253 int fsck_refs_error_function(struct fsck_options *options UNUSED,
1254 void *fsck_report,
1255 enum fsck_msg_type msg_type,
1256 enum fsck_msg_id msg_id UNUSED,
1257 const char *message)
1259 struct fsck_ref_report *report = fsck_report;
1260 struct strbuf sb = STRBUF_INIT;
1261 int ret = 0;
1263 strbuf_addstr(&sb, report->path);
1265 if (report->oid)
1266 strbuf_addf(&sb, " -> (%s)", oid_to_hex(report->oid));
1267 else if (report->referent)
1268 strbuf_addf(&sb, " -> (%s)", report->referent);
1270 if (msg_type == FSCK_WARN)
1271 warning("%s: %s", sb.buf, message);
1272 else
1273 ret = error("%s: %s", sb.buf, message);
1275 strbuf_release(&sb);
1276 return ret;
1279 static int fsck_blobs(struct oidset *blobs_found, struct oidset *blobs_done,
1280 enum fsck_msg_id msg_missing, enum fsck_msg_id msg_type,
1281 struct fsck_options *options, const char *blob_type)
1283 int ret = 0;
1284 struct oidset_iter iter;
1285 const struct object_id *oid;
1287 oidset_iter_init(blobs_found, &iter);
1288 while ((oid = oidset_iter_next(&iter))) {
1289 enum object_type type;
1290 unsigned long size;
1291 char *buf;
1293 if (oidset_contains(blobs_done, oid))
1294 continue;
1296 buf = repo_read_object_file(the_repository, oid, &type, &size);
1297 if (!buf) {
1298 if (is_promisor_object(oid))
1299 continue;
1300 ret |= report(options,
1301 oid, OBJ_BLOB, msg_missing,
1302 "unable to read %s blob", blob_type);
1303 continue;
1306 if (type == OBJ_BLOB)
1307 ret |= fsck_blob(oid, buf, size, options);
1308 else
1309 ret |= report(options, oid, type, msg_type,
1310 "non-blob found at %s", blob_type);
1311 free(buf);
1314 oidset_clear(blobs_found);
1315 oidset_clear(blobs_done);
1317 return ret;
1320 int fsck_finish(struct fsck_options *options)
1322 int ret = 0;
1324 ret |= fsck_blobs(&options->gitmodules_found, &options->gitmodules_done,
1325 FSCK_MSG_GITMODULES_MISSING, FSCK_MSG_GITMODULES_BLOB,
1326 options, ".gitmodules");
1327 ret |= fsck_blobs(&options->gitattributes_found, &options->gitattributes_done,
1328 FSCK_MSG_GITATTRIBUTES_MISSING, FSCK_MSG_GITATTRIBUTES_BLOB,
1329 options, ".gitattributes");
1331 return ret;
1334 void fsck_options_clear(struct fsck_options *options)
1336 free(options->msg_type);
1337 oidset_clear(&options->skip_oids);
1338 oidset_clear(&options->gitmodules_found);
1339 oidset_clear(&options->gitmodules_done);
1340 oidset_clear(&options->gitattributes_found);
1341 oidset_clear(&options->gitattributes_done);
1342 kh_clear_oid_map(options->object_names);
1345 int git_fsck_config(const char *var, const char *value,
1346 const struct config_context *ctx, void *cb)
1348 struct fsck_options *options = cb;
1349 const char *msg_id;
1351 if (strcmp(var, "fsck.skiplist") == 0) {
1352 char *path;
1353 struct strbuf sb = STRBUF_INIT;
1355 if (git_config_pathname(&path, var, value))
1356 return 1;
1357 strbuf_addf(&sb, "skiplist=%s", path);
1358 free(path);
1359 fsck_set_msg_types(options, sb.buf);
1360 strbuf_release(&sb);
1361 return 0;
1364 if (skip_prefix(var, "fsck.", &msg_id)) {
1365 if (!value)
1366 return config_error_nonbool(var);
1367 fsck_set_msg_type(options, msg_id, value);
1368 return 0;
1371 return git_default_config(var, value, ctx, cb);
1375 * Custom error callbacks that are used in more than one place.
1378 int fsck_objects_error_cb_print_missing_gitmodules(struct fsck_options *o,
1379 void *fsck_report,
1380 enum fsck_msg_type msg_type,
1381 enum fsck_msg_id msg_id,
1382 const char *message)
1384 if (msg_id == FSCK_MSG_GITMODULES_MISSING) {
1385 struct fsck_object_report *report = fsck_report;
1386 puts(oid_to_hex(report->oid));
1387 return 0;
1389 return fsck_objects_error_function(o, fsck_report,
1390 msg_type, msg_id, message);