model_test.go 62 KB

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