model_test.go 62 KB

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