util.go 11 KB

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