walk.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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 scanner
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "sync/atomic"
  15. "time"
  16. "unicode/utf8"
  17. metrics "github.com/rcrowley/go-metrics"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/fs"
  20. "github.com/syncthing/syncthing/lib/ignore"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "golang.org/x/text/unicode/norm"
  24. )
  25. type Config struct {
  26. // Folder for which the walker has been created
  27. Folder string
  28. // Limit walking to these paths within Dir, or no limit if Sub is empty
  29. Subs []string
  30. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  31. Matcher *ignore.Matcher
  32. // Number of hours to keep temporary files for
  33. TempLifetime time.Duration
  34. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  35. CurrentFiler CurrentFiler
  36. // The Filesystem provides an abstraction on top of the actual filesystem.
  37. Filesystem fs.Filesystem
  38. // If IgnorePerms is true, changes to permission bits will not be
  39. // detected. Scanned files will get zero permission bits and the
  40. // NoPermissionBits flag set.
  41. IgnorePerms bool
  42. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  43. // normalization form will be corrected.
  44. AutoNormalize bool
  45. // Number of routines to use for hashing
  46. Hashers int
  47. // Our vector clock id
  48. ShortID protocol.ShortID
  49. // Optional progress tick interval which defines how often FolderScanProgress
  50. // events are emitted. Negative number means disabled.
  51. ProgressTickIntervalS int
  52. // Local flags to set on scanned files
  53. LocalFlags uint32
  54. // Modification time is to be considered unchanged if the difference is lower.
  55. ModTimeWindow time.Duration
  56. // Event logger to which the scan progress events are sent
  57. EventLogger events.Logger
  58. }
  59. type CurrentFiler interface {
  60. // CurrentFile returns the file as seen at last scan.
  61. CurrentFile(name string) (protocol.FileInfo, bool)
  62. }
  63. type ScanResult struct {
  64. File protocol.FileInfo
  65. Err error
  66. Path string // to be set in case Err != nil and File == nil
  67. }
  68. func Walk(ctx context.Context, cfg Config) chan ScanResult {
  69. return newWalker(cfg).walk(ctx)
  70. }
  71. func WalkWithoutHashing(ctx context.Context, cfg Config) chan ScanResult {
  72. return newWalker(cfg).walkWithoutHashing(ctx)
  73. }
  74. func newWalker(cfg Config) *walker {
  75. w := &walker{cfg}
  76. if w.CurrentFiler == nil {
  77. w.CurrentFiler = noCurrentFiler{}
  78. }
  79. if w.Filesystem == nil {
  80. panic("no filesystem specified")
  81. }
  82. if w.Matcher == nil {
  83. w.Matcher = ignore.New(w.Filesystem)
  84. }
  85. return w
  86. }
  87. var (
  88. errUTF8Invalid = errors.New("item is not in UTF8 encoding")
  89. errUTF8Normalization = errors.New("item is not in the correct UTF8 normalization form")
  90. errUTF8Conflict = errors.New("item has UTF8 encoding conflict with another item")
  91. )
  92. type walker struct {
  93. Config
  94. }
  95. // Walk returns the list of files found in the local folder by scanning the
  96. // file system. Files are blockwise hashed.
  97. func (w *walker) walk(ctx context.Context) chan ScanResult {
  98. l.Debugln(w, "Walk", w.Subs, w.Matcher)
  99. toHashChan := make(chan protocol.FileInfo)
  100. finishedChan := make(chan ScanResult)
  101. // A routine which walks the filesystem tree, and sends files which have
  102. // been modified to the counter routine.
  103. go w.scan(ctx, toHashChan, finishedChan)
  104. // We're not required to emit scan progress events, just kick off hashers,
  105. // and feed inputs directly from the walker.
  106. if w.ProgressTickIntervalS < 0 {
  107. newParallelHasher(ctx, w.Filesystem, w.Hashers, finishedChan, toHashChan, nil, nil)
  108. return finishedChan
  109. }
  110. // Defaults to every 2 seconds.
  111. if w.ProgressTickIntervalS == 0 {
  112. w.ProgressTickIntervalS = 2
  113. }
  114. ticker := time.NewTicker(time.Duration(w.ProgressTickIntervalS) * time.Second)
  115. // We need to emit progress events, hence we create a routine which buffers
  116. // the list of files to be hashed, counts the total number of
  117. // bytes to hash, and once no more files need to be hashed (chan gets closed),
  118. // start a routine which periodically emits FolderScanProgress events,
  119. // until a stop signal is sent by the parallel hasher.
  120. // Parallel hasher is stopped by this routine when we close the channel over
  121. // which it receives the files we ask it to hash.
  122. go func() {
  123. var filesToHash []protocol.FileInfo
  124. var total int64 = 1
  125. for file := range toHashChan {
  126. filesToHash = append(filesToHash, file)
  127. total += file.Size
  128. }
  129. realToHashChan := make(chan protocol.FileInfo)
  130. done := make(chan struct{})
  131. progress := newByteCounter()
  132. newParallelHasher(ctx, w.Filesystem, w.Hashers, finishedChan, realToHashChan, progress, done)
  133. // A routine which actually emits the FolderScanProgress events
  134. // every w.ProgressTicker ticks, until the hasher routines terminate.
  135. go func() {
  136. defer progress.Close()
  137. for {
  138. select {
  139. case <-done:
  140. l.Debugln(w, "Walk progress done", w.Folder, w.Subs, w.Matcher)
  141. ticker.Stop()
  142. return
  143. case <-ticker.C:
  144. current := progress.Total()
  145. rate := progress.Rate()
  146. l.Debugf("%v: Walk %s %s current progress %d/%d at %.01f MiB/s (%d%%)", w, w.Folder, w.Subs, current, total, rate/1024/1024, current*100/total)
  147. w.EventLogger.Log(events.FolderScanProgress, map[string]interface{}{
  148. "folder": w.Folder,
  149. "current": current,
  150. "total": total,
  151. "rate": rate, // bytes per second
  152. })
  153. case <-ctx.Done():
  154. ticker.Stop()
  155. return
  156. }
  157. }
  158. }()
  159. loop:
  160. for _, file := range filesToHash {
  161. l.Debugln(w, "real to hash:", file.Name)
  162. select {
  163. case realToHashChan <- file:
  164. case <-ctx.Done():
  165. break loop
  166. }
  167. }
  168. close(realToHashChan)
  169. }()
  170. return finishedChan
  171. }
  172. func (w *walker) walkWithoutHashing(ctx context.Context) chan ScanResult {
  173. l.Debugln(w, "Walk without hashing", w.Subs, w.Matcher)
  174. toHashChan := make(chan protocol.FileInfo)
  175. finishedChan := make(chan ScanResult)
  176. // A routine which walks the filesystem tree, and sends files which have
  177. // been modified to the counter routine.
  178. go w.scan(ctx, toHashChan, finishedChan)
  179. go func() {
  180. for file := range toHashChan {
  181. finishedChan <- ScanResult{File: file}
  182. }
  183. close(finishedChan)
  184. }()
  185. return finishedChan
  186. }
  187. func (w *walker) scan(ctx context.Context, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult) {
  188. hashFiles := w.walkAndHashFiles(ctx, toHashChan, finishedChan)
  189. if len(w.Subs) == 0 {
  190. w.Filesystem.Walk(".", hashFiles)
  191. } else {
  192. for _, sub := range w.Subs {
  193. if err := osutil.TraversesSymlink(w.Filesystem, filepath.Dir(sub)); err != nil {
  194. l.Debugf("%v: Skip walking %v as it is below a symlink", w, sub)
  195. continue
  196. }
  197. w.Filesystem.Walk(sub, hashFiles)
  198. }
  199. }
  200. close(toHashChan)
  201. }
  202. func (w *walker) walkAndHashFiles(ctx context.Context, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult) fs.WalkFunc {
  203. now := time.Now()
  204. ignoredParent := ""
  205. return func(path string, info fs.FileInfo, err error) error {
  206. select {
  207. case <-ctx.Done():
  208. return ctx.Err()
  209. default:
  210. }
  211. // Return value used when we are returning early and don't want to
  212. // process the item. For directories, this means do-not-descend.
  213. var skip error // nil
  214. // info nil when error is not nil
  215. if info != nil && info.IsDir() {
  216. skip = fs.SkipDir
  217. }
  218. if !utf8.ValidString(path) {
  219. handleError(ctx, "scan", path, errUTF8Invalid, finishedChan)
  220. return skip
  221. }
  222. if fs.IsTemporary(path) {
  223. l.Debugln(w, "temporary:", path, "err:", err)
  224. if err == nil && info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  225. w.Filesystem.Remove(path)
  226. l.Debugln(w, "removing temporary:", path, info.ModTime())
  227. }
  228. return nil
  229. }
  230. if fs.IsInternal(path) {
  231. l.Debugln(w, "ignored (internal):", path)
  232. return skip
  233. }
  234. if w.Matcher.Match(path).IsIgnored() {
  235. l.Debugln(w, "ignored (patterns):", path)
  236. // Only descend if matcher says so and the current file is not a symlink.
  237. if err != nil || w.Matcher.SkipIgnoredDirs() || info.IsSymlink() {
  238. return skip
  239. }
  240. // If the parent wasn't ignored already, set this path as the "highest" ignored parent
  241. if info.IsDir() && (ignoredParent == "" || !fs.IsParent(path, ignoredParent)) {
  242. ignoredParent = path
  243. }
  244. return nil
  245. }
  246. if err != nil {
  247. // No need reporting errors for files that don't exist (e.g. scan
  248. // due to filesystem watcher)
  249. if !fs.IsNotExist(err) {
  250. handleError(ctx, "scan", path, err, finishedChan)
  251. }
  252. return skip
  253. }
  254. if path == "." {
  255. return nil
  256. }
  257. if ignoredParent == "" {
  258. // parent isn't ignored, nothing special
  259. return w.handleItem(ctx, path, info, toHashChan, finishedChan, skip)
  260. }
  261. // Part of current path below the ignored (potential) parent
  262. rel := strings.TrimPrefix(path, ignoredParent+string(fs.PathSeparator))
  263. // ignored path isn't actually a parent of the current path
  264. if rel == path {
  265. ignoredParent = ""
  266. return w.handleItem(ctx, path, info, toHashChan, finishedChan, skip)
  267. }
  268. // The previously ignored parent directories of the current, not
  269. // ignored path need to be handled as well.
  270. // Prepend an empty string to handle ignoredParent without anything
  271. // appended in the first iteration.
  272. for _, name := range append([]string{""}, fs.PathComponents(rel)...) {
  273. ignoredParent = filepath.Join(ignoredParent, name)
  274. info, err = w.Filesystem.Lstat(ignoredParent)
  275. // An error here would be weird as we've already gotten to this point, but act on it nonetheless
  276. if err != nil {
  277. handleError(ctx, "scan", ignoredParent, err, finishedChan)
  278. return skip
  279. }
  280. if err = w.handleItem(ctx, ignoredParent, info, toHashChan, finishedChan, skip); err != nil {
  281. return err
  282. }
  283. }
  284. ignoredParent = ""
  285. return nil
  286. }
  287. }
  288. func (w *walker) handleItem(ctx context.Context, path string, info fs.FileInfo, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult, skip error) error {
  289. oldPath := path
  290. path, err := w.normalizePath(path, info)
  291. if err != nil {
  292. handleError(ctx, "normalizing path", oldPath, err, finishedChan)
  293. return skip
  294. }
  295. switch {
  296. case info.IsSymlink():
  297. if err := w.walkSymlink(ctx, path, info, finishedChan); err != nil {
  298. return err
  299. }
  300. if info.IsDir() {
  301. // under no circumstances shall we descend into a symlink
  302. return fs.SkipDir
  303. }
  304. return nil
  305. case info.IsDir():
  306. err = w.walkDir(ctx, path, info, finishedChan)
  307. case info.IsRegular():
  308. err = w.walkRegular(ctx, path, info, toHashChan)
  309. }
  310. return err
  311. }
  312. func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, toHashChan chan<- protocol.FileInfo) error {
  313. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  314. blockSize := protocol.BlockSize(info.Size())
  315. if hasCurFile {
  316. // Check if we should retain current block size.
  317. curBlockSize := curFile.BlockSize()
  318. if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
  319. // New block size is larger, but not more than twice larger.
  320. // Retain.
  321. blockSize = curBlockSize
  322. } else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
  323. // Old block size is larger, but not more than twice larger.
  324. // Retain.
  325. blockSize = curBlockSize
  326. }
  327. }
  328. f, _ := CreateFileInfo(info, relPath, nil)
  329. f = w.updateFileInfo(f, curFile)
  330. f.NoPermissions = w.IgnorePerms
  331. f.RawBlockSize = blockSize
  332. if hasCurFile {
  333. if curFile.IsEquivalentOptional(f, w.ModTimeWindow, w.IgnorePerms, true, w.LocalFlags) {
  334. l.Debugln(w, "unchanged:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  335. return nil
  336. }
  337. if curFile.ShouldConflict() {
  338. // The old file was invalid for whatever reason and probably not
  339. // up to date with what was out there in the cluster. Drop all
  340. // others from the version vector to indicate that we haven't
  341. // taken their version into account, and possibly cause a
  342. // conflict.
  343. f.Version = f.Version.DropOthers(w.ShortID)
  344. }
  345. l.Debugln(w, "rescan:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  346. }
  347. l.Debugln(w, "to hash:", relPath, f)
  348. select {
  349. case toHashChan <- f:
  350. case <-ctx.Done():
  351. return ctx.Err()
  352. }
  353. return nil
  354. }
  355. func (w *walker) walkDir(ctx context.Context, relPath string, info fs.FileInfo, finishedChan chan<- ScanResult) error {
  356. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  357. f, _ := CreateFileInfo(info, relPath, nil)
  358. f = w.updateFileInfo(f, curFile)
  359. f.NoPermissions = w.IgnorePerms
  360. if hasCurFile {
  361. if curFile.IsEquivalentOptional(f, w.ModTimeWindow, w.IgnorePerms, true, w.LocalFlags) {
  362. l.Debugln(w, "unchanged:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  363. return nil
  364. }
  365. if curFile.ShouldConflict() {
  366. // The old file was invalid for whatever reason and probably not
  367. // up to date with what was out there in the cluster. Drop all
  368. // others from the version vector to indicate that we haven't
  369. // taken their version into account, and possibly cause a
  370. // conflict.
  371. f.Version = f.Version.DropOthers(w.ShortID)
  372. }
  373. }
  374. l.Debugln(w, "dir:", relPath, f)
  375. select {
  376. case finishedChan <- ScanResult{File: f}:
  377. case <-ctx.Done():
  378. return ctx.Err()
  379. }
  380. return nil
  381. }
  382. // walkSymlink returns nil or an error, if the error is of the nature that
  383. // it should stop the entire walk.
  384. func (w *walker) walkSymlink(ctx context.Context, relPath string, info fs.FileInfo, finishedChan chan<- ScanResult) error {
  385. // Symlinks are not supported on Windows. We ignore instead of returning
  386. // an error.
  387. if runtime.GOOS == "windows" {
  388. return nil
  389. }
  390. f, err := CreateFileInfo(info, relPath, w.Filesystem)
  391. if err != nil {
  392. handleError(ctx, "reading link:", relPath, err, finishedChan)
  393. return nil
  394. }
  395. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  396. f = w.updateFileInfo(f, curFile)
  397. if hasCurFile {
  398. if curFile.IsEquivalentOptional(f, w.ModTimeWindow, w.IgnorePerms, true, w.LocalFlags) {
  399. l.Debugln(w, "unchanged:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  400. return nil
  401. }
  402. if curFile.ShouldConflict() {
  403. // The old file was invalid for whatever reason and probably not
  404. // up to date with what was out there in the cluster. Drop all
  405. // others from the version vector to indicate that we haven't
  406. // taken their version into account, and possibly cause a
  407. // conflict.
  408. f.Version = f.Version.DropOthers(w.ShortID)
  409. }
  410. }
  411. l.Debugln(w, "symlink changedb:", relPath, f)
  412. select {
  413. case finishedChan <- ScanResult{File: f}:
  414. case <-ctx.Done():
  415. return ctx.Err()
  416. }
  417. return nil
  418. }
  419. // normalizePath returns the normalized relative path (possibly after fixing
  420. // it on disk), or skip is true.
  421. func (w *walker) normalizePath(path string, info fs.FileInfo) (normPath string, err error) {
  422. if runtime.GOOS == "darwin" {
  423. // Mac OS X file names should always be NFD normalized.
  424. normPath = norm.NFD.String(path)
  425. } else {
  426. // Every other OS in the known universe uses NFC or just plain
  427. // doesn't bother to define an encoding. In our case *we* do care,
  428. // so we enforce NFC regardless.
  429. normPath = norm.NFC.String(path)
  430. }
  431. if path == normPath {
  432. // The file name is already normalized: nothing to do
  433. return path, nil
  434. }
  435. if !w.AutoNormalize {
  436. // We're not authorized to do anything about it, so complain and skip.
  437. return "", errUTF8Normalization
  438. }
  439. // We will attempt to normalize it.
  440. normInfo, err := w.Filesystem.Lstat(normPath)
  441. if fs.IsNotExist(err) {
  442. // Nothing exists with the normalized filename. Good.
  443. if err = w.Filesystem.Rename(path, normPath); err != nil {
  444. return "", err
  445. }
  446. l.Infof(`Normalized UTF8 encoding of file name "%s".`, path)
  447. return normPath, nil
  448. }
  449. if w.Filesystem.SameFile(info, normInfo) {
  450. // With some filesystems (ZFS), if there is an un-normalized path and you ask whether the normalized
  451. // version exists, it responds with true. Therefore we need to check fs.SameFile as well.
  452. // In this case, a call to Rename won't do anything, so we have to rename via a temp file.
  453. // We don't want to use the standard syncthing prefix here, as that will result in the file being ignored
  454. // and eventually deleted by Syncthing if the rename back fails.
  455. tempPath := fs.TempNameWithPrefix(normPath, "")
  456. if err = w.Filesystem.Rename(path, tempPath); err != nil {
  457. return "", err
  458. }
  459. if err = w.Filesystem.Rename(tempPath, normPath); err != nil {
  460. // I don't ever expect this to happen, but if it does, we should probably tell our caller that the normalized
  461. // path is the temp path: that way at least the user's data still gets synced.
  462. l.Warnf(`Error renaming "%s" to "%s" while normalizating UTF8 encoding: %v. You will want to rename this file back manually`, tempPath, normPath, err)
  463. return tempPath, nil
  464. }
  465. return normPath, nil
  466. }
  467. // There is something already in the way at the normalized
  468. // file name.
  469. return "", errUTF8Conflict
  470. }
  471. // updateFileInfo updates walker specific members of protocol.FileInfo that do not depend on type
  472. func (w *walker) updateFileInfo(file, curFile protocol.FileInfo) protocol.FileInfo {
  473. if file.Type == protocol.FileInfoTypeFile && runtime.GOOS == "windows" {
  474. // If we have an existing index entry, copy the executable bits
  475. // from there.
  476. file.Permissions |= (curFile.Permissions & 0111)
  477. }
  478. file.Version = curFile.Version.Update(w.ShortID)
  479. file.ModifiedBy = w.ShortID
  480. file.LocalFlags = w.LocalFlags
  481. return file
  482. }
  483. func handleError(ctx context.Context, context, path string, err error, finishedChan chan<- ScanResult) {
  484. select {
  485. case finishedChan <- ScanResult{
  486. Err: fmt.Errorf("%s: %w", context, err),
  487. Path: path,
  488. }:
  489. case <-ctx.Done():
  490. }
  491. }
  492. func (w *walker) String() string {
  493. return fmt.Sprintf("walker/%s@%p", w.Folder, w)
  494. }
  495. // A byteCounter gets bytes added to it via Update() and then provides the
  496. // Total() and one minute moving average Rate() in bytes per second.
  497. type byteCounter struct {
  498. total int64 // atomic, must remain 64-bit aligned
  499. metrics.EWMA
  500. stop chan struct{}
  501. }
  502. func newByteCounter() *byteCounter {
  503. c := &byteCounter{
  504. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  505. stop: make(chan struct{}),
  506. }
  507. go c.ticker()
  508. return c
  509. }
  510. func (c *byteCounter) ticker() {
  511. // The metrics.EWMA expects clock ticks every five seconds in order to
  512. // decay the average properly.
  513. t := time.NewTicker(5 * time.Second)
  514. for {
  515. select {
  516. case <-t.C:
  517. c.Tick()
  518. case <-c.stop:
  519. t.Stop()
  520. return
  521. }
  522. }
  523. }
  524. func (c *byteCounter) Update(bytes int64) {
  525. atomic.AddInt64(&c.total, bytes)
  526. c.EWMA.Update(bytes)
  527. }
  528. func (c *byteCounter) Total() int64 {
  529. return atomic.LoadInt64(&c.total)
  530. }
  531. func (c *byteCounter) Close() {
  532. close(c.stop)
  533. }
  534. // A no-op CurrentFiler
  535. type noCurrentFiler struct{}
  536. func (noCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  537. return protocol.FileInfo{}, false
  538. }
  539. func CreateFileInfo(fi fs.FileInfo, name string, filesystem fs.Filesystem) (protocol.FileInfo, error) {
  540. f := protocol.FileInfo{Name: name}
  541. if fi.IsSymlink() {
  542. f.Type = protocol.FileInfoTypeSymlink
  543. target, err := filesystem.ReadSymlink(name)
  544. if err != nil {
  545. return protocol.FileInfo{}, err
  546. }
  547. f.SymlinkTarget = target
  548. f.NoPermissions = true // Symlinks don't have permissions of their own
  549. return f, nil
  550. }
  551. f.Permissions = uint32(fi.Mode() & fs.ModePerm)
  552. f.ModifiedS = fi.ModTime().Unix()
  553. f.ModifiedNs = fi.ModTime().Nanosecond()
  554. if fi.IsDir() {
  555. f.Type = protocol.FileInfoTypeDirectory
  556. return f, nil
  557. }
  558. f.Size = fi.Size()
  559. f.Type = protocol.FileInfoTypeFile
  560. return f, nil
  561. }