structs.go 15 KB

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