bep_fileinfo.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package protocol
  7. import (
  8. "bytes"
  9. "crypto/sha256"
  10. "encoding/binary"
  11. "fmt"
  12. "log/slog"
  13. "slices"
  14. "strings"
  15. "time"
  16. "github.com/syncthing/syncthing/internal/gen/bep"
  17. "github.com/syncthing/syncthing/lib/build"
  18. )
  19. type FlagLocal uint32
  20. // FileInfo.LocalFlags flags
  21. const (
  22. FlagLocalUnsupported FlagLocal = 1 << 0 // 1: The kind is unsupported, e.g. symlinks on Windows
  23. FlagLocalIgnored FlagLocal = 1 << 1 // 2: Matches local ignore patterns
  24. FlagLocalMustRescan FlagLocal = 1 << 2 // 4: Doesn't match content on disk, must be rechecked fully
  25. FlagLocalReceiveOnly FlagLocal = 1 << 3 // 8: Change detected on receive only folder
  26. FlagLocalGlobal FlagLocal = 1 << 4 // 16: This is the global file version
  27. FlagLocalNeeded FlagLocal = 1 << 5 // 32: We need this file
  28. FlagLocalRemoteInvalid FlagLocal = 1 << 6 // 64: The remote marked this as invalid
  29. // Flags that should result in the Invalid bit on outgoing updates (or had it on ingoing ones)
  30. LocalInvalidFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly | FlagLocalRemoteInvalid
  31. // Flags that should result in a file being in conflict with its
  32. // successor, due to us not having an up to date picture of its state on
  33. // disk.
  34. LocalConflictFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalReceiveOnly
  35. LocalAllFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly | FlagLocalGlobal | FlagLocalNeeded | FlagLocalRemoteInvalid
  36. )
  37. // localFlagBitNames maps flag values to characters which can be used to
  38. // build a permission-like bit string for easier reading.
  39. var localFlagBitNames = map[FlagLocal]string{
  40. FlagLocalUnsupported: "u",
  41. FlagLocalIgnored: "i",
  42. FlagLocalMustRescan: "r",
  43. FlagLocalReceiveOnly: "e",
  44. FlagLocalGlobal: "G",
  45. FlagLocalNeeded: "n",
  46. FlagLocalRemoteInvalid: "v",
  47. }
  48. func (f FlagLocal) IsInvalid() bool {
  49. return f&LocalInvalidFlags != 0
  50. }
  51. // HumanString returns a permission-like string representation of the flag bits
  52. func (f FlagLocal) HumanString() string {
  53. if f == 0 {
  54. return strings.Repeat("-", len(localFlagBitNames))
  55. }
  56. bit := FlagLocal(1)
  57. var res bytes.Buffer
  58. var extra strings.Builder
  59. for f != 0 {
  60. if f&bit != 0 {
  61. if name, ok := localFlagBitNames[bit]; ok {
  62. res.WriteString(name)
  63. } else {
  64. fmt.Fprintf(&extra, "+0x%x", bit)
  65. }
  66. } else {
  67. res.WriteString("-")
  68. }
  69. f &^= bit
  70. bit <<= 1
  71. }
  72. if res.Len() < len(localFlagBitNames) {
  73. res.WriteString(strings.Repeat("-", len(localFlagBitNames)-res.Len()))
  74. }
  75. base := res.Bytes()
  76. slices.Reverse(base)
  77. return string(base) + extra.String()
  78. }
  79. // BlockSizes is the list of valid block sizes, from min to max
  80. var BlockSizes []int
  81. func init() {
  82. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  83. BlockSizes = append(BlockSizes, blockSize)
  84. if _, ok := sha256OfEmptyBlock[blockSize]; !ok {
  85. panic("missing hard coded value for sha256 of empty block")
  86. }
  87. }
  88. BufferPool = newBufferPool() // must happen after BlockSizes is initialized
  89. }
  90. type FileInfoType = bep.FileInfoType
  91. const (
  92. FileInfoTypeFile = bep.FileInfoType_FILE_INFO_TYPE_FILE
  93. FileInfoTypeDirectory = bep.FileInfoType_FILE_INFO_TYPE_DIRECTORY
  94. FileInfoTypeSymlinkFile = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK_FILE
  95. FileInfoTypeSymlinkDirectory = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK_DIRECTORY
  96. FileInfoTypeSymlink = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK
  97. )
  98. type FileInfo struct {
  99. Name string
  100. Size int64
  101. ModifiedS int64
  102. ModifiedBy ShortID
  103. Version Vector
  104. Sequence int64
  105. Blocks []BlockInfo
  106. SymlinkTarget []byte
  107. BlocksHash []byte
  108. PreviousBlocksHash []byte
  109. Encrypted []byte
  110. Platform PlatformData
  111. Type FileInfoType
  112. Permissions uint32
  113. ModifiedNs int32
  114. RawBlockSize int32
  115. // The local_flags fields stores flags that are relevant to the local
  116. // host only. It is not part of the protocol, doesn't get sent or
  117. // received (we make sure to zero it), nonetheless we need it on our
  118. // struct and to be able to serialize it to/from the database.
  119. // It does carry the info to decide if the file is invalid, which is part of
  120. // the protocol.
  121. LocalFlags FlagLocal
  122. // The time when the inode was last changed (i.e., permissions, xattrs
  123. // etc changed). This is host-local, not sent over the wire.
  124. InodeChangeNs int64
  125. // The size of the data appended to the encrypted file on disk. This is
  126. // host-local, not sent over the wire.
  127. EncryptionTrailerSize int
  128. Deleted bool
  129. NoPermissions bool
  130. truncated bool // was created from a truncated file info without blocks
  131. }
  132. func (f *FileInfo) ToWire(withInternalFields bool) *bep.FileInfo {
  133. if f.truncated && !(f.IsDeleted() || f.IsInvalid() || f.IsIgnored()) {
  134. panic("bug: must not serialize truncated file info")
  135. }
  136. blocks := make([]*bep.BlockInfo, len(f.Blocks))
  137. for j, b := range f.Blocks {
  138. blocks[j] = b.ToWire()
  139. }
  140. w := &bep.FileInfo{
  141. Name: f.Name,
  142. Size: f.Size,
  143. ModifiedS: f.ModifiedS,
  144. ModifiedBy: uint64(f.ModifiedBy),
  145. Version: f.Version.ToWire(),
  146. Sequence: f.Sequence,
  147. Blocks: blocks,
  148. SymlinkTarget: f.SymlinkTarget,
  149. BlocksHash: f.BlocksHash,
  150. PreviousBlocksHash: f.PreviousBlocksHash,
  151. Encrypted: f.Encrypted,
  152. Type: f.Type,
  153. Permissions: f.Permissions,
  154. ModifiedNs: f.ModifiedNs,
  155. BlockSize: f.RawBlockSize,
  156. Platform: f.Platform.toWire(),
  157. Deleted: f.Deleted,
  158. Invalid: f.IsInvalid(),
  159. NoPermissions: f.NoPermissions,
  160. }
  161. if withInternalFields {
  162. w.LocalFlags = uint32(f.LocalFlags)
  163. w.InodeChangeNs = f.InodeChangeNs
  164. w.EncryptionTrailerSize = int32(f.EncryptionTrailerSize)
  165. }
  166. return w
  167. }
  168. func (f *FileInfo) InConflictWith(previous FileInfo) bool {
  169. if f.Version.GreaterEqual(previous.Version) {
  170. // If the new file is strictly greater in the ordering than the
  171. // existing file, it is not a conflict. If any counter has moved
  172. // backwards, or different counters have increased independently,
  173. // then the file is not greater but concurrent and we don't take
  174. // this branch.
  175. return false
  176. }
  177. if len(f.PreviousBlocksHash) == 0 || len(f.BlocksHash) == 0 {
  178. // Don't have data to make a content determination, or the type has
  179. // changed (file to directory, etc). Consider it a conflict.
  180. return true
  181. }
  182. // If the new file is based on the old contents we have, it's not really
  183. // a conflict.
  184. return !bytes.Equal(f.PreviousBlocksHash, previous.BlocksHash)
  185. }
  186. // WinsConflict returns true if "f" is the one to choose when it is in
  187. // conflict with "other".
  188. func (f *FileInfo) WinsConflict(other FileInfo) bool {
  189. // If only one of the files is invalid, that one loses.
  190. if f.IsInvalid() != other.IsInvalid() {
  191. return !f.IsInvalid()
  192. }
  193. // The one with the newer modification time wins.
  194. if f.ModTime().After(other.ModTime()) {
  195. return true
  196. }
  197. if f.ModTime().Before(other.ModTime()) {
  198. return false
  199. }
  200. // The modification times were equal. Use the device ID in the version
  201. // vector as tie breaker.
  202. return f.FileVersion().Compare(other.FileVersion()) == ConcurrentGreater
  203. }
  204. func (f *FileInfo) LogAttr() slog.Attr {
  205. attrs := []any{slog.String("name", f.Name)}
  206. var kind string
  207. switch f.Type {
  208. case FileInfoTypeFile:
  209. kind = "file"
  210. if !f.Deleted {
  211. attrs = append(attrs,
  212. slog.Any("modified", f.ModTime()),
  213. slog.String("permissions", fmt.Sprintf("0%03o", f.Permissions)),
  214. slog.Int64("size", f.Size),
  215. slog.Int("blocksize", f.BlockSize()),
  216. )
  217. }
  218. case FileInfoTypeDirectory:
  219. kind = "dir"
  220. attrs = append(attrs, slog.String("permissions", fmt.Sprintf("0%03o", f.Permissions)))
  221. case FileInfoTypeSymlink:
  222. kind = "symlink"
  223. attrs = append(attrs, slog.String("target", string(f.SymlinkTarget)))
  224. }
  225. return slog.Group(kind, attrs...)
  226. }
  227. func FileInfoFromWire(w *bep.FileInfo) FileInfo {
  228. var blocks []BlockInfo
  229. if len(w.Blocks) > 0 {
  230. blocks = make([]BlockInfo, len(w.Blocks))
  231. for j, b := range w.Blocks {
  232. blocks[j] = BlockInfoFromWire(b)
  233. }
  234. }
  235. return fileInfoFromWireWithBlocks(w, blocks)
  236. }
  237. type FileInfoWithoutBlocks interface {
  238. GetName() string
  239. GetSize() int64
  240. GetModifiedS() int64
  241. GetModifiedBy() uint64
  242. GetVersion() *bep.Vector
  243. GetSequence() int64
  244. // GetBlocks() []*bep.BlockInfo // not included
  245. GetSymlinkTarget() []byte
  246. GetBlocksHash() []byte
  247. GetPreviousBlocksHash() []byte
  248. GetEncrypted() []byte
  249. GetType() FileInfoType
  250. GetPermissions() uint32
  251. GetModifiedNs() int32
  252. GetBlockSize() int32
  253. GetPlatform() *bep.PlatformData
  254. GetLocalFlags() uint32
  255. GetInodeChangeNs() int64
  256. GetEncryptionTrailerSize() int32
  257. GetDeleted() bool
  258. GetInvalid() bool
  259. GetNoPermissions() bool
  260. }
  261. func fileInfoFromWireWithBlocks(w FileInfoWithoutBlocks, blocks []BlockInfo) FileInfo {
  262. var localFlags FlagLocal
  263. if w.GetInvalid() {
  264. localFlags = FlagLocalRemoteInvalid
  265. }
  266. return FileInfo{
  267. Name: w.GetName(),
  268. Size: w.GetSize(),
  269. ModifiedS: w.GetModifiedS(),
  270. ModifiedBy: ShortID(w.GetModifiedBy()),
  271. Version: VectorFromWire(w.GetVersion()),
  272. Sequence: w.GetSequence(),
  273. Blocks: blocks,
  274. SymlinkTarget: w.GetSymlinkTarget(),
  275. BlocksHash: w.GetBlocksHash(),
  276. PreviousBlocksHash: w.GetPreviousBlocksHash(),
  277. Encrypted: w.GetEncrypted(),
  278. Type: w.GetType(),
  279. Permissions: w.GetPermissions(),
  280. ModifiedNs: w.GetModifiedNs(),
  281. RawBlockSize: w.GetBlockSize(),
  282. Platform: platformDataFromWire(w.GetPlatform()),
  283. Deleted: w.GetDeleted(),
  284. LocalFlags: localFlags,
  285. NoPermissions: w.GetNoPermissions(),
  286. }
  287. }
  288. func FileInfoFromDB(w *bep.FileInfo) FileInfo {
  289. f := FileInfoFromWire(w)
  290. f.LocalFlags = FlagLocal(w.LocalFlags)
  291. f.InodeChangeNs = w.InodeChangeNs
  292. f.EncryptionTrailerSize = int(w.EncryptionTrailerSize)
  293. return f
  294. }
  295. func FileInfoFromDBTruncated(w FileInfoWithoutBlocks) FileInfo {
  296. f := fileInfoFromWireWithBlocks(w, nil)
  297. f.LocalFlags = FlagLocal(w.GetLocalFlags())
  298. f.InodeChangeNs = w.GetInodeChangeNs()
  299. f.EncryptionTrailerSize = int(w.GetEncryptionTrailerSize())
  300. f.truncated = true
  301. return f
  302. }
  303. func (f FileInfo) String() string {
  304. switch f.Type {
  305. case FileInfoTypeDirectory:
  306. return fmt.Sprintf("Directory{Name:%q, Sequence:%d, Permissions:0%o, ModTime:%v, Version:%v, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, Platform:%v, InodeChangeTime:%v}",
  307. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.Platform, f.InodeChangeTime())
  308. case FileInfoTypeFile:
  309. return fmt.Sprintf("File{Name:%q, Sequence:%d, Permissions:0%o, ModTime:%v, Version:%v, Length:%d, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, BlockSize:%d, NumBlocks:%d, BlocksHash:%x, Platform:%v, InodeChangeTime:%v}",
  310. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.Size, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.RawBlockSize, len(f.Blocks), f.BlocksHash, f.Platform, f.InodeChangeTime())
  311. case FileInfoTypeSymlink, FileInfoTypeSymlinkDirectory, FileInfoTypeSymlinkFile:
  312. return fmt.Sprintf("Symlink{Name:%q, Type:%v, Sequence:%d, Version:%v, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, SymlinkTarget:%q, Platform:%v, InodeChangeTime:%v}",
  313. f.Name, f.Type, f.Sequence, f.Version, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.SymlinkTarget, f.Platform, f.InodeChangeTime())
  314. default:
  315. panic("mystery file type detected")
  316. }
  317. }
  318. func (f FileInfo) IsDeleted() bool {
  319. return f.Deleted
  320. }
  321. func (f FileInfo) IsInvalid() bool {
  322. return f.LocalFlags.IsInvalid()
  323. }
  324. func (f FileInfo) IsUnsupported() bool {
  325. return f.LocalFlags&FlagLocalUnsupported != 0
  326. }
  327. func (f FileInfo) IsIgnored() bool {
  328. return f.LocalFlags&FlagLocalIgnored != 0
  329. }
  330. func (f FileInfo) MustRescan() bool {
  331. return f.LocalFlags&FlagLocalMustRescan != 0
  332. }
  333. func (f FileInfo) IsReceiveOnlyChanged() bool {
  334. return f.LocalFlags&FlagLocalReceiveOnly != 0
  335. }
  336. func (f FileInfo) IsDirectory() bool {
  337. return f.Type == FileInfoTypeDirectory
  338. }
  339. func (f FileInfo) ShouldConflict() bool {
  340. return f.LocalFlags&LocalConflictFlags != 0
  341. }
  342. func (f FileInfo) IsSymlink() bool {
  343. switch f.Type {
  344. case FileInfoTypeSymlink, FileInfoTypeSymlinkDirectory, FileInfoTypeSymlinkFile:
  345. return true
  346. default:
  347. return false
  348. }
  349. }
  350. func (f FileInfo) HasPermissionBits() bool {
  351. return !f.NoPermissions
  352. }
  353. func (f FileInfo) FileSize() int64 {
  354. if f.Deleted {
  355. return 0
  356. }
  357. if f.IsDirectory() || f.IsSymlink() {
  358. return SyntheticDirectorySize
  359. }
  360. return f.Size
  361. }
  362. func (f FileInfo) BlockSize() int {
  363. if f.RawBlockSize < MinBlockSize {
  364. return MinBlockSize
  365. }
  366. return int(f.RawBlockSize)
  367. }
  368. // BlockSize returns the block size to use for the given file size
  369. func BlockSize(fileSize int64) int {
  370. var blockSize int
  371. for _, blockSize = range BlockSizes {
  372. if fileSize < DesiredPerFileBlocks*int64(blockSize) {
  373. break
  374. }
  375. }
  376. return blockSize
  377. }
  378. func (f FileInfo) FileName() string {
  379. return f.Name
  380. }
  381. func (f FileInfo) FileLocalFlags() FlagLocal {
  382. return f.LocalFlags
  383. }
  384. func (f FileInfo) ModTime() time.Time {
  385. return time.Unix(f.ModifiedS, int64(f.ModifiedNs))
  386. }
  387. func (f FileInfo) SequenceNo() int64 {
  388. return f.Sequence
  389. }
  390. func (f FileInfo) FileVersion() Vector {
  391. return f.Version
  392. }
  393. func (f FileInfo) FileType() FileInfoType {
  394. return f.Type
  395. }
  396. func (f FileInfo) FilePermissions() uint32 {
  397. return f.Permissions
  398. }
  399. func (f FileInfo) FileModifiedBy() ShortID {
  400. return f.ModifiedBy
  401. }
  402. func (f FileInfo) PlatformData() PlatformData {
  403. return f.Platform
  404. }
  405. func (f FileInfo) InodeChangeTime() time.Time {
  406. return time.Unix(0, f.InodeChangeNs)
  407. }
  408. func (f FileInfo) FileBlocksHash() []byte {
  409. return f.BlocksHash
  410. }
  411. type FileInfoComparison struct {
  412. ModTimeWindow time.Duration
  413. IgnorePerms bool
  414. IgnoreBlocks bool
  415. IgnoreFlags FlagLocal
  416. IgnoreOwnership bool
  417. IgnoreXattrs bool
  418. }
  419. func (f FileInfo) IsEquivalent(other FileInfo, modTimeWindow time.Duration) bool {
  420. return f.isEquivalent(other, FileInfoComparison{ModTimeWindow: modTimeWindow})
  421. }
  422. func (f FileInfo) IsEquivalentOptional(other FileInfo, comp FileInfoComparison) bool {
  423. return f.isEquivalent(other, comp)
  424. }
  425. // isEquivalent checks that the two file infos represent the same actual file content,
  426. // i.e. it does purposely not check only selected (see below) struct members.
  427. // Permissions (config) and blocks (scanning) can be excluded from the comparison.
  428. // Any file info is not "equivalent", if it has different
  429. // - type
  430. // - deleted flag
  431. // - invalid flag
  432. // - permissions, unless they are ignored
  433. //
  434. // A file is not "equivalent", if it has different
  435. // - modification time (difference bigger than modTimeWindow)
  436. // - size
  437. // - blocks, unless there are no blocks to compare (scanning)
  438. // - os data
  439. //
  440. // A symlink is not "equivalent", if it has different
  441. // - target
  442. //
  443. // A directory does not have anything specific to check.
  444. func (f FileInfo) isEquivalent(other FileInfo, comp FileInfoComparison) bool {
  445. if f.MustRescan() || other.MustRescan() {
  446. // These are per definition not equivalent because they don't
  447. // represent a valid state, even if both happen to have the
  448. // MustRescan bit set.
  449. return false
  450. }
  451. // If we care about either ownership or xattrs, are recording inode change
  452. // times and it changed, they are not equal.
  453. if !(comp.IgnoreOwnership && comp.IgnoreXattrs) && f.InodeChangeNs != 0 && other.InodeChangeNs != 0 && f.InodeChangeNs != other.InodeChangeNs {
  454. return false
  455. }
  456. // Mask out the ignored local flags before checking IsInvalid() below
  457. f.LocalFlags &^= comp.IgnoreFlags
  458. other.LocalFlags &^= comp.IgnoreFlags
  459. if f.Name != other.Name || f.Type != other.Type || f.Deleted != other.Deleted || f.IsInvalid() != other.IsInvalid() {
  460. return false
  461. }
  462. if !comp.IgnoreOwnership && f.Platform != other.Platform {
  463. if !unixOwnershipEqual(f.Platform.Unix, other.Platform.Unix) {
  464. return false
  465. }
  466. if !windowsOwnershipEqual(f.Platform.Windows, other.Platform.Windows) {
  467. return false
  468. }
  469. }
  470. if !comp.IgnoreXattrs && f.Platform != other.Platform {
  471. if !xattrsEqual(f.Platform.Linux, other.Platform.Linux) {
  472. return false
  473. }
  474. if !xattrsEqual(f.Platform.Darwin, other.Platform.Darwin) {
  475. return false
  476. }
  477. if !xattrsEqual(f.Platform.FreeBSD, other.Platform.FreeBSD) {
  478. return false
  479. }
  480. if !xattrsEqual(f.Platform.NetBSD, other.Platform.NetBSD) {
  481. return false
  482. }
  483. }
  484. if !comp.IgnorePerms && !f.NoPermissions && !other.NoPermissions && !PermsEqual(f.Permissions, other.Permissions) {
  485. return false
  486. }
  487. switch f.Type {
  488. case FileInfoTypeFile:
  489. return f.Size == other.Size && ModTimeEqual(f.ModTime(), other.ModTime(), comp.ModTimeWindow) && (comp.IgnoreBlocks || f.BlocksEqual(other))
  490. case FileInfoTypeSymlink:
  491. return bytes.Equal(f.SymlinkTarget, other.SymlinkTarget)
  492. case FileInfoTypeDirectory:
  493. return true
  494. }
  495. return false
  496. }
  497. func ModTimeEqual(a, b time.Time, modTimeWindow time.Duration) bool {
  498. if a.Equal(b) {
  499. return true
  500. }
  501. diff := a.Sub(b)
  502. if diff < 0 {
  503. diff *= -1
  504. }
  505. return diff < modTimeWindow
  506. }
  507. func PermsEqual(a, b uint32) bool {
  508. if build.IsWindows {
  509. // There is only writeable and read only, represented for user, group
  510. // and other equally. We only compare against user.
  511. return a&0o600 == b&0o600
  512. }
  513. // All bits count
  514. return a&0o777 == b&0o777
  515. }
  516. // BlocksEqual returns true when the two files have identical block lists.
  517. func (f FileInfo) BlocksEqual(other FileInfo) bool {
  518. // If both sides have blocks hashes and they match, we are good. If they
  519. // don't match still check individual block hashes to catch differences
  520. // in weak hashes only (e.g. after switching weak hash algo).
  521. if len(f.BlocksHash) > 0 && len(other.BlocksHash) > 0 && bytes.Equal(f.BlocksHash, other.BlocksHash) {
  522. return true
  523. }
  524. // Actually compare the block lists in full.
  525. return blocksEqual(f.Blocks, other.Blocks)
  526. }
  527. func (f *FileInfo) SetMustRescan() {
  528. f.setLocalFlags(FlagLocalMustRescan)
  529. }
  530. func (f *FileInfo) SetIgnored() {
  531. f.setLocalFlags(FlagLocalIgnored)
  532. }
  533. func (f *FileInfo) SetUnsupported() {
  534. f.setLocalFlags(FlagLocalUnsupported)
  535. }
  536. func (f *FileInfo) SetDeleted(by ShortID) {
  537. f.ModifiedBy = by
  538. f.Deleted = true
  539. f.Version = f.Version.Update(by)
  540. f.ModifiedS = time.Now().Unix()
  541. f.setNoContent()
  542. }
  543. func (f *FileInfo) setLocalFlags(flags FlagLocal) {
  544. f.LocalFlags = flags
  545. f.setNoContent()
  546. }
  547. func (f *FileInfo) setNoContent() {
  548. f.Blocks = nil
  549. f.BlocksHash = nil
  550. f.Size = 0
  551. }
  552. type BlockInfo struct {
  553. Hash []byte
  554. Offset int64
  555. Size int
  556. }
  557. func (b BlockInfo) ToWire() *bep.BlockInfo {
  558. return &bep.BlockInfo{
  559. Hash: b.Hash,
  560. Offset: b.Offset,
  561. Size: int32(b.Size),
  562. }
  563. }
  564. func BlockInfoFromWire(w *bep.BlockInfo) BlockInfo {
  565. return BlockInfo{
  566. Hash: w.Hash,
  567. Offset: w.Offset,
  568. Size: int(w.Size),
  569. }
  570. }
  571. func (b BlockInfo) String() string {
  572. return fmt.Sprintf("Block{%d/%d/%x}", b.Offset, b.Size, b.Hash)
  573. }
  574. // For each block size, the hash of a block of all zeroes
  575. var sha256OfEmptyBlock = map[int][sha256.Size]byte{
  576. 128 << KiB: {0xfa, 0x43, 0x23, 0x9b, 0xce, 0xe7, 0xb9, 0x7c, 0xa6, 0x2f, 0x0, 0x7c, 0xc6, 0x84, 0x87, 0x56, 0xa, 0x39, 0xe1, 0x9f, 0x74, 0xf3, 0xdd, 0xe7, 0x48, 0x6d, 0xb3, 0xf9, 0x8d, 0xf8, 0xe4, 0x71},
  577. 256 << KiB: {0x8a, 0x39, 0xd2, 0xab, 0xd3, 0x99, 0x9a, 0xb7, 0x3c, 0x34, 0xdb, 0x24, 0x76, 0x84, 0x9c, 0xdd, 0xf3, 0x3, 0xce, 0x38, 0x9b, 0x35, 0x82, 0x68, 0x50, 0xf9, 0xa7, 0x0, 0x58, 0x9b, 0x4a, 0x90},
  578. 512 << KiB: {0x7, 0x85, 0x4d, 0x2f, 0xef, 0x29, 0x7a, 0x6, 0xba, 0x81, 0x68, 0x5e, 0x66, 0xc, 0x33, 0x2d, 0xe3, 0x6d, 0x5d, 0x18, 0xd5, 0x46, 0x92, 0x7d, 0x30, 0xda, 0xad, 0x6d, 0x7f, 0xda, 0x15, 0x41},
  579. 1 << MiB: {0x30, 0xe1, 0x49, 0x55, 0xeb, 0xf1, 0x35, 0x22, 0x66, 0xdc, 0x2f, 0xf8, 0x6, 0x7e, 0x68, 0x10, 0x46, 0x7, 0xe7, 0x50, 0xab, 0xb9, 0xd3, 0xb3, 0x65, 0x82, 0xb8, 0xaf, 0x90, 0x9f, 0xcb, 0x58},
  580. 2 << MiB: {0x56, 0x47, 0xf0, 0x5e, 0xc1, 0x89, 0x58, 0x94, 0x7d, 0x32, 0x87, 0x4e, 0xeb, 0x78, 0x8f, 0xa3, 0x96, 0xa0, 0x5d, 0xb, 0xab, 0x7c, 0x1b, 0x71, 0xf1, 0x12, 0xce, 0xb7, 0xe9, 0xb3, 0x1e, 0xee},
  581. 4 << MiB: {0xbb, 0x9f, 0x8d, 0xf6, 0x14, 0x74, 0xd2, 0x5e, 0x71, 0xfa, 0x0, 0x72, 0x23, 0x18, 0xcd, 0x38, 0x73, 0x96, 0xca, 0x17, 0x36, 0x60, 0x5e, 0x12, 0x48, 0x82, 0x1c, 0xc0, 0xde, 0x3d, 0x3a, 0xf8},
  582. 8 << MiB: {0x2d, 0xae, 0xb1, 0xf3, 0x60, 0x95, 0xb4, 0x4b, 0x31, 0x84, 0x10, 0xb3, 0xf4, 0xe8, 0xb5, 0xd9, 0x89, 0xdc, 0xc7, 0xbb, 0x2, 0x3d, 0x14, 0x26, 0xc4, 0x92, 0xda, 0xb0, 0xa3, 0x5, 0x3e, 0x74},
  583. 16 << MiB: {0x8, 0xa, 0xcf, 0x35, 0xa5, 0x7, 0xac, 0x98, 0x49, 0xcf, 0xcb, 0xa4, 0x7d, 0xc2, 0xad, 0x83, 0xe0, 0x1b, 0x75, 0x66, 0x3a, 0x51, 0x62, 0x79, 0xc8, 0xb9, 0xd2, 0x43, 0xb7, 0x19, 0x64, 0x3e},
  584. }
  585. // IsEmpty returns true if the block is a full block of zeroes.
  586. func (b BlockInfo) IsEmpty() bool {
  587. if v, ok := sha256OfEmptyBlock[b.Size]; ok {
  588. return bytes.Equal(b.Hash, v[:])
  589. }
  590. return false
  591. }
  592. func BlocksHash(bs []BlockInfo) []byte {
  593. h := sha256.New()
  594. for _, b := range bs {
  595. _, _ = h.Write(b.Hash)
  596. }
  597. return h.Sum(nil)
  598. }
  599. func VectorHash(v Vector) []byte {
  600. h := sha256.New()
  601. for _, c := range v.Counters {
  602. if err := binary.Write(h, binary.BigEndian, c.ID); err != nil {
  603. panic("impossible: failed to write c.ID to hash function: " + err.Error())
  604. }
  605. if err := binary.Write(h, binary.BigEndian, c.Value); err != nil {
  606. panic("impossible: failed to write c.Value to hash function: " + err.Error())
  607. }
  608. }
  609. return h.Sum(nil)
  610. }
  611. // Xattrs is a convenience method to return the extended attributes of the
  612. // file for the current platform.
  613. func (p *PlatformData) Xattrs() []Xattr {
  614. switch {
  615. case build.IsLinux && p.Linux != nil:
  616. return p.Linux.Xattrs
  617. case build.IsDarwin && p.Darwin != nil:
  618. return p.Darwin.Xattrs
  619. case build.IsFreeBSD && p.FreeBSD != nil:
  620. return p.FreeBSD.Xattrs
  621. case build.IsNetBSD && p.NetBSD != nil:
  622. return p.NetBSD.Xattrs
  623. default:
  624. return nil
  625. }
  626. }
  627. // SetXattrs is a convenience method to set the extended attributes of the
  628. // file for the current platform.
  629. func (p *PlatformData) SetXattrs(xattrs []Xattr) {
  630. switch {
  631. case build.IsLinux:
  632. if p.Linux == nil {
  633. p.Linux = &XattrData{}
  634. }
  635. p.Linux.Xattrs = xattrs
  636. case build.IsDarwin:
  637. if p.Darwin == nil {
  638. p.Darwin = &XattrData{}
  639. }
  640. p.Darwin.Xattrs = xattrs
  641. case build.IsFreeBSD:
  642. if p.FreeBSD == nil {
  643. p.FreeBSD = &XattrData{}
  644. }
  645. p.FreeBSD.Xattrs = xattrs
  646. case build.IsNetBSD:
  647. if p.NetBSD == nil {
  648. p.NetBSD = &XattrData{}
  649. }
  650. p.NetBSD.Xattrs = xattrs
  651. }
  652. }
  653. // MergeWith copies platform data from other, for platforms where it's not
  654. // already set on p.
  655. func (p *PlatformData) MergeWith(other *PlatformData) {
  656. if p.Unix == nil {
  657. p.Unix = other.Unix
  658. }
  659. if p.Windows == nil {
  660. p.Windows = other.Windows
  661. }
  662. if p.Linux == nil {
  663. p.Linux = other.Linux
  664. }
  665. if p.Darwin == nil {
  666. p.Darwin = other.Darwin
  667. }
  668. if p.FreeBSD == nil {
  669. p.FreeBSD = other.FreeBSD
  670. }
  671. if p.NetBSD == nil {
  672. p.NetBSD = other.NetBSD
  673. }
  674. }
  675. // blocksEqual returns whether two slices of blocks are exactly the same hash
  676. // and index pair wise.
  677. func blocksEqual(a, b []BlockInfo) bool {
  678. if len(b) != len(a) {
  679. return false
  680. }
  681. for i, sblk := range a {
  682. if !bytes.Equal(sblk.Hash, b[i].Hash) {
  683. return false
  684. }
  685. }
  686. return true
  687. }
  688. type PlatformData struct {
  689. Unix *UnixData
  690. Windows *WindowsData
  691. Linux *XattrData
  692. Darwin *XattrData
  693. FreeBSD *XattrData
  694. NetBSD *XattrData
  695. }
  696. func (p *PlatformData) toWire() *bep.PlatformData {
  697. return &bep.PlatformData{
  698. Unix: p.Unix.toWire(),
  699. Windows: p.Windows,
  700. Linux: p.Linux.toWire(),
  701. Darwin: p.Darwin.toWire(),
  702. Freebsd: p.FreeBSD.toWire(),
  703. Netbsd: p.NetBSD.toWire(),
  704. }
  705. }
  706. func platformDataFromWire(w *bep.PlatformData) PlatformData {
  707. if w == nil {
  708. return PlatformData{}
  709. }
  710. return PlatformData{
  711. Unix: unixDataFromWire(w.Unix),
  712. Windows: w.Windows,
  713. Linux: xattrDataFromWire(w.Linux),
  714. Darwin: xattrDataFromWire(w.Darwin),
  715. FreeBSD: xattrDataFromWire(w.Freebsd),
  716. NetBSD: xattrDataFromWire(w.Netbsd),
  717. }
  718. }
  719. type UnixData struct {
  720. // The owner name and group name are set when known (i.e., could be
  721. // resolved on the source device), while the UID and GID are always set
  722. // as they come directly from the stat() call.
  723. OwnerName string
  724. GroupName string
  725. UID int
  726. GID int
  727. }
  728. func (u *UnixData) toWire() *bep.UnixData {
  729. if u == nil {
  730. return nil
  731. }
  732. return &bep.UnixData{
  733. OwnerName: u.OwnerName,
  734. GroupName: u.GroupName,
  735. Uid: int32(u.UID),
  736. Gid: int32(u.GID),
  737. }
  738. }
  739. func unixDataFromWire(w *bep.UnixData) *UnixData {
  740. if w == nil {
  741. return nil
  742. }
  743. return &UnixData{
  744. OwnerName: w.OwnerName,
  745. GroupName: w.GroupName,
  746. UID: int(w.Uid),
  747. GID: int(w.Gid),
  748. }
  749. }
  750. type WindowsData = bep.WindowsData
  751. type XattrData struct {
  752. Xattrs []Xattr
  753. }
  754. func (x *XattrData) toWire() *bep.XattrData {
  755. if x == nil {
  756. return nil
  757. }
  758. xattrs := make([]*bep.Xattr, len(x.Xattrs))
  759. for i, a := range x.Xattrs {
  760. xattrs[i] = a.toWire()
  761. }
  762. return &bep.XattrData{
  763. Xattrs: xattrs,
  764. }
  765. }
  766. func xattrDataFromWire(w *bep.XattrData) *XattrData {
  767. if w == nil {
  768. return nil
  769. }
  770. x := &XattrData{}
  771. x.Xattrs = make([]Xattr, len(w.Xattrs))
  772. for i, a := range w.Xattrs {
  773. x.Xattrs[i] = xattrFromWire(a)
  774. }
  775. return x
  776. }
  777. type Xattr struct {
  778. Name string
  779. Value []byte
  780. }
  781. func (a Xattr) toWire() *bep.Xattr {
  782. return &bep.Xattr{
  783. Name: a.Name,
  784. Value: a.Value,
  785. }
  786. }
  787. func xattrFromWire(w *bep.Xattr) Xattr {
  788. return Xattr{
  789. Name: w.Name,
  790. Value: w.Value,
  791. }
  792. }
  793. func xattrsEqual(a, b *XattrData) bool {
  794. aEmpty := a == nil || len(a.Xattrs) == 0
  795. bEmpty := b == nil || len(b.Xattrs) == 0
  796. if aEmpty && bEmpty {
  797. return true
  798. }
  799. if aEmpty || bEmpty {
  800. // Only one side is empty, so they can't be equal.
  801. return false
  802. }
  803. if len(a.Xattrs) != len(b.Xattrs) {
  804. return false
  805. }
  806. for i := range a.Xattrs {
  807. if a.Xattrs[i].Name != b.Xattrs[i].Name {
  808. return false
  809. }
  810. if !bytes.Equal(a.Xattrs[i].Value, b.Xattrs[i].Value) {
  811. return false
  812. }
  813. }
  814. return true
  815. }
  816. func unixOwnershipEqual(a, b *UnixData) bool {
  817. if a == nil && b == nil {
  818. return true
  819. }
  820. if a == nil || b == nil {
  821. return false
  822. }
  823. if a.UID == b.UID && a.GID == b.GID {
  824. return true
  825. }
  826. if a.OwnerName == b.OwnerName && a.GroupName == b.GroupName {
  827. return true
  828. }
  829. return false
  830. }
  831. func windowsOwnershipEqual(a, b *WindowsData) bool {
  832. if a == nil && b == nil {
  833. return true
  834. }
  835. if a == nil || b == nil {
  836. return false
  837. }
  838. return a.OwnerName == b.OwnerName && a.OwnerIsGroup == b.OwnerIsGroup
  839. }