Imported Upstream version 2.18.3
[platform/upstream/git.git] / fsck.c
1 #include "cache.h"
2 #include "object.h"
3 #include "blob.h"
4 #include "tree.h"
5 #include "tree-walk.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "fsck.h"
9 #include "refs.h"
10 #include "utf8.h"
11 #include "sha1-array.h"
12 #include "decorate.h"
13 #include "oidset.h"
14 #include "packfile.h"
15 #include "submodule-config.h"
16 #include "config.h"
17 #include "credential.h"
18
19 static struct oidset gitmodules_found = OIDSET_INIT;
20 static struct oidset gitmodules_done = OIDSET_INIT;
21
22 #define FSCK_FATAL -1
23 #define FSCK_INFO -2
24
25 #define FOREACH_MSG_ID(FUNC) \
26         /* fatal errors */ \
27         FUNC(NUL_IN_HEADER, FATAL) \
28         FUNC(UNTERMINATED_HEADER, FATAL) \
29         /* errors */ \
30         FUNC(BAD_DATE, ERROR) \
31         FUNC(BAD_DATE_OVERFLOW, ERROR) \
32         FUNC(BAD_EMAIL, ERROR) \
33         FUNC(BAD_NAME, ERROR) \
34         FUNC(BAD_OBJECT_SHA1, ERROR) \
35         FUNC(BAD_PARENT_SHA1, ERROR) \
36         FUNC(BAD_TAG_OBJECT, ERROR) \
37         FUNC(BAD_TIMEZONE, ERROR) \
38         FUNC(BAD_TREE, ERROR) \
39         FUNC(BAD_TREE_SHA1, ERROR) \
40         FUNC(BAD_TYPE, ERROR) \
41         FUNC(DUPLICATE_ENTRIES, ERROR) \
42         FUNC(MISSING_AUTHOR, ERROR) \
43         FUNC(MISSING_COMMITTER, ERROR) \
44         FUNC(MISSING_EMAIL, ERROR) \
45         FUNC(MISSING_GRAFT, ERROR) \
46         FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \
47         FUNC(MISSING_OBJECT, ERROR) \
48         FUNC(MISSING_PARENT, ERROR) \
49         FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \
50         FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \
51         FUNC(MISSING_TAG, ERROR) \
52         FUNC(MISSING_TAG_ENTRY, ERROR) \
53         FUNC(MISSING_TAG_OBJECT, 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(TAG_OBJECT_NOT_TAG, ERROR) \
60         FUNC(TREE_NOT_SORTED, ERROR) \
61         FUNC(UNKNOWN_TYPE, ERROR) \
62         FUNC(ZERO_PADDED_DATE, ERROR) \
63         FUNC(GITMODULES_MISSING, ERROR) \
64         FUNC(GITMODULES_BLOB, ERROR) \
65         FUNC(GITMODULES_PARSE, ERROR) \
66         FUNC(GITMODULES_NAME, ERROR) \
67         FUNC(GITMODULES_SYMLINK, ERROR) \
68         FUNC(GITMODULES_URL, ERROR) \
69         FUNC(GITMODULES_PATH, ERROR) \
70         FUNC(GITMODULES_UPDATE, ERROR) \
71         /* warnings */ \
72         FUNC(BAD_FILEMODE, WARN) \
73         FUNC(EMPTY_NAME, WARN) \
74         FUNC(FULL_PATHNAME, WARN) \
75         FUNC(HAS_DOT, WARN) \
76         FUNC(HAS_DOTDOT, WARN) \
77         FUNC(HAS_DOTGIT, WARN) \
78         FUNC(NULL_SHA1, WARN) \
79         FUNC(ZERO_PADDED_FILEMODE, WARN) \
80         FUNC(NUL_IN_COMMIT, WARN) \
81         /* infos (reported as warnings, but ignored by default) */ \
82         FUNC(BAD_TAG_NAME, INFO) \
83         FUNC(MISSING_TAGGER_ENTRY, INFO)
84
85 #define MSG_ID(id, msg_type) FSCK_MSG_##id,
86 enum fsck_msg_id {
87         FOREACH_MSG_ID(MSG_ID)
88         FSCK_MSG_MAX
89 };
90 #undef MSG_ID
91
92 #define STR(x) #x
93 #define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type },
94 static struct {
95         const char *id_string;
96         const char *downcased;
97         int msg_type;
98 } msg_id_info[FSCK_MSG_MAX + 1] = {
99         FOREACH_MSG_ID(MSG_ID)
100         { NULL, NULL, -1 }
101 };
102 #undef MSG_ID
103
104 static int parse_msg_id(const char *text)
105 {
106         int i;
107
108         if (!msg_id_info[0].downcased) {
109                 /* convert id_string to lower case, without underscores. */
110                 for (i = 0; i < FSCK_MSG_MAX; i++) {
111                         const char *p = msg_id_info[i].id_string;
112                         int len = strlen(p);
113                         char *q = xmalloc(len);
114
115                         msg_id_info[i].downcased = q;
116                         while (*p)
117                                 if (*p == '_')
118                                         p++;
119                                 else
120                                         *(q)++ = tolower(*(p)++);
121                         *q = '\0';
122                 }
123         }
124
125         for (i = 0; i < FSCK_MSG_MAX; i++)
126                 if (!strcmp(text, msg_id_info[i].downcased))
127                         return i;
128
129         return -1;
130 }
131
132 static int fsck_msg_type(enum fsck_msg_id msg_id,
133         struct fsck_options *options)
134 {
135         int msg_type;
136
137         assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX);
138
139         if (options->msg_type)
140                 msg_type = options->msg_type[msg_id];
141         else {
142                 msg_type = msg_id_info[msg_id].msg_type;
143                 if (options->strict && msg_type == FSCK_WARN)
144                         msg_type = FSCK_ERROR;
145         }
146
147         return msg_type;
148 }
149
150 static void init_skiplist(struct fsck_options *options, const char *path)
151 {
152         static struct oid_array skiplist = OID_ARRAY_INIT;
153         int sorted, fd;
154         char buffer[GIT_MAX_HEXSZ + 1];
155         struct object_id oid;
156
157         if (options->skiplist)
158                 sorted = options->skiplist->sorted;
159         else {
160                 sorted = 1;
161                 options->skiplist = &skiplist;
162         }
163
164         fd = open(path, O_RDONLY);
165         if (fd < 0)
166                 die("Could not open skip list: %s", path);
167         for (;;) {
168                 const char *p;
169                 int result = read_in_full(fd, buffer, sizeof(buffer));
170                 if (result < 0)
171                         die_errno("Could not read '%s'", path);
172                 if (!result)
173                         break;
174                 if (parse_oid_hex(buffer, &oid, &p) || *p != '\n')
175                         die("Invalid SHA-1: %s", buffer);
176                 oid_array_append(&skiplist, &oid);
177                 if (sorted && skiplist.nr > 1 &&
178                                 oidcmp(&skiplist.oid[skiplist.nr - 2],
179                                        &oid) > 0)
180                         sorted = 0;
181         }
182         close(fd);
183
184         if (sorted)
185                 skiplist.sorted = 1;
186 }
187
188 static int parse_msg_type(const char *str)
189 {
190         if (!strcmp(str, "error"))
191                 return FSCK_ERROR;
192         else if (!strcmp(str, "warn"))
193                 return FSCK_WARN;
194         else if (!strcmp(str, "ignore"))
195                 return FSCK_IGNORE;
196         else
197                 die("Unknown fsck message type: '%s'", str);
198 }
199
200 int is_valid_msg_type(const char *msg_id, const char *msg_type)
201 {
202         if (parse_msg_id(msg_id) < 0)
203                 return 0;
204         parse_msg_type(msg_type);
205         return 1;
206 }
207
208 void fsck_set_msg_type(struct fsck_options *options,
209                 const char *msg_id, const char *msg_type)
210 {
211         int id = parse_msg_id(msg_id), type;
212
213         if (id < 0)
214                 die("Unhandled message id: %s", msg_id);
215         type = parse_msg_type(msg_type);
216
217         if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL)
218                 die("Cannot demote %s to %s", msg_id, msg_type);
219
220         if (!options->msg_type) {
221                 int i;
222                 int *msg_type;
223                 ALLOC_ARRAY(msg_type, FSCK_MSG_MAX);
224                 for (i = 0; i < FSCK_MSG_MAX; i++)
225                         msg_type[i] = fsck_msg_type(i, options);
226                 options->msg_type = msg_type;
227         }
228
229         options->msg_type[id] = type;
230 }
231
232 void fsck_set_msg_types(struct fsck_options *options, const char *values)
233 {
234         char *buf = xstrdup(values), *to_free = buf;
235         int done = 0;
236
237         while (!done) {
238                 int len = strcspn(buf, " ,|"), equal;
239
240                 done = !buf[len];
241                 if (!len) {
242                         buf++;
243                         continue;
244                 }
245                 buf[len] = '\0';
246
247                 for (equal = 0;
248                      equal < len && buf[equal] != '=' && buf[equal] != ':';
249                      equal++)
250                         buf[equal] = tolower(buf[equal]);
251                 buf[equal] = '\0';
252
253                 if (!strcmp(buf, "skiplist")) {
254                         if (equal == len)
255                                 die("skiplist requires a path");
256                         init_skiplist(options, buf + equal + 1);
257                         buf += len + 1;
258                         continue;
259                 }
260
261                 if (equal == len)
262                         die("Missing '=': '%s'", buf);
263
264                 fsck_set_msg_type(options, buf, buf + equal + 1);
265                 buf += len + 1;
266         }
267         free(to_free);
268 }
269
270 static void append_msg_id(struct strbuf *sb, const char *msg_id)
271 {
272         for (;;) {
273                 char c = *(msg_id)++;
274
275                 if (!c)
276                         break;
277                 if (c != '_')
278                         strbuf_addch(sb, tolower(c));
279                 else {
280                         assert(*msg_id);
281                         strbuf_addch(sb, *(msg_id)++);
282                 }
283         }
284
285         strbuf_addstr(sb, ": ");
286 }
287
288 __attribute__((format (printf, 4, 5)))
289 static int report(struct fsck_options *options, struct object *object,
290         enum fsck_msg_id id, const char *fmt, ...)
291 {
292         va_list ap;
293         struct strbuf sb = STRBUF_INIT;
294         int msg_type = fsck_msg_type(id, options), result;
295
296         if (msg_type == FSCK_IGNORE)
297                 return 0;
298
299         if (options->skiplist && object &&
300                         oid_array_lookup(options->skiplist, &object->oid) >= 0)
301                 return 0;
302
303         if (msg_type == FSCK_FATAL)
304                 msg_type = FSCK_ERROR;
305         else if (msg_type == FSCK_INFO)
306                 msg_type = FSCK_WARN;
307
308         append_msg_id(&sb, msg_id_info[id].id_string);
309
310         va_start(ap, fmt);
311         strbuf_vaddf(&sb, fmt, ap);
312         result = options->error_func(options, object, msg_type, sb.buf);
313         strbuf_release(&sb);
314         va_end(ap);
315
316         return result;
317 }
318
319 static char *get_object_name(struct fsck_options *options, struct object *obj)
320 {
321         if (!options->object_names)
322                 return NULL;
323         return lookup_decoration(options->object_names, obj);
324 }
325
326 static void put_object_name(struct fsck_options *options, struct object *obj,
327         const char *fmt, ...)
328 {
329         va_list ap;
330         struct strbuf buf = STRBUF_INIT;
331         char *existing;
332
333         if (!options->object_names)
334                 return;
335         existing = lookup_decoration(options->object_names, obj);
336         if (existing)
337                 return;
338         va_start(ap, fmt);
339         strbuf_vaddf(&buf, fmt, ap);
340         add_decoration(options->object_names, obj, strbuf_detach(&buf, NULL));
341         va_end(ap);
342 }
343
344 static const char *describe_object(struct fsck_options *o, struct object *obj)
345 {
346         static struct strbuf buf = STRBUF_INIT;
347         char *name;
348
349         strbuf_reset(&buf);
350         strbuf_addstr(&buf, oid_to_hex(&obj->oid));
351         if (o->object_names && (name = lookup_decoration(o->object_names, obj)))
352                 strbuf_addf(&buf, " (%s)", name);
353
354         return buf.buf;
355 }
356
357 static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options)
358 {
359         struct tree_desc desc;
360         struct name_entry entry;
361         int res = 0;
362         const char *name;
363
364         if (parse_tree(tree))
365                 return -1;
366
367         name = get_object_name(options, &tree->object);
368         if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
369                 return -1;
370         while (tree_entry_gently(&desc, &entry)) {
371                 struct object *obj;
372                 int result;
373
374                 if (S_ISGITLINK(entry.mode))
375                         continue;
376
377                 if (S_ISDIR(entry.mode)) {
378                         obj = (struct object *)lookup_tree(entry.oid);
379                         if (name && obj)
380                                 put_object_name(options, obj, "%s%s/", name,
381                                         entry.path);
382                         result = options->walk(obj, OBJ_TREE, data, options);
383                 }
384                 else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) {
385                         obj = (struct object *)lookup_blob(entry.oid);
386                         if (name && obj)
387                                 put_object_name(options, obj, "%s%s", name,
388                                         entry.path);
389                         result = options->walk(obj, OBJ_BLOB, data, options);
390                 }
391                 else {
392                         result = error("in tree %s: entry %s has bad mode %.6o",
393                                         describe_object(options, &tree->object), entry.path, entry.mode);
394                 }
395                 if (result < 0)
396                         return result;
397                 if (!res)
398                         res = result;
399         }
400         return res;
401 }
402
403 static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options)
404 {
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;
410
411         if (parse_commit(commit))
412                 return -1;
413
414         name = get_object_name(options, &commit->object);
415         if (name)
416                 put_object_name(options, &get_commit_tree(commit)->object,
417                                 "%s:", name);
418
419         result = options->walk((struct object *)get_commit_tree(commit),
420                                OBJ_TREE, data, options);
421         if (result < 0)
422                 return result;
423         res = result;
424
425         parents = commit->parents;
426         if (name && parents) {
427                 int len = strlen(name), power;
428
429                 if (len && name[len - 1] == '^') {
430                         generation = 1;
431                         name_prefix_len = len - 1;
432                 }
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                 }
441         }
442
443         while (parents) {
444                 if (name) {
445                         struct object *obj = &parents->item->object;
446
447                         if (++counter > 1)
448                                 put_object_name(options, obj, "%s^%d",
449                                         name, counter);
450                         else if (generation > 0)
451                                 put_object_name(options, obj, "%.*s~%d",
452                                         name_prefix_len, name, generation + 1);
453                         else
454                                 put_object_name(options, obj, "%s^", name);
455                 }
456                 result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options);
457                 if (result < 0)
458                         return result;
459                 if (!res)
460                         res = result;
461                 parents = parents->next;
462         }
463         return res;
464 }
465
466 static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options)
467 {
468         char *name = get_object_name(options, &tag->object);
469
470         if (parse_tag(tag))
471                 return -1;
472         if (name)
473                 put_object_name(options, tag->tagged, "%s", name);
474         return options->walk(tag->tagged, OBJ_ANY, data, options);
475 }
476
477 int fsck_walk(struct object *obj, void *data, struct fsck_options *options)
478 {
479         if (!obj)
480                 return -1;
481
482         if (obj->type == OBJ_NONE)
483                 parse_object(&obj->oid);
484
485         switch (obj->type) {
486         case OBJ_BLOB:
487                 return 0;
488         case OBJ_TREE:
489                 return fsck_walk_tree((struct tree *)obj, data, options);
490         case OBJ_COMMIT:
491                 return fsck_walk_commit((struct commit *)obj, data, options);
492         case OBJ_TAG:
493                 return fsck_walk_tag((struct tag *)obj, data, options);
494         default:
495                 error("Unknown object type for %s", describe_object(options, obj));
496                 return -1;
497         }
498 }
499
500 /*
501  * The entries in a tree are ordered in the _path_ order,
502  * which means that a directory entry is ordered by adding
503  * a slash to the end of it.
504  *
505  * So a directory called "a" is ordered _after_ a file
506  * called "a.c", because "a/" sorts after "a.c".
507  */
508 #define TREE_UNORDERED (-1)
509 #define TREE_HAS_DUPS  (-2)
510
511 static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
512 {
513         int len1 = strlen(name1);
514         int len2 = strlen(name2);
515         int len = len1 < len2 ? len1 : len2;
516         unsigned char c1, c2;
517         int cmp;
518
519         cmp = memcmp(name1, name2, len);
520         if (cmp < 0)
521                 return 0;
522         if (cmp > 0)
523                 return TREE_UNORDERED;
524
525         /*
526          * Ok, the first <len> characters are the same.
527          * Now we need to order the next one, but turn
528          * a '\0' into a '/' for a directory entry.
529          */
530         c1 = name1[len];
531         c2 = name2[len];
532         if (!c1 && !c2)
533                 /*
534                  * git-write-tree used to write out a nonsense tree that has
535                  * entries with the same name, one blob and one tree.  Make
536                  * sure we do not have duplicate entries.
537                  */
538                 return TREE_HAS_DUPS;
539         if (!c1 && S_ISDIR(mode1))
540                 c1 = '/';
541         if (!c2 && S_ISDIR(mode2))
542                 c2 = '/';
543         return c1 < c2 ? 0 : TREE_UNORDERED;
544 }
545
546 static int fsck_tree(struct tree *item, struct fsck_options *options)
547 {
548         int retval = 0;
549         int has_null_sha1 = 0;
550         int has_full_path = 0;
551         int has_empty_name = 0;
552         int has_dot = 0;
553         int has_dotdot = 0;
554         int has_dotgit = 0;
555         int has_zero_pad = 0;
556         int has_bad_modes = 0;
557         int has_dup_entries = 0;
558         int not_properly_sorted = 0;
559         struct tree_desc desc;
560         unsigned o_mode;
561         const char *o_name;
562
563         if (init_tree_desc_gently(&desc, item->buffer, item->size)) {
564                 retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
565                 return retval;
566         }
567
568         o_mode = 0;
569         o_name = NULL;
570
571         while (desc.size) {
572                 unsigned mode;
573                 const char *name, *backslash;
574                 const struct object_id *oid;
575
576                 oid = tree_entry_extract(&desc, &name, &mode);
577
578                 has_null_sha1 |= is_null_oid(oid);
579                 has_full_path |= !!strchr(name, '/');
580                 has_empty_name |= !*name;
581                 has_dot |= !strcmp(name, ".");
582                 has_dotdot |= !strcmp(name, "..");
583                 has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
584                 has_zero_pad |= *(char *)desc.buffer == '0';
585
586                 if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
587                         if (!S_ISLNK(mode))
588                                 oidset_insert(&gitmodules_found, oid);
589                         else
590                                 retval += report(options, &item->object,
591                                                  FSCK_MSG_GITMODULES_SYMLINK,
592                                                  ".gitmodules is a symbolic link");
593                 }
594
595                 if ((backslash = strchr(name, '\\'))) {
596                         while (backslash) {
597                                 backslash++;
598                                 has_dotgit |= is_ntfs_dotgit(backslash);
599                                 if (is_ntfs_dotgitmodules(backslash)) {
600                                         if (!S_ISLNK(mode))
601                                                 oidset_insert(&gitmodules_found, oid);
602                                         else
603                                                 retval += report(options, &item->object,
604                                                                  FSCK_MSG_GITMODULES_SYMLINK,
605                                                                  ".gitmodules is a symbolic link");
606                                 }
607                                 backslash = strchr(backslash, '\\');
608                         }
609                 }
610
611                 if (update_tree_entry_gently(&desc)) {
612                         retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
613                         break;
614                 }
615
616                 switch (mode) {
617                 /*
618                  * Standard modes..
619                  */
620                 case S_IFREG | 0755:
621                 case S_IFREG | 0644:
622                 case S_IFLNK:
623                 case S_IFDIR:
624                 case S_IFGITLINK:
625                         break;
626                 /*
627                  * This is nonstandard, but we had a few of these
628                  * early on when we honored the full set of mode
629                  * bits..
630                  */
631                 case S_IFREG | 0664:
632                         if (!options->strict)
633                                 break;
634                         /* fallthrough */
635                 default:
636                         has_bad_modes = 1;
637                 }
638
639                 if (o_name) {
640                         switch (verify_ordered(o_mode, o_name, mode, name)) {
641                         case TREE_UNORDERED:
642                                 not_properly_sorted = 1;
643                                 break;
644                         case TREE_HAS_DUPS:
645                                 has_dup_entries = 1;
646                                 break;
647                         default:
648                                 break;
649                         }
650                 }
651
652                 o_mode = mode;
653                 o_name = name;
654         }
655
656         if (has_null_sha1)
657                 retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1");
658         if (has_full_path)
659                 retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames");
660         if (has_empty_name)
661                 retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname");
662         if (has_dot)
663                 retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'");
664         if (has_dotdot)
665                 retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'");
666         if (has_dotgit)
667                 retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'");
668         if (has_zero_pad)
669                 retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes");
670         if (has_bad_modes)
671                 retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes");
672         if (has_dup_entries)
673                 retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries");
674         if (not_properly_sorted)
675                 retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted");
676         return retval;
677 }
678
679 static int verify_headers(const void *data, unsigned long size,
680                           struct object *obj, struct fsck_options *options)
681 {
682         const char *buffer = (const char *)data;
683         unsigned long i;
684
685         for (i = 0; i < size; i++) {
686                 switch (buffer[i]) {
687                 case '\0':
688                         return report(options, obj,
689                                 FSCK_MSG_NUL_IN_HEADER,
690                                 "unterminated header: NUL at offset %ld", i);
691                 case '\n':
692                         if (i + 1 < size && buffer[i + 1] == '\n')
693                                 return 0;
694                 }
695         }
696
697         /*
698          * We did not find double-LF that separates the header
699          * and the body.  Not having a body is not a crime but
700          * we do want to see the terminating LF for the last header
701          * line.
702          */
703         if (size && buffer[size - 1] == '\n')
704                 return 0;
705
706         return report(options, obj,
707                 FSCK_MSG_UNTERMINATED_HEADER, "unterminated header");
708 }
709
710 static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options)
711 {
712         const char *p = *ident;
713         char *end;
714
715         *ident = strchrnul(*ident, '\n');
716         if (**ident == '\n')
717                 (*ident)++;
718
719         if (*p == '<')
720                 return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
721         p += strcspn(p, "<>\n");
722         if (*p == '>')
723                 return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name");
724         if (*p != '<')
725                 return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email");
726         if (p[-1] != ' ')
727                 return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
728         p++;
729         p += strcspn(p, "<>\n");
730         if (*p != '>')
731                 return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email");
732         p++;
733         if (*p != ' ')
734                 return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date");
735         p++;
736         if (*p == '0' && p[1] != ' ')
737                 return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date");
738         if (date_overflows(parse_timestamp(p, &end, 10)))
739                 return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow");
740         if ((end == p || *end != ' '))
741                 return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date");
742         p = end + 1;
743         if ((*p != '+' && *p != '-') ||
744             !isdigit(p[1]) ||
745             !isdigit(p[2]) ||
746             !isdigit(p[3]) ||
747             !isdigit(p[4]) ||
748             (p[5] != '\n'))
749                 return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone");
750         p += 6;
751         return 0;
752 }
753
754 static int fsck_commit_buffer(struct commit *commit, const char *buffer,
755         unsigned long size, struct fsck_options *options)
756 {
757         struct object_id tree_oid, oid;
758         struct commit_graft *graft;
759         unsigned parent_count, parent_line_count = 0, author_count;
760         int err;
761         const char *buffer_begin = buffer;
762         const char *p;
763
764         if (verify_headers(buffer, size, &commit->object, options))
765                 return -1;
766
767         if (!skip_prefix(buffer, "tree ", &buffer))
768                 return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
769         if (parse_oid_hex(buffer, &tree_oid, &p) || *p != '\n') {
770                 err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
771                 if (err)
772                         return err;
773         }
774         buffer = p + 1;
775         while (skip_prefix(buffer, "parent ", &buffer)) {
776                 if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') {
777                         err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
778                         if (err)
779                                 return err;
780                 }
781                 buffer = p + 1;
782                 parent_line_count++;
783         }
784         graft = lookup_commit_graft(&commit->object.oid);
785         parent_count = commit_list_count(commit->parents);
786         if (graft) {
787                 if (graft->nr_parent == -1 && !parent_count)
788                         ; /* shallow commit */
789                 else if (graft->nr_parent != parent_count) {
790                         err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing");
791                         if (err)
792                                 return err;
793                 }
794         } else {
795                 if (parent_count != parent_line_count) {
796                         err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing");
797                         if (err)
798                                 return err;
799                 }
800         }
801         author_count = 0;
802         while (skip_prefix(buffer, "author ", &buffer)) {
803                 author_count++;
804                 err = fsck_ident(&buffer, &commit->object, options);
805                 if (err)
806                         return err;
807         }
808         if (author_count < 1)
809                 err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line");
810         else if (author_count > 1)
811                 err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines");
812         if (err)
813                 return err;
814         if (!skip_prefix(buffer, "committer ", &buffer))
815                 return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line");
816         err = fsck_ident(&buffer, &commit->object, options);
817         if (err)
818                 return err;
819         if (!get_commit_tree(commit)) {
820                 err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", oid_to_hex(&tree_oid));
821                 if (err)
822                         return err;
823         }
824         if (memchr(buffer_begin, '\0', size)) {
825                 err = report(options, &commit->object, FSCK_MSG_NUL_IN_COMMIT,
826                              "NUL byte in the commit object body");
827                 if (err)
828                         return err;
829         }
830         return 0;
831 }
832
833 static int fsck_commit(struct commit *commit, const char *data,
834         unsigned long size, struct fsck_options *options)
835 {
836         const char *buffer = data ?  data : get_commit_buffer(commit, &size);
837         int ret = fsck_commit_buffer(commit, buffer, size, options);
838         if (!data)
839                 unuse_commit_buffer(commit, buffer);
840         return ret;
841 }
842
843 static int fsck_tag_buffer(struct tag *tag, const char *data,
844         unsigned long size, struct fsck_options *options)
845 {
846         struct object_id oid;
847         int ret = 0;
848         const char *buffer;
849         char *to_free = NULL, *eol;
850         struct strbuf sb = STRBUF_INIT;
851         const char *p;
852
853         if (data)
854                 buffer = data;
855         else {
856                 enum object_type type;
857
858                 buffer = to_free =
859                         read_object_file(&tag->object.oid, &type, &size);
860                 if (!buffer)
861                         return report(options, &tag->object,
862                                 FSCK_MSG_MISSING_TAG_OBJECT,
863                                 "cannot read tag object");
864
865                 if (type != OBJ_TAG) {
866                         ret = report(options, &tag->object,
867                                 FSCK_MSG_TAG_OBJECT_NOT_TAG,
868                                 "expected tag got %s",
869                             type_name(type));
870                         goto done;
871                 }
872         }
873
874         ret = verify_headers(buffer, size, &tag->object, options);
875         if (ret)
876                 goto done;
877
878         if (!skip_prefix(buffer, "object ", &buffer)) {
879                 ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
880                 goto done;
881         }
882         if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') {
883                 ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
884                 if (ret)
885                         goto done;
886         }
887         buffer = p + 1;
888
889         if (!skip_prefix(buffer, "type ", &buffer)) {
890                 ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
891                 goto done;
892         }
893         eol = strchr(buffer, '\n');
894         if (!eol) {
895                 ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line");
896                 goto done;
897         }
898         if (type_from_string_gently(buffer, eol - buffer, 1) < 0)
899                 ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value");
900         if (ret)
901                 goto done;
902         buffer = eol + 1;
903
904         if (!skip_prefix(buffer, "tag ", &buffer)) {
905                 ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line");
906                 goto done;
907         }
908         eol = strchr(buffer, '\n');
909         if (!eol) {
910                 ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line");
911                 goto done;
912         }
913         strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
914         if (check_refname_format(sb.buf, 0)) {
915                 ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME,
916                            "invalid 'tag' name: %.*s",
917                            (int)(eol - buffer), buffer);
918                 if (ret)
919                         goto done;
920         }
921         buffer = eol + 1;
922
923         if (!skip_prefix(buffer, "tagger ", &buffer)) {
924                 /* early tags do not contain 'tagger' lines; warn only */
925                 ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line");
926                 if (ret)
927                         goto done;
928         }
929         else
930                 ret = fsck_ident(&buffer, &tag->object, options);
931
932 done:
933         strbuf_release(&sb);
934         free(to_free);
935         return ret;
936 }
937
938 static int fsck_tag(struct tag *tag, const char *data,
939         unsigned long size, struct fsck_options *options)
940 {
941         struct object *tagged = tag->tagged;
942
943         if (!tagged)
944                 return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object");
945
946         return fsck_tag_buffer(tag, data, size, options);
947 }
948
949 static int check_submodule_url(const char *url)
950 {
951         struct credential c = CREDENTIAL_INIT;
952         int ret;
953
954         if (looks_like_command_line_option(url))
955                 return -1;
956
957         ret = credential_from_url_gently(&c, url, 1);
958         credential_clear(&c);
959         return ret;
960 }
961
962 struct fsck_gitmodules_data {
963         struct object *obj;
964         struct fsck_options *options;
965         int ret;
966 };
967
968 static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
969 {
970         struct fsck_gitmodules_data *data = vdata;
971         const char *subsection, *key;
972         int subsection_len;
973         char *name;
974
975         if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
976             !subsection)
977                 return 0;
978
979         name = xmemdupz(subsection, subsection_len);
980         if (check_submodule_name(name) < 0)
981                 data->ret |= report(data->options, data->obj,
982                                     FSCK_MSG_GITMODULES_NAME,
983                                     "disallowed submodule name: %s",
984                                     name);
985         if (!strcmp(key, "url") && value &&
986             check_submodule_url(value) < 0)
987                 data->ret |= report(data->options, data->obj,
988                                     FSCK_MSG_GITMODULES_URL,
989                                     "disallowed submodule url: %s",
990                                     value);
991         if (!strcmp(key, "path") && value &&
992             looks_like_command_line_option(value))
993                 data->ret |= report(data->options, data->obj,
994                                     FSCK_MSG_GITMODULES_PATH,
995                                     "disallowed submodule path: %s",
996                                     value);
997         if (!strcmp(key, "update") && value &&
998             parse_submodule_update_type(value) == SM_UPDATE_COMMAND)
999                 data->ret |= report(data->options, data->obj,
1000                                     FSCK_MSG_GITMODULES_UPDATE,
1001                                     "disallowed submodule update setting: %s",
1002                                     value);
1003         free(name);
1004
1005         return 0;
1006 }
1007
1008 static int fsck_blob(struct blob *blob, const char *buf,
1009                      unsigned long size, struct fsck_options *options)
1010 {
1011         struct fsck_gitmodules_data data;
1012
1013         if (!oidset_contains(&gitmodules_found, &blob->object.oid))
1014                 return 0;
1015         oidset_insert(&gitmodules_done, &blob->object.oid);
1016
1017         if (!buf) {
1018                 /*
1019                  * A missing buffer here is a sign that the caller found the
1020                  * blob too gigantic to load into memory. Let's just consider
1021                  * that an error.
1022                  */
1023                 return report(options, &blob->object,
1024                               FSCK_MSG_GITMODULES_PARSE,
1025                               ".gitmodules too large to parse");
1026         }
1027
1028         data.obj = &blob->object;
1029         data.options = options;
1030         data.ret = 0;
1031         if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
1032                                 ".gitmodules", buf, size, &data))
1033                 data.ret |= report(options, &blob->object,
1034                                    FSCK_MSG_GITMODULES_PARSE,
1035                                    "could not parse gitmodules blob");
1036
1037         return data.ret;
1038 }
1039
1040 int fsck_object(struct object *obj, void *data, unsigned long size,
1041         struct fsck_options *options)
1042 {
1043         if (!obj)
1044                 return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
1045
1046         if (obj->type == OBJ_BLOB)
1047                 return fsck_blob((struct blob *)obj, data, size, options);
1048         if (obj->type == OBJ_TREE)
1049                 return fsck_tree((struct tree *) obj, options);
1050         if (obj->type == OBJ_COMMIT)
1051                 return fsck_commit((struct commit *) obj, (const char *) data,
1052                         size, options);
1053         if (obj->type == OBJ_TAG)
1054                 return fsck_tag((struct tag *) obj, (const char *) data,
1055                         size, options);
1056
1057         return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)",
1058                           obj->type);
1059 }
1060
1061 int fsck_error_function(struct fsck_options *o,
1062         struct object *obj, int msg_type, const char *message)
1063 {
1064         if (msg_type == FSCK_WARN) {
1065                 warning("object %s: %s", describe_object(o, obj), message);
1066                 return 0;
1067         }
1068         error("object %s: %s", describe_object(o, obj), message);
1069         return 1;
1070 }
1071
1072 int fsck_finish(struct fsck_options *options)
1073 {
1074         int ret = 0;
1075         struct oidset_iter iter;
1076         const struct object_id *oid;
1077
1078         oidset_iter_init(&gitmodules_found, &iter);
1079         while ((oid = oidset_iter_next(&iter))) {
1080                 struct blob *blob;
1081                 enum object_type type;
1082                 unsigned long size;
1083                 char *buf;
1084
1085                 if (oidset_contains(&gitmodules_done, oid))
1086                         continue;
1087
1088                 blob = lookup_blob(oid);
1089                 if (!blob) {
1090                         struct object *obj = lookup_unknown_object(oid->hash);
1091                         ret |= report(options, obj,
1092                                       FSCK_MSG_GITMODULES_BLOB,
1093                                       "non-blob found at .gitmodules");
1094                         continue;
1095                 }
1096
1097                 buf = read_object_file(oid, &type, &size);
1098                 if (!buf) {
1099                         if (is_promisor_object(&blob->object.oid))
1100                                 continue;
1101                         ret |= report(options, &blob->object,
1102                                       FSCK_MSG_GITMODULES_MISSING,
1103                                       "unable to read .gitmodules blob");
1104                         continue;
1105                 }
1106
1107                 if (type == OBJ_BLOB)
1108                         ret |= fsck_blob(blob, buf, size, options);
1109                 else
1110                         ret |= report(options, &blob->object,
1111                                       FSCK_MSG_GITMODULES_BLOB,
1112                                       "non-blob found at .gitmodules");
1113                 free(buf);
1114         }
1115
1116
1117         oidset_clear(&gitmodules_found);
1118         oidset_clear(&gitmodules_done);
1119         return ret;
1120 }