util.go 12 KB

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