util.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. //go:build integration
  7. // +build integration
  8. package integration
  9. import (
  10. cr "crypto/rand"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "log"
  15. "math/rand"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "sort"
  20. "strings"
  21. "testing"
  22. "time"
  23. "unicode"
  24. "github.com/syncthing/syncthing/lib/build"
  25. "github.com/syncthing/syncthing/lib/rc"
  26. "github.com/syncthing/syncthing/lib/sha256"
  27. )
  28. func init() {
  29. rand.Seed(42)
  30. }
  31. const (
  32. id1 = "I6KAH76-66SLLLB-5PFXSOA-UFJCDZC-YAOMLEK-CP2GB32-BV5RQST-3PSROAU"
  33. id2 = "MRIW7OK-NETT3M4-N6SBWME-N25O76W-YJKVXPH-FUMQJ3S-P57B74J-GBITBAC"
  34. id3 = "373HSRP-QLPNLIE-JYKZVQF-P4PKZ63-R2ZE6K3-YD442U2-JHBGBQG-WWXAHAU"
  35. apiKey = "abc123"
  36. )
  37. func generateFiles(dir string, files, maxexp int, srcname string) error {
  38. return generateFilesWithTime(dir, files, maxexp, srcname, time.Now())
  39. }
  40. func generateFilesWithTime(dir string, files, maxexp int, srcname string, t0 time.Time) error {
  41. fd, err := os.Open(srcname)
  42. if err != nil {
  43. return err
  44. }
  45. for i := 0; i < files; i++ {
  46. n := randomName()
  47. if rand.Float64() < 0.05 {
  48. // Some files and directories are dotfiles
  49. n = "." + n
  50. }
  51. p0 := filepath.Join(dir, string(n[0]), n[0:2])
  52. err = os.MkdirAll(p0, 0755)
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. p1 := filepath.Join(p0, n)
  57. s := int64(1 << uint(rand.Intn(maxexp)))
  58. a := int64(128 * 1024)
  59. if a > s {
  60. a = s
  61. }
  62. s += rand.Int63n(a)
  63. if err := generateOneFile(fd, p1, s, t0); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }
  69. func generateOneFile(fd io.ReadSeeker, p1 string, s int64, t0 time.Time) error {
  70. src := io.LimitReader(&infiniteReader{fd}, int64(s))
  71. dst, err := os.Create(p1)
  72. if err != nil {
  73. return err
  74. }
  75. _, err = io.Copy(dst, src)
  76. if err != nil {
  77. return err
  78. }
  79. err = dst.Close()
  80. if err != nil {
  81. return err
  82. }
  83. os.Chmod(p1, os.FileMode(rand.Intn(0777)|0400))
  84. t := t0.Add(-time.Duration(rand.Intn(30*86400)) * time.Second)
  85. err = os.Chtimes(p1, t, t)
  86. if err != nil {
  87. return err
  88. }
  89. return nil
  90. }
  91. func alterFiles(dir string) error {
  92. err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  93. if os.IsNotExist(err) {
  94. // Something we deleted. Never mind.
  95. return nil
  96. }
  97. info, err = os.Stat(path)
  98. if err != nil {
  99. // Something we deleted while walking. Ignore.
  100. return nil
  101. }
  102. if strings.HasPrefix(filepath.Base(path), "test-") {
  103. return nil
  104. }
  105. switch filepath.Base(path) {
  106. case ".stfolder":
  107. return nil
  108. case ".stversions":
  109. return nil
  110. }
  111. // File structure is base/x/xy/xyz12345...
  112. // comps == 1: base (don't touch)
  113. // comps == 2: base/x (must be dir)
  114. // comps == 3: base/x/xy (must be dir)
  115. // comps > 3: base/x/xy/xyz12345... (can be dir or file)
  116. comps := len(strings.Split(path, string(os.PathSeparator)))
  117. r := rand.Intn(10)
  118. switch {
  119. case r == 0 && comps > 2:
  120. // Delete every tenth file or directory, except top levels
  121. return removeAll(path)
  122. case r == 1 && info.Mode().IsRegular():
  123. if info.Mode()&0200 != 0200 {
  124. // Not owner writable. Fix.
  125. if err = os.Chmod(path, 0644); err != nil {
  126. return err
  127. }
  128. }
  129. // Overwrite a random kilobyte of every tenth file
  130. fd, err := os.OpenFile(path, os.O_RDWR, 0644)
  131. if err != nil {
  132. return err
  133. }
  134. if info.Size() > 1024 {
  135. _, err = fd.Seek(rand.Int63n(info.Size()), os.SEEK_SET)
  136. if err != nil {
  137. return err
  138. }
  139. }
  140. _, err = io.Copy(fd, io.LimitReader(cr.Reader, 1024))
  141. if err != nil {
  142. return err
  143. }
  144. return fd.Close()
  145. // Change capitalization
  146. case r == 2 && comps > 3 && rand.Float64() < 0.2:
  147. if build.IsDarwin || build.IsWindows {
  148. // Syncthing is currently broken for case-only renames on case-
  149. // insensitive platforms.
  150. // https://github.com/syncthing/syncthing/issues/1787
  151. return nil
  152. }
  153. base := []rune(filepath.Base(path))
  154. for i, r := range base {
  155. if rand.Float64() < 0.5 {
  156. base[i] = unicode.ToLower(r)
  157. } else {
  158. base[i] = unicode.ToUpper(r)
  159. }
  160. }
  161. newPath := filepath.Join(filepath.Dir(path), string(base))
  162. if newPath != path {
  163. return os.Rename(path, newPath)
  164. }
  165. /*
  166. This doesn't in fact work. Sometimes it appears to. We need to get this sorted...
  167. // Switch between files and directories
  168. case r == 3 && comps > 3 && rand.Float64() < 0.2:
  169. if !info.Mode().IsRegular() {
  170. err = removeAll(path)
  171. if err != nil {
  172. return err
  173. }
  174. d1 := []byte("I used to be a dir: " + path)
  175. err := os.WriteFile(path, d1, 0644)
  176. if err != nil {
  177. return err
  178. }
  179. } else {
  180. err := os.Remove(path)
  181. if err != nil {
  182. return err
  183. }
  184. err = os.MkdirAll(path, 0755)
  185. if err != nil {
  186. return err
  187. }
  188. generateFiles(path, 10, 20, "../LICENSE")
  189. }
  190. return err
  191. */
  192. /*
  193. This fails. Bug?
  194. // Rename the file, while potentially moving it up in the directory hierarchy
  195. case r == 4 && comps > 2 && (info.Mode().IsRegular() || rand.Float64() < 0.2):
  196. rpath := filepath.Dir(path)
  197. if rand.Float64() < 0.2 {
  198. for move := rand.Intn(comps - 1); move > 0; move-- {
  199. rpath = filepath.Join(rpath, "..")
  200. }
  201. }
  202. return osutil.TryRename(path, filepath.Join(rpath, randomName()))
  203. */
  204. }
  205. return nil
  206. })
  207. if err != nil {
  208. return err
  209. }
  210. return generateFiles(dir, 25, 20, "../LICENSE")
  211. }
  212. func ReadRand(bs []byte) (int, error) {
  213. var r uint32
  214. for i := range bs {
  215. if i%4 == 0 {
  216. r = uint32(rand.Int63())
  217. }
  218. bs[i] = byte(r >> uint((i%4)*8))
  219. }
  220. return len(bs), nil
  221. }
  222. func randomName() string {
  223. var b [16]byte
  224. ReadRand(b[:])
  225. return fmt.Sprintf("%x", b[:])
  226. }
  227. type infiniteReader struct {
  228. rd io.ReadSeeker
  229. }
  230. func (i *infiniteReader) Read(bs []byte) (int, error) {
  231. n, err := i.rd.Read(bs)
  232. if err == io.EOF {
  233. err = nil
  234. i.rd.Seek(0, 0)
  235. }
  236. return n, err
  237. }
  238. // rm -rf
  239. func removeAll(dirs ...string) error {
  240. for _, dir := range dirs {
  241. files, err := filepath.Glob(dir)
  242. if err != nil {
  243. return err
  244. }
  245. for _, file := range files {
  246. // Set any non-writeable files and dirs to writeable. This is necessary for os.RemoveAll to work on Windows.
  247. filepath.Walk(file, func(path string, info os.FileInfo, err error) error {
  248. if err != nil {
  249. return err
  250. }
  251. if info.Mode()&0700 != 0700 {
  252. os.Chmod(path, 0777)
  253. }
  254. return nil
  255. })
  256. os.RemoveAll(file)
  257. }
  258. }
  259. return nil
  260. }
  261. // Compare a number of directories. Returns nil if the contents are identical,
  262. // otherwise an error describing the first found difference.
  263. func compareDirectories(dirs ...string) error {
  264. chans := make([]chan fileInfo, len(dirs))
  265. for i := range chans {
  266. chans[i] = make(chan fileInfo)
  267. }
  268. errcs := make([]chan error, len(dirs))
  269. abort := make(chan struct{})
  270. for i := range dirs {
  271. errcs[i] = startWalker(dirs[i], chans[i], abort)
  272. }
  273. res := make([]fileInfo, len(dirs))
  274. for {
  275. numDone := 0
  276. for i := range chans {
  277. fi, ok := <-chans[i]
  278. if !ok {
  279. err, hasError := <-errcs[i]
  280. if hasError {
  281. close(abort)
  282. return err
  283. }
  284. numDone++
  285. }
  286. res[i] = fi
  287. }
  288. for i := 1; i < len(res); i++ {
  289. if res[i] != res[0] {
  290. close(abort)
  291. return fmt.Errorf("mismatch; %#v (%s) != %#v (%s)", res[i], dirs[i], res[0], dirs[0])
  292. }
  293. }
  294. if numDone == len(dirs) {
  295. return nil
  296. }
  297. }
  298. }
  299. func directoryContents(dir string) ([]fileInfo, error) {
  300. res := make(chan fileInfo)
  301. errc := startWalker(dir, res, nil)
  302. var files []fileInfo
  303. for f := range res {
  304. files = append(files, f)
  305. }
  306. return files, <-errc
  307. }
  308. func mergeDirectoryContents(c ...[]fileInfo) []fileInfo {
  309. m := make(map[string]fileInfo)
  310. for _, l := range c {
  311. for _, f := range l {
  312. if cur, ok := m[f.name]; !ok || cur.mod < f.mod {
  313. m[f.name] = f
  314. }
  315. }
  316. }
  317. res := make([]fileInfo, len(m))
  318. i := 0
  319. for _, f := range m {
  320. res[i] = f
  321. i++
  322. }
  323. sort.Sort(fileInfoList(res))
  324. return res
  325. }
  326. func compareDirectoryContents(actual, expected []fileInfo) error {
  327. if len(actual) != len(expected) {
  328. return fmt.Errorf("len(actual) = %d; len(expected) = %d", len(actual), len(expected))
  329. }
  330. for i := range actual {
  331. if actual[i] != expected[i] {
  332. return fmt.Errorf("mismatch; actual %#v != expected %#v", actual[i], expected[i])
  333. }
  334. }
  335. return nil
  336. }
  337. type fileInfo struct {
  338. name string
  339. mode os.FileMode
  340. mod int64
  341. hash [sha256.Size]byte
  342. size int64
  343. }
  344. func (f fileInfo) String() string {
  345. return fmt.Sprintf("%s %04o %d %x", f.name, f.mode, f.mod, f.hash)
  346. }
  347. type fileInfoList []fileInfo
  348. func (l fileInfoList) Len() int {
  349. return len(l)
  350. }
  351. func (l fileInfoList) Less(a, b int) bool {
  352. return l[a].name < l[b].name
  353. }
  354. func (l fileInfoList) Swap(a, b int) {
  355. l[a], l[b] = l[b], l[a]
  356. }
  357. func startWalker(dir string, res chan<- fileInfo, abort <-chan struct{}) chan error {
  358. walker := func(path string, info os.FileInfo, err error) error {
  359. if err != nil {
  360. return err
  361. }
  362. rn, _ := filepath.Rel(dir, path)
  363. if rn == "." || rn == ".stfolder" {
  364. return nil
  365. }
  366. if rn == ".stversions" {
  367. return filepath.SkipDir
  368. }
  369. var f fileInfo
  370. if info.Mode()&os.ModeSymlink != 0 {
  371. f = fileInfo{
  372. name: rn,
  373. mode: os.ModeSymlink,
  374. }
  375. tgt, err := os.Readlink(path)
  376. if err != nil {
  377. return err
  378. }
  379. f.hash = sha256.Sum256([]byte(tgt))
  380. } else if info.IsDir() {
  381. f = fileInfo{
  382. name: rn,
  383. mode: info.Mode(),
  384. // hash and modtime zero for directories
  385. }
  386. } else {
  387. f = fileInfo{
  388. name: rn,
  389. mode: info.Mode(),
  390. // comparing timestamps with better precision than a second
  391. // is problematic as there is rounding and truncatign going
  392. // on at every level
  393. mod: info.ModTime().Unix(),
  394. size: info.Size(),
  395. }
  396. sum, err := sha256file(path)
  397. if err != nil {
  398. return err
  399. }
  400. f.hash = sum
  401. }
  402. select {
  403. case res <- f:
  404. return nil
  405. case <-abort:
  406. return errors.New("abort")
  407. }
  408. }
  409. errc := make(chan error)
  410. go func() {
  411. err := filepath.Walk(dir, walker)
  412. close(res)
  413. if err != nil {
  414. errc <- err
  415. }
  416. close(errc)
  417. }()
  418. return errc
  419. }
  420. func sha256file(fname string) (hash [sha256.Size]byte, err error) {
  421. f, err := os.Open(fname)
  422. if err != nil {
  423. return
  424. }
  425. defer f.Close()
  426. h := sha256.New()
  427. io.Copy(h, f)
  428. hb := h.Sum(nil)
  429. copy(hash[:], hb)
  430. return
  431. }
  432. func isTimeout(err error) bool {
  433. if err == nil {
  434. return false
  435. }
  436. return strings.Contains(err.Error(), "use of closed network connection") ||
  437. strings.Contains(err.Error(), "request canceled while waiting") ||
  438. strings.Contains(err.Error(), "operation timed out")
  439. }
  440. func getTestName() string {
  441. callers := make([]uintptr, 100)
  442. runtime.Callers(1, callers)
  443. for i, caller := range callers {
  444. f := runtime.FuncForPC(caller)
  445. if f != nil {
  446. if f.Name() == "testing.tRunner" {
  447. testf := runtime.FuncForPC(callers[i-1])
  448. if testf != nil {
  449. path := strings.Split(testf.Name(), ".")
  450. return path[len(path)-1]
  451. }
  452. }
  453. }
  454. }
  455. return time.Now().String()
  456. }
  457. func checkedStop(t *testing.T, p *rc.Process) {
  458. if _, err := p.Stop(); err != nil {
  459. t.Fatal(err)
  460. }
  461. }
  462. func startInstance(t *testing.T, i int) *rc.Process {
  463. log.Printf("Starting instance %d...", i)
  464. addr := fmt.Sprintf("127.0.0.1:%d", 8080+i)
  465. log := fmt.Sprintf("logs/%s-%d-%d.out", getTestName(), i, time.Now().Unix()%86400)
  466. p := rc.NewProcess(addr)
  467. p.LogTo(log)
  468. if err := p.Start("../bin/syncthing", "--home", fmt.Sprintf("h%d", i), "--no-browser"); err != nil {
  469. t.Fatal(err)
  470. }
  471. p.AwaitStartup()
  472. p.PauseAll()
  473. return p
  474. }
  475. func symlinksSupported() bool {
  476. tmp, err := os.MkdirTemp("", "symlink-test")
  477. if err != nil {
  478. return false
  479. }
  480. defer os.RemoveAll(tmp)
  481. err = os.Symlink("tmp", filepath.Join(tmp, "link"))
  482. return err == nil
  483. }
  484. // checkRemoteInSync checks if the devices associated twith the given processes
  485. // are in sync according to the remote status on both sides.
  486. func checkRemoteInSync(folder string, p1, p2 *rc.Process) error {
  487. if inSync, err := p1.RemoteInSync(folder, p2.ID()); err != nil {
  488. return err
  489. } else if !inSync {
  490. return fmt.Errorf(`from device %v folder "%v" is not in sync on device %v`, p1.ID(), folder, p2.ID())
  491. }
  492. if inSync, err := p2.RemoteInSync(folder, p1.ID()); err != nil {
  493. return err
  494. } else if !inSync {
  495. return fmt.Errorf(`from device %v folder "%v" is not in sync on device %v`, p2.ID(), folder, p1.ID())
  496. }
  497. return nil
  498. }