maintenance: use 'git fetch --prefetch'
[git] / fsck.c
1 #include "cache.h"
2 #include "object-store.h"
3 #include "repository.h"
4 #include "object.h"
5 #include "blob.h"
6 #include "tree.h"
7 #include "tree-walk.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "fsck.h"
11 #include "refs.h"
12 #include "url.h"
13 #include "utf8.h"
14 #include "decorate.h"
15 #include "oidset.h"
16 #include "packfile.h"
17 #include "submodule-config.h"
18 #include "config.h"
19 #include "credential.h"
20 #include "help.h"
21
22 static struct oidset gitmodules_found = OIDSET_INIT;
23 static struct oidset gitmodules_done = OIDSET_INIT;
24
25 #define FSCK_FATAL -1
26 #define FSCK_INFO -2
27
28 #define FOREACH_MSG_ID(FUNC) \
29         /* fatal errors */ \
30         FUNC(NUL_IN_HEADER, FATAL) \
31         FUNC(UNTERMINATED_HEADER, FATAL) \
32         /* errors */ \
33         FUNC(BAD_DATE, ERROR) \
34         FUNC(BAD_DATE_OVERFLOW, ERROR) \
35         FUNC(BAD_EMAIL, ERROR) \
36         FUNC(BAD_NAME, ERROR) \
37         FUNC(BAD_OBJECT_SHA1, ERROR) \
38         FUNC(BAD_PARENT_SHA1, ERROR) \
39         FUNC(BAD_TAG_OBJECT, ERROR) \
40         FUNC(BAD_TIMEZONE, ERROR) \
41         FUNC(BAD_TREE, ERROR) \
42         FUNC(BAD_TREE_SHA1, ERROR) \
43         FUNC(BAD_TYPE, ERROR) \
44         FUNC(DUPLICATE_ENTRIES, ERROR) \
45         FUNC(MISSING_AUTHOR, ERROR) \
46         FUNC(MISSING_COMMITTER, ERROR) \
47         FUNC(MISSING_EMAIL, ERROR) \
48         FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \
49         FUNC(MISSING_OBJECT, ERROR) \
50         FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \
51         FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \
52         FUNC(MISSING_TAG, ERROR) \
53         FUNC(MISSING_TAG_ENTRY, ERROR) \
54         FUNC(MISSING_TREE, ERROR) \
55         FUNC(MISSING_TREE_OBJECT, ERROR) \
56         FUNC(MISSING_TYPE, ERROR) \
57         FUNC(MISSING_TYPE_ENTRY, ERROR) \
58         FUNC(MULTIPLE_AUTHORS, ERROR) \
59         FUNC(TREE_NOT_SORTED, ERROR) \
60         FUNC(UNKNOWN_TYPE, ERROR) \
61         FUNC(ZERO_PADDED_DATE, ERROR) \
62         FUNC(GITMODULES_MISSING, ERROR) \
63         FUNC(GITMODULES_BLOB, ERROR) \
64         FUNC(GITMODULES_LARGE, ERROR) \
65         FUNC(GITMODULES_NAME, ERROR) \
66         FUNC(GITMODULES_SYMLINK, ERROR) \
67         FUNC(GITMODULES_URL, ERROR) \
68         FUNC(GITMODULES_PATH, ERROR) \
69         FUNC(GITMODULES_UPDATE, ERROR) \
70         /* warnings */ \
71         FUNC(BAD_FILEMODE, WARN) \
72         FUNC(EMPTY_NAME, WARN) \
73         FUNC(FULL_PATHNAME, WARN) \
74         FUNC(HAS_DOT, WARN) \
75         FUNC(HAS_DOTDOT, WARN) \
76         FUNC(HAS_DOTGIT, WARN) \
77         FUNC(NULL_SHA1, WARN) \
78         FUNC(ZERO_PADDED_FILEMODE, WARN) \
79         FUNC(NUL_IN_COMMIT, WARN) \
80         /* infos (reported as warnings, but ignored by default) */ \
81         FUNC(GITMODULES_PARSE, INFO) \
82         FUNC(BAD_TAG_NAME, INFO) \
83         FUNC(MISSING_TAGGER_ENTRY, INFO) \
84         /* ignored (elevated when requested) */ \
85         FUNC(EXTRA_HEADER_ENTRY, IGNORE)
86
87 #define MSG_ID(id, msg_type) FSCK_MSG_##id,
88 enum fsck_msg_id {
89         FOREACH_MSG_ID(MSG_ID)
90         FSCK_MSG_MAX
91 };
92 #undef MSG_ID
93
94 #define STR(x) #x
95 #define MSG_ID(id, msg_type) { STR(id), NULL, NULL, FSCK_##msg_type },
96 static struct {
97         const char *id_string;
98         const char *downcased;
99         const char *camelcased;
100         int msg_type;
101 } msg_id_info[FSCK_MSG_MAX + 1] = {
102         FOREACH_MSG_ID(MSG_ID)
103         { NULL, NULL, NULL, -1 }
104 };
105 #undef MSG_ID
106
107 static void prepare_msg_ids(void)
108 {
109         int i;
110
111         if (msg_id_info[0].downcased)
112                 return;
113
114         /* convert id_string to lower case, without underscores. */
115         for (i = 0; i < FSCK_MSG_MAX; i++) {
116                 const char *p = msg_id_info[i].id_string;
117                 int len = strlen(p);
118                 char *q = xmalloc(len);
119
120                 msg_id_info[i].downcased = q;
121                 while (*p)
122                         if (*p == '_')
123                                 p++;
124                         else
125                                 *(q)++ = tolower(*(p)++);
126                 *q = '\0';
127
128                 p = msg_id_info[i].id_string;
129                 q = xmalloc(len);
130                 msg_id_info[i].camelcased = q;
131                 while (*p) {
132                         if (*p == '_') {
133                                 p++;
134                                 if (*p)
135                                         *q++ = *p++;
136                         } else {
137                                 *q++ = tolower(*p++);
138                         }
139                 }
140                 *q = '\0';
141         }
142 }
143
144 static int parse_msg_id(const char *text)
145 {
146         int i;
147
148         prepare_msg_ids();
149
150         for (i = 0; i < FSCK_MSG_MAX; i++)
151                 if (!strcmp(text, msg_id_info[i].downcased))
152                         return i;
153
154         return -1;
155 }
156
157 void list_config_fsck_msg_ids(struct string_list *list, const char *prefix)
158 {
159         int i;
160
161         prepare_msg_ids();
162
163         for (i = 0; i < FSCK_MSG_MAX; i++)
164                 list_config_item(list, prefix, msg_id_info[i].camelcased);
165 }
166
167 static int fsck_msg_type(enum fsck_msg_id msg_id,
168         struct fsck_options *options)
169 {
170         int msg_type;
171
172         assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX);
173
174         if (options->msg_type)
175                 msg_type = options->msg_type[msg_id];
176         else {
177                 msg_type = msg_id_info[msg_id].msg_type;
178                 if (options->strict && msg_type == FSCK_WARN)
179                         msg_type = FSCK_ERROR;
180         }
181
182         return msg_type;
183 }
184
185 static int parse_msg_type(const char *str)
186 {
187         if (!strcmp(str, "error"))
188                 return FSCK_ERROR;
189         else if (!strcmp(str, "warn"))
190                 return FSCK_WARN;
191         else if (!strcmp(str, "ignore"))
192                 return FSCK_IGNORE;
193         else
194                 die("Unknown fsck message type: '%s'", str);
195 }
196
197 int is_valid_msg_type(const char *msg_id, const char *msg_type)
198 {
199         if (parse_msg_id(msg_id) < 0)
200                 return 0;
201         parse_msg_type(msg_type);
202         return 1;
203 }
204
205 void fsck_set_msg_type(struct fsck_options *options,
206                 const char *msg_id, const char *msg_type)
207 {
208         int id = parse_msg_id(msg_id), type;
209
210         if (id < 0)
211                 die("Unhandled message id: %s", msg_id);
212         type = parse_msg_type(msg_type);
213
214         if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL)
215                 die("Cannot demote %s to %s", msg_id, msg_type);
216
217         if (!options->msg_type) {
218                 int i;
219                 int *msg_type;
220                 ALLOC_ARRAY(msg_type, FSCK_MSG_MAX);
221                 for (i = 0; i < FSCK_MSG_MAX; i++)
222                         msg_type[i] = fsck_msg_type(i, options);
223                 options->msg_type = msg_type;
224         }
225
226         options->msg_type[id] = type;
227 }
228
229 void fsck_set_msg_types(struct fsck_options *options, const char *values)
230 {
231         char *buf = xstrdup(values), *to_free = buf;
232         int done = 0;
233
234         while (!done) {
235                 int len = strcspn(buf, " ,|"), equal;
236
237                 done = !buf[len];
238                 if (!len) {
239                         buf++;
240                         continue;
241                 }
242                 buf[len] = '\0';
243
244                 for (equal = 0;
245                      equal < len && buf[equal] != '=' && buf[equal] != ':';
246                      equal++)
247                         buf[equal] = tolower(buf[equal]);
248                 buf[equal] = '\0';
249
250                 if (!strcmp(buf, "skiplist")) {
251                         if (equal == len)
252                                 die("skiplist requires a path");
253                         oidset_parse_file(&options->skiplist, buf + equal + 1);
254                         buf += len + 1;
255                         continue;
256                 }
257
258                 if (equal == len)
259                         die("Missing '=': '%s'", buf);
260
261                 fsck_set_msg_type(options, buf, buf + equal + 1);
262                 buf += len + 1;
263         }
264         free(to_free);
265 }
266
267 static void append_msg_id(struct strbuf *sb, const char *msg_id)
268 {
269         for (;;) {
270                 char c = *(msg_id)++;
271
272                 if (!c)
273                         break;
274                 if (c != '_')
275                         strbuf_addch(sb, tolower(c));
276                 else {
277                         assert(*msg_id);
278                         strbuf_addch(sb, *(msg_id)++);
279                 }
280         }
281
282         strbuf_addstr(sb, ": ");
283 }
284
285 static int object_on_skiplist(struct fsck_options *opts,
286                               const struct object_id *oid)
287 {
288         return opts && oid && oidset_contains(&opts->skiplist, oid);
289 }
290
291 __attribute__((format (printf, 5, 6)))
292 static int report(struct fsck_options *options,
293                   const struct object_id *oid, enum object_type object_type,
294                   enum fsck_msg_id id, const char *fmt, ...)
295 {
296         va_list ap;
297         struct strbuf sb = STRBUF_INIT;
298         int msg_type = fsck_msg_type(id, options), result;
299
300         if (msg_type == FSCK_IGNORE)
301                 return 0;
302
303         if (object_on_skiplist(options, oid))
304                 return 0;
305
306         if (msg_type == FSCK_FATAL)
307                 msg_type = FSCK_ERROR;
308         else if (msg_type == FSCK_INFO)
309                 msg_type = FSCK_WARN;
310
311         append_msg_id(&sb, msg_id_info[id].id_string);
312
313         va_start(ap, fmt);
314         strbuf_vaddf(&sb, fmt, ap);
315         result = options->error_func(options, oid, object_type,
316                                      msg_type, sb.buf);
317         strbuf_release(&sb);
318         va_end(ap);
319
320         return result;
321 }
322
323 void fsck_enable_object_names(struct fsck_options *options)
324 {
325         if (!options->object_names)
326                 options->object_names = kh_init_oid_map();
327 }
328
329 const char *fsck_get_object_name(struct fsck_options *options,
330                                  const struct object_id *oid)
331 {
332         khiter_t pos;
333         if (!options->object_names)
334                 return NULL;
335         pos = kh_get_oid_map(options->object_names, *oid);
336         if (pos >= kh_end(options->object_names))
337                 return NULL;
338         return kh_value(options->object_names, pos);
339 }
340
341 void fsck_put_object_name(struct fsck_options *options,
342                           const struct object_id *oid,
343                           const char *fmt, ...)
344 {
345         va_list ap;
346         struct strbuf buf = STRBUF_INIT;
347         khiter_t pos;
348         int hashret;
349
350         if (!options->object_names)
351                 return;
352
353         pos = kh_put_oid_map(options->object_names, *oid, &hashret);
354         if (!hashret)
355                 return;
356         va_start(ap, fmt);
357         strbuf_vaddf(&buf, fmt, ap);
358         kh_value(options->object_names, pos) = strbuf_detach(&buf, NULL);
359         va_end(ap);
360 }
361
362 const char *fsck_describe_object(struct fsck_options *options,
363                                  const struct object_id *oid)
364 {
365         static struct strbuf bufs[] = {
366                 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
367         };
368         static int b = 0;
369         struct strbuf *buf;
370         const char *name = fsck_get_object_name(options, oid);
371
372         buf = bufs + b;
373         b = (b + 1) % ARRAY_SIZE(bufs);
374         strbuf_reset(buf);
375         strbuf_addstr(buf, oid_to_hex(oid));
376         if (name)
377                 strbuf_addf(buf, " (%s)", name);
378
379         return buf->buf;
380 }
381
382 static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options)
383 {
384         struct tree_desc desc;
385         struct name_entry entry;
386         int res = 0;
387         const char *name;
388
389         if (parse_tree(tree))
390                 return -1;
391
392         name = fsck_get_object_name(options, &tree->object.oid);
393         if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
394                 return -1;
395         while (tree_entry_gently(&desc, &entry)) {
396                 struct object *obj;
397                 int result;
398
399                 if (S_ISGITLINK(entry.mode))
400                         continue;
401
402                 if (S_ISDIR(entry.mode)) {
403                         obj = (struct object *)lookup_tree(the_repository, &entry.oid);
404                         if (name && obj)
405                                 fsck_put_object_name(options, &entry.oid, "%s%s/",
406                                                      name, entry.path);
407                         result = options->walk(obj, OBJ_TREE, data, options);
408                 }
409                 else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) {
410                         obj = (struct object *)lookup_blob(the_repository, &entry.oid);
411                         if (name && obj)
412                                 fsck_put_object_name(options, &entry.oid, "%s%s",
413                                                      name, entry.path);
414                         result = options->walk(obj, OBJ_BLOB, data, options);
415                 }
416                 else {
417                         result = error("in tree %s: entry %s has bad mode %.6o",
418                                        fsck_describe_object(options, &tree->object.oid),
419                                        entry.path, entry.mode);
420                 }
421                 if (result < 0)
422                         return result;
423                 if (!res)
424                         res = result;
425         }
426         return res;
427 }
428
429 static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options)
430 {
431         int counter = 0, generation = 0, name_prefix_len = 0;
432         struct commit_list *parents;
433         int res;
434         int result;
435         const char *name;
436
437         if (parse_commit(commit))
438                 return -1;
439
440         name = fsck_get_object_name(options, &commit->object.oid);
441         if (name)
442                 fsck_put_object_name(options, get_commit_tree_oid(commit),
443                                      "%s:", name);
444
445         result = options->walk((struct object *)get_commit_tree(commit),
446                                OBJ_TREE, data, options);
447         if (result < 0)
448                 return result;
449         res = result;
450
451         parents = commit->parents;
452         if (name && parents) {
453                 int len = strlen(name), power;
454
455                 if (len && name[len - 1] == '^') {
456                         generation = 1;
457                         name_prefix_len = len - 1;
458                 }
459                 else { /* parse ~<generation> suffix */
460                         for (generation = 0, power = 1;
461                              len && isdigit(name[len - 1]);
462                              power *= 10)
463                                 generation += power * (name[--len] - '0');
464                         if (power > 1 && len && name[len - 1] == '~')
465                                 name_prefix_len = len - 1;
466                         else {
467                                 /* Maybe a non-first parent, e.g. HEAD^2 */
468                                 generation = 0;
469                                 name_prefix_len = len;
470                         }
471                 }
472         }
473
474         while (parents) {
475                 if (name) {
476                         struct object_id *oid = &parents->item->object.oid;
477
478                         if (counter++)
479                                 fsck_put_object_name(options, oid, "%s^%d",
480                                                      name, counter);
481                         else if (generation > 0)
482                                 fsck_put_object_name(options, oid, "%.*s~%d",
483                                                      name_prefix_len, name,
484                                                      generation + 1);
485                         else
486                                 fsck_put_object_name(options, oid, "%s^", name);
487                 }
488                 result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options);
489                 if (result < 0)
490                         return result;
491                 if (!res)
492                         res = result;
493                 parents = parents->next;
494         }
495         return res;
496 }
497
498 static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options)
499 {
500         const char *name = fsck_get_object_name(options, &tag->object.oid);
501
502         if (parse_tag(tag))
503                 return -1;
504         if (name)
505                 fsck_put_object_name(options, &tag->tagged->oid, "%s", name);
506         return options->walk(tag->tagged, OBJ_ANY, data, options);
507 }
508
509 int fsck_walk(struct object *obj, void *data, struct fsck_options *options)
510 {
511         if (!obj)
512                 return -1;
513
514         if (obj->type == OBJ_NONE)
515                 parse_object(the_repository, &obj->oid);
516
517         switch (obj->type) {
518         case OBJ_BLOB:
519                 return 0;
520         case OBJ_TREE:
521                 return fsck_walk_tree((struct tree *)obj, data, options);
522         case OBJ_COMMIT:
523                 return fsck_walk_commit((struct commit *)obj, data, options);
524         case OBJ_TAG:
525                 return fsck_walk_tag((struct tag *)obj, data, options);
526         default:
527                 error("Unknown object type for %s",
528                       fsck_describe_object(options, &obj->oid));
529                 return -1;
530         }
531 }
532
533 struct name_stack {
534         const char **names;
535         size_t nr, alloc;
536 };
537
538 static void name_stack_push(struct name_stack *stack, const char *name)
539 {
540         ALLOC_GROW(stack->names, stack->nr + 1, stack->alloc);
541         stack->names[stack->nr++] = name;
542 }
543
544 static const char *name_stack_pop(struct name_stack *stack)
545 {
546         return stack->nr ? stack->names[--stack->nr] : NULL;
547 }
548
549 static void name_stack_clear(struct name_stack *stack)
550 {
551         FREE_AND_NULL(stack->names);
552         stack->nr = stack->alloc = 0;
553 }
554
555 /*
556  * The entries in a tree are ordered in the _path_ order,
557  * which means that a directory entry is ordered by adding
558  * a slash to the end of it.
559  *
560  * So a directory called "a" is ordered _after_ a file
561  * called "a.c", because "a/" sorts after "a.c".
562  */
563 #define TREE_UNORDERED (-1)
564 #define TREE_HAS_DUPS  (-2)
565
566 static int is_less_than_slash(unsigned char c)
567 {
568         return '\0' < c && c < '/';
569 }
570
571 static int verify_ordered(unsigned mode1, const char *name1,
572                           unsigned mode2, const char *name2,
573                           struct name_stack *candidates)
574 {
575         int len1 = strlen(name1);
576         int len2 = strlen(name2);
577         int len = len1 < len2 ? len1 : len2;
578         unsigned char c1, c2;
579         int cmp;
580
581         cmp = memcmp(name1, name2, len);
582         if (cmp < 0)
583                 return 0;
584         if (cmp > 0)
585                 return TREE_UNORDERED;
586
587         /*
588          * Ok, the first <len> characters are the same.
589          * Now we need to order the next one, but turn
590          * a '\0' into a '/' for a directory entry.
591          */
592         c1 = name1[len];
593         c2 = name2[len];
594         if (!c1 && !c2)
595                 /*
596                  * git-write-tree used to write out a nonsense tree that has
597                  * entries with the same name, one blob and one tree.  Make
598                  * sure we do not have duplicate entries.
599                  */
600                 return TREE_HAS_DUPS;
601         if (!c1 && S_ISDIR(mode1))
602                 c1 = '/';
603         if (!c2 && S_ISDIR(mode2))
604                 c2 = '/';
605
606         /*
607          * There can be non-consecutive duplicates due to the implicitly
608          * added slash, e.g.:
609          *
610          *   foo
611          *   foo.bar
612          *   foo.bar.baz
613          *   foo.bar/
614          *   foo/
615          *
616          * Record non-directory candidates (like "foo" and "foo.bar" in
617          * the example) on a stack and check directory candidates (like
618          * foo/" and "foo.bar/") against that stack.
619          */
620         if (!c1 && is_less_than_slash(c2)) {
621                 name_stack_push(candidates, name1);
622         } else if (c2 == '/' && is_less_than_slash(c1)) {
623                 for (;;) {
624                         const char *p;
625                         const char *f_name = name_stack_pop(candidates);
626
627                         if (!f_name)
628                                 break;
629                         if (!skip_prefix(name2, f_name, &p))
630                                 continue;
631                         if (!*p)
632                                 return TREE_HAS_DUPS;
633                         if (is_less_than_slash(*p)) {
634                                 name_stack_push(candidates, f_name);
635                                 break;
636                         }
637                 }
638         }
639
640         return c1 < c2 ? 0 : TREE_UNORDERED;
641 }
642
643 static int fsck_tree(const struct object_id *oid,
644                      const char *buffer, unsigned long size,
645                      struct fsck_options *options)
646 {
647         int retval = 0;
648         int has_null_sha1 = 0;
649         int has_full_path = 0;
650         int has_empty_name = 0;
651         int has_dot = 0;
652         int has_dotdot = 0;
653         int has_dotgit = 0;
654         int has_zero_pad = 0;
655         int has_bad_modes = 0;
656         int has_dup_entries = 0;
657         int not_properly_sorted = 0;
658         struct tree_desc desc;
659         unsigned o_mode;
660         const char *o_name;
661         struct name_stack df_dup_candidates = { NULL };
662
663         if (init_tree_desc_gently(&desc, buffer, size)) {
664                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
665                 return retval;
666         }
667
668         o_mode = 0;
669         o_name = NULL;
670
671         while (desc.size) {
672                 unsigned short mode;
673                 const char *name, *backslash;
674                 const struct object_id *oid;
675
676                 oid = tree_entry_extract(&desc, &name, &mode);
677
678                 has_null_sha1 |= is_null_oid(oid);
679                 has_full_path |= !!strchr(name, '/');
680                 has_empty_name |= !*name;
681                 has_dot |= !strcmp(name, ".");
682                 has_dotdot |= !strcmp(name, "..");
683                 has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
684                 has_zero_pad |= *(char *)desc.buffer == '0';
685
686                 if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
687                         if (!S_ISLNK(mode))
688                                 oidset_insert(&gitmodules_found, oid);
689                         else
690                                 retval += report(options,
691                                                  oid, OBJ_TREE,
692                                                  FSCK_MSG_GITMODULES_SYMLINK,
693                                                  ".gitmodules is a symbolic link");
694                 }
695
696                 if ((backslash = strchr(name, '\\'))) {
697                         while (backslash) {
698                                 backslash++;
699                                 has_dotgit |= is_ntfs_dotgit(backslash);
700                                 if (is_ntfs_dotgitmodules(backslash)) {
701                                         if (!S_ISLNK(mode))
702                                                 oidset_insert(&gitmodules_found, oid);
703                                         else
704                                                 retval += report(options, oid, OBJ_TREE,
705                                                                  FSCK_MSG_GITMODULES_SYMLINK,
706                                                                  ".gitmodules is a symbolic link");
707                                 }
708                                 backslash = strchr(backslash, '\\');
709                         }
710                 }
711
712                 if (update_tree_entry_gently(&desc)) {
713                         retval += report(options, oid, OBJ_TREE, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
714                         break;
715                 }
716
717                 switch (mode) {
718                 /*
719                  * Standard modes..
720                  */
721                 case S_IFREG | 0755:
722                 case S_IFREG | 0644:
723                 case S_IFLNK:
724                 case S_IFDIR:
725                 case S_IFGITLINK:
726                         break;
727                 /*
728                  * This is nonstandard, but we had a few of these
729                  * early on when we honored the full set of mode
730                  * bits..
731                  */
732                 case S_IFREG | 0664:
733                         if (!options->strict)
734                                 break;
735                         /* fallthrough */
736                 default:
737                         has_bad_modes = 1;
738                 }
739
740                 if (o_name) {
741                         switch (verify_ordered(o_mode, o_name, mode, name,
742                                                &df_dup_candidates)) {
743                         case TREE_UNORDERED:
744                                 not_properly_sorted = 1;
745                                 break;
746                         case TREE_HAS_DUPS:
747                                 has_dup_entries = 1;
748                                 break;
749                         default:
750                                 break;
751                         }
752                 }
753
754                 o_mode = mode;
755                 o_name = name;
756         }
757
758         name_stack_clear(&df_dup_candidates);
759
760         if (has_null_sha1)
761                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1");
762         if (has_full_path)
763                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_FULL_PATHNAME, "contains full pathnames");
764         if (has_empty_name)
765                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_EMPTY_NAME, "contains empty pathname");
766         if (has_dot)
767                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_HAS_DOT, "contains '.'");
768         if (has_dotdot)
769                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_HAS_DOTDOT, "contains '..'");
770         if (has_dotgit)
771                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_HAS_DOTGIT, "contains '.git'");
772         if (has_zero_pad)
773                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes");
774         if (has_bad_modes)
775                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_BAD_FILEMODE, "contains bad file modes");
776         if (has_dup_entries)
777                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries");
778         if (not_properly_sorted)
779                 retval += report(options, oid, OBJ_TREE, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted");
780         return retval;
781 }
782
783 static int verify_headers(const void *data, unsigned long size,
784                           const struct object_id *oid, enum object_type type,
785                           struct fsck_options *options)
786 {
787         const char *buffer = (const char *)data;
788         unsigned long i;
789
790         for (i = 0; i < size; i++) {
791                 switch (buffer[i]) {
792                 case '\0':
793                         return report(options, oid, type,
794                                 FSCK_MSG_NUL_IN_HEADER,
795                                 "unterminated header: NUL at offset %ld", i);
796                 case '\n':
797                         if (i + 1 < size && buffer[i + 1] == '\n')
798                                 return 0;
799                 }
800         }
801
802         /*
803          * We did not find double-LF that separates the header
804          * and the body.  Not having a body is not a crime but
805          * we do want to see the terminating LF for the last header
806          * line.
807          */
808         if (size && buffer[size - 1] == '\n')
809                 return 0;
810
811         return report(options, oid, type,
812                 FSCK_MSG_UNTERMINATED_HEADER, "unterminated header");
813 }
814
815 static int fsck_ident(const char **ident,
816                       const struct object_id *oid, enum object_type type,
817                       struct fsck_options *options)
818 {
819         const char *p = *ident;
820         char *end;
821
822         *ident = strchrnul(*ident, '\n');
823         if (**ident == '\n')
824                 (*ident)++;
825
826         if (*p == '<')
827                 return report(options, oid, type, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
828         p += strcspn(p, "<>\n");
829         if (*p == '>')
830                 return report(options, oid, type, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name");
831         if (*p != '<')
832                 return report(options, oid, type, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email");
833         if (p[-1] != ' ')
834                 return report(options, oid, type, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
835         p++;
836         p += strcspn(p, "<>\n");
837         if (*p != '>')
838                 return report(options, oid, type, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email");
839         p++;
840         if (*p != ' ')
841                 return report(options, oid, type, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date");
842         p++;
843         if (*p == '0' && p[1] != ' ')
844                 return report(options, oid, type, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date");
845         if (date_overflows(parse_timestamp(p, &end, 10)))
846                 return report(options, oid, type, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow");
847         if ((end == p || *end != ' '))
848                 return report(options, oid, type, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date");
849         p = end + 1;
850         if ((*p != '+' && *p != '-') ||
851             !isdigit(p[1]) ||
852             !isdigit(p[2]) ||
853             !isdigit(p[3]) ||
854             !isdigit(p[4]) ||
855             (p[5] != '\n'))
856                 return report(options, oid, type, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone");
857         p += 6;
858         return 0;
859 }
860
861 static int fsck_commit(const struct object_id *oid,
862                        const char *buffer, unsigned long size,
863                        struct fsck_options *options)
864 {
865         struct object_id tree_oid, parent_oid;
866         unsigned author_count;
867         int err;
868         const char *buffer_begin = buffer;
869         const char *p;
870
871         if (verify_headers(buffer, size, oid, OBJ_COMMIT, options))
872                 return -1;
873
874         if (!skip_prefix(buffer, "tree ", &buffer))
875                 return report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
876         if (parse_oid_hex(buffer, &tree_oid, &p) || *p != '\n') {
877                 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
878                 if (err)
879                         return err;
880         }
881         buffer = p + 1;
882         while (skip_prefix(buffer, "parent ", &buffer)) {
883                 if (parse_oid_hex(buffer, &parent_oid, &p) || *p != '\n') {
884                         err = report(options, oid, OBJ_COMMIT, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
885                         if (err)
886                                 return err;
887                 }
888                 buffer = p + 1;
889         }
890         author_count = 0;
891         while (skip_prefix(buffer, "author ", &buffer)) {
892                 author_count++;
893                 err = fsck_ident(&buffer, oid, OBJ_COMMIT, options);
894                 if (err)
895                         return err;
896         }
897         if (author_count < 1)
898                 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line");
899         else if (author_count > 1)
900                 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines");
901         if (err)
902                 return err;
903         if (!skip_prefix(buffer, "committer ", &buffer))
904                 return report(options, oid, OBJ_COMMIT, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line");
905         err = fsck_ident(&buffer, oid, OBJ_COMMIT, options);
906         if (err)
907                 return err;
908         if (memchr(buffer_begin, '\0', size)) {
909                 err = report(options, oid, OBJ_COMMIT, FSCK_MSG_NUL_IN_COMMIT,
910                              "NUL byte in the commit object body");
911                 if (err)
912                         return err;
913         }
914         return 0;
915 }
916
917 static int fsck_tag(const struct object_id *oid, const char *buffer,
918                     unsigned long size, struct fsck_options *options)
919 {
920         struct object_id tagged_oid;
921         int tagged_type;
922         return fsck_tag_standalone(oid, buffer, size, options, &tagged_oid,
923                                    &tagged_type);
924 }
925
926 int fsck_tag_standalone(const struct object_id *oid, const char *buffer,
927                         unsigned long size, struct fsck_options *options,
928                         struct object_id *tagged_oid,
929                         int *tagged_type)
930 {
931         int ret = 0;
932         char *eol;
933         struct strbuf sb = STRBUF_INIT;
934         const char *p;
935
936         ret = verify_headers(buffer, size, oid, OBJ_TAG, options);
937         if (ret)
938                 goto done;
939
940         if (!skip_prefix(buffer, "object ", &buffer)) {
941                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
942                 goto done;
943         }
944         if (parse_oid_hex(buffer, tagged_oid, &p) || *p != '\n') {
945                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
946                 if (ret)
947                         goto done;
948         }
949         buffer = p + 1;
950
951         if (!skip_prefix(buffer, "type ", &buffer)) {
952                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
953                 goto done;
954         }
955         eol = strchr(buffer, '\n');
956         if (!eol) {
957                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line");
958                 goto done;
959         }
960         *tagged_type = type_from_string_gently(buffer, eol - buffer, 1);
961         if (*tagged_type < 0)
962                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_BAD_TYPE, "invalid 'type' value");
963         if (ret)
964                 goto done;
965         buffer = eol + 1;
966
967         if (!skip_prefix(buffer, "tag ", &buffer)) {
968                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line");
969                 goto done;
970         }
971         eol = strchr(buffer, '\n');
972         if (!eol) {
973                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line");
974                 goto done;
975         }
976         strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
977         if (check_refname_format(sb.buf, 0)) {
978                 ret = report(options, oid, OBJ_TAG,
979                              FSCK_MSG_BAD_TAG_NAME,
980                              "invalid 'tag' name: %.*s",
981                              (int)(eol - buffer), buffer);
982                 if (ret)
983                         goto done;
984         }
985         buffer = eol + 1;
986
987         if (!skip_prefix(buffer, "tagger ", &buffer)) {
988                 /* early tags do not contain 'tagger' lines; warn only */
989                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line");
990                 if (ret)
991                         goto done;
992         }
993         else
994                 ret = fsck_ident(&buffer, oid, OBJ_TAG, options);
995         if (!*buffer)
996                 goto done;
997
998         if (!starts_with(buffer, "\n")) {
999                 /*
1000                  * The verify_headers() check will allow
1001                  * e.g. "[...]tagger <tagger>\nsome
1002                  * garbage\n\nmessage" to pass, thinking "some
1003                  * garbage" could be a custom header. E.g. "mktag"
1004                  * doesn't want any unknown headers.
1005                  */
1006                 ret = report(options, oid, OBJ_TAG, FSCK_MSG_EXTRA_HEADER_ENTRY, "invalid format - extra header(s) after 'tagger'");
1007                 if (ret)
1008                         goto done;
1009         }
1010
1011 done:
1012         strbuf_release(&sb);
1013         return ret;
1014 }
1015
1016 /*
1017  * Like builtin/submodule--helper.c's starts_with_dot_slash, but without
1018  * relying on the platform-dependent is_dir_sep helper.
1019  *
1020  * This is for use in checking whether a submodule URL is interpreted as
1021  * relative to the current directory on any platform, since \ is a
1022  * directory separator on Windows but not on other platforms.
1023  */
1024 static int starts_with_dot_slash(const char *str)
1025 {
1026         return str[0] == '.' && (str[1] == '/' || str[1] == '\\');
1027 }
1028
1029 /*
1030  * Like starts_with_dot_slash, this is a variant of submodule--helper's
1031  * helper of the same name with the twist that it accepts backslash as a
1032  * directory separator even on non-Windows platforms.
1033  */
1034 static int starts_with_dot_dot_slash(const char *str)
1035 {
1036         return str[0] == '.' && starts_with_dot_slash(str + 1);
1037 }
1038
1039 static int submodule_url_is_relative(const char *url)
1040 {
1041         return starts_with_dot_slash(url) || starts_with_dot_dot_slash(url);
1042 }
1043
1044 /*
1045  * Count directory components that a relative submodule URL should chop
1046  * from the remote_url it is to be resolved against.
1047  *
1048  * In other words, this counts "../" components at the start of a
1049  * submodule URL.
1050  *
1051  * Returns the number of directory components to chop and writes a
1052  * pointer to the next character of url after all leading "./" and
1053  * "../" components to out.
1054  */
1055 static int count_leading_dotdots(const char *url, const char **out)
1056 {
1057         int result = 0;
1058         while (1) {
1059                 if (starts_with_dot_dot_slash(url)) {
1060                         result++;
1061                         url += strlen("../");
1062                         continue;
1063                 }
1064                 if (starts_with_dot_slash(url)) {
1065                         url += strlen("./");
1066                         continue;
1067                 }
1068                 *out = url;
1069                 return result;
1070         }
1071 }
1072 /*
1073  * Check whether a transport is implemented by git-remote-curl.
1074  *
1075  * If it is, returns 1 and writes the URL that would be passed to
1076  * git-remote-curl to the "out" parameter.
1077  *
1078  * Otherwise, returns 0 and leaves "out" untouched.
1079  *
1080  * Examples:
1081  *   http::https://example.com/repo.git -> 1, https://example.com/repo.git
1082  *   https://example.com/repo.git -> 1, https://example.com/repo.git
1083  *   git://example.com/repo.git -> 0
1084  *
1085  * This is for use in checking for previously exploitable bugs that
1086  * required a submodule URL to be passed to git-remote-curl.
1087  */
1088 static int url_to_curl_url(const char *url, const char **out)
1089 {
1090         /*
1091          * We don't need to check for case-aliases, "http.exe", and so
1092          * on because in the default configuration, is_transport_allowed
1093          * prevents URLs with those schemes from being cloned
1094          * automatically.
1095          */
1096         if (skip_prefix(url, "http::", out) ||
1097             skip_prefix(url, "https::", out) ||
1098             skip_prefix(url, "ftp::", out) ||
1099             skip_prefix(url, "ftps::", out))
1100                 return 1;
1101         if (starts_with(url, "http://") ||
1102             starts_with(url, "https://") ||
1103             starts_with(url, "ftp://") ||
1104             starts_with(url, "ftps://")) {
1105                 *out = url;
1106                 return 1;
1107         }
1108         return 0;
1109 }
1110
1111 static int check_submodule_url(const char *url)
1112 {
1113         const char *curl_url;
1114
1115         if (looks_like_command_line_option(url))
1116                 return -1;
1117
1118         if (submodule_url_is_relative(url) || starts_with(url, "git://")) {
1119                 char *decoded;
1120                 const char *next;
1121                 int has_nl;
1122
1123                 /*
1124                  * This could be appended to an http URL and url-decoded;
1125                  * check for malicious characters.
1126                  */
1127                 decoded = url_decode(url);
1128                 has_nl = !!strchr(decoded, '\n');
1129
1130                 free(decoded);
1131                 if (has_nl)
1132                         return -1;
1133
1134                 /*
1135                  * URLs which escape their root via "../" can overwrite
1136                  * the host field and previous components, resolving to
1137                  * URLs like https::example.com/submodule.git and
1138                  * https:///example.com/submodule.git that were
1139                  * susceptible to CVE-2020-11008.
1140                  */
1141                 if (count_leading_dotdots(url, &next) > 0 &&
1142                     (*next == ':' || *next == '/'))
1143                         return -1;
1144         }
1145
1146         else if (url_to_curl_url(url, &curl_url)) {
1147                 struct credential c = CREDENTIAL_INIT;
1148                 int ret = 0;
1149                 if (credential_from_url_gently(&c, curl_url, 1) ||
1150                     !*c.host)
1151                         ret = -1;
1152                 credential_clear(&c);
1153                 return ret;
1154         }
1155
1156         return 0;
1157 }
1158
1159 struct fsck_gitmodules_data {
1160         const struct object_id *oid;
1161         struct fsck_options *options;
1162         int ret;
1163 };
1164
1165 static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
1166 {
1167         struct fsck_gitmodules_data *data = vdata;
1168         const char *subsection, *key;
1169         size_t subsection_len;
1170         char *name;
1171
1172         if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
1173             !subsection)
1174                 return 0;
1175
1176         name = xmemdupz(subsection, subsection_len);
1177         if (check_submodule_name(name) < 0)
1178                 data->ret |= report(data->options,
1179                                     data->oid, OBJ_BLOB,
1180                                     FSCK_MSG_GITMODULES_NAME,
1181                                     "disallowed submodule name: %s",
1182                                     name);
1183         if (!strcmp(key, "url") && value &&
1184             check_submodule_url(value) < 0)
1185                 data->ret |= report(data->options,
1186                                     data->oid, OBJ_BLOB,
1187                                     FSCK_MSG_GITMODULES_URL,
1188                                     "disallowed submodule url: %s",
1189                                     value);
1190         if (!strcmp(key, "path") && value &&
1191             looks_like_command_line_option(value))
1192                 data->ret |= report(data->options,
1193                                     data->oid, OBJ_BLOB,
1194                                     FSCK_MSG_GITMODULES_PATH,
1195                                     "disallowed submodule path: %s",
1196                                     value);
1197         if (!strcmp(key, "update") && value &&
1198             parse_submodule_update_type(value) == SM_UPDATE_COMMAND)
1199                 data->ret |= report(data->options, data->oid, OBJ_BLOB,
1200                                     FSCK_MSG_GITMODULES_UPDATE,
1201                                     "disallowed submodule update setting: %s",
1202                                     value);
1203         free(name);
1204
1205         return 0;
1206 }
1207
1208 static int fsck_blob(const struct object_id *oid, const char *buf,
1209                      unsigned long size, struct fsck_options *options)
1210 {
1211         struct fsck_gitmodules_data data;
1212         struct config_options config_opts = { 0 };
1213
1214         if (!oidset_contains(&gitmodules_found, oid))
1215                 return 0;
1216         oidset_insert(&gitmodules_done, oid);
1217
1218         if (object_on_skiplist(options, oid))
1219                 return 0;
1220
1221         if (!buf) {
1222                 /*
1223                  * A missing buffer here is a sign that the caller found the
1224                  * blob too gigantic to load into memory. Let's just consider
1225                  * that an error.
1226                  */
1227                 return report(options, oid, OBJ_BLOB,
1228                               FSCK_MSG_GITMODULES_LARGE,
1229                               ".gitmodules too large to parse");
1230         }
1231
1232         data.oid = oid;
1233         data.options = options;
1234         data.ret = 0;
1235         config_opts.error_action = CONFIG_ERROR_SILENT;
1236         if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
1237                                 ".gitmodules", buf, size, &data, &config_opts))
1238                 data.ret |= report(options, oid, OBJ_BLOB,
1239                                    FSCK_MSG_GITMODULES_PARSE,
1240                                    "could not parse gitmodules blob");
1241
1242         return data.ret;
1243 }
1244
1245 int fsck_object(struct object *obj, void *data, unsigned long size,
1246         struct fsck_options *options)
1247 {
1248         if (!obj)
1249                 return report(options, NULL, OBJ_NONE, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
1250
1251         if (obj->type == OBJ_BLOB)
1252                 return fsck_blob(&obj->oid, data, size, options);
1253         if (obj->type == OBJ_TREE)
1254                 return fsck_tree(&obj->oid, data, size, options);
1255         if (obj->type == OBJ_COMMIT)
1256                 return fsck_commit(&obj->oid, data, size, options);
1257         if (obj->type == OBJ_TAG)
1258                 return fsck_tag(&obj->oid, data, size, options);
1259
1260         return report(options, &obj->oid, obj->type,
1261                       FSCK_MSG_UNKNOWN_TYPE,
1262                       "unknown type '%d' (internal fsck error)",
1263                       obj->type);
1264 }
1265
1266 int fsck_error_function(struct fsck_options *o,
1267                         const struct object_id *oid,
1268                         enum object_type object_type,
1269                         int msg_type, const char *message)
1270 {
1271         if (msg_type == FSCK_WARN) {
1272                 warning("object %s: %s", fsck_describe_object(o, oid), message);
1273                 return 0;
1274         }
1275         error("object %s: %s", fsck_describe_object(o, oid), message);
1276         return 1;
1277 }
1278
1279 void register_found_gitmodules(const struct object_id *oid)
1280 {
1281         oidset_insert(&gitmodules_found, oid);
1282 }
1283
1284 int fsck_finish(struct fsck_options *options)
1285 {
1286         int ret = 0;
1287         struct oidset_iter iter;
1288         const struct object_id *oid;
1289
1290         oidset_iter_init(&gitmodules_found, &iter);
1291         while ((oid = oidset_iter_next(&iter))) {
1292                 enum object_type type;
1293                 unsigned long size;
1294                 char *buf;
1295
1296                 if (oidset_contains(&gitmodules_done, oid))
1297                         continue;
1298
1299                 buf = read_object_file(oid, &type, &size);
1300                 if (!buf) {
1301                         if (is_promisor_object(oid))
1302                                 continue;
1303                         ret |= report(options,
1304                                       oid, OBJ_BLOB,
1305                                       FSCK_MSG_GITMODULES_MISSING,
1306                                       "unable to read .gitmodules blob");
1307                         continue;
1308                 }
1309
1310                 if (type == OBJ_BLOB)
1311                         ret |= fsck_blob(oid, buf, size, options);
1312                 else
1313                         ret |= report(options,
1314                                       oid, type,
1315                                       FSCK_MSG_GITMODULES_BLOB,
1316                                       "non-blob found at .gitmodules");
1317                 free(buf);
1318         }
1319
1320
1321         oidset_clear(&gitmodules_found);
1322         oidset_clear(&gitmodules_done);
1323         return ret;
1324 }
1325
1326 int fsck_config_internal(const char *var, const char *value, void *cb,
1327                          struct fsck_options *options)
1328 {
1329         if (strcmp(var, "fsck.skiplist") == 0) {
1330                 const char *path;
1331                 struct strbuf sb = STRBUF_INIT;
1332
1333                 if (git_config_pathname(&path, var, value))
1334                         return 1;
1335                 strbuf_addf(&sb, "skiplist=%s", path);
1336                 free((char *)path);
1337                 fsck_set_msg_types(options, sb.buf);
1338                 strbuf_release(&sb);
1339                 return 0;
1340         }
1341
1342         if (skip_prefix(var, "fsck.", &var)) {
1343                 fsck_set_msg_type(options, var, value);
1344                 return 0;
1345         }
1346
1347         return git_default_config(var, value, cb);
1348 }