structs.go 15 KB

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