util.go 9.5 KB

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