util.go 9.8 KB

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