model_test.go 61 KB

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