device.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package main
  2. // 本机目录的设备识别(docs/design/21-knowledge-sources.md §4.4):
  3. // 系统盘上的目录只按路径识别;其他设备上的目录记录文件系统 UUID 与设备内路径,
  4. // 每次解析时找到这个 UUID 当前挂在哪里,再拼出实际路径。
  5. import (
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "golang.org/x/sys/unix"
  11. )
  12. type mountEntry struct {
  13. Major, Minor uint32
  14. Root string // 文件系统内被挂载的路径(bind mount 时不是 /)
  15. Point string
  16. FSType string
  17. Source string
  18. }
  19. func unescapeMountinfo(s string) string {
  20. if !strings.Contains(s, `\`) {
  21. return s
  22. }
  23. var b strings.Builder
  24. for i := 0; i < len(s); i++ {
  25. if s[i] == '\\' && i+3 < len(s) {
  26. if n, err := strconv.ParseUint(s[i+1:i+4], 8, 8); err == nil {
  27. b.WriteByte(byte(n))
  28. i += 3
  29. continue
  30. }
  31. }
  32. b.WriteByte(s[i])
  33. }
  34. return b.String()
  35. }
  36. // parseMountinfo 解析 /proc/self/mountinfo
  37. func parseMountinfo(data string) []mountEntry {
  38. var out []mountEntry
  39. for _, line := range strings.Split(data, "\n") {
  40. f := strings.Fields(line)
  41. if len(f) < 10 {
  42. continue
  43. }
  44. sep := -1
  45. for i := 6; i < len(f); i++ {
  46. if f[i] == "-" {
  47. sep = i
  48. break
  49. }
  50. }
  51. if sep < 0 || sep+2 >= len(f) {
  52. continue
  53. }
  54. mm := strings.SplitN(f[2], ":", 2)
  55. if len(mm) != 2 {
  56. continue
  57. }
  58. maj, err1 := strconv.ParseUint(mm[0], 10, 32)
  59. min, err2 := strconv.ParseUint(mm[1], 10, 32)
  60. if err1 != nil || err2 != nil {
  61. continue
  62. }
  63. out = append(out, mountEntry{
  64. Major: uint32(maj), Minor: uint32(min),
  65. Root: unescapeMountinfo(f[3]), Point: unescapeMountinfo(f[4]),
  66. FSType: f[sep+1], Source: unescapeMountinfo(f[sep+2]),
  67. })
  68. }
  69. return out
  70. }
  71. // system 提供识别所需的系统信息,测试中替换为模拟数据
  72. type system interface {
  73. mountinfo() []mountEntry
  74. // uuids 返回 设备号 → 文件系统 UUID(来自 /dev/disk/by-uuid)
  75. uuids() map[uint64]string
  76. // stat 返回路径所在的设备号(不跟随最后的符号链接以外的行为与 stat 相同)
  77. devOf(path string) (uint64, error)
  78. }
  79. type realSystem struct{}
  80. func (realSystem) mountinfo() []mountEntry {
  81. b, err := os.ReadFile("/proc/self/mountinfo")
  82. if err != nil {
  83. return nil
  84. }
  85. return parseMountinfo(string(b))
  86. }
  87. func (realSystem) uuids() map[uint64]string {
  88. out := map[uint64]string{}
  89. ents, err := os.ReadDir("/dev/disk/by-uuid")
  90. if err != nil {
  91. return out
  92. }
  93. for _, e := range ents {
  94. var st unix.Stat_t
  95. if unix.Stat(filepath.Join("/dev/disk/by-uuid", e.Name()), &st) == nil && st.Mode&unix.S_IFMT == unix.S_IFBLK {
  96. out[st.Rdev] = e.Name()
  97. }
  98. }
  99. return out
  100. }
  101. func (realSystem) devOf(path string) (uint64, error) {
  102. var st unix.Stat_t
  103. if err := unix.Stat(path, &st); err != nil {
  104. return 0, err
  105. }
  106. return st.Dev, nil
  107. }
  108. func devOfEntry(e mountEntry) uint64 { return unix.Mkdev(e.Major, e.Minor) }
  109. // within 判断 p 是否等于 base 或在 base 之下
  110. func within(p, base string) bool {
  111. return p == base || base == "/" || strings.HasPrefix(p, base+"/")
  112. }
  113. // identity 本机目录的识别结果
  114. type identity struct {
  115. Path string `json:"path"`
  116. UUID string `json:"uuid"` // 系统盘或无法识别的设备上为空
  117. RelPath string `json:"relPath"` // 设备内路径
  118. SystemDisk bool `json:"systemDisk"`
  119. MountPoint string `json:"mountPoint"`
  120. FSType string `json:"fsType"`
  121. Device string `json:"device"`
  122. }
  123. // identify 识别已检查通过的真实路径所在的文件系统
  124. func identify(sys system, real string) identity {
  125. id := identity{Path: real}
  126. dev, err := sys.devOf(real)
  127. if err != nil {
  128. return id
  129. }
  130. rootDev, _ := sys.devOf("/")
  131. // 找到包含该路径、设备号相同、挂载点最长的条目
  132. var best *mountEntry
  133. for _, e := range sys.mountinfo() {
  134. if devOfEntry(e) == dev && within(real, e.Point) && (best == nil || len(e.Point) >= len(best.Point)) {
  135. e := e
  136. best = &e
  137. }
  138. }
  139. if best != nil {
  140. id.MountPoint, id.FSType, id.Device = best.Point, best.FSType, best.Source
  141. }
  142. if dev == rootDev {
  143. id.SystemDisk = true
  144. return id
  145. }
  146. uuid := sys.uuids()[dev]
  147. if uuid == "" || best == nil {
  148. return id
  149. }
  150. id.UUID = uuid
  151. id.RelPath = filepath.Join(best.Root, strings.TrimPrefix(real, best.Point))
  152. if !strings.HasPrefix(id.RelPath, "/") {
  153. id.RelPath = "/" + id.RelPath
  154. }
  155. return id
  156. }
  157. // localSource 平台登记的本机目录
  158. type localSource struct {
  159. Path string `json:"path"`
  160. UUID string `json:"uuid"`
  161. RelPath string `json:"relPath"`
  162. }
  163. // locate 找到本机目录当前的实际路径。返回的路径还需要经过 checkSource。
  164. func locate(sys system, src localSource) (string, *checkError) {
  165. if src.UUID == "" {
  166. return src.Path, nil
  167. }
  168. var dev uint64
  169. found := false
  170. for d, u := range sys.uuids() {
  171. if u == src.UUID {
  172. dev, found = d, true
  173. break
  174. }
  175. }
  176. if !found {
  177. return "", &checkError{"device_missing", "设备未连接(文件系统 UUID " + src.UUID + ")"}
  178. }
  179. candidates := func() []string {
  180. var out []string
  181. for _, e := range sys.mountinfo() {
  182. if devOfEntry(e) == dev && within(src.RelPath, e.Root) {
  183. rest := strings.TrimPrefix(src.RelPath, e.Root)
  184. if e.Root == "/" {
  185. rest = src.RelPath
  186. }
  187. out = append(out, filepath.Join(e.Point, rest))
  188. }
  189. }
  190. return out
  191. }
  192. list := candidates()
  193. if len(list) == 0 {
  194. // 可能是 x-systemd.automount:访问原路径触发自动挂载后再找一次
  195. _, _ = sys.devOf(src.Path)
  196. list = candidates()
  197. }
  198. if len(list) == 0 {
  199. return "", &checkError{"device_missing", "设备已连接,但没有挂载到系统上(文件系统 UUID " + src.UUID + ")"}
  200. }
  201. // 优先选原来的路径,其次选第一个在允许范围内的
  202. for _, p := range list {
  203. if p == src.Path {
  204. return p, nil
  205. }
  206. }
  207. for _, p := range list {
  208. if ruleProblem(p, allowedRoots) == "" {
  209. return p, nil
  210. }
  211. }
  212. return list[0], nil
  213. }