structs.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 db
  7. import (
  8. "bytes"
  9. "fmt"
  10. "strings"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/protocol"
  13. )
  14. func (f FileInfoTruncated) String() string {
  15. switch f.Type {
  16. case protocol.FileInfoTypeDirectory:
  17. return fmt.Sprintf("Directory{Name:%q, Sequence:%d, Permissions:0%o, ModTime:%v, Version:%v, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v}",
  18. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.Deleted, f.RawInvalid, f.LocalFlags, f.NoPermissions)
  19. case protocol.FileInfoTypeFile:
  20. 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}",
  21. f.Name, f.Sequence, f.Permissions, f.ModTime(), f.Version, f.Size, f.Deleted, f.RawInvalid, f.LocalFlags, f.NoPermissions, f.RawBlockSize)
  22. case protocol.FileInfoTypeSymlink, protocol.FileInfoTypeSymlinkDirectory, protocol.FileInfoTypeSymlinkFile:
  23. return fmt.Sprintf("Symlink{Name:%q, Type:%v, Sequence:%d, Version:%v, Deleted:%v, Invalid:%v, LocalFlags:0x%x, NoPermissions:%v, SymlinkTarget:%q}",
  24. f.Name, f.Type, f.Sequence, f.Version, f.Deleted, f.RawInvalid, f.LocalFlags, f.NoPermissions, f.SymlinkTarget)
  25. default:
  26. panic("mystery file type detected")
  27. }
  28. }
  29. func (f FileInfoTruncated) IsDeleted() bool {
  30. return f.Deleted
  31. }
  32. func (f FileInfoTruncated) IsInvalid() bool {
  33. return f.RawInvalid || f.LocalFlags&protocol.LocalInvalidFlags != 0
  34. }
  35. func (f FileInfoTruncated) IsUnsupported() bool {
  36. return f.LocalFlags&protocol.FlagLocalUnsupported != 0
  37. }
  38. func (f FileInfoTruncated) IsIgnored() bool {
  39. return f.LocalFlags&protocol.FlagLocalIgnored != 0
  40. }
  41. func (f FileInfoTruncated) MustRescan() bool {
  42. return f.LocalFlags&protocol.FlagLocalMustRescan != 0
  43. }
  44. func (f FileInfoTruncated) IsReceiveOnlyChanged() bool {
  45. return f.LocalFlags&protocol.FlagLocalReceiveOnly != 0
  46. }
  47. func (f FileInfoTruncated) IsDirectory() bool {
  48. return f.Type == protocol.FileInfoTypeDirectory
  49. }
  50. func (f FileInfoTruncated) IsSymlink() bool {
  51. switch f.Type {
  52. case protocol.FileInfoTypeSymlink, protocol.FileInfoTypeSymlinkDirectory, protocol.FileInfoTypeSymlinkFile:
  53. return true
  54. default:
  55. return false
  56. }
  57. }
  58. func (f FileInfoTruncated) ShouldConflict() bool {
  59. return f.LocalFlags&protocol.LocalConflictFlags != 0
  60. }
  61. func (f FileInfoTruncated) HasPermissionBits() bool {
  62. return !f.NoPermissions
  63. }
  64. func (f FileInfoTruncated) FileSize() int64 {
  65. if f.Deleted {
  66. return 0
  67. }
  68. if f.IsDirectory() || f.IsSymlink() {
  69. return protocol.SyntheticDirectorySize
  70. }
  71. return f.Size
  72. }
  73. func (f FileInfoTruncated) BlockSize() int {
  74. if f.RawBlockSize == 0 {
  75. return protocol.MinBlockSize
  76. }
  77. return int(f.RawBlockSize)
  78. }
  79. func (f FileInfoTruncated) FileName() string {
  80. return f.Name
  81. }
  82. func (f FileInfoTruncated) FileLocalFlags() uint32 {
  83. return f.LocalFlags
  84. }
  85. func (f FileInfoTruncated) ModTime() time.Time {
  86. return time.Unix(f.ModifiedS, int64(f.ModifiedNs))
  87. }
  88. func (f FileInfoTruncated) SequenceNo() int64 {
  89. return f.Sequence
  90. }
  91. func (f FileInfoTruncated) FileVersion() protocol.Vector {
  92. return f.Version
  93. }
  94. func (f FileInfoTruncated) FileType() protocol.FileInfoType {
  95. return f.Type
  96. }
  97. func (f FileInfoTruncated) FilePermissions() uint32 {
  98. return f.Permissions
  99. }
  100. func (f FileInfoTruncated) FileModifiedBy() protocol.ShortID {
  101. return f.ModifiedBy
  102. }
  103. func (f FileInfoTruncated) PlatformData() protocol.PlatformData {
  104. return f.Platform
  105. }
  106. func (f FileInfoTruncated) InodeChangeTime() time.Time {
  107. return time.Unix(0, f.InodeChangeNs)
  108. }
  109. func (f FileInfoTruncated) FileBlocksHash() []byte {
  110. return f.BlocksHash
  111. }
  112. func (f FileInfoTruncated) ConvertToIgnoredFileInfo() protocol.FileInfo {
  113. file := f.copyToFileInfo()
  114. file.SetIgnored()
  115. return file
  116. }
  117. func (f FileInfoTruncated) ConvertToDeletedFileInfo(by protocol.ShortID) protocol.FileInfo {
  118. file := f.copyToFileInfo()
  119. file.SetDeleted(by)
  120. return file
  121. }
  122. // ConvertDeletedToFileInfo converts a deleted truncated file info to a regular file info
  123. func (f FileInfoTruncated) ConvertDeletedToFileInfo() protocol.FileInfo {
  124. if !f.Deleted {
  125. panic("ConvertDeletedToFileInfo must only be called on deleted items")
  126. }
  127. return f.copyToFileInfo()
  128. }
  129. // copyToFileInfo just copies all members of FileInfoTruncated to protocol.FileInfo
  130. func (f FileInfoTruncated) copyToFileInfo() protocol.FileInfo {
  131. return protocol.FileInfo{
  132. Name: f.Name,
  133. Size: f.Size,
  134. ModifiedS: f.ModifiedS,
  135. ModifiedBy: f.ModifiedBy,
  136. Version: f.Version,
  137. Sequence: f.Sequence,
  138. SymlinkTarget: f.SymlinkTarget,
  139. BlocksHash: f.BlocksHash,
  140. Type: f.Type,
  141. Permissions: f.Permissions,
  142. ModifiedNs: f.ModifiedNs,
  143. RawBlockSize: f.RawBlockSize,
  144. LocalFlags: f.LocalFlags,
  145. Deleted: f.Deleted,
  146. RawInvalid: f.RawInvalid,
  147. NoPermissions: f.NoPermissions,
  148. }
  149. }
  150. func (c Counts) Add(other Counts) Counts {
  151. return Counts{
  152. Files: c.Files + other.Files,
  153. Directories: c.Directories + other.Directories,
  154. Symlinks: c.Symlinks + other.Symlinks,
  155. Deleted: c.Deleted + other.Deleted,
  156. Bytes: c.Bytes + other.Bytes,
  157. Sequence: c.Sequence + other.Sequence,
  158. DeviceID: protocol.EmptyDeviceID[:],
  159. LocalFlags: c.LocalFlags | other.LocalFlags,
  160. }
  161. }
  162. func (c Counts) TotalItems() int {
  163. return c.Files + c.Directories + c.Symlinks + c.Deleted
  164. }
  165. func (c Counts) String() string {
  166. dev, _ := protocol.DeviceIDFromBytes(c.DeviceID)
  167. var flags strings.Builder
  168. if c.LocalFlags&needFlag != 0 {
  169. flags.WriteString("Need")
  170. }
  171. if c.LocalFlags&protocol.FlagLocalIgnored != 0 {
  172. flags.WriteString("Ignored")
  173. }
  174. if c.LocalFlags&protocol.FlagLocalMustRescan != 0 {
  175. flags.WriteString("Rescan")
  176. }
  177. if c.LocalFlags&protocol.FlagLocalReceiveOnly != 0 {
  178. flags.WriteString("Recvonly")
  179. }
  180. if c.LocalFlags&protocol.FlagLocalUnsupported != 0 {
  181. flags.WriteString("Unsupported")
  182. }
  183. if c.LocalFlags != 0 {
  184. flags.WriteString(fmt.Sprintf("(%x)", c.LocalFlags))
  185. }
  186. if flags.Len() == 0 {
  187. flags.WriteString("---")
  188. }
  189. return fmt.Sprintf("{Device:%v, Files:%d, Dirs:%d, Symlinks:%d, Del:%d, Bytes:%d, Seq:%d, Flags:%s}", dev, c.Files, c.Directories, c.Symlinks, c.Deleted, c.Bytes, c.Sequence, flags.String())
  190. }
  191. // Equal compares the numbers only, not sequence/dev/flags.
  192. func (c Counts) Equal(o Counts) bool {
  193. return c.Files == o.Files && c.Directories == o.Directories && c.Symlinks == o.Symlinks && c.Deleted == o.Deleted && c.Bytes == o.Bytes
  194. }
  195. func (vl VersionList) String() string {
  196. var b bytes.Buffer
  197. var id protocol.DeviceID
  198. b.WriteString("{")
  199. for i, v := range vl.RawVersions {
  200. if i > 0 {
  201. b.WriteString(", ")
  202. }
  203. fmt.Fprintf(&b, "{Version:%v, Deleted:%v, Devices:{", v.Version, v.Deleted)
  204. for j, dev := range v.Devices {
  205. if j > 0 {
  206. b.WriteString(", ")
  207. }
  208. copy(id[:], dev)
  209. fmt.Fprint(&b, id.Short())
  210. }
  211. b.WriteString("}, Invalid:{")
  212. for j, dev := range v.InvalidDevices {
  213. if j > 0 {
  214. b.WriteString(", ")
  215. }
  216. copy(id[:], dev)
  217. fmt.Fprint(&b, id.Short())
  218. }
  219. fmt.Fprint(&b, "}}")
  220. }
  221. b.WriteString("}")
  222. return b.String()
  223. }
  224. // update brings the VersionList up to date with file. It returns the updated
  225. // VersionList, a device that has the global/newest version, a device that previously
  226. // had the global/newest version, a boolean indicating if the global version has
  227. // changed and if any error occurred (only possible in db interaction).
  228. func (vl *VersionList) update(folder, device []byte, file protocol.FileIntf, t readOnlyTransaction) (FileVersion, FileVersion, FileVersion, bool, bool, bool, error) {
  229. if len(vl.RawVersions) == 0 {
  230. nv := newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted())
  231. vl.RawVersions = append(vl.RawVersions, nv)
  232. return nv, FileVersion{}, FileVersion{}, false, false, true, nil
  233. }
  234. // Get the current global (before updating)
  235. oldFV, haveOldGlobal := vl.GetGlobal()
  236. oldFV = oldFV.copy()
  237. // Remove ourselves first
  238. removedFV, haveRemoved, _ := vl.pop(device)
  239. // Find position and insert the file
  240. err := vl.insert(folder, device, file, t)
  241. if err != nil {
  242. return FileVersion{}, FileVersion{}, FileVersion{}, false, false, false, err
  243. }
  244. newFV, _ := vl.GetGlobal() // We just inserted something above, can't be empty
  245. if !haveOldGlobal {
  246. return newFV, FileVersion{}, removedFV, false, haveRemoved, true, nil
  247. }
  248. globalChanged := true
  249. if oldFV.IsInvalid() == newFV.IsInvalid() && oldFV.Version.Equal(newFV.Version) {
  250. globalChanged = false
  251. }
  252. return newFV, oldFV, removedFV, true, haveRemoved, globalChanged, nil
  253. }
  254. func (vl *VersionList) insert(folder, device []byte, file protocol.FileIntf, t readOnlyTransaction) error {
  255. var added bool
  256. var err error
  257. i := 0
  258. for ; i < len(vl.RawVersions); i++ {
  259. // Insert our new version
  260. added, err = vl.checkInsertAt(i, folder, device, file, t)
  261. if err != nil {
  262. return err
  263. }
  264. if added {
  265. break
  266. }
  267. }
  268. if i == len(vl.RawVersions) {
  269. // Append to the end
  270. vl.RawVersions = append(vl.RawVersions, newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted()))
  271. }
  272. return nil
  273. }
  274. func (vl *VersionList) insertAt(i int, v FileVersion) {
  275. vl.RawVersions = append(vl.RawVersions, FileVersion{})
  276. copy(vl.RawVersions[i+1:], vl.RawVersions[i:])
  277. vl.RawVersions[i] = v
  278. }
  279. // pop removes the given device from the VersionList and returns the FileVersion
  280. // before removing the device, whether it was found/removed at all and whether
  281. // the global changed in the process.
  282. func (vl *VersionList) pop(device []byte) (FileVersion, bool, bool) {
  283. invDevice, i, j, ok := vl.findDevice(device)
  284. if !ok {
  285. return FileVersion{}, false, false
  286. }
  287. globalPos := vl.findGlobal()
  288. if vl.RawVersions[i].deviceCount() == 1 {
  289. fv := vl.RawVersions[i]
  290. vl.popVersionAt(i)
  291. return fv, true, globalPos == i
  292. }
  293. oldFV := vl.RawVersions[i].copy()
  294. if invDevice {
  295. vl.RawVersions[i].InvalidDevices = popDeviceAt(vl.RawVersions[i].InvalidDevices, j)
  296. return oldFV, true, false
  297. }
  298. vl.RawVersions[i].Devices = popDeviceAt(vl.RawVersions[i].Devices, j)
  299. // If the last valid device of the previous global was removed above,
  300. // the global changed.
  301. return oldFV, true, len(vl.RawVersions[i].Devices) == 0 && globalPos == i
  302. }
  303. // Get returns a FileVersion that contains the given device and whether it has
  304. // been found at all.
  305. func (vl *VersionList) Get(device []byte) (FileVersion, bool) {
  306. _, i, _, ok := vl.findDevice(device)
  307. if !ok {
  308. return FileVersion{}, false
  309. }
  310. return vl.RawVersions[i], true
  311. }
  312. // GetGlobal returns the current global FileVersion. The returned FileVersion
  313. // may be invalid, if all FileVersions are invalid. Returns false only if
  314. // VersionList is empty.
  315. func (vl *VersionList) GetGlobal() (FileVersion, bool) {
  316. i := vl.findGlobal()
  317. if i == -1 {
  318. return FileVersion{}, false
  319. }
  320. return vl.RawVersions[i], true
  321. }
  322. func (vl *VersionList) Empty() bool {
  323. return len(vl.RawVersions) == 0
  324. }
  325. // findGlobal returns the first version that isn't invalid, or if all versions are
  326. // invalid just the first version (i.e. 0) or -1, if there's no versions at all.
  327. func (vl *VersionList) findGlobal() int {
  328. for i, fv := range vl.RawVersions {
  329. if !fv.IsInvalid() {
  330. return i
  331. }
  332. }
  333. if len(vl.RawVersions) == 0 {
  334. return -1
  335. }
  336. return 0
  337. }
  338. // findDevices returns whether the device is in InvalidVersions or Versions and
  339. // in InvalidDevices or Devices (true for invalid), the positions in the version
  340. // and device slices and whether it has been found at all.
  341. func (vl *VersionList) findDevice(device []byte) (bool, int, int, bool) {
  342. for i, v := range vl.RawVersions {
  343. if j := deviceIndex(v.Devices, device); j != -1 {
  344. return false, i, j, true
  345. }
  346. if j := deviceIndex(v.InvalidDevices, device); j != -1 {
  347. return true, i, j, true
  348. }
  349. }
  350. return false, -1, -1, false
  351. }
  352. func (vl *VersionList) popVersionAt(i int) {
  353. vl.RawVersions = append(vl.RawVersions[:i], vl.RawVersions[i+1:]...)
  354. }
  355. // checkInsertAt determines if the given device and associated file should be
  356. // inserted into the FileVersion at position i or into a new FileVersion at
  357. // position i.
  358. func (vl *VersionList) checkInsertAt(i int, folder, device []byte, file protocol.FileIntf, t readOnlyTransaction) (bool, error) {
  359. ordering := vl.RawVersions[i].Version.Compare(file.FileVersion())
  360. if ordering == protocol.Equal {
  361. if !file.IsInvalid() {
  362. vl.RawVersions[i].Devices = append(vl.RawVersions[i].Devices, device)
  363. } else {
  364. vl.RawVersions[i].InvalidDevices = append(vl.RawVersions[i].InvalidDevices, device)
  365. }
  366. return true, nil
  367. }
  368. existingDevice, _ := vl.RawVersions[i].FirstDevice()
  369. insert, err := shouldInsertBefore(ordering, folder, existingDevice, vl.RawVersions[i].IsInvalid(), file, t)
  370. if err != nil {
  371. return false, err
  372. }
  373. if insert {
  374. vl.insertAt(i, newFileVersion(device, file.FileVersion(), file.IsInvalid(), file.IsDeleted()))
  375. return true, nil
  376. }
  377. return false, nil
  378. }
  379. // shouldInsertBefore determines whether the file comes before an existing
  380. // entry, given the version ordering (existing compared to new one), existing
  381. // device and if the existing version is invalid.
  382. func shouldInsertBefore(ordering protocol.Ordering, folder, existingDevice []byte, existingInvalid bool, file protocol.FileIntf, t readOnlyTransaction) (bool, error) {
  383. switch ordering {
  384. case protocol.Lesser:
  385. // The version at this point in the list is lesser
  386. // ("older") than us. We insert ourselves in front of it.
  387. return true, nil
  388. case protocol.ConcurrentLesser, protocol.ConcurrentGreater:
  389. // The version in conflict with us.
  390. // Check if we can shortcut due to one being invalid.
  391. if existingInvalid != file.IsInvalid() {
  392. return existingInvalid, nil
  393. }
  394. // We must pull the actual file metadata to determine who wins.
  395. // If we win, we insert ourselves in front of the loser here.
  396. // (The "Lesser" and "Greater" in the condition above is just
  397. // based on the device IDs in the version vector, which is not
  398. // the only thing we use to determine the winner.)
  399. of, ok, err := t.getFile(folder, existingDevice, []byte(file.FileName()))
  400. if err != nil {
  401. return false, err
  402. }
  403. // A surprise missing file entry here is counted as a win for us.
  404. if !ok {
  405. return true, nil
  406. }
  407. if err != nil {
  408. return false, err
  409. }
  410. if protocol.WinsConflict(file, of) {
  411. return true, nil
  412. }
  413. }
  414. return false, nil
  415. }
  416. func deviceIndex(devices [][]byte, device []byte) int {
  417. for i, dev := range devices {
  418. if bytes.Equal(device, dev) {
  419. return i
  420. }
  421. }
  422. return -1
  423. }
  424. func popDeviceAt(devices [][]byte, i int) [][]byte {
  425. return append(devices[:i], devices[i+1:]...)
  426. }
  427. func newFileVersion(device []byte, version protocol.Vector, invalid, deleted bool) FileVersion {
  428. fv := FileVersion{
  429. Version: version,
  430. Deleted: deleted,
  431. }
  432. if invalid {
  433. fv.InvalidDevices = [][]byte{device}
  434. } else {
  435. fv.Devices = [][]byte{device}
  436. }
  437. return fv
  438. }
  439. func (fv FileVersion) FirstDevice() ([]byte, bool) {
  440. if len(fv.Devices) != 0 {
  441. return fv.Devices[0], true
  442. }
  443. if len(fv.InvalidDevices) != 0 {
  444. return fv.InvalidDevices[0], true
  445. }
  446. return nil, false
  447. }
  448. func (fv FileVersion) IsInvalid() bool {
  449. return len(fv.Devices) == 0
  450. }
  451. func (fv FileVersion) deviceCount() int {
  452. return len(fv.Devices) + len(fv.InvalidDevices)
  453. }
  454. func (fv FileVersion) copy() FileVersion {
  455. n := fv
  456. n.Version = fv.Version.Copy()
  457. n.Devices = append([][]byte{}, fv.Devices...)
  458. n.InvalidDevices = append([][]byte{}, fv.InvalidDevices...)
  459. return n
  460. }