model_test.go 63 KB

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