bep_fileinfo.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. "time"
  13. "github.com/syncthing/syncthing/internal/gen/bep"
  14. "github.com/syncthing/syncthing/lib/build"
  15. )
  16. type FlagLocal uint32
  17. // FileInfo.LocalFlags flags
  18. const (
  19. FlagLocalUnsupported FlagLocal = 1 << 0 // 1: The kind is unsupported, e.g. symlinks on Windows
  20. FlagLocalIgnored FlagLocal = 1 << 1 // 2: Matches local ignore patterns
  21. FlagLocalMustRescan FlagLocal = 1 << 2 // 4: Doesn't match content on disk, must be rechecked fully
  22. FlagLocalReceiveOnly FlagLocal = 1 << 3 // 8: Change detected on receive only folder
  23. FlagLocalGlobal FlagLocal = 1 << 4 // 16: This is the global file version
  24. FlagLocalNeeded FlagLocal = 1 << 5 // 32: We need this file
  25. FlagLocalRemoteInvalid FlagLocal = 1 << 6 // 64: The remote marked this as invalid
  26. // Flags that should result in the Invalid bit on outgoing updates (or had it on ingoing ones)
  27. LocalInvalidFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly | FlagLocalRemoteInvalid
  28. // Flags that should result in a file being in conflict with its
  29. // successor, due to us not having an up to date picture of its state on
  30. // disk.
  31. LocalConflictFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalReceiveOnly
  32. LocalAllFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly | FlagLocalGlobal | FlagLocalNeeded | FlagLocalRemoteInvalid
  33. )
  34. func (f FlagLocal) IsInvalid() bool {
  35. return f&LocalInvalidFlags != 0
  36. }
  37. // BlockSizes is the list of valid block sizes, from min to max
  38. var BlockSizes []int
  39. func init() {
  40. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  41. BlockSizes = append(BlockSizes, blockSize)
  42. if _, ok := sha256OfEmptyBlock[blockSize]; !ok {
  43. panic("missing hard coded value for sha256 of empty block")
  44. }
  45. }
  46. BufferPool = newBufferPool() // must happen after BlockSizes is initialized
  47. }
  48. type FileInfoType = bep.FileInfoType
  49. const (
  50. FileInfoTypeFile = bep.FileInfoType_FILE_INFO_TYPE_FILE
  51. FileInfoTypeDirectory = bep.FileInfoType_FILE_INFO_TYPE_DIRECTORY
  52. FileInfoTypeSymlinkFile = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK_FILE
  53. FileInfoTypeSymlinkDirectory = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK_DIRECTORY
  54. FileInfoTypeSymlink = bep.FileInfoType_FILE_INFO_TYPE_SYMLINK
  55. )
  56. type FileInfo struct {
  57. Name string
  58. Size int64
  59. ModifiedS int64
  60. ModifiedBy ShortID
  61. Version Vector
  62. Sequence int64
  63. Blocks []BlockInfo
  64. SymlinkTarget []byte
  65. BlocksHash []byte
  66. Encrypted []byte
  67. Platform PlatformData
  68. Type FileInfoType
  69. Permissions uint32
  70. ModifiedNs int32
  71. RawBlockSize int32
  72. // The local_flags fields stores flags that are relevant to the local
  73. // host only. It is not part of the protocol, doesn't get sent or
  74. // received (we make sure to zero it), nonetheless we need it on our
  75. // struct and to be able to serialize it to/from the database.
  76. // It does carry the info to decide if the file is invalid, which is part of
  77. // the protocol.
  78. LocalFlags FlagLocal
  79. // The version_hash is an implementation detail and not part of the wire
  80. // format.
  81. VersionHash []byte
  82. // The time when the inode was last changed (i.e., permissions, xattrs
  83. // etc changed). This is host-local, not sent over the wire.
  84. InodeChangeNs int64
  85. // The size of the data appended to the encrypted file on disk. This is
  86. // host-local, not sent over the wire.
  87. EncryptionTrailerSize int
  88. Deleted bool
  89. NoPermissions bool
  90. truncated bool // was created from a truncated file info without blocks
  91. }
  92. func (f *FileInfo) ToWire(withInternalFields bool) *bep.FileInfo {
  93. if f.truncated && !(f.IsDeleted() || f.IsInvalid() || f.IsIgnored()) {
  94. panic("bug: must not serialize truncated file info")
  95. }
  96. blocks := make([]*bep.BlockInfo, len(f.Blocks))
  97. for j, b := range f.Blocks {
  98. blocks[j] = b.ToWire()
  99. }
  100. w := &bep.FileInfo{
  101. Name: f.Name,
  102. Size: f.Size,
  103. ModifiedS: f.ModifiedS,
  104. ModifiedBy: uint64(f.ModifiedBy),
  105. Version: f.Version.ToWire(),
  106. Sequence: f.Sequence,
  107. Blocks: blocks,
  108. SymlinkTarget: f.SymlinkTarget,
  109. BlocksHash: f.BlocksHash,
  110. Encrypted: f.Encrypted,
  111. Type: f.Type,
  112. Permissions: f.Permissions,
  113. ModifiedNs: f.ModifiedNs,
  114. BlockSize: f.RawBlockSize,
  115. Platform: f.Platform.toWire(),
  116. Deleted: f.Deleted,
  117. Invalid: f.IsInvalid(),
  118. NoPermissions: f.NoPermissions,
  119. }
  120. if withInternalFields {
  121. w.LocalFlags = uint32(f.LocalFlags)
  122. w.VersionHash = f.VersionHash
  123. w.InodeChangeNs = f.InodeChangeNs
  124. w.EncryptionTrailerSize = int32(f.EncryptionTrailerSize)
  125. }
  126. return w
  127. }
  128. // WinsConflict returns true if "f" is the one to choose when it is in
  129. // conflict with "other".
  130. func (f *FileInfo) WinsConflict(other FileInfo) bool {
  131. // If only one of the files is invalid, that one loses.
  132. if f.IsInvalid() != other.IsInvalid() {
  133. return !f.IsInvalid()
  134. }
  135. // If a modification is in conflict with a delete, we pick the
  136. // modification.
  137. if !f.IsDeleted() && other.IsDeleted() {
  138. return true
  139. }
  140. if f.IsDeleted() && !other.IsDeleted() {
  141. return false
  142. }
  143. // The one with the newer modification time wins.
  144. if f.ModTime().After(other.ModTime()) {
  145. return true
  146. }
  147. if f.ModTime().Before(other.ModTime()) {
  148. return false
  149. }
  150. // The modification times were equal. Use the device ID in the version
  151. // vector as tie breaker.
  152. return f.FileVersion().Compare(other.FileVersion()) == ConcurrentGreater
  153. }
  154. func FileInfoFromWire(w *bep.FileInfo) FileInfo {
  155. var blocks []BlockInfo
  156. if len(w.Blocks) > 0 {
  157. blocks = make([]BlockInfo, len(w.Blocks))
  158. for j, b := range w.Blocks {
  159. blocks[j] = BlockInfoFromWire(b)
  160. }
  161. }
  162. return fileInfoFromWireWithBlocks(w, blocks)
  163. }
  164. type FileInfoWithoutBlocks interface {
  165. GetName() string
  166. GetSize() int64
  167. GetModifiedS() int64
  168. GetModifiedBy() uint64
  169. GetVersion() *bep.Vector
  170. GetSequence() int64
  171. // GetBlocks() []*bep.BlockInfo // not included
  172. GetSymlinkTarget() []byte
  173. GetBlocksHash() []byte
  174. GetEncrypted() []byte
  175. GetType() FileInfoType
  176. GetPermissions() uint32
  177. GetModifiedNs() int32
  178. GetBlockSize() int32
  179. GetPlatform() *bep.PlatformData
  180. GetLocalFlags() uint32
  181. GetVersionHash() []byte
  182. GetInodeChangeNs() int64
  183. GetEncryptionTrailerSize() int32
  184. GetDeleted() bool
  185. GetInvalid() bool
  186. GetNoPermissions() bool
  187. }
  188. func fileInfoFromWireWithBlocks(w FileInfoWithoutBlocks, blocks []BlockInfo) FileInfo {
  189. var localFlags FlagLocal
  190. if w.GetInvalid() {
  191. localFlags = FlagLocalRemoteInvalid
  192. }
  193. return FileInfo{
  194. Name: w.GetName(),
  195. Size: w.GetSize(),
  196. ModifiedS: w.GetModifiedS(),
  197. ModifiedBy: ShortID(w.GetModifiedBy()),
  198. Version: VectorFromWire(w.GetVersion()),
  199. Sequence: w.GetSequence(),
  200. Blocks: blocks,
  201. SymlinkTarget: w.GetSymlinkTarget(),
  202. BlocksHash: w.GetBlocksHash(),
  203. Encrypted: w.GetEncrypted(),
  204. Type: w.GetType(),
  205. Permissions: w.GetPermissions(),
  206. ModifiedNs: w.GetModifiedNs(),
  207. RawBlockSize: w.GetBlockSize(),
  208. Platform: platformDataFromWire(w.GetPlatform()),
  209. Deleted: w.GetDeleted(),
  210. LocalFlags: localFlags,
  211. NoPermissions: w.GetNoPermissions(),
  212. }
  213. }
  214. func FileInfoFromDB(w *bep.FileInfo) FileInfo {
  215. f := FileInfoFromWire(w)
  216. f.LocalFlags = FlagLocal(w.LocalFlags)
  217. f.VersionHash = w.VersionHash
  218. f.InodeChangeNs = w.InodeChangeNs
  219. f.EncryptionTrailerSize = int(w.EncryptionTrailerSize)
  220. return f
  221. }
  222. func FileInfoFromDBTruncated(w FileInfoWithoutBlocks) FileInfo {
  223. f := fileInfoFromWireWithBlocks(w, nil)
  224. f.LocalFlags = FlagLocal(w.GetLocalFlags())
  225. f.VersionHash = w.GetVersionHash()
  226. f.InodeChangeNs = w.GetInodeChangeNs()
  227. f.EncryptionTrailerSize = int(w.GetEncryptionTrailerSize())
  228. f.truncated = true
  229. return f
  230. }
  231. func (f FileInfo) String() string {
  232. switch f.Type {
  233. case FileInfoTypeDirectory:
  234. return fmt.Sprintf("Directory{Name:%q, Sequence:%d, Permissions:0%o, ModTime:%v, Version:%v, VersionHash:%x, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, Platform:%v, InodeChangeTime:%v}",
  235. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.VersionHash, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.Platform, f.InodeChangeTime())
  236. case FileInfoTypeFile:
  237. return fmt.Sprintf("File{Name:%q, Sequence:%d, Permissions:0%o, ModTime:%v, Version:%v, VersionHash:%x, Length:%d, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, BlockSize:%d, NumBlocks:%d, BlocksHash:%x, Platform:%v, InodeChangeTime:%v}",
  238. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.VersionHash, f.Size, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.RawBlockSize, len(f.Blocks), f.BlocksHash, f.Platform, f.InodeChangeTime())
  239. case FileInfoTypeSymlink, FileInfoTypeSymlinkDirectory, FileInfoTypeSymlinkFile:
  240. return fmt.Sprintf("Symlink{Name:%q, Type:%v, Sequence:%d, Version:%v, VersionHash:%x, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, SymlinkTarget:%q, Platform:%v, InodeChangeTime:%v}",
  241. f.Name, f.Type, f.Sequence, f.Version, f.VersionHash, f.Deleted, f.IsInvalid(), f.LocalFlags, f.NoPermissions, f.SymlinkTarget, f.Platform, f.InodeChangeTime())
  242. default:
  243. panic("mystery file type detected")
  244. }
  245. }
  246. func (f FileInfo) IsDeleted() bool {
  247. return f.Deleted
  248. }
  249. func (f FileInfo) IsInvalid() bool {
  250. return f.LocalFlags.IsInvalid()
  251. }
  252. func (f FileInfo) IsUnsupported() bool {
  253. return f.LocalFlags&FlagLocalUnsupported != 0
  254. }
  255. func (f FileInfo) IsIgnored() bool {
  256. return f.LocalFlags&FlagLocalIgnored != 0
  257. }
  258. func (f FileInfo) MustRescan() bool {
  259. return f.LocalFlags&FlagLocalMustRescan != 0
  260. }
  261. func (f FileInfo) IsReceiveOnlyChanged() bool {
  262. return f.LocalFlags&FlagLocalReceiveOnly != 0
  263. }
  264. func (f FileInfo) IsDirectory() bool {
  265. return f.Type == FileInfoTypeDirectory
  266. }
  267. func (f FileInfo) ShouldConflict() bool {
  268. return f.LocalFlags&LocalConflictFlags != 0
  269. }
  270. func (f FileInfo) IsSymlink() bool {
  271. switch f.Type {
  272. case FileInfoTypeSymlink, FileInfoTypeSymlinkDirectory, FileInfoTypeSymlinkFile:
  273. return true
  274. default:
  275. return false
  276. }
  277. }
  278. func (f FileInfo) HasPermissionBits() bool {
  279. return !f.NoPermissions
  280. }
  281. func (f FileInfo) FileSize() int64 {
  282. if f.Deleted {
  283. return 0
  284. }
  285. if f.IsDirectory() || f.IsSymlink() {
  286. return SyntheticDirectorySize
  287. }
  288. return f.Size
  289. }
  290. func (f FileInfo) BlockSize() int {
  291. if f.RawBlockSize < MinBlockSize {
  292. return MinBlockSize
  293. }
  294. return int(f.RawBlockSize)
  295. }
  296. // BlockSize returns the block size to use for the given file size
  297. func BlockSize(fileSize int64) int {
  298. var blockSize int
  299. for _, blockSize = range BlockSizes {
  300. if fileSize < DesiredPerFileBlocks*int64(blockSize) {
  301. break
  302. }
  303. }
  304. return blockSize
  305. }
  306. func (f FileInfo) FileName() string {
  307. return f.Name
  308. }
  309. func (f FileInfo) FileLocalFlags() FlagLocal {
  310. return f.LocalFlags
  311. }
  312. func (f FileInfo) ModTime() time.Time {
  313. return time.Unix(f.ModifiedS, int64(f.ModifiedNs))
  314. }
  315. func (f FileInfo) SequenceNo() int64 {
  316. return f.Sequence
  317. }
  318. func (f FileInfo) FileVersion() Vector {
  319. return f.Version
  320. }
  321. func (f FileInfo) FileType() FileInfoType {
  322. return f.Type
  323. }
  324. func (f FileInfo) FilePermissions() uint32 {
  325. return f.Permissions
  326. }
  327. func (f FileInfo) FileModifiedBy() ShortID {
  328. return f.ModifiedBy
  329. }
  330. func (f FileInfo) PlatformData() PlatformData {
  331. return f.Platform
  332. }
  333. func (f FileInfo) InodeChangeTime() time.Time {
  334. return time.Unix(0, f.InodeChangeNs)
  335. }
  336. func (f FileInfo) FileBlocksHash() []byte {
  337. return f.BlocksHash
  338. }
  339. type FileInfoComparison struct {
  340. ModTimeWindow time.Duration
  341. IgnorePerms bool
  342. IgnoreBlocks bool
  343. IgnoreFlags FlagLocal
  344. IgnoreOwnership bool
  345. IgnoreXattrs bool
  346. }
  347. func (f FileInfo) IsEquivalent(other FileInfo, modTimeWindow time.Duration) bool {
  348. return f.isEquivalent(other, FileInfoComparison{ModTimeWindow: modTimeWindow})
  349. }
  350. func (f FileInfo) IsEquivalentOptional(other FileInfo, comp FileInfoComparison) bool {
  351. return f.isEquivalent(other, comp)
  352. }
  353. // isEquivalent checks that the two file infos represent the same actual file content,
  354. // i.e. it does purposely not check only selected (see below) struct members.
  355. // Permissions (config) and blocks (scanning) can be excluded from the comparison.
  356. // Any file info is not "equivalent", if it has different
  357. // - type
  358. // - deleted flag
  359. // - invalid flag
  360. // - permissions, unless they are ignored
  361. //
  362. // A file is not "equivalent", if it has different
  363. // - modification time (difference bigger than modTimeWindow)
  364. // - size
  365. // - blocks, unless there are no blocks to compare (scanning)
  366. // - os data
  367. //
  368. // A symlink is not "equivalent", if it has different
  369. // - target
  370. //
  371. // A directory does not have anything specific to check.
  372. func (f FileInfo) isEquivalent(other FileInfo, comp FileInfoComparison) bool {
  373. if f.MustRescan() || other.MustRescan() {
  374. // These are per definition not equivalent because they don't
  375. // represent a valid state, even if both happen to have the
  376. // MustRescan bit set.
  377. return false
  378. }
  379. // If we care about either ownership or xattrs, are recording inode change
  380. // times and it changed, they are not equal.
  381. if !(comp.IgnoreOwnership && comp.IgnoreXattrs) && f.InodeChangeNs != 0 && other.InodeChangeNs != 0 && f.InodeChangeNs != other.InodeChangeNs {
  382. return false
  383. }
  384. // Mask out the ignored local flags before checking IsInvalid() below
  385. f.LocalFlags &^= comp.IgnoreFlags
  386. other.LocalFlags &^= comp.IgnoreFlags
  387. if f.Name != other.Name || f.Type != other.Type || f.Deleted != other.Deleted || f.IsInvalid() != other.IsInvalid() {
  388. return false
  389. }
  390. if !comp.IgnoreOwnership && f.Platform != other.Platform {
  391. if !unixOwnershipEqual(f.Platform.Unix, other.Platform.Unix) {
  392. return false
  393. }
  394. if !windowsOwnershipEqual(f.Platform.Windows, other.Platform.Windows) {
  395. return false
  396. }
  397. }
  398. if !comp.IgnoreXattrs && f.Platform != other.Platform {
  399. if !xattrsEqual(f.Platform.Linux, other.Platform.Linux) {
  400. return false
  401. }
  402. if !xattrsEqual(f.Platform.Darwin, other.Platform.Darwin) {
  403. return false
  404. }
  405. if !xattrsEqual(f.Platform.FreeBSD, other.Platform.FreeBSD) {
  406. return false
  407. }
  408. if !xattrsEqual(f.Platform.NetBSD, other.Platform.NetBSD) {
  409. return false
  410. }
  411. }
  412. if !comp.IgnorePerms && !f.NoPermissions && !other.NoPermissions && !PermsEqual(f.Permissions, other.Permissions) {
  413. return false
  414. }
  415. switch f.Type {
  416. case FileInfoTypeFile:
  417. return f.Size == other.Size && ModTimeEqual(f.ModTime(), other.ModTime(), comp.ModTimeWindow) && (comp.IgnoreBlocks || f.BlocksEqual(other))
  418. case FileInfoTypeSymlink:
  419. return bytes.Equal(f.SymlinkTarget, other.SymlinkTarget)
  420. case FileInfoTypeDirectory:
  421. return true
  422. }
  423. return false
  424. }
  425. func ModTimeEqual(a, b time.Time, modTimeWindow time.Duration) bool {
  426. if a.Equal(b) {
  427. return true
  428. }
  429. diff := a.Sub(b)
  430. if diff < 0 {
  431. diff *= -1
  432. }
  433. return diff < modTimeWindow
  434. }
  435. func PermsEqual(a, b uint32) bool {
  436. if build.IsWindows {
  437. // There is only writeable and read only, represented for user, group
  438. // and other equally. We only compare against user.
  439. return a&0o600 == b&0o600
  440. }
  441. // All bits count
  442. return a&0o777 == b&0o777
  443. }
  444. // BlocksEqual returns true when the two files have identical block lists.
  445. func (f FileInfo) BlocksEqual(other FileInfo) bool {
  446. // If both sides have blocks hashes and they match, we are good. If they
  447. // don't match still check individual block hashes to catch differences
  448. // in weak hashes only (e.g. after switching weak hash algo).
  449. if len(f.BlocksHash) > 0 && len(other.BlocksHash) > 0 && bytes.Equal(f.BlocksHash, other.BlocksHash) {
  450. return true
  451. }
  452. // Actually compare the block lists in full.
  453. return blocksEqual(f.Blocks, other.Blocks)
  454. }
  455. func (f *FileInfo) SetMustRescan() {
  456. f.setLocalFlags(FlagLocalMustRescan)
  457. }
  458. func (f *FileInfo) SetIgnored() {
  459. f.setLocalFlags(FlagLocalIgnored)
  460. }
  461. func (f *FileInfo) SetUnsupported() {
  462. f.setLocalFlags(FlagLocalUnsupported)
  463. }
  464. func (f *FileInfo) SetDeleted(by ShortID) {
  465. f.ModifiedBy = by
  466. f.Deleted = true
  467. f.Version = f.Version.Update(by)
  468. f.ModifiedS = time.Now().Unix()
  469. f.setNoContent()
  470. }
  471. func (f *FileInfo) setLocalFlags(flags FlagLocal) {
  472. f.LocalFlags = flags
  473. f.setNoContent()
  474. }
  475. func (f *FileInfo) setNoContent() {
  476. f.Blocks = nil
  477. f.BlocksHash = nil
  478. f.Size = 0
  479. }
  480. type BlockInfo struct {
  481. Hash []byte
  482. Offset int64
  483. Size int
  484. }
  485. func (b BlockInfo) ToWire() *bep.BlockInfo {
  486. return &bep.BlockInfo{
  487. Hash: b.Hash,
  488. Offset: b.Offset,
  489. Size: int32(b.Size),
  490. }
  491. }
  492. func BlockInfoFromWire(w *bep.BlockInfo) BlockInfo {
  493. return BlockInfo{
  494. Hash: w.Hash,
  495. Offset: w.Offset,
  496. Size: int(w.Size),
  497. }
  498. }
  499. func (b BlockInfo) String() string {
  500. return fmt.Sprintf("Block{%d/%d/%x}", b.Offset, b.Size, b.Hash)
  501. }
  502. // For each block size, the hash of a block of all zeroes
  503. var sha256OfEmptyBlock = map[int][sha256.Size]byte{
  504. 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},
  505. 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},
  506. 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},
  507. 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},
  508. 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},
  509. 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},
  510. 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},
  511. 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},
  512. }
  513. // IsEmpty returns true if the block is a full block of zeroes.
  514. func (b BlockInfo) IsEmpty() bool {
  515. if v, ok := sha256OfEmptyBlock[b.Size]; ok {
  516. return bytes.Equal(b.Hash, v[:])
  517. }
  518. return false
  519. }
  520. func BlocksHash(bs []BlockInfo) []byte {
  521. h := sha256.New()
  522. for _, b := range bs {
  523. _, _ = h.Write(b.Hash)
  524. }
  525. return h.Sum(nil)
  526. }
  527. func VectorHash(v Vector) []byte {
  528. h := sha256.New()
  529. for _, c := range v.Counters {
  530. if err := binary.Write(h, binary.BigEndian, c.ID); err != nil {
  531. panic("impossible: failed to write c.ID to hash function: " + err.Error())
  532. }
  533. if err := binary.Write(h, binary.BigEndian, c.Value); err != nil {
  534. panic("impossible: failed to write c.Value to hash function: " + err.Error())
  535. }
  536. }
  537. return h.Sum(nil)
  538. }
  539. // Xattrs is a convenience method to return the extended attributes of the
  540. // file for the current platform.
  541. func (p *PlatformData) Xattrs() []Xattr {
  542. switch {
  543. case build.IsLinux && p.Linux != nil:
  544. return p.Linux.Xattrs
  545. case build.IsDarwin && p.Darwin != nil:
  546. return p.Darwin.Xattrs
  547. case build.IsFreeBSD && p.FreeBSD != nil:
  548. return p.FreeBSD.Xattrs
  549. case build.IsNetBSD && p.NetBSD != nil:
  550. return p.NetBSD.Xattrs
  551. default:
  552. return nil
  553. }
  554. }
  555. // SetXattrs is a convenience method to set the extended attributes of the
  556. // file for the current platform.
  557. func (p *PlatformData) SetXattrs(xattrs []Xattr) {
  558. switch {
  559. case build.IsLinux:
  560. if p.Linux == nil {
  561. p.Linux = &XattrData{}
  562. }
  563. p.Linux.Xattrs = xattrs
  564. case build.IsDarwin:
  565. if p.Darwin == nil {
  566. p.Darwin = &XattrData{}
  567. }
  568. p.Darwin.Xattrs = xattrs
  569. case build.IsFreeBSD:
  570. if p.FreeBSD == nil {
  571. p.FreeBSD = &XattrData{}
  572. }
  573. p.FreeBSD.Xattrs = xattrs
  574. case build.IsNetBSD:
  575. if p.NetBSD == nil {
  576. p.NetBSD = &XattrData{}
  577. }
  578. p.NetBSD.Xattrs = xattrs
  579. }
  580. }
  581. // MergeWith copies platform data from other, for platforms where it's not
  582. // already set on p.
  583. func (p *PlatformData) MergeWith(other *PlatformData) {
  584. if p.Unix == nil {
  585. p.Unix = other.Unix
  586. }
  587. if p.Windows == nil {
  588. p.Windows = other.Windows
  589. }
  590. if p.Linux == nil {
  591. p.Linux = other.Linux
  592. }
  593. if p.Darwin == nil {
  594. p.Darwin = other.Darwin
  595. }
  596. if p.FreeBSD == nil {
  597. p.FreeBSD = other.FreeBSD
  598. }
  599. if p.NetBSD == nil {
  600. p.NetBSD = other.NetBSD
  601. }
  602. }
  603. // blocksEqual returns whether two slices of blocks are exactly the same hash
  604. // and index pair wise.
  605. func blocksEqual(a, b []BlockInfo) bool {
  606. if len(b) != len(a) {
  607. return false
  608. }
  609. for i, sblk := range a {
  610. if !bytes.Equal(sblk.Hash, b[i].Hash) {
  611. return false
  612. }
  613. }
  614. return true
  615. }
  616. type PlatformData struct {
  617. Unix *UnixData
  618. Windows *WindowsData
  619. Linux *XattrData
  620. Darwin *XattrData
  621. FreeBSD *XattrData
  622. NetBSD *XattrData
  623. }
  624. func (p *PlatformData) toWire() *bep.PlatformData {
  625. return &bep.PlatformData{
  626. Unix: p.Unix.toWire(),
  627. Windows: p.Windows,
  628. Linux: p.Linux.toWire(),
  629. Darwin: p.Darwin.toWire(),
  630. Freebsd: p.FreeBSD.toWire(),
  631. Netbsd: p.NetBSD.toWire(),
  632. }
  633. }
  634. func platformDataFromWire(w *bep.PlatformData) PlatformData {
  635. if w == nil {
  636. return PlatformData{}
  637. }
  638. return PlatformData{
  639. Unix: unixDataFromWire(w.Unix),
  640. Windows: w.Windows,
  641. Linux: xattrDataFromWire(w.Linux),
  642. Darwin: xattrDataFromWire(w.Darwin),
  643. FreeBSD: xattrDataFromWire(w.Freebsd),
  644. NetBSD: xattrDataFromWire(w.Netbsd),
  645. }
  646. }
  647. type UnixData struct {
  648. // The owner name and group name are set when known (i.e., could be
  649. // resolved on the source device), while the UID and GID are always set
  650. // as they come directly from the stat() call.
  651. OwnerName string
  652. GroupName string
  653. UID int
  654. GID int
  655. }
  656. func (u *UnixData) toWire() *bep.UnixData {
  657. if u == nil {
  658. return nil
  659. }
  660. return &bep.UnixData{
  661. OwnerName: u.OwnerName,
  662. GroupName: u.GroupName,
  663. Uid: int32(u.UID),
  664. Gid: int32(u.GID),
  665. }
  666. }
  667. func unixDataFromWire(w *bep.UnixData) *UnixData {
  668. if w == nil {
  669. return nil
  670. }
  671. return &UnixData{
  672. OwnerName: w.OwnerName,
  673. GroupName: w.GroupName,
  674. UID: int(w.Uid),
  675. GID: int(w.Gid),
  676. }
  677. }
  678. type WindowsData = bep.WindowsData
  679. type XattrData struct {
  680. Xattrs []Xattr
  681. }
  682. func (x *XattrData) toWire() *bep.XattrData {
  683. if x == nil {
  684. return nil
  685. }
  686. xattrs := make([]*bep.Xattr, len(x.Xattrs))
  687. for i, a := range x.Xattrs {
  688. xattrs[i] = a.toWire()
  689. }
  690. return &bep.XattrData{
  691. Xattrs: xattrs,
  692. }
  693. }
  694. func xattrDataFromWire(w *bep.XattrData) *XattrData {
  695. if w == nil {
  696. return nil
  697. }
  698. x := &XattrData{}
  699. x.Xattrs = make([]Xattr, len(w.Xattrs))
  700. for i, a := range w.Xattrs {
  701. x.Xattrs[i] = xattrFromWire(a)
  702. }
  703. return x
  704. }
  705. type Xattr struct {
  706. Name string
  707. Value []byte
  708. }
  709. func (a Xattr) toWire() *bep.Xattr {
  710. return &bep.Xattr{
  711. Name: a.Name,
  712. Value: a.Value,
  713. }
  714. }
  715. func xattrFromWire(w *bep.Xattr) Xattr {
  716. return Xattr{
  717. Name: w.Name,
  718. Value: w.Value,
  719. }
  720. }
  721. func xattrsEqual(a, b *XattrData) bool {
  722. aEmpty := a == nil || len(a.Xattrs) == 0
  723. bEmpty := b == nil || len(b.Xattrs) == 0
  724. if aEmpty && bEmpty {
  725. return true
  726. }
  727. if aEmpty || bEmpty {
  728. // Only one side is empty, so they can't be equal.
  729. return false
  730. }
  731. if len(a.Xattrs) != len(b.Xattrs) {
  732. return false
  733. }
  734. for i := range a.Xattrs {
  735. if a.Xattrs[i].Name != b.Xattrs[i].Name {
  736. return false
  737. }
  738. if !bytes.Equal(a.Xattrs[i].Value, b.Xattrs[i].Value) {
  739. return false
  740. }
  741. }
  742. return true
  743. }
  744. func unixOwnershipEqual(a, b *UnixData) bool {
  745. if a == nil && b == nil {
  746. return true
  747. }
  748. if a == nil || b == nil {
  749. return false
  750. }
  751. ownerEqual := a.OwnerName == "" || b.OwnerName == "" || a.OwnerName == b.OwnerName
  752. groupEqual := a.GroupName == "" || b.GroupName == "" || a.GroupName == b.GroupName
  753. return a.UID == b.UID && a.GID == b.GID && ownerEqual && groupEqual
  754. }
  755. func windowsOwnershipEqual(a, b *WindowsData) bool {
  756. if a == nil && b == nil {
  757. return true
  758. }
  759. if a == nil || b == nil {
  760. return false
  761. }
  762. return a.OwnerName == b.OwnerName && a.OwnerIsGroup == b.OwnerIsGroup
  763. }