model_test.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  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. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "math/rand"
  14. "net"
  15. "os"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "sync"
  20. "testing"
  21. "time"
  22. "github.com/d4l3k/messagediff"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/db"
  25. "github.com/syncthing/syncthing/lib/fs"
  26. "github.com/syncthing/syncthing/lib/ignore"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. srand "github.com/syncthing/syncthing/lib/rand"
  29. "github.com/syncthing/syncthing/lib/scanner"
  30. )
  31. var device1, device2 protocol.DeviceID
  32. var defaultConfig *config.Wrapper
  33. var defaultFolderConfig config.FolderConfiguration
  34. var defaultFs fs.Filesystem
  35. func init() {
  36. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  37. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  38. defaultFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  39. defaultFolderConfig = config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  40. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  41. _defaultConfig := config.Configuration{
  42. Folders: []config.FolderConfiguration{defaultFolderConfig},
  43. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  44. Options: config.OptionsConfiguration{
  45. // Don't remove temporaries directly on startup
  46. KeepTemporariesH: 1,
  47. },
  48. }
  49. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  50. }
  51. var testDataExpected = map[string]protocol.FileInfo{
  52. "foo": {
  53. Name: "foo",
  54. Type: protocol.FileInfoTypeFile,
  55. ModifiedS: 0,
  56. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x7, Hash: []uint8{0xae, 0xc0, 0x70, 0x64, 0x5f, 0xe5, 0x3e, 0xe3, 0xb3, 0x76, 0x30, 0x59, 0x37, 0x61, 0x34, 0xf0, 0x58, 0xcc, 0x33, 0x72, 0x47, 0xc9, 0x78, 0xad, 0xd1, 0x78, 0xb6, 0xcc, 0xdf, 0xb0, 0x1, 0x9f}}},
  57. },
  58. "empty": {
  59. Name: "empty",
  60. Type: protocol.FileInfoTypeFile,
  61. ModifiedS: 0,
  62. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x0, Hash: []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}},
  63. },
  64. "bar": {
  65. Name: "bar",
  66. Type: protocol.FileInfoTypeFile,
  67. ModifiedS: 0,
  68. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}},
  69. },
  70. }
  71. func init() {
  72. // Fix expected test data to match reality
  73. for n, f := range testDataExpected {
  74. fi, _ := os.Stat("testdata/" + n)
  75. f.Permissions = uint32(fi.Mode())
  76. f.ModifiedS = fi.ModTime().Unix()
  77. f.Size = fi.Size()
  78. testDataExpected[n] = f
  79. }
  80. }
  81. func TestRequest(t *testing.T) {
  82. db := db.OpenMemory()
  83. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  84. // device1 shares default, but device2 doesn't
  85. m.AddFolder(defaultFolderConfig)
  86. m.StartFolder("default")
  87. m.ServeBackground()
  88. defer m.Stop()
  89. m.ScanFolder("default")
  90. bs := make([]byte, protocol.BlockSize)
  91. // Existing, shared file
  92. bs = bs[:6]
  93. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  94. if err != nil {
  95. t.Error(err)
  96. }
  97. if !bytes.Equal(bs, []byte("foobar")) {
  98. t.Errorf("Incorrect data from request: %q", string(bs))
  99. }
  100. // Existing, nonshared file
  101. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  102. if err == nil {
  103. t.Error("Unexpected nil error on insecure file read")
  104. }
  105. // Nonexistent file
  106. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  107. if err == nil {
  108. t.Error("Unexpected nil error on insecure file read")
  109. }
  110. // Shared folder, but disallowed file name
  111. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  112. if err == nil {
  113. t.Error("Unexpected nil error on insecure file read")
  114. }
  115. // Negative offset
  116. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  117. if err == nil {
  118. t.Error("Unexpected nil error on insecure file read")
  119. }
  120. // Larger block than available
  121. bs = bs[:42]
  122. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  123. if err == nil {
  124. t.Error("Unexpected nil error on insecure file read")
  125. }
  126. }
  127. func genFiles(n int) []protocol.FileInfo {
  128. files := make([]protocol.FileInfo, n)
  129. t := time.Now().Unix()
  130. for i := 0; i < n; i++ {
  131. files[i] = protocol.FileInfo{
  132. Name: fmt.Sprintf("file%d", i),
  133. ModifiedS: t,
  134. Sequence: int64(i + 1),
  135. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  136. }
  137. }
  138. return files
  139. }
  140. func BenchmarkIndex_10000(b *testing.B) {
  141. benchmarkIndex(b, 10000)
  142. }
  143. func BenchmarkIndex_100(b *testing.B) {
  144. benchmarkIndex(b, 100)
  145. }
  146. func benchmarkIndex(b *testing.B, nfiles int) {
  147. db := db.OpenMemory()
  148. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  149. m.AddFolder(defaultFolderConfig)
  150. m.StartFolder("default")
  151. m.ServeBackground()
  152. defer m.Stop()
  153. files := genFiles(nfiles)
  154. m.Index(device1, "default", files)
  155. b.ResetTimer()
  156. for i := 0; i < b.N; i++ {
  157. m.Index(device1, "default", files)
  158. }
  159. b.ReportAllocs()
  160. }
  161. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  162. benchmarkIndexUpdate(b, 10000, 10000)
  163. }
  164. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  165. benchmarkIndexUpdate(b, 10000, 100)
  166. }
  167. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  168. benchmarkIndexUpdate(b, 10000, 1)
  169. }
  170. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  171. db := db.OpenMemory()
  172. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  173. m.AddFolder(defaultFolderConfig)
  174. m.StartFolder("default")
  175. m.ServeBackground()
  176. defer m.Stop()
  177. files := genFiles(nfiles)
  178. ufiles := genFiles(nufiles)
  179. m.Index(device1, "default", files)
  180. b.ResetTimer()
  181. for i := 0; i < b.N; i++ {
  182. m.IndexUpdate(device1, "default", ufiles)
  183. }
  184. b.ReportAllocs()
  185. }
  186. type downloadProgressMessage struct {
  187. folder string
  188. updates []protocol.FileDownloadProgressUpdate
  189. }
  190. type fakeConnection struct {
  191. id protocol.DeviceID
  192. downloadProgressMessages []downloadProgressMessage
  193. closed bool
  194. files []protocol.FileInfo
  195. fileData map[string][]byte
  196. folder string
  197. model *Model
  198. indexFn func(string, []protocol.FileInfo)
  199. requestFn func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error)
  200. mut sync.Mutex
  201. }
  202. func (f *fakeConnection) Close() error {
  203. f.mut.Lock()
  204. defer f.mut.Unlock()
  205. f.closed = true
  206. return nil
  207. }
  208. func (f *fakeConnection) Start() {
  209. }
  210. func (f *fakeConnection) ID() protocol.DeviceID {
  211. return f.id
  212. }
  213. func (f *fakeConnection) Name() string {
  214. return ""
  215. }
  216. func (f *fakeConnection) Option(string) string {
  217. return ""
  218. }
  219. func (f *fakeConnection) Index(folder string, fs []protocol.FileInfo) error {
  220. f.mut.Lock()
  221. defer f.mut.Unlock()
  222. if f.indexFn != nil {
  223. f.indexFn(folder, fs)
  224. }
  225. return nil
  226. }
  227. func (f *fakeConnection) IndexUpdate(folder string, fs []protocol.FileInfo) error {
  228. f.mut.Lock()
  229. defer f.mut.Unlock()
  230. if f.indexFn != nil {
  231. f.indexFn(folder, fs)
  232. }
  233. return nil
  234. }
  235. func (f *fakeConnection) Request(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  236. f.mut.Lock()
  237. defer f.mut.Unlock()
  238. if f.requestFn != nil {
  239. return f.requestFn(folder, name, offset, size, hash, fromTemporary)
  240. }
  241. return f.fileData[name], nil
  242. }
  243. func (f *fakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  244. func (f *fakeConnection) Ping() bool {
  245. f.mut.Lock()
  246. defer f.mut.Unlock()
  247. return f.closed
  248. }
  249. func (f *fakeConnection) Closed() bool {
  250. f.mut.Lock()
  251. defer f.mut.Unlock()
  252. return f.closed
  253. }
  254. func (f *fakeConnection) Statistics() protocol.Statistics {
  255. return protocol.Statistics{}
  256. }
  257. func (f *fakeConnection) RemoteAddr() net.Addr {
  258. return &fakeAddr{}
  259. }
  260. func (f *fakeConnection) Type() string {
  261. return "fake"
  262. }
  263. func (f *fakeConnection) Transport() string {
  264. return "fake"
  265. }
  266. func (f *fakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  267. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  268. folder: folder,
  269. updates: updates,
  270. })
  271. }
  272. func (f *fakeConnection) addFile(name string, flags uint32, ftype protocol.FileInfoType, data []byte) {
  273. f.mut.Lock()
  274. defer f.mut.Unlock()
  275. blocks, _ := scanner.Blocks(context.TODO(), bytes.NewReader(data), protocol.BlockSize, int64(len(data)), nil, true)
  276. var version protocol.Vector
  277. version = version.Update(f.id.Short())
  278. if ftype == protocol.FileInfoTypeFile || ftype == protocol.FileInfoTypeDirectory {
  279. f.files = append(f.files, protocol.FileInfo{
  280. Name: name,
  281. Type: ftype,
  282. Size: int64(len(data)),
  283. ModifiedS: time.Now().Unix(),
  284. Permissions: flags,
  285. Version: version,
  286. Sequence: time.Now().UnixNano(),
  287. Blocks: blocks,
  288. })
  289. } else {
  290. // Symlink
  291. f.files = append(f.files, protocol.FileInfo{
  292. Name: name,
  293. Type: ftype,
  294. Version: version,
  295. Sequence: time.Now().UnixNano(),
  296. SymlinkTarget: string(data),
  297. })
  298. }
  299. if f.fileData == nil {
  300. f.fileData = make(map[string][]byte)
  301. }
  302. f.fileData[name] = data
  303. }
  304. func (f *fakeConnection) deleteFile(name string) {
  305. f.mut.Lock()
  306. defer f.mut.Unlock()
  307. for i, fi := range f.files {
  308. if fi.Name == name {
  309. fi.Deleted = true
  310. fi.ModifiedS = time.Now().Unix()
  311. fi.Version = fi.Version.Update(f.id.Short())
  312. fi.Sequence = time.Now().UnixNano()
  313. fi.Blocks = nil
  314. f.files = append(append(f.files[:i], f.files[i+1:]...), fi)
  315. return
  316. }
  317. }
  318. }
  319. func (f *fakeConnection) sendIndexUpdate() {
  320. f.model.IndexUpdate(f.id, f.folder, f.files)
  321. }
  322. func BenchmarkRequestOut(b *testing.B) {
  323. db := db.OpenMemory()
  324. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  325. m.AddFolder(defaultFolderConfig)
  326. m.ServeBackground()
  327. defer m.Stop()
  328. m.ScanFolder("default")
  329. const n = 1000
  330. files := genFiles(n)
  331. fc := &fakeConnection{id: device1}
  332. for _, f := range files {
  333. fc.addFile(f.Name, 0644, protocol.FileInfoTypeFile, []byte("some data to return"))
  334. }
  335. m.AddConnection(fc, protocol.HelloResult{})
  336. m.Index(device1, "default", files)
  337. b.ResetTimer()
  338. for i := 0; i < b.N; i++ {
  339. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, false)
  340. if err != nil {
  341. b.Error(err)
  342. }
  343. if data == nil {
  344. b.Error("nil data")
  345. }
  346. }
  347. }
  348. func BenchmarkRequestInSingleFile(b *testing.B) {
  349. db := db.OpenMemory()
  350. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  351. m.AddFolder(defaultFolderConfig)
  352. m.ServeBackground()
  353. defer m.Stop()
  354. m.ScanFolder("default")
  355. buf := make([]byte, 128<<10)
  356. rand.Read(buf)
  357. os.RemoveAll("testdata/request")
  358. defer os.RemoveAll("testdata/request")
  359. os.MkdirAll("testdata/request/for/a/file/in/a/couple/of/dirs", 0755)
  360. ioutil.WriteFile("testdata/request/for/a/file/in/a/couple/of/dirs/128k", buf, 0644)
  361. b.ResetTimer()
  362. for i := 0; i < b.N; i++ {
  363. if err := m.Request(device1, "default", "request/for/a/file/in/a/couple/of/dirs/128k", 0, nil, false, buf); err != nil {
  364. b.Error(err)
  365. }
  366. }
  367. b.SetBytes(128 << 10)
  368. }
  369. func TestDeviceRename(t *testing.T) {
  370. hello := protocol.HelloResult{
  371. ClientName: "syncthing",
  372. ClientVersion: "v0.9.4",
  373. }
  374. defer os.Remove("tmpconfig.xml")
  375. rawCfg := config.New(device1)
  376. rawCfg.Devices = []config.DeviceConfiguration{
  377. {
  378. DeviceID: device1,
  379. },
  380. }
  381. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  382. db := db.OpenMemory()
  383. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  384. if cfg.Devices()[device1].Name != "" {
  385. t.Errorf("Device already has a name")
  386. }
  387. conn := &fakeConnection{id: device1}
  388. m.AddConnection(conn, hello)
  389. m.ServeBackground()
  390. defer m.Stop()
  391. if cfg.Devices()[device1].Name != "" {
  392. t.Errorf("Device already has a name")
  393. }
  394. m.Closed(conn, protocol.ErrTimeout)
  395. hello.DeviceName = "tester"
  396. m.AddConnection(conn, hello)
  397. if cfg.Devices()[device1].Name != "tester" {
  398. t.Errorf("Device did not get a name")
  399. }
  400. m.Closed(conn, protocol.ErrTimeout)
  401. hello.DeviceName = "tester2"
  402. m.AddConnection(conn, hello)
  403. if cfg.Devices()[device1].Name != "tester" {
  404. t.Errorf("Device name got overwritten")
  405. }
  406. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  407. if err != nil {
  408. t.Error(err)
  409. return
  410. }
  411. if cfgw.Devices()[device1].Name != "tester" {
  412. t.Errorf("Device name not saved in config")
  413. }
  414. m.Closed(conn, protocol.ErrTimeout)
  415. opts := cfg.Options()
  416. opts.OverwriteRemoteDevNames = true
  417. cfg.SetOptions(opts)
  418. hello.DeviceName = "tester2"
  419. m.AddConnection(conn, hello)
  420. if cfg.Devices()[device1].Name != "tester2" {
  421. t.Errorf("Device name not overwritten")
  422. }
  423. }
  424. func TestClusterConfig(t *testing.T) {
  425. cfg := config.New(device1)
  426. cfg.Devices = []config.DeviceConfiguration{
  427. {
  428. DeviceID: device1,
  429. Introducer: true,
  430. },
  431. {
  432. DeviceID: device2,
  433. },
  434. }
  435. cfg.Folders = []config.FolderConfiguration{
  436. {
  437. ID: "folder1",
  438. Path: "testdata",
  439. Devices: []config.FolderDeviceConfiguration{
  440. {DeviceID: device1},
  441. {DeviceID: device2},
  442. },
  443. },
  444. {
  445. ID: "folder2",
  446. Path: "testdata",
  447. Devices: []config.FolderDeviceConfiguration{
  448. {DeviceID: device1},
  449. {DeviceID: device2},
  450. },
  451. },
  452. }
  453. db := db.OpenMemory()
  454. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  455. m.AddFolder(cfg.Folders[0])
  456. m.AddFolder(cfg.Folders[1])
  457. m.ServeBackground()
  458. defer m.Stop()
  459. cm := m.generateClusterConfig(device2)
  460. if l := len(cm.Folders); l != 2 {
  461. t.Fatalf("Incorrect number of folders %d != 2", l)
  462. }
  463. r := cm.Folders[0]
  464. if r.ID != "folder1" {
  465. t.Errorf("Incorrect folder %q != folder1", r.ID)
  466. }
  467. if l := len(r.Devices); l != 2 {
  468. t.Errorf("Incorrect number of devices %d != 2", l)
  469. }
  470. if id := r.Devices[0].ID; id != device1 {
  471. t.Errorf("Incorrect device ID %s != %s", id, device1)
  472. }
  473. if !r.Devices[0].Introducer {
  474. t.Error("Device1 should be flagged as Introducer")
  475. }
  476. if id := r.Devices[1].ID; id != device2 {
  477. t.Errorf("Incorrect device ID %s != %s", id, device2)
  478. }
  479. if r.Devices[1].Introducer {
  480. t.Error("Device2 should not be flagged as Introducer")
  481. }
  482. r = cm.Folders[1]
  483. if r.ID != "folder2" {
  484. t.Errorf("Incorrect folder %q != folder2", r.ID)
  485. }
  486. if l := len(r.Devices); l != 2 {
  487. t.Errorf("Incorrect number of devices %d != 2", l)
  488. }
  489. if id := r.Devices[0].ID; id != device1 {
  490. t.Errorf("Incorrect device ID %s != %s", id, device1)
  491. }
  492. if !r.Devices[0].Introducer {
  493. t.Error("Device1 should be flagged as Introducer")
  494. }
  495. if id := r.Devices[1].ID; id != device2 {
  496. t.Errorf("Incorrect device ID %s != %s", id, device2)
  497. }
  498. if r.Devices[1].Introducer {
  499. t.Error("Device2 should not be flagged as Introducer")
  500. }
  501. }
  502. func TestIntroducer(t *testing.T) {
  503. var introducedByAnyone protocol.DeviceID
  504. // LocalDeviceID is a magic value meaning don't check introducer
  505. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  506. for _, dev := range cfg.Devices {
  507. if dev.DeviceID.Equals(id) {
  508. if introducedBy.Equals(introducedByAnyone) {
  509. return true
  510. }
  511. return introducedBy.Equals(introducedBy)
  512. }
  513. }
  514. return false
  515. }
  516. newState := func(cfg config.Configuration) (*config.Wrapper, *Model) {
  517. db := db.OpenMemory()
  518. wcfg := config.Wrap("/tmp/test", cfg)
  519. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  520. for _, folder := range cfg.Folders {
  521. m.AddFolder(folder)
  522. }
  523. m.ServeBackground()
  524. m.AddConnection(&fakeConnection{id: device1}, protocol.HelloResult{})
  525. return wcfg, m
  526. }
  527. wcfg, m := newState(config.Configuration{
  528. Devices: []config.DeviceConfiguration{
  529. {
  530. DeviceID: device1,
  531. Introducer: true,
  532. },
  533. },
  534. Folders: []config.FolderConfiguration{
  535. {
  536. ID: "folder1",
  537. Path: "testdata",
  538. Devices: []config.FolderDeviceConfiguration{
  539. {DeviceID: device1},
  540. },
  541. },
  542. {
  543. ID: "folder2",
  544. Path: "testdata",
  545. Devices: []config.FolderDeviceConfiguration{
  546. {DeviceID: device1},
  547. },
  548. },
  549. },
  550. })
  551. m.ClusterConfig(device1, protocol.ClusterConfig{
  552. Folders: []protocol.Folder{
  553. {
  554. ID: "folder1",
  555. Devices: []protocol.Device{
  556. {
  557. ID: device2,
  558. Introducer: true,
  559. SkipIntroductionRemovals: true,
  560. },
  561. },
  562. },
  563. },
  564. })
  565. if newDev, ok := wcfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  566. t.Error("devie 2 missing or wrong flags")
  567. }
  568. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  569. t.Error("expected folder 1 to have device2 introduced by device 1")
  570. }
  571. wcfg, m = newState(config.Configuration{
  572. Devices: []config.DeviceConfiguration{
  573. {
  574. DeviceID: device1,
  575. Introducer: true,
  576. },
  577. {
  578. DeviceID: device2,
  579. IntroducedBy: device1,
  580. },
  581. },
  582. Folders: []config.FolderConfiguration{
  583. {
  584. ID: "folder1",
  585. Path: "testdata",
  586. Devices: []config.FolderDeviceConfiguration{
  587. {DeviceID: device1},
  588. {DeviceID: device2, IntroducedBy: device1},
  589. },
  590. },
  591. {
  592. ID: "folder2",
  593. Path: "testdata",
  594. Devices: []config.FolderDeviceConfiguration{
  595. {DeviceID: device1},
  596. },
  597. },
  598. },
  599. })
  600. m.ClusterConfig(device1, protocol.ClusterConfig{
  601. Folders: []protocol.Folder{
  602. {
  603. ID: "folder2",
  604. Devices: []protocol.Device{
  605. {
  606. ID: device2,
  607. Introducer: true,
  608. SkipIntroductionRemovals: true,
  609. },
  610. },
  611. },
  612. },
  613. })
  614. // Should not get introducer, as it's already unset, and it's an existing device.
  615. if newDev, ok := wcfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  616. t.Error("device 2 missing or changed flags")
  617. }
  618. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  619. t.Error("expected device 2 to be removed from folder 1")
  620. }
  621. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  622. t.Error("expected device 2 to be added to folder 2")
  623. }
  624. wcfg, m = newState(config.Configuration{
  625. Devices: []config.DeviceConfiguration{
  626. {
  627. DeviceID: device1,
  628. Introducer: true,
  629. },
  630. {
  631. DeviceID: device2,
  632. IntroducedBy: device1,
  633. },
  634. },
  635. Folders: []config.FolderConfiguration{
  636. {
  637. ID: "folder1",
  638. Path: "testdata",
  639. Devices: []config.FolderDeviceConfiguration{
  640. {DeviceID: device1},
  641. {DeviceID: device2, IntroducedBy: device1},
  642. },
  643. },
  644. {
  645. ID: "folder2",
  646. Path: "testdata",
  647. Devices: []config.FolderDeviceConfiguration{
  648. {DeviceID: device1},
  649. {DeviceID: device2, IntroducedBy: device1},
  650. },
  651. },
  652. },
  653. })
  654. m.ClusterConfig(device1, protocol.ClusterConfig{})
  655. if _, ok := wcfg.Device(device2); ok {
  656. t.Error("device 2 should have been removed")
  657. }
  658. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  659. t.Error("expected device 2 to be removed from folder 1")
  660. }
  661. if contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  662. t.Error("expected device 2 to be removed from folder 2")
  663. }
  664. // Two cases when removals should not happen
  665. // 1. Introducer flag no longer set on device
  666. wcfg, m = newState(config.Configuration{
  667. Devices: []config.DeviceConfiguration{
  668. {
  669. DeviceID: device1,
  670. Introducer: false,
  671. },
  672. {
  673. DeviceID: device2,
  674. IntroducedBy: device1,
  675. },
  676. },
  677. Folders: []config.FolderConfiguration{
  678. {
  679. ID: "folder1",
  680. Path: "testdata",
  681. Devices: []config.FolderDeviceConfiguration{
  682. {DeviceID: device1},
  683. {DeviceID: device2, IntroducedBy: device1},
  684. },
  685. },
  686. {
  687. ID: "folder2",
  688. Path: "testdata",
  689. Devices: []config.FolderDeviceConfiguration{
  690. {DeviceID: device1},
  691. {DeviceID: device2, IntroducedBy: device1},
  692. },
  693. },
  694. },
  695. })
  696. m.ClusterConfig(device1, protocol.ClusterConfig{})
  697. if _, ok := wcfg.Device(device2); !ok {
  698. t.Error("device 2 should not have been removed")
  699. }
  700. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  701. t.Error("expected device 2 not to be removed from folder 1")
  702. }
  703. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  704. t.Error("expected device 2 not to be removed from folder 2")
  705. }
  706. // 2. SkipIntroductionRemovals is set
  707. wcfg, m = newState(config.Configuration{
  708. Devices: []config.DeviceConfiguration{
  709. {
  710. DeviceID: device1,
  711. Introducer: true,
  712. SkipIntroductionRemovals: true,
  713. },
  714. {
  715. DeviceID: device2,
  716. IntroducedBy: device1,
  717. },
  718. },
  719. Folders: []config.FolderConfiguration{
  720. {
  721. ID: "folder1",
  722. Path: "testdata",
  723. Devices: []config.FolderDeviceConfiguration{
  724. {DeviceID: device1},
  725. {DeviceID: device2, IntroducedBy: device1},
  726. },
  727. },
  728. {
  729. ID: "folder2",
  730. Path: "testdata",
  731. Devices: []config.FolderDeviceConfiguration{
  732. {DeviceID: device1},
  733. },
  734. },
  735. },
  736. })
  737. m.ClusterConfig(device1, protocol.ClusterConfig{
  738. Folders: []protocol.Folder{
  739. {
  740. ID: "folder2",
  741. Devices: []protocol.Device{
  742. {
  743. ID: device2,
  744. Introducer: true,
  745. SkipIntroductionRemovals: true,
  746. },
  747. },
  748. },
  749. },
  750. })
  751. if _, ok := wcfg.Device(device2); !ok {
  752. t.Error("device 2 should not have been removed")
  753. }
  754. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  755. t.Error("expected device 2 not to be removed from folder 1")
  756. }
  757. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  758. t.Error("expected device 2 not to be added to folder 2")
  759. }
  760. // Test device not being removed as it's shared without an introducer.
  761. wcfg, m = newState(config.Configuration{
  762. Devices: []config.DeviceConfiguration{
  763. {
  764. DeviceID: device1,
  765. Introducer: true,
  766. },
  767. {
  768. DeviceID: device2,
  769. IntroducedBy: device1,
  770. },
  771. },
  772. Folders: []config.FolderConfiguration{
  773. {
  774. ID: "folder1",
  775. Path: "testdata",
  776. Devices: []config.FolderDeviceConfiguration{
  777. {DeviceID: device1},
  778. {DeviceID: device2, IntroducedBy: device1},
  779. },
  780. },
  781. {
  782. ID: "folder2",
  783. Path: "testdata",
  784. Devices: []config.FolderDeviceConfiguration{
  785. {DeviceID: device1},
  786. {DeviceID: device2},
  787. },
  788. },
  789. },
  790. })
  791. m.ClusterConfig(device1, protocol.ClusterConfig{})
  792. if _, ok := wcfg.Device(device2); !ok {
  793. t.Error("device 2 should not have been removed")
  794. }
  795. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  796. t.Error("expected device 2 to be removed from folder 1")
  797. }
  798. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  799. t.Error("expected device 2 not to be removed from folder 2")
  800. }
  801. // Test device not being removed as it's shared by a different introducer.
  802. wcfg, m = newState(config.Configuration{
  803. Devices: []config.DeviceConfiguration{
  804. {
  805. DeviceID: device1,
  806. Introducer: true,
  807. },
  808. {
  809. DeviceID: device2,
  810. IntroducedBy: device1,
  811. },
  812. },
  813. Folders: []config.FolderConfiguration{
  814. {
  815. ID: "folder1",
  816. Path: "testdata",
  817. Devices: []config.FolderDeviceConfiguration{
  818. {DeviceID: device1},
  819. {DeviceID: device2, IntroducedBy: device1},
  820. },
  821. },
  822. {
  823. ID: "folder2",
  824. Path: "testdata",
  825. Devices: []config.FolderDeviceConfiguration{
  826. {DeviceID: device1},
  827. {DeviceID: device2, IntroducedBy: protocol.LocalDeviceID},
  828. },
  829. },
  830. },
  831. })
  832. m.ClusterConfig(device1, protocol.ClusterConfig{})
  833. if _, ok := wcfg.Device(device2); !ok {
  834. t.Error("device 2 should not have been removed")
  835. }
  836. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  837. t.Error("expected device 2 to be removed from folder 1")
  838. }
  839. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  840. t.Error("expected device 2 not to be removed from folder 2")
  841. }
  842. }
  843. func changeIgnores(t *testing.T, m *Model, expected []string) {
  844. arrEqual := func(a, b []string) bool {
  845. if len(a) != len(b) {
  846. return false
  847. }
  848. for i := range a {
  849. if a[i] != b[i] {
  850. return false
  851. }
  852. }
  853. return true
  854. }
  855. ignores, _, err := m.GetIgnores("default")
  856. if err != nil {
  857. t.Error(err)
  858. }
  859. if !arrEqual(ignores, expected) {
  860. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  861. }
  862. ignores = append(ignores, "pox")
  863. err = m.SetIgnores("default", ignores)
  864. if err != nil {
  865. t.Error(err)
  866. }
  867. ignores2, _, err := m.GetIgnores("default")
  868. if err != nil {
  869. t.Error(err)
  870. }
  871. if !arrEqual(ignores, ignores2) {
  872. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  873. }
  874. if runtime.GOOS == "darwin" {
  875. // see above
  876. time.Sleep(time.Second)
  877. } else {
  878. time.Sleep(time.Millisecond)
  879. }
  880. err = m.SetIgnores("default", expected)
  881. if err != nil {
  882. t.Error(err)
  883. }
  884. ignores, _, err = m.GetIgnores("default")
  885. if err != nil {
  886. t.Error(err)
  887. }
  888. if !arrEqual(ignores, expected) {
  889. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  890. }
  891. }
  892. func TestIgnores(t *testing.T) {
  893. // Assure a clean start state
  894. os.RemoveAll("testdata/.stfolder")
  895. os.MkdirAll("testdata/.stfolder", 0644)
  896. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  897. db := db.OpenMemory()
  898. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  899. m.ServeBackground()
  900. defer m.Stop()
  901. // m.cfg.SetFolder is not usable as it is non-blocking, and there is no
  902. // way to know when the folder is actually added.
  903. m.AddFolder(defaultFolderConfig)
  904. m.StartFolder("default")
  905. // Reach in and update the ignore matcher to one that always does
  906. // reloads when asked to, instead of checking file mtimes. This is
  907. // because we will be changing the files on disk often enough that the
  908. // mtimes will be unreliable to determine change status.
  909. m.fmut.Lock()
  910. m.folderIgnores["default"] = ignore.New(defaultFs, ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  911. m.fmut.Unlock()
  912. // Make sure the initial scan has finished (ScanFolders is blocking)
  913. m.ScanFolders()
  914. expected := []string{
  915. ".*",
  916. "quux",
  917. }
  918. changeIgnores(t, m, expected)
  919. _, _, err := m.GetIgnores("doesnotexist")
  920. if err == nil {
  921. t.Error("No error")
  922. }
  923. err = m.SetIgnores("doesnotexist", expected)
  924. if err == nil {
  925. t.Error("No error")
  926. }
  927. // Invalid path, marker should be missing, hence returns an error.
  928. m.AddFolder(config.FolderConfiguration{ID: "fresh", Path: "XXX"})
  929. _, _, err = m.GetIgnores("fresh")
  930. if err == nil {
  931. t.Error("No error")
  932. }
  933. // Repeat tests with paused folder
  934. pausedDefaultFolderConfig := defaultFolderConfig
  935. pausedDefaultFolderConfig.Paused = true
  936. m.RestartFolder(pausedDefaultFolderConfig)
  937. // Here folder initialization is not an issue as a paused folder isn't
  938. // added to the model and thus there is no initial scan happening.
  939. changeIgnores(t, m, expected)
  940. // Make sure no .stignore file is considered valid
  941. os.Rename("testdata/.stignore", "testdata/.stignore.bak")
  942. changeIgnores(t, m, []string{})
  943. os.Rename("testdata/.stignore.bak", "testdata/.stignore")
  944. }
  945. func TestROScanRecovery(t *testing.T) {
  946. ldb := db.OpenMemory()
  947. set := db.NewFileSet("default", defaultFs, ldb)
  948. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  949. {Name: "dummyfile"},
  950. })
  951. fcfg := config.FolderConfiguration{
  952. ID: "default",
  953. Path: "testdata/rotestfolder",
  954. Type: config.FolderTypeSendOnly,
  955. RescanIntervalS: 1,
  956. }
  957. cfg := config.Wrap("/tmp/test", config.Configuration{
  958. Folders: []config.FolderConfiguration{fcfg},
  959. Devices: []config.DeviceConfiguration{
  960. {
  961. DeviceID: device1,
  962. },
  963. },
  964. })
  965. os.RemoveAll(fcfg.Path)
  966. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  967. m.AddFolder(fcfg)
  968. m.StartFolder("default")
  969. m.ServeBackground()
  970. defer m.Stop()
  971. waitFor := func(status string) error {
  972. timeout := time.Now().Add(2 * time.Second)
  973. for {
  974. _, _, err := m.State("default")
  975. if err == nil && status == "" {
  976. return nil
  977. }
  978. if err != nil && err.Error() == status {
  979. return nil
  980. }
  981. if time.Now().After(timeout) {
  982. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  983. }
  984. time.Sleep(10 * time.Millisecond)
  985. }
  986. }
  987. if err := waitFor("folder path missing"); err != nil {
  988. t.Error(err)
  989. return
  990. }
  991. os.Mkdir(fcfg.Path, 0700)
  992. if err := waitFor("folder marker missing"); err != nil {
  993. t.Error(err)
  994. return
  995. }
  996. fd, err := os.Create(filepath.Join(fcfg.Path, ".stfolder"))
  997. if err != nil {
  998. t.Error(err)
  999. return
  1000. }
  1001. fd.Close()
  1002. if err := waitFor(""); err != nil {
  1003. t.Error(err)
  1004. return
  1005. }
  1006. os.Remove(filepath.Join(fcfg.Path, ".stfolder"))
  1007. if err := waitFor("folder marker missing"); err != nil {
  1008. t.Error(err)
  1009. return
  1010. }
  1011. os.Remove(fcfg.Path)
  1012. if err := waitFor("folder path missing"); err != nil {
  1013. t.Error(err)
  1014. return
  1015. }
  1016. }
  1017. func TestRWScanRecovery(t *testing.T) {
  1018. ldb := db.OpenMemory()
  1019. set := db.NewFileSet("default", defaultFs, ldb)
  1020. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1021. {Name: "dummyfile"},
  1022. })
  1023. fcfg := config.FolderConfiguration{
  1024. ID: "default",
  1025. Path: "testdata/rwtestfolder",
  1026. Type: config.FolderTypeSendReceive,
  1027. RescanIntervalS: 1,
  1028. }
  1029. cfg := config.Wrap("/tmp/test", config.Configuration{
  1030. Folders: []config.FolderConfiguration{fcfg},
  1031. Devices: []config.DeviceConfiguration{
  1032. {
  1033. DeviceID: device1,
  1034. },
  1035. },
  1036. })
  1037. os.RemoveAll(fcfg.Path)
  1038. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1039. m.AddFolder(fcfg)
  1040. m.StartFolder("default")
  1041. m.ServeBackground()
  1042. defer m.Stop()
  1043. waitFor := func(status string) error {
  1044. timeout := time.Now().Add(2 * time.Second)
  1045. for {
  1046. _, _, err := m.State("default")
  1047. if err == nil && status == "" {
  1048. return nil
  1049. }
  1050. if err != nil && err.Error() == status {
  1051. return nil
  1052. }
  1053. if time.Now().After(timeout) {
  1054. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1055. }
  1056. time.Sleep(10 * time.Millisecond)
  1057. }
  1058. }
  1059. if err := waitFor("folder path missing"); err != nil {
  1060. t.Error(err)
  1061. return
  1062. }
  1063. os.Mkdir(fcfg.Path, 0700)
  1064. if err := waitFor("folder marker missing"); err != nil {
  1065. t.Error(err)
  1066. return
  1067. }
  1068. fd, err := os.Create(filepath.Join(fcfg.Path, ".stfolder"))
  1069. if err != nil {
  1070. t.Error(err)
  1071. return
  1072. }
  1073. fd.Close()
  1074. if err := waitFor(""); err != nil {
  1075. t.Error(err)
  1076. return
  1077. }
  1078. os.Remove(filepath.Join(fcfg.Path, ".stfolder"))
  1079. if err := waitFor("folder marker missing"); err != nil {
  1080. t.Error(err)
  1081. return
  1082. }
  1083. os.Remove(fcfg.Path)
  1084. if err := waitFor("folder path missing"); err != nil {
  1085. t.Error(err)
  1086. return
  1087. }
  1088. }
  1089. func TestGlobalDirectoryTree(t *testing.T) {
  1090. db := db.OpenMemory()
  1091. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1092. m.AddFolder(defaultFolderConfig)
  1093. m.ServeBackground()
  1094. defer m.Stop()
  1095. b := func(isfile bool, path ...string) protocol.FileInfo {
  1096. typ := protocol.FileInfoTypeDirectory
  1097. blocks := []protocol.BlockInfo{}
  1098. if isfile {
  1099. typ = protocol.FileInfoTypeFile
  1100. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  1101. }
  1102. return protocol.FileInfo{
  1103. Name: filepath.Join(path...),
  1104. Type: typ,
  1105. ModifiedS: 0x666,
  1106. Blocks: blocks,
  1107. Size: 0xa,
  1108. }
  1109. }
  1110. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1111. testdata := []protocol.FileInfo{
  1112. b(false, "another"),
  1113. b(false, "another", "directory"),
  1114. b(true, "another", "directory", "afile"),
  1115. b(false, "another", "directory", "with"),
  1116. b(false, "another", "directory", "with", "a"),
  1117. b(true, "another", "directory", "with", "a", "file"),
  1118. b(true, "another", "directory", "with", "file"),
  1119. b(true, "another", "file"),
  1120. b(false, "other"),
  1121. b(false, "other", "rand"),
  1122. b(false, "other", "random"),
  1123. b(false, "other", "random", "dir"),
  1124. b(false, "other", "random", "dirx"),
  1125. b(false, "other", "randomx"),
  1126. b(false, "some"),
  1127. b(false, "some", "directory"),
  1128. b(false, "some", "directory", "with"),
  1129. b(false, "some", "directory", "with", "a"),
  1130. b(true, "some", "directory", "with", "a", "file"),
  1131. b(true, "rootfile"),
  1132. }
  1133. expectedResult := map[string]interface{}{
  1134. "another": map[string]interface{}{
  1135. "directory": map[string]interface{}{
  1136. "afile": filedata,
  1137. "with": map[string]interface{}{
  1138. "a": map[string]interface{}{
  1139. "file": filedata,
  1140. },
  1141. "file": filedata,
  1142. },
  1143. },
  1144. "file": filedata,
  1145. },
  1146. "other": map[string]interface{}{
  1147. "rand": map[string]interface{}{},
  1148. "random": map[string]interface{}{
  1149. "dir": map[string]interface{}{},
  1150. "dirx": map[string]interface{}{},
  1151. },
  1152. "randomx": map[string]interface{}{},
  1153. },
  1154. "some": map[string]interface{}{
  1155. "directory": map[string]interface{}{
  1156. "with": map[string]interface{}{
  1157. "a": map[string]interface{}{
  1158. "file": filedata,
  1159. },
  1160. },
  1161. },
  1162. },
  1163. "rootfile": filedata,
  1164. }
  1165. mm := func(data interface{}) string {
  1166. bytes, err := json.Marshal(data)
  1167. if err != nil {
  1168. panic(err)
  1169. }
  1170. return string(bytes)
  1171. }
  1172. m.Index(device1, "default", testdata)
  1173. result := m.GlobalDirectoryTree("default", "", -1, false)
  1174. if mm(result) != mm(expectedResult) {
  1175. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1176. }
  1177. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1178. if mm(result) != mm(expectedResult["another"]) {
  1179. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1180. }
  1181. result = m.GlobalDirectoryTree("default", "", 0, false)
  1182. currentResult := map[string]interface{}{
  1183. "another": map[string]interface{}{},
  1184. "other": map[string]interface{}{},
  1185. "some": map[string]interface{}{},
  1186. "rootfile": filedata,
  1187. }
  1188. if mm(result) != mm(currentResult) {
  1189. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1190. }
  1191. result = m.GlobalDirectoryTree("default", "", 1, false)
  1192. currentResult = map[string]interface{}{
  1193. "another": map[string]interface{}{
  1194. "directory": map[string]interface{}{},
  1195. "file": filedata,
  1196. },
  1197. "other": map[string]interface{}{
  1198. "rand": map[string]interface{}{},
  1199. "random": map[string]interface{}{},
  1200. "randomx": map[string]interface{}{},
  1201. },
  1202. "some": map[string]interface{}{
  1203. "directory": map[string]interface{}{},
  1204. },
  1205. "rootfile": filedata,
  1206. }
  1207. if mm(result) != mm(currentResult) {
  1208. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1209. }
  1210. result = m.GlobalDirectoryTree("default", "", -1, true)
  1211. currentResult = map[string]interface{}{
  1212. "another": map[string]interface{}{
  1213. "directory": map[string]interface{}{
  1214. "with": map[string]interface{}{
  1215. "a": map[string]interface{}{},
  1216. },
  1217. },
  1218. },
  1219. "other": map[string]interface{}{
  1220. "rand": map[string]interface{}{},
  1221. "random": map[string]interface{}{
  1222. "dir": map[string]interface{}{},
  1223. "dirx": map[string]interface{}{},
  1224. },
  1225. "randomx": map[string]interface{}{},
  1226. },
  1227. "some": map[string]interface{}{
  1228. "directory": map[string]interface{}{
  1229. "with": map[string]interface{}{
  1230. "a": map[string]interface{}{},
  1231. },
  1232. },
  1233. },
  1234. }
  1235. if mm(result) != mm(currentResult) {
  1236. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1237. }
  1238. result = m.GlobalDirectoryTree("default", "", 1, true)
  1239. currentResult = map[string]interface{}{
  1240. "another": map[string]interface{}{
  1241. "directory": map[string]interface{}{},
  1242. },
  1243. "other": map[string]interface{}{
  1244. "rand": map[string]interface{}{},
  1245. "random": map[string]interface{}{},
  1246. "randomx": map[string]interface{}{},
  1247. },
  1248. "some": map[string]interface{}{
  1249. "directory": map[string]interface{}{},
  1250. },
  1251. }
  1252. if mm(result) != mm(currentResult) {
  1253. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1254. }
  1255. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1256. currentResult = map[string]interface{}{
  1257. "directory": map[string]interface{}{},
  1258. "file": filedata,
  1259. }
  1260. if mm(result) != mm(currentResult) {
  1261. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1262. }
  1263. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1264. currentResult = map[string]interface{}{
  1265. "with": map[string]interface{}{},
  1266. }
  1267. if mm(result) != mm(currentResult) {
  1268. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1269. }
  1270. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1271. currentResult = map[string]interface{}{
  1272. "with": map[string]interface{}{
  1273. "a": map[string]interface{}{},
  1274. },
  1275. }
  1276. if mm(result) != mm(currentResult) {
  1277. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1278. }
  1279. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1280. currentResult = map[string]interface{}{
  1281. "with": map[string]interface{}{
  1282. "a": map[string]interface{}{
  1283. "file": filedata,
  1284. },
  1285. },
  1286. }
  1287. if mm(result) != mm(currentResult) {
  1288. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1289. }
  1290. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1291. currentResult = map[string]interface{}{
  1292. "directory": map[string]interface{}{
  1293. "with": map[string]interface{}{
  1294. "a": map[string]interface{}{},
  1295. },
  1296. },
  1297. }
  1298. if mm(result) != mm(currentResult) {
  1299. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1300. }
  1301. // No prefix matching!
  1302. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1303. currentResult = map[string]interface{}{}
  1304. if mm(result) != mm(currentResult) {
  1305. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1306. }
  1307. }
  1308. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1309. db := db.OpenMemory()
  1310. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1311. m.AddFolder(defaultFolderConfig)
  1312. m.ServeBackground()
  1313. b := func(isfile bool, path ...string) protocol.FileInfo {
  1314. typ := protocol.FileInfoTypeDirectory
  1315. blocks := []protocol.BlockInfo{}
  1316. if isfile {
  1317. typ = protocol.FileInfoTypeFile
  1318. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  1319. }
  1320. return protocol.FileInfo{
  1321. Name: filepath.Join(path...),
  1322. Type: typ,
  1323. ModifiedS: 0x666,
  1324. Blocks: blocks,
  1325. Size: 0xa,
  1326. }
  1327. }
  1328. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1329. testdata := []protocol.FileInfo{
  1330. b(true, "another", "directory", "afile"),
  1331. b(true, "another", "directory", "with", "a", "file"),
  1332. b(true, "another", "directory", "with", "file"),
  1333. b(false, "other", "random", "dirx"),
  1334. b(false, "other", "randomx"),
  1335. b(false, "some", "directory", "with", "x"),
  1336. b(true, "some", "directory", "with", "a", "file"),
  1337. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1338. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1339. }
  1340. expectedResult := map[string]interface{}{
  1341. "another": map[string]interface{}{
  1342. "directory": map[string]interface{}{
  1343. "afile": filedata,
  1344. "with": map[string]interface{}{
  1345. "a": map[string]interface{}{
  1346. "file": filedata,
  1347. },
  1348. "file": filedata,
  1349. },
  1350. },
  1351. },
  1352. "other": map[string]interface{}{
  1353. "random": map[string]interface{}{
  1354. "dirx": map[string]interface{}{},
  1355. },
  1356. "randomx": map[string]interface{}{},
  1357. },
  1358. "some": map[string]interface{}{
  1359. "directory": map[string]interface{}{
  1360. "with": map[string]interface{}{
  1361. "a": map[string]interface{}{
  1362. "file": filedata,
  1363. },
  1364. "x": map[string]interface{}{},
  1365. },
  1366. },
  1367. },
  1368. "this": map[string]interface{}{
  1369. "is": map[string]interface{}{
  1370. "a": map[string]interface{}{
  1371. "deep": map[string]interface{}{
  1372. "invalid": map[string]interface{}{
  1373. "directory": map[string]interface{}{},
  1374. },
  1375. },
  1376. },
  1377. },
  1378. },
  1379. "xthis": map[string]interface{}{
  1380. "is": map[string]interface{}{
  1381. "a": map[string]interface{}{
  1382. "deep": map[string]interface{}{
  1383. "invalid": map[string]interface{}{
  1384. "file": filedata,
  1385. },
  1386. },
  1387. },
  1388. },
  1389. },
  1390. }
  1391. mm := func(data interface{}) string {
  1392. bytes, err := json.Marshal(data)
  1393. if err != nil {
  1394. panic(err)
  1395. }
  1396. return string(bytes)
  1397. }
  1398. m.Index(device1, "default", testdata)
  1399. result := m.GlobalDirectoryTree("default", "", -1, false)
  1400. if mm(result) != mm(expectedResult) {
  1401. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1402. }
  1403. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1404. currentResult := map[string]interface{}{
  1405. "invalid": map[string]interface{}{
  1406. "file": filedata,
  1407. },
  1408. }
  1409. if mm(result) != mm(currentResult) {
  1410. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1411. }
  1412. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1413. currentResult = map[string]interface{}{
  1414. "invalid": map[string]interface{}{},
  1415. }
  1416. if mm(result) != mm(currentResult) {
  1417. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1418. }
  1419. // !!! This is actually BAD, because we don't have enough level allowance
  1420. // to accept this file, hence the tree is left unbuilt !!!
  1421. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1422. currentResult = map[string]interface{}{}
  1423. if mm(result) != mm(currentResult) {
  1424. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1425. }
  1426. }
  1427. func genDeepFiles(n, d int) []protocol.FileInfo {
  1428. rand.Seed(int64(n))
  1429. files := make([]protocol.FileInfo, n)
  1430. t := time.Now().Unix()
  1431. for i := 0; i < n; i++ {
  1432. path := ""
  1433. for i := 0; i <= d; i++ {
  1434. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1435. }
  1436. sofar := ""
  1437. for _, path := range filepath.SplitList(path) {
  1438. sofar = filepath.Join(sofar, path)
  1439. files[i] = protocol.FileInfo{
  1440. Name: sofar,
  1441. }
  1442. i++
  1443. }
  1444. files[i].ModifiedS = t
  1445. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1446. }
  1447. return files
  1448. }
  1449. func BenchmarkTree_10000_50(b *testing.B) {
  1450. benchmarkTree(b, 10000, 50)
  1451. }
  1452. func BenchmarkTree_100_50(b *testing.B) {
  1453. benchmarkTree(b, 100, 50)
  1454. }
  1455. func BenchmarkTree_100_10(b *testing.B) {
  1456. benchmarkTree(b, 100, 10)
  1457. }
  1458. func benchmarkTree(b *testing.B, n1, n2 int) {
  1459. db := db.OpenMemory()
  1460. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1461. m.AddFolder(defaultFolderConfig)
  1462. m.ServeBackground()
  1463. m.ScanFolder("default")
  1464. files := genDeepFiles(n1, n2)
  1465. m.Index(device1, "default", files)
  1466. b.ResetTimer()
  1467. for i := 0; i < b.N; i++ {
  1468. m.GlobalDirectoryTree("default", "", -1, false)
  1469. }
  1470. b.ReportAllocs()
  1471. }
  1472. func TestUnifySubs(t *testing.T) {
  1473. cases := []struct {
  1474. in []string // input to unifySubs
  1475. exists []string // paths that exist in the database
  1476. out []string // expected output
  1477. }{
  1478. {
  1479. // 0. trailing slashes are cleaned, known paths are just passed on
  1480. []string{"foo/", "bar//"},
  1481. []string{"foo", "bar"},
  1482. []string{"bar", "foo"}, // the output is sorted
  1483. },
  1484. {
  1485. // 1. "foo/bar" gets trimmed as it's covered by foo
  1486. []string{"foo", "bar/", "foo/bar/"},
  1487. []string{"foo", "bar"},
  1488. []string{"bar", "foo"},
  1489. },
  1490. {
  1491. // 2. "" gets simplified to the empty list; ie scan all
  1492. []string{"foo", ""},
  1493. []string{"foo"},
  1494. nil,
  1495. },
  1496. {
  1497. // 3. "foo/bar" is unknown, but it's kept
  1498. // because its parent is known
  1499. []string{"foo/bar"},
  1500. []string{"foo"},
  1501. []string{"foo/bar"},
  1502. },
  1503. {
  1504. // 4. two independent known paths, both are kept
  1505. // "usr/lib" is not a prefix of "usr/libexec"
  1506. []string{"usr/lib", "usr/libexec"},
  1507. []string{"usr", "usr/lib", "usr/libexec"},
  1508. []string{"usr/lib", "usr/libexec"},
  1509. },
  1510. {
  1511. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1512. []string{"usr/lib", "usr/lib/exec"},
  1513. []string{"usr", "usr/lib", "usr/libexec"},
  1514. []string{"usr/lib"},
  1515. },
  1516. {
  1517. // 6. .stignore and .stfolder are special and are passed on
  1518. // verbatim even though they are unknown
  1519. []string{".stfolder", ".stignore"},
  1520. []string{},
  1521. []string{".stfolder", ".stignore"},
  1522. },
  1523. {
  1524. // 7. but the presence of something else unknown forces an actual
  1525. // scan
  1526. []string{".stfolder", ".stignore", "foo/bar"},
  1527. []string{},
  1528. []string{".stfolder", ".stignore", "foo"},
  1529. },
  1530. {
  1531. // 8. explicit request to scan all
  1532. nil,
  1533. []string{"foo"},
  1534. nil,
  1535. },
  1536. {
  1537. // 9. empty list of subs
  1538. []string{},
  1539. []string{"foo"},
  1540. nil,
  1541. },
  1542. }
  1543. if runtime.GOOS == "windows" {
  1544. // Fixup path separators
  1545. for i := range cases {
  1546. for j, p := range cases[i].in {
  1547. cases[i].in[j] = filepath.FromSlash(p)
  1548. }
  1549. for j, p := range cases[i].exists {
  1550. cases[i].exists[j] = filepath.FromSlash(p)
  1551. }
  1552. for j, p := range cases[i].out {
  1553. cases[i].out[j] = filepath.FromSlash(p)
  1554. }
  1555. }
  1556. }
  1557. for i, tc := range cases {
  1558. exists := func(f string) bool {
  1559. for _, e := range tc.exists {
  1560. if f == e {
  1561. return true
  1562. }
  1563. }
  1564. return false
  1565. }
  1566. out := unifySubs(tc.in, exists)
  1567. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1568. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1569. }
  1570. }
  1571. }
  1572. func TestIssue3028(t *testing.T) {
  1573. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1574. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1575. t.Fatal(err)
  1576. }
  1577. defer os.Remove("testdata/testrm")
  1578. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1579. t.Fatal(err)
  1580. }
  1581. defer os.Remove("testdata/testrm2")
  1582. // Create a model and default folder
  1583. db := db.OpenMemory()
  1584. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1585. defCfg := defaultFolderConfig.Copy()
  1586. defCfg.RescanIntervalS = 86400
  1587. m.AddFolder(defCfg)
  1588. m.StartFolder("default")
  1589. m.ServeBackground()
  1590. // Make sure the initial scan has finished (ScanFolders is blocking)
  1591. m.ScanFolders()
  1592. // Get a count of how many files are there now
  1593. locorigfiles := m.LocalSize("default").Files
  1594. globorigfiles := m.GlobalSize("default").Files
  1595. // Delete and rescan specifically these two
  1596. os.Remove("testdata/testrm")
  1597. os.Remove("testdata/testrm2")
  1598. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1599. // Verify that the number of files decreased by two and the number of
  1600. // deleted files increases by two
  1601. loc := m.LocalSize("default")
  1602. glob := m.GlobalSize("default")
  1603. if loc.Files != locorigfiles-2 {
  1604. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1605. }
  1606. if glob.Files != globorigfiles-2 {
  1607. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1608. }
  1609. if loc.Deleted != 2 {
  1610. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1611. }
  1612. if glob.Deleted != 2 {
  1613. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1614. }
  1615. }
  1616. func TestIssue3164(t *testing.T) {
  1617. os.RemoveAll("testdata/issue3164")
  1618. defer os.RemoveAll("testdata/issue3164")
  1619. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1620. t.Fatal(err)
  1621. }
  1622. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1623. t.Fatal(err)
  1624. }
  1625. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1626. t.Fatal(err)
  1627. }
  1628. f := protocol.FileInfo{
  1629. Name: "issue3164",
  1630. }
  1631. m := ignore.New(defaultFs)
  1632. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1633. t.Fatal(err)
  1634. }
  1635. fl := sendReceiveFolder{
  1636. dbUpdates: make(chan dbUpdateJob, 1),
  1637. fs: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  1638. }
  1639. fl.deleteDir(f, m)
  1640. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1641. t.Fatal(err)
  1642. }
  1643. }
  1644. func TestIssue4357(t *testing.T) {
  1645. db := db.OpenMemory()
  1646. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1647. m.ServeBackground()
  1648. defer m.Stop()
  1649. cfg := m.cfg.RawCopy()
  1650. m.CommitConfiguration(config.Configuration{}, cfg)
  1651. if _, ok := m.folderCfgs["default"]; !ok {
  1652. t.Error("Folder should be running")
  1653. }
  1654. newCfg := m.cfg.RawCopy()
  1655. newCfg.Folders[0].Paused = true
  1656. m.CommitConfiguration(cfg, newCfg)
  1657. if _, ok := m.folderCfgs["default"]; ok {
  1658. t.Error("Folder should not be running")
  1659. }
  1660. // Should not panic when removing a paused folder.
  1661. m.RemoveFolder("default")
  1662. // Add the folder back, should be running
  1663. m.CommitConfiguration(config.Configuration{}, cfg)
  1664. if _, ok := m.folderCfgs["default"]; !ok {
  1665. t.Error("Folder should be running")
  1666. }
  1667. // Should not panic when removing a running folder.
  1668. m.RemoveFolder("default")
  1669. if _, ok := m.folderCfgs["default"]; ok {
  1670. t.Error("Folder should not be running")
  1671. }
  1672. // Should panic when removing a non-existing folder
  1673. defer func() {
  1674. if recover() == nil {
  1675. t.Error("expected a panic")
  1676. }
  1677. }()
  1678. m.RemoveFolder("non-existing")
  1679. }
  1680. func TestScanNoDatabaseWrite(t *testing.T) {
  1681. // When scanning, nothing should be committed to database unless
  1682. // something actually changed.
  1683. db := db.OpenMemory()
  1684. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1685. m.AddFolder(defaultFolderConfig)
  1686. m.StartFolder("default")
  1687. m.ServeBackground()
  1688. // Start with no ignores, and restore the previous state when the test completes
  1689. curIgn, _, err := m.GetIgnores("default")
  1690. if err != nil {
  1691. t.Fatal(err)
  1692. }
  1693. defer m.SetIgnores("default", curIgn)
  1694. m.SetIgnores("default", nil)
  1695. fakeTime := time.Now().Add(5 * time.Second)
  1696. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1697. // Scan the folder twice. The second scan should be a no-op database wise
  1698. m.ScanFolder("default")
  1699. c0 := db.Committed()
  1700. m.ScanFolder("default")
  1701. c1 := db.Committed()
  1702. if c1 != c0 {
  1703. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1704. }
  1705. // Ignore a file we know exists. It'll be updated in the database.
  1706. m.SetIgnores("default", []string{"foo"})
  1707. fakeTime = time.Now().Add(10 * time.Second)
  1708. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1709. m.ScanFolder("default")
  1710. c2 := db.Committed()
  1711. if c2 <= c1 {
  1712. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1713. }
  1714. // Scan again. Nothing should happen.
  1715. m.ScanFolder("default")
  1716. c3 := db.Committed()
  1717. if c3 != c2 {
  1718. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1719. }
  1720. }
  1721. func TestIssue2782(t *testing.T) {
  1722. // CheckFolderHealth should accept a symlinked folder, when using tilde-expanded path.
  1723. if runtime.GOOS == "windows" {
  1724. t.Skip("not reliable on Windows")
  1725. return
  1726. }
  1727. home := os.Getenv("HOME")
  1728. if home == "" {
  1729. t.Skip("no home")
  1730. }
  1731. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1732. // part of the issue. Skip the test if any of this fails, as we are a
  1733. // bit outside of our stated domain here...
  1734. testName := ".syncthing-test." + srand.String(16)
  1735. testDir := filepath.Join(home, testName)
  1736. if err := os.RemoveAll(testDir); err != nil {
  1737. t.Skip(err)
  1738. }
  1739. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1740. t.Skip(err)
  1741. }
  1742. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1743. t.Skip(err)
  1744. }
  1745. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1746. t.Skip(err)
  1747. }
  1748. defer os.RemoveAll(testDir)
  1749. db := db.OpenMemory()
  1750. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1751. m.AddFolder(config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  1752. m.StartFolder("default")
  1753. m.ServeBackground()
  1754. defer m.Stop()
  1755. if err := m.ScanFolder("default"); err != nil {
  1756. t.Error("scan error:", err)
  1757. }
  1758. if err := m.CheckFolderHealth("default"); err != nil {
  1759. t.Error("health check error:", err)
  1760. }
  1761. }
  1762. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1763. dbi := db.OpenMemory()
  1764. files := db.NewFileSet("default", defaultFs, dbi)
  1765. files.Replace(device1, genFiles(1))
  1766. files.Replace(device2, genFiles(1))
  1767. if len(files.ListDevices()) != 2 {
  1768. t.Error("expected two devices")
  1769. }
  1770. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1771. m.AddFolder(defaultFolderConfig)
  1772. m.StartFolder("default")
  1773. // Remote sequence is cached, hence need to recreated.
  1774. files = db.NewFileSet("default", defaultFs, dbi)
  1775. if len(files.ListDevices()) != 1 {
  1776. t.Error("Expected one device")
  1777. }
  1778. }
  1779. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1780. dbi := db.OpenMemory()
  1781. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  1782. fcfg.Devices = []config.FolderDeviceConfiguration{
  1783. {DeviceID: device1},
  1784. {DeviceID: device2},
  1785. }
  1786. cfg := config.Configuration{
  1787. Folders: []config.FolderConfiguration{fcfg},
  1788. Devices: []config.DeviceConfiguration{
  1789. config.NewDeviceConfiguration(device1, "device1"),
  1790. config.NewDeviceConfiguration(device2, "device2"),
  1791. },
  1792. Options: config.OptionsConfiguration{
  1793. // Don't remove temporaries directly on startup
  1794. KeepTemporariesH: 1,
  1795. },
  1796. }
  1797. wcfg := config.Wrap("/tmp/test", cfg)
  1798. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1799. m.AddFolder(fcfg)
  1800. m.StartFolder(fcfg.ID)
  1801. m.ServeBackground()
  1802. conn1 := &fakeConnection{id: device1}
  1803. m.AddConnection(conn1, protocol.HelloResult{})
  1804. conn2 := &fakeConnection{id: device2}
  1805. m.AddConnection(conn2, protocol.HelloResult{})
  1806. m.ClusterConfig(device1, protocol.ClusterConfig{
  1807. Folders: []protocol.Folder{
  1808. {
  1809. ID: "default",
  1810. Devices: []protocol.Device{
  1811. {ID: device1},
  1812. {ID: device2},
  1813. },
  1814. },
  1815. },
  1816. })
  1817. m.ClusterConfig(device2, protocol.ClusterConfig{
  1818. Folders: []protocol.Folder{
  1819. {
  1820. ID: "default",
  1821. Devices: []protocol.Device{
  1822. {ID: device1},
  1823. {ID: device2},
  1824. },
  1825. },
  1826. },
  1827. })
  1828. if !m.folderSharedWith("default", device1) {
  1829. t.Error("not shared with device1")
  1830. }
  1831. if !m.folderSharedWith("default", device2) {
  1832. t.Error("not shared with device2")
  1833. }
  1834. if conn2.Closed() {
  1835. t.Error("conn already closed")
  1836. }
  1837. cfg = cfg.Copy()
  1838. cfg.Devices = cfg.Devices[:1]
  1839. if err := wcfg.Replace(cfg); err != nil {
  1840. t.Error(err)
  1841. }
  1842. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1843. if !m.folderSharedWith("default", device1) {
  1844. t.Error("not shared with device1")
  1845. }
  1846. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1847. t.Error("shared with device2")
  1848. }
  1849. if !conn2.Closed() {
  1850. t.Error("connection not closed")
  1851. }
  1852. if _, ok := wcfg.Devices()[device2]; ok {
  1853. t.Error("device still in config")
  1854. }
  1855. fdevs, ok := m.folderDevices["default"]
  1856. if !ok {
  1857. t.Error("folder missing?")
  1858. }
  1859. for id := range fdevs {
  1860. if id == device2 {
  1861. t.Error("still there")
  1862. }
  1863. }
  1864. if _, ok := m.conn[device2]; !ok {
  1865. t.Error("conn missing early")
  1866. }
  1867. if _, ok := m.helloMessages[device2]; !ok {
  1868. t.Error("hello missing early")
  1869. }
  1870. if _, ok := m.deviceDownloads[device2]; !ok {
  1871. t.Error("downloads missing early")
  1872. }
  1873. m.Closed(conn2, fmt.Errorf("foo"))
  1874. if _, ok := m.conn[device2]; ok {
  1875. t.Error("conn not missing")
  1876. }
  1877. if _, ok := m.helloMessages[device2]; ok {
  1878. t.Error("hello not missing")
  1879. }
  1880. if _, ok := m.deviceDownloads[device2]; ok {
  1881. t.Error("downloads not missing")
  1882. }
  1883. }
  1884. func TestIssue3496(t *testing.T) {
  1885. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  1886. // It seems like lots of deleted files can cause negative completion
  1887. // percentages. Lets make sure that doesn't happen. Also do some general
  1888. // checks on the completion calculation stuff.
  1889. dbi := db.OpenMemory()
  1890. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1891. m.AddFolder(defaultFolderConfig)
  1892. m.StartFolder("default")
  1893. m.ServeBackground()
  1894. defer m.Stop()
  1895. m.ScanFolder("default")
  1896. addFakeConn(m, device1)
  1897. addFakeConn(m, device2)
  1898. // Reach into the model and grab the current file list...
  1899. m.fmut.RLock()
  1900. fs := m.folderFiles["default"]
  1901. m.fmut.RUnlock()
  1902. var localFiles []protocol.FileInfo
  1903. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1904. localFiles = append(localFiles, i.(protocol.FileInfo))
  1905. return true
  1906. })
  1907. // Mark all files as deleted and fake it as update from device1
  1908. for i := range localFiles {
  1909. localFiles[i].Deleted = true
  1910. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1911. localFiles[i].Blocks = nil
  1912. }
  1913. // Also add a small file that we're supposed to need, or the global size
  1914. // stuff will bail out early due to the entire folder being zero size.
  1915. localFiles = append(localFiles, protocol.FileInfo{
  1916. Name: "fake",
  1917. Size: 1234,
  1918. Type: protocol.FileInfoTypeFile,
  1919. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1920. })
  1921. m.IndexUpdate(device1, "default", localFiles)
  1922. // Check that the completion percentage for us makes sense
  1923. comp := m.Completion(protocol.LocalDeviceID, "default")
  1924. if comp.NeedBytes > comp.GlobalBytes {
  1925. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1926. }
  1927. if comp.CompletionPct < 0 {
  1928. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1929. }
  1930. if comp.NeedBytes == 0 {
  1931. t.Error("Need no bytes even though some files are deleted")
  1932. }
  1933. if comp.CompletionPct == 100 {
  1934. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1935. }
  1936. t.Log(comp)
  1937. // Check that NeedSize does the correct thing
  1938. need := m.NeedSize("default")
  1939. if need.Files != 1 || need.Bytes != 1234 {
  1940. // The one we added synthetically above
  1941. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1942. }
  1943. if need.Deleted != len(localFiles)-1 {
  1944. // The rest
  1945. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1946. }
  1947. }
  1948. func TestIssue3804(t *testing.T) {
  1949. dbi := db.OpenMemory()
  1950. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1951. m.AddFolder(defaultFolderConfig)
  1952. m.StartFolder("default")
  1953. m.ServeBackground()
  1954. defer m.Stop()
  1955. // Subdirs ending in slash should be accepted
  1956. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1957. t.Error("Unexpected error:", err)
  1958. }
  1959. }
  1960. func TestIssue3829(t *testing.T) {
  1961. dbi := db.OpenMemory()
  1962. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1963. m.AddFolder(defaultFolderConfig)
  1964. m.StartFolder("default")
  1965. m.ServeBackground()
  1966. defer m.Stop()
  1967. // Empty subdirs should be accepted
  1968. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1969. t.Error("Unexpected error:", err)
  1970. }
  1971. }
  1972. func TestNoRequestsFromPausedDevices(t *testing.T) {
  1973. t.Skip("broken, fails randomly, #3843")
  1974. dbi := db.OpenMemory()
  1975. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  1976. fcfg.Devices = []config.FolderDeviceConfiguration{
  1977. {DeviceID: device1},
  1978. {DeviceID: device2},
  1979. }
  1980. cfg := config.Configuration{
  1981. Folders: []config.FolderConfiguration{fcfg},
  1982. Devices: []config.DeviceConfiguration{
  1983. config.NewDeviceConfiguration(device1, "device1"),
  1984. config.NewDeviceConfiguration(device2, "device2"),
  1985. },
  1986. Options: config.OptionsConfiguration{
  1987. // Don't remove temporaries directly on startup
  1988. KeepTemporariesH: 1,
  1989. },
  1990. }
  1991. wcfg := config.Wrap("/tmp/test", cfg)
  1992. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1993. m.AddFolder(fcfg)
  1994. m.StartFolder(fcfg.ID)
  1995. m.ServeBackground()
  1996. file := testDataExpected["foo"]
  1997. files := m.folderFiles["default"]
  1998. files.Update(device1, []protocol.FileInfo{file})
  1999. files.Update(device2, []protocol.FileInfo{file})
  2000. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2001. if len(avail) != 0 {
  2002. t.Errorf("should not be available, no connections")
  2003. }
  2004. addFakeConn(m, device1)
  2005. addFakeConn(m, device2)
  2006. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2007. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2008. if len(avail) != 2 {
  2009. t.Errorf("should have two available")
  2010. }
  2011. cc := protocol.ClusterConfig{
  2012. Folders: []protocol.Folder{
  2013. {
  2014. ID: "default",
  2015. Devices: []protocol.Device{
  2016. {ID: device1},
  2017. {ID: device2},
  2018. },
  2019. },
  2020. },
  2021. }
  2022. m.ClusterConfig(device1, cc)
  2023. m.ClusterConfig(device2, cc)
  2024. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2025. if len(avail) != 2 {
  2026. t.Errorf("should have two available")
  2027. }
  2028. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2029. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2030. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2031. if len(avail) != 0 {
  2032. t.Errorf("should have no available")
  2033. }
  2034. // Test that remote paused folders are not used.
  2035. addFakeConn(m, device1)
  2036. addFakeConn(m, device2)
  2037. m.ClusterConfig(device1, cc)
  2038. ccp := cc
  2039. ccp.Folders[0].Paused = true
  2040. m.ClusterConfig(device1, ccp)
  2041. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2042. if len(avail) != 1 {
  2043. t.Errorf("should have one available")
  2044. }
  2045. }
  2046. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2047. fc := &fakeConnection{id: dev, model: m}
  2048. m.AddConnection(fc, protocol.HelloResult{})
  2049. m.ClusterConfig(dev, protocol.ClusterConfig{
  2050. Folders: []protocol.Folder{
  2051. {
  2052. ID: "default",
  2053. Devices: []protocol.Device{
  2054. {ID: device1},
  2055. {ID: device2},
  2056. },
  2057. },
  2058. },
  2059. })
  2060. return fc
  2061. }
  2062. type fakeAddr struct{}
  2063. func (fakeAddr) Network() string {
  2064. return "network"
  2065. }
  2066. func (fakeAddr) String() string {
  2067. return "address"
  2068. }
  2069. type alwaysChangedKey struct {
  2070. fs fs.Filesystem
  2071. name string
  2072. }
  2073. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  2074. type alwaysChanged struct {
  2075. seen map[alwaysChangedKey]struct{}
  2076. }
  2077. func newAlwaysChanged() *alwaysChanged {
  2078. return &alwaysChanged{
  2079. seen: make(map[alwaysChangedKey]struct{}),
  2080. }
  2081. }
  2082. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  2083. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  2084. }
  2085. func (c *alwaysChanged) Reset() {
  2086. c.seen = make(map[alwaysChangedKey]struct{})
  2087. }
  2088. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  2089. _, ok := c.seen[alwaysChangedKey{fs, name}]
  2090. return ok
  2091. }
  2092. func (c *alwaysChanged) Changed() bool {
  2093. return true
  2094. }