summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/distinfo.go
blob: fcb5793cef8456044185ddd342ec02b449d38714 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package pkglint

import (
	"bytes"
	"crypto/sha1"
	"crypto/sha512"
	"encoding/hex"
	"golang.org/x/crypto/ripemd160"
	"hash"
	"io"
	"strings"
)

func CheckLinesDistinfo(pkg *Package, lines *Lines) {
	if trace.Tracing {
		defer trace.Call(lines.Filename)()
	}

	filename := lines.Filename
	patchdir := NewPackagePath("patches")
	if pkg != nil && pkg.File(pkg.Patchdir).IsDir() {
		patchdir = pkg.Patchdir
	}
	if trace.Tracing {
		trace.Stepf("patchdir=%q", patchdir)
	}

	distinfoIsCommitted := isCommitted(filename)
	ck := distinfoLinesChecker{
		pkg, lines, patchdir, distinfoIsCommitted,
		nil, make(map[RelPath]distinfoFileInfo)}
	ck.parse()
	ck.check()
	CheckLinesTrailingEmptyLines(lines)
	ck.checkUnrecordedPatches()

	SaveAutofixChanges(lines)
}

type distinfoLinesChecker struct {
	pkg                 *Package
	lines               *Lines
	patchdir            PackagePath
	distinfoIsCommitted bool

	filenames []RelPath // For keeping the order from top to bottom
	infos     map[RelPath]distinfoFileInfo
}

func (ck *distinfoLinesChecker) parse() {
	lines := ck.lines

	llex := NewLinesLexer(lines)
	if !llex.EOF() && lines.CheckCvsID(0, ``, "") {
		llex.Skip()
	}
	llex.SkipEmptyOrNote()

	prevFilename := NewRelPath("")
	var hashes []distinfoHash

	isPatch := func() YesNoUnknown {
		switch {
		case !prevFilename.HasPrefixText("patch-"):
			return no
		case ck.pkg == nil:
			return unknown
		case ck.pkg.File(ck.patchdir.JoinNoClean(prevFilename)).IsFile():
			return yes
		default:
			return no
		}
	}

	finishGroup := func() {
		ck.filenames = append(ck.filenames, prevFilename)
		ck.infos[prevFilename] = distinfoFileInfo{isPatch(), hashes}
		hashes = nil
	}

	for !llex.EOF() {
		line := llex.CurrentLine()
		llex.Skip()

		m, alg, file, hash := match3(line.Text, `^(\w+) \((\w[^)]*)\) = (\S+(?: bytes)?)$`)
		filename := NewRelPathString(file)
		if !m {
			line.Errorf("Invalid line: %s", line.Text)
			continue
		}

		if !prevFilename.IsEmpty() && filename != prevFilename {
			finishGroup()
		}
		prevFilename = filename

		hashes = append(hashes, distinfoHash{line, filename, alg, hash})
	}

	if !prevFilename.IsEmpty() {
		finishGroup()
	}
}

func (ck *distinfoLinesChecker) check() {
	for _, filename := range ck.filenames {
		info := ck.infos[filename]

		ck.checkAlgorithms(info)
		for _, hash := range info.hashes {
			ck.checkGlobalDistfileMismatch(hash)
			if info.isPatch == yes {
				ck.checkUncommittedPatch(hash)
			}
		}
	}
}

func (ck *distinfoLinesChecker) checkAlgorithms(info distinfoFileInfo) {
	filename := info.filename()
	algorithms := info.algorithms()
	line := info.line()

	isPatch := info.isPatch

	switch {
	case algorithms == "SHA1" && isPatch != no:
		return

	case algorithms == "SHA1, RMD160, SHA512, Size" && isPatch != yes:
		return
	}

	switch {
	case isPatch == yes:
		line.Errorf("Expected SHA1 hash for %s, got %s.", filename, algorithms)

	case isPatch == unknown:
		line.Errorf("Wrong checksum algorithms %s for %s.", algorithms, filename)
		line.Explain(
			"Distfiles that are downloaded from external sources must have the",
			"checksum algorithms SHA1, RMD160, SHA512, Size.",
			"",
			"Patch files from pkgsrc must have only the SHA1 hash.")

	// At this point, the file is either a missing patch file or a distfile.

	case filename.HasPrefixText("patch-") && algorithms == "SHA1":
		if ck.pkg.IgnoreMissingPatches {
			break
		}

		line.Warnf("Patch file %q does not exist in directory %q.",
			filename, line.Rel(ck.pkg.File(ck.patchdir)))
		line.Explain(
			"If the patches directory looks correct, the patch may have been",
			"removed without updating the distinfo file.",
			"In such a case please update the distinfo file.",
			"",
			"In rare cases, pkglint cannot determine the correct location of the patches directory.",
			"In that case, see the pkglint man page for contact information.")

	default:
		ck.checkAlgorithmsDistfile(info)
	}
}

// checkAlgorithmsDistfile checks whether some of the standard algorithms are
// missing. If so and the downloaded distfile exists, they are calculated and
// added to the distinfo file via an autofix.
func (ck *distinfoLinesChecker) checkAlgorithmsDistfile(info distinfoFileInfo) {
	line := info.line()
	line.Errorf("Expected SHA1, RMD160, SHA512, Size checksums for %q, got %s.", info.filename(), info.algorithms())

	algorithms := [...]string{"SHA1", "RMD160", "SHA512", "Size"}

	missing := map[string]bool{}
	for _, alg := range algorithms {
		missing[alg] = true
	}
	seen := map[string]distinfoHash{}

	for _, hash := range info.hashes {
		alg := hash.algorithm
		if missing[alg] {
			seen[alg] = hash
			delete(missing, alg)
		}
	}

	if len(missing) == 0 || len(seen) == 0 {
		return
	}

	distdir := G.Pkgsrc.File("distfiles")

	distfile := distdir.JoinNoClean(info.filename()).CleanPath()
	if !distfile.IsFile() {

		// It's a rare situation that the explanation is generated
		// this far from the corresponding diagnostic.
		// This explanation only makes sense when there are some
		// hashes missing that can be automatically added by pkglint.
		line.Explain(
			"To add the missing lines to the distinfo file, run",
			sprintf("\t%s", bmake("distinfo")),
			"for each variant of the package until all distfiles are downloaded to",
			"${PKGSRCDIR}/distfiles.",
			"",
			"The variants are typically selected by setting EMUL_PLATFORM",
			"or similar variables in the command line.",
			"",
			"After that, run",
			sprintf("%q", "cvs update -C distinfo"),
			"to revert the distinfo file to the previous state, since the above",
			"commands have removed some of the entries.",
			"",
			"After downloading all possible distfiles, run",
			sprintf("%q,", "pkglint --autofix"),
			"which will find the downloaded distfiles and add the missing",
			"hashes to the distinfo file.")

		return
	}

	computeHash := func(hasher hash.Hash) string {
		f, err := distfile.Open()
		assertNil(err, "Opening distfile")

		// Don't load the distfile into memory since some of them
		// are hundreds of MB in size.
		_, err = io.Copy(hasher, f)
		assertNil(err, "Computing hash of distfile")

		hexHash := hex.EncodeToString(hasher.Sum(nil))

		err = f.Close()
		assertNil(err, "Closing distfile")

		return hexHash
	}

	compute := func(alg string) string {
		switch alg {
		case "SHA1":
			return computeHash(sha1.New())
		case "RMD160":
			return computeHash(ripemd160.New())
		case "SHA512":
			return computeHash(sha512.New())
		default:
			fileInfo, err := distfile.Lstat()
			assertNil(err, "Inaccessible distfile info")
			return sprintf("%d bytes", fileInfo.Size())
		}
	}

	for alg, hash := range seen {
		computed := compute(alg)

		if computed != hash.hash {
			// Do not try to autofix anything in this situation.
			// Wrong hashes are a serious issue.
			line.Errorf("The %s checksum for %q is %s in distinfo, %s in %s.",
				alg, hash.filename, hash.hash, computed, line.Rel(distfile))
			return
		}
	}

	// At this point, all the existing hash algorithms are correct,
	// and there is at least one hash algorithm. This is evidence enough
	// that the distfile is the expected one. Now generate the missing hashes
	// and insert them, in the correct order.

	var insertion *Line
	var remainingHashes = info.hashes
	for _, alg := range algorithms {
		if missing[alg] {
			computed := compute(alg)

			if insertion == nil {
				fix := line.Autofix()
				fix.Errorf("Missing %s hash for %s.", alg, info.filename())
				fix.InsertBefore(sprintf("%s (%s) = %s", alg, info.filename(), computed))
				fix.Apply()
			} else {
				fix := insertion.Autofix()
				fix.Errorf("Missing %s hash for %s.", alg, info.filename())
				fix.InsertAfter(sprintf("%s (%s) = %s", alg, info.filename(), computed))
				fix.Apply()
			}

		} else if remainingHashes[0].algorithm == alg {
			insertion = remainingHashes[0].line
			remainingHashes = remainingHashes[1:]
		}
	}
}

func (ck *distinfoLinesChecker) checkUnrecordedPatches() {
	if ck.pkg == nil {
		return
	}
	patchFiles, err := ck.pkg.File(ck.patchdir).ReadDir()
	if err != nil {
		if trace.Tracing {
			trace.Stepf("Cannot read patchdir %q: %s", ck.patchdir, err)
		}
		return
	}

	for _, file := range patchFiles {
		patchName := NewRelPathString(file.Name())
		if file.Mode().IsRegular() && ck.infos[patchName].isPatch != yes && patchName.HasPrefixText("patch-") {
			line := NewLineWhole(ck.lines.Filename)
			line.Errorf("Patch %q is not recorded. Run %q.",
				line.Rel(ck.pkg.File(ck.patchdir.JoinNoClean(patchName))),
				bmake("makepatchsum"))
		}
	}
}

// Inter-package check for differing distfile checksums.
func (ck *distinfoLinesChecker) checkGlobalDistfileMismatch(info distinfoHash) {

	if !G.InterPackage.Enabled() {
		return
	}

	filename := info.filename
	alg := info.algorithm
	hash := info.hash
	line := info.line

	// Intentionally checking the filename instead of ck.isPatch.
	// Missing the few distfiles that actually start with patch-*
	// is more convenient than having lots of false positive mismatches.
	if filename.HasPrefixText("patch-") {
		return
	}

	// The Size hash is not encoded in hex, therefore it would trigger wrong error messages below.
	// Since the Size hash is targeted towards humans and not really useful for detecting duplicates,
	// omitting the check here is ok. Any mismatches will be reliably detected because the other
	// hashes will be different, too.
	if alg == "Size" {
		return
	}

	// See https://github.com/golang/go/issues/29802
	hashBytes := make([]byte, hex.DecodedLen(len(hash)))
	_, err := hex.Decode(hashBytes, []byte(hash))
	if err != nil {
		line.Errorf("The %s hash for %s contains a non-hex character.", alg, filename)
		return
	}

	otherHash := G.InterPackage.Hash(alg, filename, hashBytes, &line.Location)
	if otherHash != nil {
		if !bytes.Equal(otherHash.hash, hashBytes) {
			line.Errorf("The %s hash for %s is %s, which conflicts with %s in %s.",
				alg, filename, hash, hex.EncodeToString(otherHash.hash), line.RelLocation(otherHash.location))
		}
	}
}

func (ck *distinfoLinesChecker) checkUncommittedPatch(info distinfoHash) {
	patchName := info.filename
	alg := info.algorithm
	hash := info.hash
	line := info.line

	patchFileName := ck.patchdir.JoinNoClean(patchName)
	resolvedPatchFileName := ck.pkg.File(patchFileName)
	if ck.distinfoIsCommitted && !isCommitted(resolvedPatchFileName) {
		line.Warnf("%s is registered in distinfo but not added to CVS.", line.Rel(resolvedPatchFileName))
	}
	if alg == "SHA1" {
		ck.checkPatchSha1(line, patchFileName, hash)
	}
}

func (ck *distinfoLinesChecker) checkPatchSha1(line *Line, patchFileName PackagePath, distinfoSha1Hex string) {
	lines := Load(ck.pkg.File(patchFileName), 0)
	if lines == nil {
		line.Errorf("Patch %s does not exist.", patchFileName.AsRelPath())
		return
	}

	fileSha1Hex := computePatchSha1Hex(lines)
	if distinfoSha1Hex != fileSha1Hex {
		fix := line.Autofix()
		fix.Errorf("SHA1 hash of %s differs (distinfo has %s, patch file has %s).",
			line.Rel(ck.pkg.File(patchFileName)), distinfoSha1Hex, fileSha1Hex)
		fix.Explain(
			"To fix the hashes, either let pkglint --autofix do the work",
			sprintf("or run %q.", bmake("makepatchsum")))
		fix.Replace(distinfoSha1Hex, fileSha1Hex)
		fix.Apply()
	}
}

type distinfoFileInfo struct {
	//  yes     = the patch file exists
	//  unknown = distinfo file is checked without a pkgsrc package
	//  no      = distfile or nonexistent patch file
	isPatch YesNoUnknown
	hashes  []distinfoHash
}

func (info *distinfoFileInfo) filename() RelPath { return info.hashes[0].filename }
func (info *distinfoFileInfo) line() *Line       { return info.hashes[0].line }

func (info *distinfoFileInfo) algorithms() string {
	var algs []string
	for _, hash := range info.hashes {
		algs = append(algs, hash.algorithm)
	}
	return strings.Join(algs, ", ")
}

type distinfoHash struct {
	line      *Line
	filename  RelPath
	algorithm string
	hash      string
}

// Same as in mk/checksum/distinfo.awk:/function patchsum/
func computePatchSha1Hex(lines *Lines) string {

	hasher := sha1.New()
	skipText := "$" + "NetBSD"
	for _, line := range lines.Lines {
		for _, raw := range line.raw {
			textnl := raw.orignl
			if !contains(textnl, skipText) {
				_, _ = hasher.Write([]byte(textnl))
			}
		}
	}
	return sprintf("%x", hasher.Sum(nil))
}