model_test.go 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  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(filepath.Join("testdata", config.DefaultMarkerName))
  895. os.MkdirAll(filepath.Join("testdata", config.DefaultMarkerName), 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. MarkerName: config.DefaultMarkerName,
  957. }
  958. cfg := config.Wrap("/tmp/test", config.Configuration{
  959. Folders: []config.FolderConfiguration{fcfg},
  960. Devices: []config.DeviceConfiguration{
  961. {
  962. DeviceID: device1,
  963. },
  964. },
  965. })
  966. os.RemoveAll(fcfg.Path)
  967. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  968. m.AddFolder(fcfg)
  969. m.StartFolder("default")
  970. m.ServeBackground()
  971. defer m.Stop()
  972. waitFor := func(status string) error {
  973. timeout := time.Now().Add(2 * time.Second)
  974. for {
  975. _, _, err := m.State("default")
  976. if err == nil && status == "" {
  977. return nil
  978. }
  979. if err != nil && err.Error() == status {
  980. return nil
  981. }
  982. if time.Now().After(timeout) {
  983. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  984. }
  985. time.Sleep(10 * time.Millisecond)
  986. }
  987. }
  988. if err := waitFor("folder path missing"); err != nil {
  989. t.Error(err)
  990. return
  991. }
  992. os.Mkdir(fcfg.Path, 0700)
  993. if err := waitFor("folder marker missing"); err != nil {
  994. t.Error(err)
  995. return
  996. }
  997. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  998. if err != nil {
  999. t.Error(err)
  1000. return
  1001. }
  1002. fd.Close()
  1003. if err := waitFor(""); err != nil {
  1004. t.Error(err)
  1005. return
  1006. }
  1007. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1008. if err := waitFor("folder marker missing"); err != nil {
  1009. t.Error(err)
  1010. return
  1011. }
  1012. os.Remove(fcfg.Path)
  1013. if err := waitFor("folder path missing"); err != nil {
  1014. t.Error(err)
  1015. return
  1016. }
  1017. }
  1018. func TestRWScanRecovery(t *testing.T) {
  1019. ldb := db.OpenMemory()
  1020. set := db.NewFileSet("default", defaultFs, ldb)
  1021. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1022. {Name: "dummyfile"},
  1023. })
  1024. fcfg := config.FolderConfiguration{
  1025. ID: "default",
  1026. Path: "testdata/rwtestfolder",
  1027. Type: config.FolderTypeSendReceive,
  1028. RescanIntervalS: 1,
  1029. MarkerName: config.DefaultMarkerName,
  1030. }
  1031. cfg := config.Wrap("/tmp/test", config.Configuration{
  1032. Folders: []config.FolderConfiguration{fcfg},
  1033. Devices: []config.DeviceConfiguration{
  1034. {
  1035. DeviceID: device1,
  1036. },
  1037. },
  1038. })
  1039. os.RemoveAll(fcfg.Path)
  1040. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1041. m.AddFolder(fcfg)
  1042. m.StartFolder("default")
  1043. m.ServeBackground()
  1044. defer m.Stop()
  1045. waitFor := func(status string) error {
  1046. timeout := time.Now().Add(2 * time.Second)
  1047. for {
  1048. _, _, err := m.State("default")
  1049. if err == nil && status == "" {
  1050. return nil
  1051. }
  1052. if err != nil && err.Error() == status {
  1053. return nil
  1054. }
  1055. if time.Now().After(timeout) {
  1056. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1057. }
  1058. time.Sleep(10 * time.Millisecond)
  1059. }
  1060. }
  1061. if err := waitFor("folder path missing"); err != nil {
  1062. t.Error(err)
  1063. return
  1064. }
  1065. os.Mkdir(fcfg.Path, 0700)
  1066. if err := waitFor("folder marker missing"); err != nil {
  1067. t.Error(err)
  1068. return
  1069. }
  1070. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1071. if err != nil {
  1072. t.Error(err)
  1073. return
  1074. }
  1075. fd.Close()
  1076. if err := waitFor(""); err != nil {
  1077. t.Error(err)
  1078. return
  1079. }
  1080. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1081. if err := waitFor("folder marker missing"); err != nil {
  1082. t.Error(err)
  1083. return
  1084. }
  1085. os.Remove(fcfg.Path)
  1086. if err := waitFor("folder path missing"); err != nil {
  1087. t.Error(err)
  1088. return
  1089. }
  1090. }
  1091. func TestGlobalDirectoryTree(t *testing.T) {
  1092. db := db.OpenMemory()
  1093. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1094. m.AddFolder(defaultFolderConfig)
  1095. m.ServeBackground()
  1096. defer m.Stop()
  1097. b := func(isfile bool, path ...string) protocol.FileInfo {
  1098. typ := protocol.FileInfoTypeDirectory
  1099. blocks := []protocol.BlockInfo{}
  1100. if isfile {
  1101. typ = protocol.FileInfoTypeFile
  1102. 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}}}
  1103. }
  1104. return protocol.FileInfo{
  1105. Name: filepath.Join(path...),
  1106. Type: typ,
  1107. ModifiedS: 0x666,
  1108. Blocks: blocks,
  1109. Size: 0xa,
  1110. }
  1111. }
  1112. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1113. testdata := []protocol.FileInfo{
  1114. b(false, "another"),
  1115. b(false, "another", "directory"),
  1116. b(true, "another", "directory", "afile"),
  1117. b(false, "another", "directory", "with"),
  1118. b(false, "another", "directory", "with", "a"),
  1119. b(true, "another", "directory", "with", "a", "file"),
  1120. b(true, "another", "directory", "with", "file"),
  1121. b(true, "another", "file"),
  1122. b(false, "other"),
  1123. b(false, "other", "rand"),
  1124. b(false, "other", "random"),
  1125. b(false, "other", "random", "dir"),
  1126. b(false, "other", "random", "dirx"),
  1127. b(false, "other", "randomx"),
  1128. b(false, "some"),
  1129. b(false, "some", "directory"),
  1130. b(false, "some", "directory", "with"),
  1131. b(false, "some", "directory", "with", "a"),
  1132. b(true, "some", "directory", "with", "a", "file"),
  1133. b(true, "rootfile"),
  1134. }
  1135. expectedResult := map[string]interface{}{
  1136. "another": map[string]interface{}{
  1137. "directory": map[string]interface{}{
  1138. "afile": filedata,
  1139. "with": map[string]interface{}{
  1140. "a": map[string]interface{}{
  1141. "file": filedata,
  1142. },
  1143. "file": filedata,
  1144. },
  1145. },
  1146. "file": filedata,
  1147. },
  1148. "other": map[string]interface{}{
  1149. "rand": map[string]interface{}{},
  1150. "random": map[string]interface{}{
  1151. "dir": map[string]interface{}{},
  1152. "dirx": map[string]interface{}{},
  1153. },
  1154. "randomx": map[string]interface{}{},
  1155. },
  1156. "some": map[string]interface{}{
  1157. "directory": map[string]interface{}{
  1158. "with": map[string]interface{}{
  1159. "a": map[string]interface{}{
  1160. "file": filedata,
  1161. },
  1162. },
  1163. },
  1164. },
  1165. "rootfile": filedata,
  1166. }
  1167. mm := func(data interface{}) string {
  1168. bytes, err := json.Marshal(data)
  1169. if err != nil {
  1170. panic(err)
  1171. }
  1172. return string(bytes)
  1173. }
  1174. m.Index(device1, "default", testdata)
  1175. result := m.GlobalDirectoryTree("default", "", -1, false)
  1176. if mm(result) != mm(expectedResult) {
  1177. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1178. }
  1179. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1180. if mm(result) != mm(expectedResult["another"]) {
  1181. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1182. }
  1183. result = m.GlobalDirectoryTree("default", "", 0, false)
  1184. currentResult := map[string]interface{}{
  1185. "another": map[string]interface{}{},
  1186. "other": map[string]interface{}{},
  1187. "some": map[string]interface{}{},
  1188. "rootfile": filedata,
  1189. }
  1190. if mm(result) != mm(currentResult) {
  1191. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1192. }
  1193. result = m.GlobalDirectoryTree("default", "", 1, false)
  1194. currentResult = map[string]interface{}{
  1195. "another": map[string]interface{}{
  1196. "directory": map[string]interface{}{},
  1197. "file": filedata,
  1198. },
  1199. "other": map[string]interface{}{
  1200. "rand": map[string]interface{}{},
  1201. "random": map[string]interface{}{},
  1202. "randomx": map[string]interface{}{},
  1203. },
  1204. "some": map[string]interface{}{
  1205. "directory": map[string]interface{}{},
  1206. },
  1207. "rootfile": filedata,
  1208. }
  1209. if mm(result) != mm(currentResult) {
  1210. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1211. }
  1212. result = m.GlobalDirectoryTree("default", "", -1, true)
  1213. currentResult = map[string]interface{}{
  1214. "another": map[string]interface{}{
  1215. "directory": map[string]interface{}{
  1216. "with": map[string]interface{}{
  1217. "a": map[string]interface{}{},
  1218. },
  1219. },
  1220. },
  1221. "other": map[string]interface{}{
  1222. "rand": map[string]interface{}{},
  1223. "random": map[string]interface{}{
  1224. "dir": map[string]interface{}{},
  1225. "dirx": map[string]interface{}{},
  1226. },
  1227. "randomx": map[string]interface{}{},
  1228. },
  1229. "some": map[string]interface{}{
  1230. "directory": map[string]interface{}{
  1231. "with": map[string]interface{}{
  1232. "a": map[string]interface{}{},
  1233. },
  1234. },
  1235. },
  1236. }
  1237. if mm(result) != mm(currentResult) {
  1238. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1239. }
  1240. result = m.GlobalDirectoryTree("default", "", 1, true)
  1241. currentResult = map[string]interface{}{
  1242. "another": map[string]interface{}{
  1243. "directory": map[string]interface{}{},
  1244. },
  1245. "other": map[string]interface{}{
  1246. "rand": map[string]interface{}{},
  1247. "random": map[string]interface{}{},
  1248. "randomx": map[string]interface{}{},
  1249. },
  1250. "some": map[string]interface{}{
  1251. "directory": map[string]interface{}{},
  1252. },
  1253. }
  1254. if mm(result) != mm(currentResult) {
  1255. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1256. }
  1257. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1258. currentResult = map[string]interface{}{
  1259. "directory": map[string]interface{}{},
  1260. "file": filedata,
  1261. }
  1262. if mm(result) != mm(currentResult) {
  1263. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1264. }
  1265. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1266. currentResult = map[string]interface{}{
  1267. "with": map[string]interface{}{},
  1268. }
  1269. if mm(result) != mm(currentResult) {
  1270. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1271. }
  1272. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1273. currentResult = map[string]interface{}{
  1274. "with": map[string]interface{}{
  1275. "a": map[string]interface{}{},
  1276. },
  1277. }
  1278. if mm(result) != mm(currentResult) {
  1279. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1280. }
  1281. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1282. currentResult = map[string]interface{}{
  1283. "with": map[string]interface{}{
  1284. "a": map[string]interface{}{
  1285. "file": filedata,
  1286. },
  1287. },
  1288. }
  1289. if mm(result) != mm(currentResult) {
  1290. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1291. }
  1292. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1293. currentResult = map[string]interface{}{
  1294. "directory": map[string]interface{}{
  1295. "with": map[string]interface{}{
  1296. "a": map[string]interface{}{},
  1297. },
  1298. },
  1299. }
  1300. if mm(result) != mm(currentResult) {
  1301. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1302. }
  1303. // No prefix matching!
  1304. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1305. currentResult = map[string]interface{}{}
  1306. if mm(result) != mm(currentResult) {
  1307. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1308. }
  1309. }
  1310. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1311. db := db.OpenMemory()
  1312. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1313. m.AddFolder(defaultFolderConfig)
  1314. m.ServeBackground()
  1315. b := func(isfile bool, path ...string) protocol.FileInfo {
  1316. typ := protocol.FileInfoTypeDirectory
  1317. blocks := []protocol.BlockInfo{}
  1318. if isfile {
  1319. typ = protocol.FileInfoTypeFile
  1320. 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}}}
  1321. }
  1322. return protocol.FileInfo{
  1323. Name: filepath.Join(path...),
  1324. Type: typ,
  1325. ModifiedS: 0x666,
  1326. Blocks: blocks,
  1327. Size: 0xa,
  1328. }
  1329. }
  1330. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1331. testdata := []protocol.FileInfo{
  1332. b(true, "another", "directory", "afile"),
  1333. b(true, "another", "directory", "with", "a", "file"),
  1334. b(true, "another", "directory", "with", "file"),
  1335. b(false, "other", "random", "dirx"),
  1336. b(false, "other", "randomx"),
  1337. b(false, "some", "directory", "with", "x"),
  1338. b(true, "some", "directory", "with", "a", "file"),
  1339. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1340. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1341. }
  1342. expectedResult := map[string]interface{}{
  1343. "another": map[string]interface{}{
  1344. "directory": map[string]interface{}{
  1345. "afile": filedata,
  1346. "with": map[string]interface{}{
  1347. "a": map[string]interface{}{
  1348. "file": filedata,
  1349. },
  1350. "file": filedata,
  1351. },
  1352. },
  1353. },
  1354. "other": map[string]interface{}{
  1355. "random": map[string]interface{}{
  1356. "dirx": map[string]interface{}{},
  1357. },
  1358. "randomx": map[string]interface{}{},
  1359. },
  1360. "some": map[string]interface{}{
  1361. "directory": map[string]interface{}{
  1362. "with": map[string]interface{}{
  1363. "a": map[string]interface{}{
  1364. "file": filedata,
  1365. },
  1366. "x": map[string]interface{}{},
  1367. },
  1368. },
  1369. },
  1370. "this": map[string]interface{}{
  1371. "is": map[string]interface{}{
  1372. "a": map[string]interface{}{
  1373. "deep": map[string]interface{}{
  1374. "invalid": map[string]interface{}{
  1375. "directory": map[string]interface{}{},
  1376. },
  1377. },
  1378. },
  1379. },
  1380. },
  1381. "xthis": map[string]interface{}{
  1382. "is": map[string]interface{}{
  1383. "a": map[string]interface{}{
  1384. "deep": map[string]interface{}{
  1385. "invalid": map[string]interface{}{
  1386. "file": filedata,
  1387. },
  1388. },
  1389. },
  1390. },
  1391. },
  1392. }
  1393. mm := func(data interface{}) string {
  1394. bytes, err := json.Marshal(data)
  1395. if err != nil {
  1396. panic(err)
  1397. }
  1398. return string(bytes)
  1399. }
  1400. m.Index(device1, "default", testdata)
  1401. result := m.GlobalDirectoryTree("default", "", -1, false)
  1402. if mm(result) != mm(expectedResult) {
  1403. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1404. }
  1405. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1406. currentResult := map[string]interface{}{
  1407. "invalid": map[string]interface{}{
  1408. "file": filedata,
  1409. },
  1410. }
  1411. if mm(result) != mm(currentResult) {
  1412. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1413. }
  1414. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1415. currentResult = map[string]interface{}{
  1416. "invalid": map[string]interface{}{},
  1417. }
  1418. if mm(result) != mm(currentResult) {
  1419. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1420. }
  1421. // !!! This is actually BAD, because we don't have enough level allowance
  1422. // to accept this file, hence the tree is left unbuilt !!!
  1423. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1424. currentResult = map[string]interface{}{}
  1425. if mm(result) != mm(currentResult) {
  1426. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1427. }
  1428. }
  1429. func genDeepFiles(n, d int) []protocol.FileInfo {
  1430. rand.Seed(int64(n))
  1431. files := make([]protocol.FileInfo, n)
  1432. t := time.Now().Unix()
  1433. for i := 0; i < n; i++ {
  1434. path := ""
  1435. for i := 0; i <= d; i++ {
  1436. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1437. }
  1438. sofar := ""
  1439. for _, path := range filepath.SplitList(path) {
  1440. sofar = filepath.Join(sofar, path)
  1441. files[i] = protocol.FileInfo{
  1442. Name: sofar,
  1443. }
  1444. i++
  1445. }
  1446. files[i].ModifiedS = t
  1447. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1448. }
  1449. return files
  1450. }
  1451. func BenchmarkTree_10000_50(b *testing.B) {
  1452. benchmarkTree(b, 10000, 50)
  1453. }
  1454. func BenchmarkTree_100_50(b *testing.B) {
  1455. benchmarkTree(b, 100, 50)
  1456. }
  1457. func BenchmarkTree_100_10(b *testing.B) {
  1458. benchmarkTree(b, 100, 10)
  1459. }
  1460. func benchmarkTree(b *testing.B, n1, n2 int) {
  1461. db := db.OpenMemory()
  1462. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1463. m.AddFolder(defaultFolderConfig)
  1464. m.ServeBackground()
  1465. m.ScanFolder("default")
  1466. files := genDeepFiles(n1, n2)
  1467. m.Index(device1, "default", files)
  1468. b.ResetTimer()
  1469. for i := 0; i < b.N; i++ {
  1470. m.GlobalDirectoryTree("default", "", -1, false)
  1471. }
  1472. b.ReportAllocs()
  1473. }
  1474. func TestUnifySubs(t *testing.T) {
  1475. cases := []struct {
  1476. in []string // input to unifySubs
  1477. exists []string // paths that exist in the database
  1478. out []string // expected output
  1479. }{
  1480. {
  1481. // 0. trailing slashes are cleaned, known paths are just passed on
  1482. []string{"foo/", "bar//"},
  1483. []string{"foo", "bar"},
  1484. []string{"bar", "foo"}, // the output is sorted
  1485. },
  1486. {
  1487. // 1. "foo/bar" gets trimmed as it's covered by foo
  1488. []string{"foo", "bar/", "foo/bar/"},
  1489. []string{"foo", "bar"},
  1490. []string{"bar", "foo"},
  1491. },
  1492. {
  1493. // 2. "" gets simplified to the empty list; ie scan all
  1494. []string{"foo", ""},
  1495. []string{"foo"},
  1496. nil,
  1497. },
  1498. {
  1499. // 3. "foo/bar" is unknown, but it's kept
  1500. // because its parent is known
  1501. []string{"foo/bar"},
  1502. []string{"foo"},
  1503. []string{"foo/bar"},
  1504. },
  1505. {
  1506. // 4. two independent known paths, both are kept
  1507. // "usr/lib" is not a prefix of "usr/libexec"
  1508. []string{"usr/lib", "usr/libexec"},
  1509. []string{"usr", "usr/lib", "usr/libexec"},
  1510. []string{"usr/lib", "usr/libexec"},
  1511. },
  1512. {
  1513. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1514. []string{"usr/lib", "usr/lib/exec"},
  1515. []string{"usr", "usr/lib", "usr/libexec"},
  1516. []string{"usr/lib"},
  1517. },
  1518. {
  1519. // 6. .stignore and .stfolder are special and are passed on
  1520. // verbatim even though they are unknown
  1521. []string{config.DefaultMarkerName, ".stignore"},
  1522. []string{},
  1523. []string{config.DefaultMarkerName, ".stignore"},
  1524. },
  1525. {
  1526. // 7. but the presence of something else unknown forces an actual
  1527. // scan
  1528. []string{config.DefaultMarkerName, ".stignore", "foo/bar"},
  1529. []string{},
  1530. []string{config.DefaultMarkerName, ".stignore", "foo"},
  1531. },
  1532. {
  1533. // 8. explicit request to scan all
  1534. nil,
  1535. []string{"foo"},
  1536. nil,
  1537. },
  1538. {
  1539. // 9. empty list of subs
  1540. []string{},
  1541. []string{"foo"},
  1542. nil,
  1543. },
  1544. }
  1545. if runtime.GOOS == "windows" {
  1546. // Fixup path separators
  1547. for i := range cases {
  1548. for j, p := range cases[i].in {
  1549. cases[i].in[j] = filepath.FromSlash(p)
  1550. }
  1551. for j, p := range cases[i].exists {
  1552. cases[i].exists[j] = filepath.FromSlash(p)
  1553. }
  1554. for j, p := range cases[i].out {
  1555. cases[i].out[j] = filepath.FromSlash(p)
  1556. }
  1557. }
  1558. }
  1559. for i, tc := range cases {
  1560. exists := func(f string) bool {
  1561. for _, e := range tc.exists {
  1562. if f == e {
  1563. return true
  1564. }
  1565. }
  1566. return false
  1567. }
  1568. out := unifySubs(tc.in, exists)
  1569. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1570. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1571. }
  1572. }
  1573. }
  1574. func TestIssue3028(t *testing.T) {
  1575. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1576. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1577. t.Fatal(err)
  1578. }
  1579. defer os.Remove("testdata/testrm")
  1580. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1581. t.Fatal(err)
  1582. }
  1583. defer os.Remove("testdata/testrm2")
  1584. // Create a model and default folder
  1585. db := db.OpenMemory()
  1586. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1587. defCfg := defaultFolderConfig.Copy()
  1588. defCfg.RescanIntervalS = 86400
  1589. m.AddFolder(defCfg)
  1590. m.StartFolder("default")
  1591. m.ServeBackground()
  1592. // Make sure the initial scan has finished (ScanFolders is blocking)
  1593. m.ScanFolders()
  1594. // Get a count of how many files are there now
  1595. locorigfiles := m.LocalSize("default").Files
  1596. globorigfiles := m.GlobalSize("default").Files
  1597. // Delete and rescan specifically these two
  1598. os.Remove("testdata/testrm")
  1599. os.Remove("testdata/testrm2")
  1600. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1601. // Verify that the number of files decreased by two and the number of
  1602. // deleted files increases by two
  1603. loc := m.LocalSize("default")
  1604. glob := m.GlobalSize("default")
  1605. if loc.Files != locorigfiles-2 {
  1606. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1607. }
  1608. if glob.Files != globorigfiles-2 {
  1609. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1610. }
  1611. if loc.Deleted != 2 {
  1612. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1613. }
  1614. if glob.Deleted != 2 {
  1615. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1616. }
  1617. }
  1618. func TestIssue3164(t *testing.T) {
  1619. os.RemoveAll("testdata/issue3164")
  1620. defer os.RemoveAll("testdata/issue3164")
  1621. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1622. t.Fatal(err)
  1623. }
  1624. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1625. t.Fatal(err)
  1626. }
  1627. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1628. t.Fatal(err)
  1629. }
  1630. f := protocol.FileInfo{
  1631. Name: "issue3164",
  1632. }
  1633. m := ignore.New(defaultFs)
  1634. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1635. t.Fatal(err)
  1636. }
  1637. fl := sendReceiveFolder{
  1638. dbUpdates: make(chan dbUpdateJob, 1),
  1639. fs: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  1640. }
  1641. fl.deleteDir(f, m)
  1642. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1643. t.Fatal(err)
  1644. }
  1645. }
  1646. func TestIssue4357(t *testing.T) {
  1647. db := db.OpenMemory()
  1648. cfg := defaultConfig.RawCopy()
  1649. // Create a separate wrapper not to pollute other tests.
  1650. wrapper := config.Wrap("/tmp/test", config.Configuration{})
  1651. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1652. m.ServeBackground()
  1653. defer m.Stop()
  1654. // Force the model to wire itself and add the folders
  1655. if err := wrapper.ReplaceBlocking(cfg); err != nil {
  1656. t.Error(err)
  1657. }
  1658. if _, ok := m.folderCfgs["default"]; !ok {
  1659. t.Error("Folder should be running")
  1660. }
  1661. newCfg := wrapper.RawCopy()
  1662. newCfg.Folders[0].Paused = true
  1663. if err := wrapper.ReplaceBlocking(newCfg); err != nil {
  1664. t.Error(err)
  1665. }
  1666. if _, ok := m.folderCfgs["default"]; ok {
  1667. t.Error("Folder should not be running")
  1668. }
  1669. if _, ok := m.cfg.Folder("default"); !ok {
  1670. t.Error("should still have folder in config")
  1671. }
  1672. if err := wrapper.ReplaceBlocking(config.Configuration{}); err != nil {
  1673. t.Error(err)
  1674. }
  1675. if _, ok := m.cfg.Folder("default"); ok {
  1676. t.Error("should not have folder in config")
  1677. }
  1678. // Add the folder back, should be running
  1679. if err := wrapper.ReplaceBlocking(cfg); err != nil {
  1680. t.Error(err)
  1681. }
  1682. if _, ok := m.folderCfgs["default"]; !ok {
  1683. t.Error("Folder should be running")
  1684. }
  1685. if _, ok := m.cfg.Folder("default"); !ok {
  1686. t.Error("should still have folder in config")
  1687. }
  1688. // Should not panic when removing a running folder.
  1689. if err := wrapper.ReplaceBlocking(config.Configuration{}); err != nil {
  1690. t.Error(err)
  1691. }
  1692. if _, ok := m.folderCfgs["default"]; ok {
  1693. t.Error("Folder should not be running")
  1694. }
  1695. if _, ok := m.cfg.Folder("default"); ok {
  1696. t.Error("should not have folder in config")
  1697. }
  1698. }
  1699. func TestScanNoDatabaseWrite(t *testing.T) {
  1700. // When scanning, nothing should be committed to database unless
  1701. // something actually changed.
  1702. db := db.OpenMemory()
  1703. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1704. m.AddFolder(defaultFolderConfig)
  1705. m.StartFolder("default")
  1706. m.ServeBackground()
  1707. // Start with no ignores, and restore the previous state when the test completes
  1708. curIgn, _, err := m.GetIgnores("default")
  1709. if err != nil {
  1710. t.Fatal(err)
  1711. }
  1712. defer m.SetIgnores("default", curIgn)
  1713. m.SetIgnores("default", nil)
  1714. fakeTime := time.Now().Add(5 * time.Second)
  1715. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1716. // Scan the folder twice. The second scan should be a no-op database wise
  1717. m.ScanFolder("default")
  1718. c0 := db.Committed()
  1719. m.ScanFolder("default")
  1720. c1 := db.Committed()
  1721. if c1 != c0 {
  1722. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1723. }
  1724. // Ignore a file we know exists. It'll be updated in the database.
  1725. m.SetIgnores("default", []string{"foo"})
  1726. fakeTime = time.Now().Add(10 * time.Second)
  1727. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1728. m.ScanFolder("default")
  1729. c2 := db.Committed()
  1730. if c2 <= c1 {
  1731. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1732. }
  1733. // Scan again. Nothing should happen.
  1734. m.ScanFolder("default")
  1735. c3 := db.Committed()
  1736. if c3 != c2 {
  1737. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1738. }
  1739. }
  1740. func TestIssue2782(t *testing.T) {
  1741. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  1742. if runtime.GOOS == "windows" {
  1743. t.Skip("not reliable on Windows")
  1744. return
  1745. }
  1746. home := os.Getenv("HOME")
  1747. if home == "" {
  1748. t.Skip("no home")
  1749. }
  1750. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1751. // part of the issue. Skip the test if any of this fails, as we are a
  1752. // bit outside of our stated domain here...
  1753. testName := ".syncthing-test." + srand.String(16)
  1754. testDir := filepath.Join(home, testName)
  1755. if err := os.RemoveAll(testDir); err != nil {
  1756. t.Skip(err)
  1757. }
  1758. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1759. t.Skip(err)
  1760. }
  1761. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1762. t.Skip(err)
  1763. }
  1764. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1765. t.Skip(err)
  1766. }
  1767. defer os.RemoveAll(testDir)
  1768. db := db.OpenMemory()
  1769. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1770. m.AddFolder(config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  1771. m.StartFolder("default")
  1772. m.ServeBackground()
  1773. defer m.Stop()
  1774. if err := m.ScanFolder("default"); err != nil {
  1775. t.Error("scan error:", err)
  1776. }
  1777. m.fmut.Lock()
  1778. runner, _ := m.folderRunners["default"]
  1779. m.fmut.Unlock()
  1780. if err := runner.CheckHealth(); err != nil {
  1781. t.Error("health check error:", err)
  1782. }
  1783. }
  1784. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1785. dbi := db.OpenMemory()
  1786. files := db.NewFileSet("default", defaultFs, dbi)
  1787. files.Drop(device1)
  1788. files.Update(device1, genFiles(1))
  1789. files.Drop(device2)
  1790. files.Update(device2, genFiles(1))
  1791. if len(files.ListDevices()) != 2 {
  1792. t.Error("expected two devices")
  1793. }
  1794. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1795. m.AddFolder(defaultFolderConfig)
  1796. m.StartFolder("default")
  1797. // Remote sequence is cached, hence need to recreated.
  1798. files = db.NewFileSet("default", defaultFs, dbi)
  1799. if len(files.ListDevices()) != 1 {
  1800. t.Error("Expected one device")
  1801. }
  1802. }
  1803. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1804. dbi := db.OpenMemory()
  1805. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  1806. fcfg.Devices = []config.FolderDeviceConfiguration{
  1807. {DeviceID: device1},
  1808. {DeviceID: device2},
  1809. }
  1810. cfg := config.Configuration{
  1811. Folders: []config.FolderConfiguration{fcfg},
  1812. Devices: []config.DeviceConfiguration{
  1813. config.NewDeviceConfiguration(device1, "device1"),
  1814. config.NewDeviceConfiguration(device2, "device2"),
  1815. },
  1816. Options: config.OptionsConfiguration{
  1817. // Don't remove temporaries directly on startup
  1818. KeepTemporariesH: 1,
  1819. },
  1820. }
  1821. wcfg := config.Wrap("/tmp/test", cfg)
  1822. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1823. m.AddFolder(fcfg)
  1824. m.StartFolder(fcfg.ID)
  1825. m.ServeBackground()
  1826. conn1 := &fakeConnection{id: device1}
  1827. m.AddConnection(conn1, protocol.HelloResult{})
  1828. conn2 := &fakeConnection{id: device2}
  1829. m.AddConnection(conn2, protocol.HelloResult{})
  1830. m.ClusterConfig(device1, protocol.ClusterConfig{
  1831. Folders: []protocol.Folder{
  1832. {
  1833. ID: "default",
  1834. Devices: []protocol.Device{
  1835. {ID: device1},
  1836. {ID: device2},
  1837. },
  1838. },
  1839. },
  1840. })
  1841. m.ClusterConfig(device2, protocol.ClusterConfig{
  1842. Folders: []protocol.Folder{
  1843. {
  1844. ID: "default",
  1845. Devices: []protocol.Device{
  1846. {ID: device1},
  1847. {ID: device2},
  1848. },
  1849. },
  1850. },
  1851. })
  1852. if !m.folderSharedWith("default", device1) {
  1853. t.Error("not shared with device1")
  1854. }
  1855. if !m.folderSharedWith("default", device2) {
  1856. t.Error("not shared with device2")
  1857. }
  1858. if conn2.Closed() {
  1859. t.Error("conn already closed")
  1860. }
  1861. cfg = cfg.Copy()
  1862. cfg.Devices = cfg.Devices[:1]
  1863. if err := wcfg.Replace(cfg); err != nil {
  1864. t.Error(err)
  1865. }
  1866. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1867. if !m.folderSharedWith("default", device1) {
  1868. t.Error("not shared with device1")
  1869. }
  1870. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1871. t.Error("shared with device2")
  1872. }
  1873. if !conn2.Closed() {
  1874. t.Error("connection not closed")
  1875. }
  1876. if _, ok := wcfg.Devices()[device2]; ok {
  1877. t.Error("device still in config")
  1878. }
  1879. fdevs, ok := m.folderDevices["default"]
  1880. if !ok {
  1881. t.Error("folder missing?")
  1882. }
  1883. for id := range fdevs {
  1884. if id == device2 {
  1885. t.Error("still there")
  1886. }
  1887. }
  1888. if _, ok := m.conn[device2]; !ok {
  1889. t.Error("conn missing early")
  1890. }
  1891. if _, ok := m.helloMessages[device2]; !ok {
  1892. t.Error("hello missing early")
  1893. }
  1894. if _, ok := m.deviceDownloads[device2]; !ok {
  1895. t.Error("downloads missing early")
  1896. }
  1897. m.Closed(conn2, fmt.Errorf("foo"))
  1898. if _, ok := m.conn[device2]; ok {
  1899. t.Error("conn not missing")
  1900. }
  1901. if _, ok := m.helloMessages[device2]; ok {
  1902. t.Error("hello not missing")
  1903. }
  1904. if _, ok := m.deviceDownloads[device2]; ok {
  1905. t.Error("downloads not missing")
  1906. }
  1907. }
  1908. func TestIssue3496(t *testing.T) {
  1909. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  1910. // It seems like lots of deleted files can cause negative completion
  1911. // percentages. Lets make sure that doesn't happen. Also do some general
  1912. // checks on the completion calculation stuff.
  1913. dbi := db.OpenMemory()
  1914. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1915. m.AddFolder(defaultFolderConfig)
  1916. m.StartFolder("default")
  1917. m.ServeBackground()
  1918. defer m.Stop()
  1919. m.ScanFolder("default")
  1920. addFakeConn(m, device1)
  1921. addFakeConn(m, device2)
  1922. // Reach into the model and grab the current file list...
  1923. m.fmut.RLock()
  1924. fs := m.folderFiles["default"]
  1925. m.fmut.RUnlock()
  1926. var localFiles []protocol.FileInfo
  1927. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1928. localFiles = append(localFiles, i.(protocol.FileInfo))
  1929. return true
  1930. })
  1931. // Mark all files as deleted and fake it as update from device1
  1932. for i := range localFiles {
  1933. localFiles[i].Deleted = true
  1934. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1935. localFiles[i].Blocks = nil
  1936. }
  1937. // Also add a small file that we're supposed to need, or the global size
  1938. // stuff will bail out early due to the entire folder being zero size.
  1939. localFiles = append(localFiles, protocol.FileInfo{
  1940. Name: "fake",
  1941. Size: 1234,
  1942. Type: protocol.FileInfoTypeFile,
  1943. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1944. })
  1945. m.IndexUpdate(device1, "default", localFiles)
  1946. // Check that the completion percentage for us makes sense
  1947. comp := m.Completion(protocol.LocalDeviceID, "default")
  1948. if comp.NeedBytes > comp.GlobalBytes {
  1949. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1950. }
  1951. if comp.CompletionPct < 0 {
  1952. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1953. }
  1954. if comp.NeedBytes == 0 {
  1955. t.Error("Need no bytes even though some files are deleted")
  1956. }
  1957. if comp.CompletionPct == 100 {
  1958. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1959. }
  1960. t.Log(comp)
  1961. // Check that NeedSize does the correct thing
  1962. need := m.NeedSize("default")
  1963. if need.Files != 1 || need.Bytes != 1234 {
  1964. // The one we added synthetically above
  1965. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1966. }
  1967. if need.Deleted != len(localFiles)-1 {
  1968. // The rest
  1969. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1970. }
  1971. }
  1972. func TestIssue3804(t *testing.T) {
  1973. dbi := db.OpenMemory()
  1974. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1975. m.AddFolder(defaultFolderConfig)
  1976. m.StartFolder("default")
  1977. m.ServeBackground()
  1978. defer m.Stop()
  1979. // Subdirs ending in slash should be accepted
  1980. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1981. t.Error("Unexpected error:", err)
  1982. }
  1983. }
  1984. func TestIssue3829(t *testing.T) {
  1985. dbi := db.OpenMemory()
  1986. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1987. m.AddFolder(defaultFolderConfig)
  1988. m.StartFolder("default")
  1989. m.ServeBackground()
  1990. defer m.Stop()
  1991. // Empty subdirs should be accepted
  1992. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1993. t.Error("Unexpected error:", err)
  1994. }
  1995. }
  1996. func TestNoRequestsFromPausedDevices(t *testing.T) {
  1997. t.Skip("broken, fails randomly, #3843")
  1998. dbi := db.OpenMemory()
  1999. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  2000. fcfg.Devices = []config.FolderDeviceConfiguration{
  2001. {DeviceID: device1},
  2002. {DeviceID: device2},
  2003. }
  2004. cfg := config.Configuration{
  2005. Folders: []config.FolderConfiguration{fcfg},
  2006. Devices: []config.DeviceConfiguration{
  2007. config.NewDeviceConfiguration(device1, "device1"),
  2008. config.NewDeviceConfiguration(device2, "device2"),
  2009. },
  2010. Options: config.OptionsConfiguration{
  2011. // Don't remove temporaries directly on startup
  2012. KeepTemporariesH: 1,
  2013. },
  2014. }
  2015. wcfg := config.Wrap("/tmp/test", cfg)
  2016. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2017. m.AddFolder(fcfg)
  2018. m.StartFolder(fcfg.ID)
  2019. m.ServeBackground()
  2020. file := testDataExpected["foo"]
  2021. files := m.folderFiles["default"]
  2022. files.Update(device1, []protocol.FileInfo{file})
  2023. files.Update(device2, []protocol.FileInfo{file})
  2024. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2025. if len(avail) != 0 {
  2026. t.Errorf("should not be available, no connections")
  2027. }
  2028. addFakeConn(m, device1)
  2029. addFakeConn(m, device2)
  2030. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2031. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2032. if len(avail) != 2 {
  2033. t.Errorf("should have two available")
  2034. }
  2035. cc := protocol.ClusterConfig{
  2036. Folders: []protocol.Folder{
  2037. {
  2038. ID: "default",
  2039. Devices: []protocol.Device{
  2040. {ID: device1},
  2041. {ID: device2},
  2042. },
  2043. },
  2044. },
  2045. }
  2046. m.ClusterConfig(device1, cc)
  2047. m.ClusterConfig(device2, cc)
  2048. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2049. if len(avail) != 2 {
  2050. t.Errorf("should have two available")
  2051. }
  2052. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2053. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2054. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2055. if len(avail) != 0 {
  2056. t.Errorf("should have no available")
  2057. }
  2058. // Test that remote paused folders are not used.
  2059. addFakeConn(m, device1)
  2060. addFakeConn(m, device2)
  2061. m.ClusterConfig(device1, cc)
  2062. ccp := cc
  2063. ccp.Folders[0].Paused = true
  2064. m.ClusterConfig(device1, ccp)
  2065. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2066. if len(avail) != 1 {
  2067. t.Errorf("should have one available")
  2068. }
  2069. }
  2070. func TestCustomMarkerName(t *testing.T) {
  2071. ldb := db.OpenMemory()
  2072. set := db.NewFileSet("default", defaultFs, ldb)
  2073. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2074. {Name: "dummyfile"},
  2075. })
  2076. fcfg := config.FolderConfiguration{
  2077. ID: "default",
  2078. Path: "testdata/rwtestfolder",
  2079. Type: config.FolderTypeSendReceive,
  2080. RescanIntervalS: 1,
  2081. MarkerName: "myfile",
  2082. }
  2083. cfg := config.Wrap("/tmp/test", config.Configuration{
  2084. Folders: []config.FolderConfiguration{fcfg},
  2085. Devices: []config.DeviceConfiguration{
  2086. {
  2087. DeviceID: device1,
  2088. },
  2089. },
  2090. })
  2091. os.RemoveAll(fcfg.Path)
  2092. defer os.RemoveAll(fcfg.Path)
  2093. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  2094. m.AddFolder(fcfg)
  2095. m.StartFolder("default")
  2096. m.ServeBackground()
  2097. defer m.Stop()
  2098. waitFor := func(status string) error {
  2099. timeout := time.Now().Add(2 * time.Second)
  2100. for {
  2101. _, _, err := m.State("default")
  2102. if err == nil && status == "" {
  2103. return nil
  2104. }
  2105. if err != nil && err.Error() == status {
  2106. return nil
  2107. }
  2108. if time.Now().After(timeout) {
  2109. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  2110. }
  2111. time.Sleep(10 * time.Millisecond)
  2112. }
  2113. }
  2114. if err := waitFor("folder path missing"); err != nil {
  2115. t.Error(err)
  2116. return
  2117. }
  2118. os.Mkdir(fcfg.Path, 0700)
  2119. fd, err := os.Create(filepath.Join(fcfg.Path, "myfile"))
  2120. if err != nil {
  2121. t.Error(err)
  2122. return
  2123. }
  2124. fd.Close()
  2125. if err := waitFor(""); err != nil {
  2126. t.Error(err)
  2127. return
  2128. }
  2129. }
  2130. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2131. fc := &fakeConnection{id: dev, model: m}
  2132. m.AddConnection(fc, protocol.HelloResult{})
  2133. m.ClusterConfig(dev, protocol.ClusterConfig{
  2134. Folders: []protocol.Folder{
  2135. {
  2136. ID: "default",
  2137. Devices: []protocol.Device{
  2138. {ID: device1},
  2139. {ID: device2},
  2140. },
  2141. },
  2142. },
  2143. })
  2144. return fc
  2145. }
  2146. type fakeAddr struct{}
  2147. func (fakeAddr) Network() string {
  2148. return "network"
  2149. }
  2150. func (fakeAddr) String() string {
  2151. return "address"
  2152. }
  2153. type alwaysChangedKey struct {
  2154. fs fs.Filesystem
  2155. name string
  2156. }
  2157. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  2158. type alwaysChanged struct {
  2159. seen map[alwaysChangedKey]struct{}
  2160. }
  2161. func newAlwaysChanged() *alwaysChanged {
  2162. return &alwaysChanged{
  2163. seen: make(map[alwaysChangedKey]struct{}),
  2164. }
  2165. }
  2166. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  2167. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  2168. }
  2169. func (c *alwaysChanged) Reset() {
  2170. c.seen = make(map[alwaysChangedKey]struct{})
  2171. }
  2172. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  2173. _, ok := c.seen[alwaysChangedKey{fs, name}]
  2174. return ok
  2175. }
  2176. func (c *alwaysChanged) Changed() bool {
  2177. return true
  2178. }