util.go 11 KB

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