1package config
2
3import (
4 "io"
5 "io/fs"
6 "os"
7 "syscall"
8)
9
10func readRegular(path string, limit int, tooLarge string, check func(fs.FileMode) string) ([]byte, string) {
11 f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0)
12 if err != nil {
13 return nil, reasonUnreadable
14 }
15 defer f.Close()
16 info, err := f.Stat()
17 if err != nil || !info.Mode().IsRegular() {
18 return nil, reasonUnreadable
19 }
20 if check != nil {
21 if reason := check(info.Mode()); reason != "" {
22 return nil, reason
23 }
24 }
25 if info.Size() > int64(limit) {
26 return nil, tooLarge
27 }
28 data, err := io.ReadAll(io.LimitReader(f, int64(limit)+1))
29 if err != nil {
30 return nil, reasonUnreadable
31 }
32 if len(data) > limit {
33 return nil, tooLarge
34 }
35 return data, ""
36}