model_test.go 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505
  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. "strings"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/d4l3k/messagediff"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/db"
  26. "github.com/syncthing/syncthing/lib/fs"
  27. "github.com/syncthing/syncthing/lib/ignore"
  28. "github.com/syncthing/syncthing/lib/osutil"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. srand "github.com/syncthing/syncthing/lib/rand"
  31. "github.com/syncthing/syncthing/lib/scanner"
  32. "github.com/syncthing/syncthing/lib/versioner"
  33. )
  34. var device1, device2 protocol.DeviceID
  35. var defaultConfig *config.Wrapper
  36. var defaultFolderConfig config.FolderConfiguration
  37. var defaultFs fs.Filesystem
  38. var defaultAutoAcceptCfg config.Configuration
  39. func init() {
  40. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  41. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  42. defaultFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  43. defaultFolderConfig = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  44. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  45. _defaultConfig := config.Configuration{
  46. Version: config.CurrentVersion,
  47. Folders: []config.FolderConfiguration{defaultFolderConfig},
  48. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  49. Options: config.OptionsConfiguration{
  50. // Don't remove temporaries directly on startup
  51. KeepTemporariesH: 1,
  52. },
  53. }
  54. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  55. defaultAutoAcceptCfg = config.Configuration{
  56. Devices: []config.DeviceConfiguration{
  57. {
  58. DeviceID: protocol.LocalDeviceID, // self
  59. },
  60. {
  61. DeviceID: device1,
  62. AutoAcceptFolders: true,
  63. },
  64. },
  65. Options: config.OptionsConfiguration{
  66. DefaultFolderPath: "testdata",
  67. },
  68. }
  69. }
  70. var testDataExpected = map[string]protocol.FileInfo{
  71. "foo": {
  72. Name: "foo",
  73. Type: protocol.FileInfoTypeFile,
  74. ModifiedS: 0,
  75. 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}}},
  76. },
  77. "empty": {
  78. Name: "empty",
  79. Type: protocol.FileInfoTypeFile,
  80. ModifiedS: 0,
  81. 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}}},
  82. },
  83. "bar": {
  84. Name: "bar",
  85. Type: protocol.FileInfoTypeFile,
  86. ModifiedS: 0,
  87. 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}}},
  88. },
  89. }
  90. func init() {
  91. // Fix expected test data to match reality
  92. for n, f := range testDataExpected {
  93. fi, _ := os.Stat("testdata/" + n)
  94. f.Permissions = uint32(fi.Mode())
  95. f.ModifiedS = fi.ModTime().Unix()
  96. f.Size = fi.Size()
  97. testDataExpected[n] = f
  98. }
  99. }
  100. func newState(cfg config.Configuration) (*config.Wrapper, *Model) {
  101. db := db.OpenMemory()
  102. wcfg := config.Wrap("/tmp/test", cfg)
  103. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  104. for _, folder := range cfg.Folders {
  105. if !folder.Paused {
  106. m.AddFolder(folder)
  107. }
  108. }
  109. m.ServeBackground()
  110. m.AddConnection(&fakeConnection{id: device1}, protocol.HelloResult{})
  111. return wcfg, m
  112. }
  113. func TestRequest(t *testing.T) {
  114. db := db.OpenMemory()
  115. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  116. // device1 shares default, but device2 doesn't
  117. m.AddFolder(defaultFolderConfig)
  118. m.StartFolder("default")
  119. m.ServeBackground()
  120. defer m.Stop()
  121. m.ScanFolder("default")
  122. bs := make([]byte, protocol.BlockSize)
  123. // Existing, shared file
  124. bs = bs[:6]
  125. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  126. if err != nil {
  127. t.Error(err)
  128. }
  129. if !bytes.Equal(bs, []byte("foobar")) {
  130. t.Errorf("Incorrect data from request: %q", string(bs))
  131. }
  132. // Existing, nonshared file
  133. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  134. if err == nil {
  135. t.Error("Unexpected nil error on insecure file read")
  136. }
  137. // Nonexistent file
  138. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  139. if err == nil {
  140. t.Error("Unexpected nil error on insecure file read")
  141. }
  142. // Shared folder, but disallowed file name
  143. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  144. if err == nil {
  145. t.Error("Unexpected nil error on insecure file read")
  146. }
  147. // Negative offset
  148. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  149. if err == nil {
  150. t.Error("Unexpected nil error on insecure file read")
  151. }
  152. // Larger block than available
  153. bs = bs[:42]
  154. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  155. if err == nil {
  156. t.Error("Unexpected nil error on insecure file read")
  157. }
  158. }
  159. func genFiles(n int) []protocol.FileInfo {
  160. files := make([]protocol.FileInfo, n)
  161. t := time.Now().Unix()
  162. for i := 0; i < n; i++ {
  163. files[i] = protocol.FileInfo{
  164. Name: fmt.Sprintf("file%d", i),
  165. ModifiedS: t,
  166. Sequence: int64(i + 1),
  167. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  168. Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}},
  169. }
  170. }
  171. return files
  172. }
  173. func BenchmarkIndex_10000(b *testing.B) {
  174. benchmarkIndex(b, 10000)
  175. }
  176. func BenchmarkIndex_100(b *testing.B) {
  177. benchmarkIndex(b, 100)
  178. }
  179. func benchmarkIndex(b *testing.B, nfiles int) {
  180. db := db.OpenMemory()
  181. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  182. m.AddFolder(defaultFolderConfig)
  183. m.StartFolder("default")
  184. m.ServeBackground()
  185. defer m.Stop()
  186. files := genFiles(nfiles)
  187. m.Index(device1, "default", files)
  188. b.ResetTimer()
  189. for i := 0; i < b.N; i++ {
  190. m.Index(device1, "default", files)
  191. }
  192. b.ReportAllocs()
  193. }
  194. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  195. benchmarkIndexUpdate(b, 10000, 10000)
  196. }
  197. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  198. benchmarkIndexUpdate(b, 10000, 100)
  199. }
  200. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  201. benchmarkIndexUpdate(b, 10000, 1)
  202. }
  203. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  204. db := db.OpenMemory()
  205. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  206. m.AddFolder(defaultFolderConfig)
  207. m.StartFolder("default")
  208. m.ServeBackground()
  209. defer m.Stop()
  210. files := genFiles(nfiles)
  211. ufiles := genFiles(nufiles)
  212. m.Index(device1, "default", files)
  213. b.ResetTimer()
  214. for i := 0; i < b.N; i++ {
  215. m.IndexUpdate(device1, "default", ufiles)
  216. }
  217. b.ReportAllocs()
  218. }
  219. type downloadProgressMessage struct {
  220. folder string
  221. updates []protocol.FileDownloadProgressUpdate
  222. }
  223. type fakeConnection struct {
  224. id protocol.DeviceID
  225. downloadProgressMessages []downloadProgressMessage
  226. closed bool
  227. files []protocol.FileInfo
  228. fileData map[string][]byte
  229. folder string
  230. model *Model
  231. indexFn func(string, []protocol.FileInfo)
  232. requestFn func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error)
  233. mut sync.Mutex
  234. }
  235. func (f *fakeConnection) Close() error {
  236. f.mut.Lock()
  237. defer f.mut.Unlock()
  238. f.closed = true
  239. return nil
  240. }
  241. func (f *fakeConnection) Start() {
  242. }
  243. func (f *fakeConnection) ID() protocol.DeviceID {
  244. return f.id
  245. }
  246. func (f *fakeConnection) Name() string {
  247. return ""
  248. }
  249. func (f *fakeConnection) String() string {
  250. return ""
  251. }
  252. func (f *fakeConnection) Option(string) string {
  253. return ""
  254. }
  255. func (f *fakeConnection) Index(folder string, fs []protocol.FileInfo) error {
  256. f.mut.Lock()
  257. defer f.mut.Unlock()
  258. if f.indexFn != nil {
  259. f.indexFn(folder, fs)
  260. }
  261. return nil
  262. }
  263. func (f *fakeConnection) IndexUpdate(folder string, fs []protocol.FileInfo) error {
  264. f.mut.Lock()
  265. defer f.mut.Unlock()
  266. if f.indexFn != nil {
  267. f.indexFn(folder, fs)
  268. }
  269. return nil
  270. }
  271. func (f *fakeConnection) Request(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  272. f.mut.Lock()
  273. defer f.mut.Unlock()
  274. if f.requestFn != nil {
  275. return f.requestFn(folder, name, offset, size, hash, fromTemporary)
  276. }
  277. return f.fileData[name], nil
  278. }
  279. func (f *fakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  280. func (f *fakeConnection) Ping() bool {
  281. f.mut.Lock()
  282. defer f.mut.Unlock()
  283. return f.closed
  284. }
  285. func (f *fakeConnection) Closed() bool {
  286. f.mut.Lock()
  287. defer f.mut.Unlock()
  288. return f.closed
  289. }
  290. func (f *fakeConnection) Statistics() protocol.Statistics {
  291. return protocol.Statistics{}
  292. }
  293. func (f *fakeConnection) RemoteAddr() net.Addr {
  294. return &fakeAddr{}
  295. }
  296. func (f *fakeConnection) Type() string {
  297. return "fake"
  298. }
  299. func (f *fakeConnection) Transport() string {
  300. return "fake"
  301. }
  302. func (f *fakeConnection) Priority() int {
  303. return 9000
  304. }
  305. func (f *fakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  306. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  307. folder: folder,
  308. updates: updates,
  309. })
  310. }
  311. func (f *fakeConnection) addFile(name string, flags uint32, ftype protocol.FileInfoType, data []byte) {
  312. f.mut.Lock()
  313. defer f.mut.Unlock()
  314. blocks, _ := scanner.Blocks(context.TODO(), bytes.NewReader(data), protocol.BlockSize, int64(len(data)), nil, true)
  315. var version protocol.Vector
  316. version = version.Update(f.id.Short())
  317. if ftype == protocol.FileInfoTypeFile || ftype == protocol.FileInfoTypeDirectory {
  318. f.files = append(f.files, protocol.FileInfo{
  319. Name: name,
  320. Type: ftype,
  321. Size: int64(len(data)),
  322. ModifiedS: time.Now().Unix(),
  323. Permissions: flags,
  324. Version: version,
  325. Sequence: time.Now().UnixNano(),
  326. Blocks: blocks,
  327. })
  328. } else {
  329. // Symlink
  330. f.files = append(f.files, protocol.FileInfo{
  331. Name: name,
  332. Type: ftype,
  333. Version: version,
  334. Sequence: time.Now().UnixNano(),
  335. SymlinkTarget: string(data),
  336. })
  337. }
  338. if f.fileData == nil {
  339. f.fileData = make(map[string][]byte)
  340. }
  341. f.fileData[name] = data
  342. }
  343. func (f *fakeConnection) deleteFile(name string) {
  344. f.mut.Lock()
  345. defer f.mut.Unlock()
  346. for i, fi := range f.files {
  347. if fi.Name == name {
  348. fi.Deleted = true
  349. fi.ModifiedS = time.Now().Unix()
  350. fi.Version = fi.Version.Update(f.id.Short())
  351. fi.Sequence = time.Now().UnixNano()
  352. fi.Blocks = nil
  353. f.files = append(append(f.files[:i], f.files[i+1:]...), fi)
  354. return
  355. }
  356. }
  357. }
  358. func (f *fakeConnection) sendIndexUpdate() {
  359. f.model.IndexUpdate(f.id, f.folder, f.files)
  360. }
  361. func BenchmarkRequestOut(b *testing.B) {
  362. db := db.OpenMemory()
  363. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  364. m.AddFolder(defaultFolderConfig)
  365. m.ServeBackground()
  366. defer m.Stop()
  367. m.ScanFolder("default")
  368. const n = 1000
  369. files := genFiles(n)
  370. fc := &fakeConnection{id: device1}
  371. for _, f := range files {
  372. fc.addFile(f.Name, 0644, protocol.FileInfoTypeFile, []byte("some data to return"))
  373. }
  374. m.AddConnection(fc, protocol.HelloResult{})
  375. m.Index(device1, "default", files)
  376. b.ResetTimer()
  377. for i := 0; i < b.N; i++ {
  378. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, false)
  379. if err != nil {
  380. b.Error(err)
  381. }
  382. if data == nil {
  383. b.Error("nil data")
  384. }
  385. }
  386. }
  387. func BenchmarkRequestInSingleFile(b *testing.B) {
  388. db := db.OpenMemory()
  389. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  390. m.AddFolder(defaultFolderConfig)
  391. m.ServeBackground()
  392. defer m.Stop()
  393. m.ScanFolder("default")
  394. buf := make([]byte, 128<<10)
  395. rand.Read(buf)
  396. os.RemoveAll("testdata/request")
  397. defer os.RemoveAll("testdata/request")
  398. os.MkdirAll("testdata/request/for/a/file/in/a/couple/of/dirs", 0755)
  399. ioutil.WriteFile("testdata/request/for/a/file/in/a/couple/of/dirs/128k", buf, 0644)
  400. b.ResetTimer()
  401. for i := 0; i < b.N; i++ {
  402. if err := m.Request(device1, "default", "request/for/a/file/in/a/couple/of/dirs/128k", 0, nil, false, buf); err != nil {
  403. b.Error(err)
  404. }
  405. }
  406. b.SetBytes(128 << 10)
  407. }
  408. func TestDeviceRename(t *testing.T) {
  409. hello := protocol.HelloResult{
  410. ClientName: "syncthing",
  411. ClientVersion: "v0.9.4",
  412. }
  413. defer os.Remove("tmpconfig.xml")
  414. rawCfg := config.New(device1)
  415. rawCfg.Devices = []config.DeviceConfiguration{
  416. {
  417. DeviceID: device1,
  418. },
  419. }
  420. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  421. db := db.OpenMemory()
  422. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  423. if cfg.Devices()[device1].Name != "" {
  424. t.Errorf("Device already has a name")
  425. }
  426. conn := &fakeConnection{id: device1}
  427. m.AddConnection(conn, hello)
  428. m.ServeBackground()
  429. defer m.Stop()
  430. if cfg.Devices()[device1].Name != "" {
  431. t.Errorf("Device already has a name")
  432. }
  433. m.Closed(conn, protocol.ErrTimeout)
  434. hello.DeviceName = "tester"
  435. m.AddConnection(conn, hello)
  436. if cfg.Devices()[device1].Name != "tester" {
  437. t.Errorf("Device did not get a name")
  438. }
  439. m.Closed(conn, protocol.ErrTimeout)
  440. hello.DeviceName = "tester2"
  441. m.AddConnection(conn, hello)
  442. if cfg.Devices()[device1].Name != "tester" {
  443. t.Errorf("Device name got overwritten")
  444. }
  445. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  446. if err != nil {
  447. t.Error(err)
  448. return
  449. }
  450. if cfgw.Devices()[device1].Name != "tester" {
  451. t.Errorf("Device name not saved in config")
  452. }
  453. m.Closed(conn, protocol.ErrTimeout)
  454. opts := cfg.Options()
  455. opts.OverwriteRemoteDevNames = true
  456. cfg.SetOptions(opts)
  457. hello.DeviceName = "tester2"
  458. m.AddConnection(conn, hello)
  459. if cfg.Devices()[device1].Name != "tester2" {
  460. t.Errorf("Device name not overwritten")
  461. }
  462. }
  463. func TestClusterConfig(t *testing.T) {
  464. cfg := config.New(device1)
  465. cfg.Devices = []config.DeviceConfiguration{
  466. {
  467. DeviceID: device1,
  468. Introducer: true,
  469. },
  470. {
  471. DeviceID: device2,
  472. },
  473. }
  474. cfg.Folders = []config.FolderConfiguration{
  475. {
  476. ID: "folder1",
  477. Path: "testdata",
  478. Devices: []config.FolderDeviceConfiguration{
  479. {DeviceID: device1},
  480. {DeviceID: device2},
  481. },
  482. },
  483. {
  484. ID: "folder2",
  485. Path: "testdata",
  486. Devices: []config.FolderDeviceConfiguration{
  487. {DeviceID: device1},
  488. {DeviceID: device2},
  489. },
  490. },
  491. }
  492. db := db.OpenMemory()
  493. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  494. m.AddFolder(cfg.Folders[0])
  495. m.AddFolder(cfg.Folders[1])
  496. m.ServeBackground()
  497. defer m.Stop()
  498. cm := m.generateClusterConfig(device2)
  499. if l := len(cm.Folders); l != 2 {
  500. t.Fatalf("Incorrect number of folders %d != 2", l)
  501. }
  502. r := cm.Folders[0]
  503. if r.ID != "folder1" {
  504. t.Errorf("Incorrect folder %q != folder1", r.ID)
  505. }
  506. if l := len(r.Devices); l != 2 {
  507. t.Errorf("Incorrect number of devices %d != 2", l)
  508. }
  509. if id := r.Devices[0].ID; id != device1 {
  510. t.Errorf("Incorrect device ID %s != %s", id, device1)
  511. }
  512. if !r.Devices[0].Introducer {
  513. t.Error("Device1 should be flagged as Introducer")
  514. }
  515. if id := r.Devices[1].ID; id != device2 {
  516. t.Errorf("Incorrect device ID %s != %s", id, device2)
  517. }
  518. if r.Devices[1].Introducer {
  519. t.Error("Device2 should not be flagged as Introducer")
  520. }
  521. r = cm.Folders[1]
  522. if r.ID != "folder2" {
  523. t.Errorf("Incorrect folder %q != folder2", r.ID)
  524. }
  525. if l := len(r.Devices); l != 2 {
  526. t.Errorf("Incorrect number of devices %d != 2", l)
  527. }
  528. if id := r.Devices[0].ID; id != device1 {
  529. t.Errorf("Incorrect device ID %s != %s", id, device1)
  530. }
  531. if !r.Devices[0].Introducer {
  532. t.Error("Device1 should be flagged as Introducer")
  533. }
  534. if id := r.Devices[1].ID; id != device2 {
  535. t.Errorf("Incorrect device ID %s != %s", id, device2)
  536. }
  537. if r.Devices[1].Introducer {
  538. t.Error("Device2 should not be flagged as Introducer")
  539. }
  540. }
  541. func TestIntroducer(t *testing.T) {
  542. var introducedByAnyone protocol.DeviceID
  543. // LocalDeviceID is a magic value meaning don't check introducer
  544. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  545. for _, dev := range cfg.Devices {
  546. if dev.DeviceID.Equals(id) {
  547. if introducedBy.Equals(introducedByAnyone) {
  548. return true
  549. }
  550. return introducedBy.Equals(introducedBy)
  551. }
  552. }
  553. return false
  554. }
  555. wcfg, m := newState(config.Configuration{
  556. Devices: []config.DeviceConfiguration{
  557. {
  558. DeviceID: device1,
  559. Introducer: true,
  560. },
  561. },
  562. Folders: []config.FolderConfiguration{
  563. {
  564. ID: "folder1",
  565. Path: "testdata",
  566. Devices: []config.FolderDeviceConfiguration{
  567. {DeviceID: device1},
  568. },
  569. },
  570. {
  571. ID: "folder2",
  572. Path: "testdata",
  573. Devices: []config.FolderDeviceConfiguration{
  574. {DeviceID: device1},
  575. },
  576. },
  577. },
  578. })
  579. m.ClusterConfig(device1, protocol.ClusterConfig{
  580. Folders: []protocol.Folder{
  581. {
  582. ID: "folder1",
  583. Devices: []protocol.Device{
  584. {
  585. ID: device2,
  586. Introducer: true,
  587. SkipIntroductionRemovals: true,
  588. },
  589. },
  590. },
  591. },
  592. })
  593. if newDev, ok := wcfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  594. t.Error("devie 2 missing or wrong flags")
  595. }
  596. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  597. t.Error("expected folder 1 to have device2 introduced by device 1")
  598. }
  599. wcfg, m = newState(config.Configuration{
  600. Devices: []config.DeviceConfiguration{
  601. {
  602. DeviceID: device1,
  603. Introducer: true,
  604. },
  605. {
  606. DeviceID: device2,
  607. IntroducedBy: device1,
  608. },
  609. },
  610. Folders: []config.FolderConfiguration{
  611. {
  612. ID: "folder1",
  613. Path: "testdata",
  614. Devices: []config.FolderDeviceConfiguration{
  615. {DeviceID: device1},
  616. {DeviceID: device2, IntroducedBy: device1},
  617. },
  618. },
  619. {
  620. ID: "folder2",
  621. Path: "testdata",
  622. Devices: []config.FolderDeviceConfiguration{
  623. {DeviceID: device1},
  624. },
  625. },
  626. },
  627. })
  628. m.ClusterConfig(device1, protocol.ClusterConfig{
  629. Folders: []protocol.Folder{
  630. {
  631. ID: "folder2",
  632. Devices: []protocol.Device{
  633. {
  634. ID: device2,
  635. Introducer: true,
  636. SkipIntroductionRemovals: true,
  637. },
  638. },
  639. },
  640. },
  641. })
  642. // Should not get introducer, as it's already unset, and it's an existing device.
  643. if newDev, ok := wcfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  644. t.Error("device 2 missing or changed flags")
  645. }
  646. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  647. t.Error("expected device 2 to be removed from folder 1")
  648. }
  649. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  650. t.Error("expected device 2 to be added to folder 2")
  651. }
  652. wcfg, m = newState(config.Configuration{
  653. Devices: []config.DeviceConfiguration{
  654. {
  655. DeviceID: device1,
  656. Introducer: true,
  657. },
  658. {
  659. DeviceID: device2,
  660. IntroducedBy: device1,
  661. },
  662. },
  663. Folders: []config.FolderConfiguration{
  664. {
  665. ID: "folder1",
  666. Path: "testdata",
  667. Devices: []config.FolderDeviceConfiguration{
  668. {DeviceID: device1},
  669. {DeviceID: device2, IntroducedBy: device1},
  670. },
  671. },
  672. {
  673. ID: "folder2",
  674. Path: "testdata",
  675. Devices: []config.FolderDeviceConfiguration{
  676. {DeviceID: device1},
  677. {DeviceID: device2, IntroducedBy: device1},
  678. },
  679. },
  680. },
  681. })
  682. m.ClusterConfig(device1, protocol.ClusterConfig{})
  683. if _, ok := wcfg.Device(device2); ok {
  684. t.Error("device 2 should have been removed")
  685. }
  686. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  687. t.Error("expected device 2 to be removed from folder 1")
  688. }
  689. if contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  690. t.Error("expected device 2 to be removed from folder 2")
  691. }
  692. // Two cases when removals should not happen
  693. // 1. Introducer flag no longer set on device
  694. wcfg, m = newState(config.Configuration{
  695. Devices: []config.DeviceConfiguration{
  696. {
  697. DeviceID: device1,
  698. Introducer: false,
  699. },
  700. {
  701. DeviceID: device2,
  702. IntroducedBy: device1,
  703. },
  704. },
  705. Folders: []config.FolderConfiguration{
  706. {
  707. ID: "folder1",
  708. Path: "testdata",
  709. Devices: []config.FolderDeviceConfiguration{
  710. {DeviceID: device1},
  711. {DeviceID: device2, IntroducedBy: device1},
  712. },
  713. },
  714. {
  715. ID: "folder2",
  716. Path: "testdata",
  717. Devices: []config.FolderDeviceConfiguration{
  718. {DeviceID: device1},
  719. {DeviceID: device2, IntroducedBy: device1},
  720. },
  721. },
  722. },
  723. })
  724. m.ClusterConfig(device1, protocol.ClusterConfig{})
  725. if _, ok := wcfg.Device(device2); !ok {
  726. t.Error("device 2 should not have been removed")
  727. }
  728. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  729. t.Error("expected device 2 not to be removed from folder 1")
  730. }
  731. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  732. t.Error("expected device 2 not to be removed from folder 2")
  733. }
  734. // 2. SkipIntroductionRemovals is set
  735. wcfg, m = newState(config.Configuration{
  736. Devices: []config.DeviceConfiguration{
  737. {
  738. DeviceID: device1,
  739. Introducer: true,
  740. SkipIntroductionRemovals: true,
  741. },
  742. {
  743. DeviceID: device2,
  744. IntroducedBy: device1,
  745. },
  746. },
  747. Folders: []config.FolderConfiguration{
  748. {
  749. ID: "folder1",
  750. Path: "testdata",
  751. Devices: []config.FolderDeviceConfiguration{
  752. {DeviceID: device1},
  753. {DeviceID: device2, IntroducedBy: device1},
  754. },
  755. },
  756. {
  757. ID: "folder2",
  758. Path: "testdata",
  759. Devices: []config.FolderDeviceConfiguration{
  760. {DeviceID: device1},
  761. },
  762. },
  763. },
  764. })
  765. m.ClusterConfig(device1, protocol.ClusterConfig{
  766. Folders: []protocol.Folder{
  767. {
  768. ID: "folder2",
  769. Devices: []protocol.Device{
  770. {
  771. ID: device2,
  772. Introducer: true,
  773. SkipIntroductionRemovals: true,
  774. },
  775. },
  776. },
  777. },
  778. })
  779. if _, ok := wcfg.Device(device2); !ok {
  780. t.Error("device 2 should not have been removed")
  781. }
  782. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  783. t.Error("expected device 2 not to be removed from folder 1")
  784. }
  785. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  786. t.Error("expected device 2 not to be added to folder 2")
  787. }
  788. // Test device not being removed as it's shared without an introducer.
  789. wcfg, m = newState(config.Configuration{
  790. Devices: []config.DeviceConfiguration{
  791. {
  792. DeviceID: device1,
  793. Introducer: true,
  794. },
  795. {
  796. DeviceID: device2,
  797. IntroducedBy: device1,
  798. },
  799. },
  800. Folders: []config.FolderConfiguration{
  801. {
  802. ID: "folder1",
  803. Path: "testdata",
  804. Devices: []config.FolderDeviceConfiguration{
  805. {DeviceID: device1},
  806. {DeviceID: device2, IntroducedBy: device1},
  807. },
  808. },
  809. {
  810. ID: "folder2",
  811. Path: "testdata",
  812. Devices: []config.FolderDeviceConfiguration{
  813. {DeviceID: device1},
  814. {DeviceID: device2},
  815. },
  816. },
  817. },
  818. })
  819. m.ClusterConfig(device1, protocol.ClusterConfig{})
  820. if _, ok := wcfg.Device(device2); !ok {
  821. t.Error("device 2 should not have been removed")
  822. }
  823. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  824. t.Error("expected device 2 to be removed from folder 1")
  825. }
  826. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  827. t.Error("expected device 2 not to be removed from folder 2")
  828. }
  829. // Test device not being removed as it's shared by a different introducer.
  830. wcfg, m = newState(config.Configuration{
  831. Devices: []config.DeviceConfiguration{
  832. {
  833. DeviceID: device1,
  834. Introducer: true,
  835. },
  836. {
  837. DeviceID: device2,
  838. IntroducedBy: device1,
  839. },
  840. },
  841. Folders: []config.FolderConfiguration{
  842. {
  843. ID: "folder1",
  844. Path: "testdata",
  845. Devices: []config.FolderDeviceConfiguration{
  846. {DeviceID: device1},
  847. {DeviceID: device2, IntroducedBy: device1},
  848. },
  849. },
  850. {
  851. ID: "folder2",
  852. Path: "testdata",
  853. Devices: []config.FolderDeviceConfiguration{
  854. {DeviceID: device1},
  855. {DeviceID: device2, IntroducedBy: protocol.LocalDeviceID},
  856. },
  857. },
  858. },
  859. })
  860. m.ClusterConfig(device1, protocol.ClusterConfig{})
  861. if _, ok := wcfg.Device(device2); !ok {
  862. t.Error("device 2 should not have been removed")
  863. }
  864. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  865. t.Error("expected device 2 to be removed from folder 1")
  866. }
  867. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  868. t.Error("expected device 2 not to be removed from folder 2")
  869. }
  870. }
  871. func TestAutoAcceptRejected(t *testing.T) {
  872. // Nothing happens if AutoAcceptFolders not set
  873. tcfg := defaultAutoAcceptCfg.Copy()
  874. for i := range tcfg.Devices {
  875. tcfg.Devices[i].AutoAcceptFolders = false
  876. }
  877. wcfg, m := newState(tcfg)
  878. id := srand.String(8)
  879. defer os.RemoveAll(filepath.Join("testdata", id))
  880. m.ClusterConfig(device1, protocol.ClusterConfig{
  881. Folders: []protocol.Folder{
  882. {
  883. ID: id,
  884. Label: id,
  885. },
  886. },
  887. })
  888. if _, ok := wcfg.Folder(id); ok || m.folderSharedWith(id, device1) {
  889. t.Error("unexpected shared", id)
  890. }
  891. }
  892. func TestAutoAcceptNewFolder(t *testing.T) {
  893. // New folder
  894. wcfg, m := newState(defaultAutoAcceptCfg)
  895. id := srand.String(8)
  896. defer os.RemoveAll(filepath.Join("testdata", id))
  897. m.ClusterConfig(device1, protocol.ClusterConfig{
  898. Folders: []protocol.Folder{
  899. {
  900. ID: id,
  901. Label: id,
  902. },
  903. },
  904. })
  905. if _, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) {
  906. t.Error("expected shared", id)
  907. }
  908. }
  909. func TestAutoAcceptMultipleFolders(t *testing.T) {
  910. // Multiple new folders
  911. wcfg, m := newState(defaultAutoAcceptCfg)
  912. id1 := srand.String(8)
  913. defer os.RemoveAll(filepath.Join("testdata", id1))
  914. id2 := srand.String(8)
  915. defer os.RemoveAll(filepath.Join("testdata", id2))
  916. m.ClusterConfig(device1, protocol.ClusterConfig{
  917. Folders: []protocol.Folder{
  918. {
  919. ID: id1,
  920. Label: id1,
  921. },
  922. {
  923. ID: id2,
  924. Label: id2,
  925. },
  926. },
  927. })
  928. if _, ok := wcfg.Folder(id1); !ok || !m.folderSharedWith(id1, device1) {
  929. t.Error("expected shared", id1)
  930. }
  931. if _, ok := wcfg.Folder(id2); !ok || !m.folderSharedWith(id2, device1) {
  932. t.Error("expected shared", id2)
  933. }
  934. }
  935. func TestAutoAcceptExistingFolder(t *testing.T) {
  936. // Existing folder
  937. id := srand.String(8)
  938. idOther := srand.String(8) // To check that path does not get changed.
  939. defer os.RemoveAll(filepath.Join("testdata", id))
  940. defer os.RemoveAll(filepath.Join("testdata", idOther))
  941. tcfg := defaultAutoAcceptCfg.Copy()
  942. tcfg.Folders = []config.FolderConfiguration{
  943. {
  944. ID: id,
  945. Path: filepath.Join("testdata", idOther), // To check that path does not get changed.
  946. },
  947. }
  948. wcfg, m := newState(tcfg)
  949. if _, ok := wcfg.Folder(id); !ok || m.folderSharedWith(id, device1) {
  950. t.Error("missing folder, or shared", id)
  951. }
  952. m.ClusterConfig(device1, protocol.ClusterConfig{
  953. Folders: []protocol.Folder{
  954. {
  955. ID: id,
  956. Label: id,
  957. },
  958. },
  959. })
  960. if fcfg, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) || fcfg.Path != filepath.Join("testdata", idOther) {
  961. t.Error("missing folder, or unshared, or path changed", id)
  962. }
  963. }
  964. func TestAutoAcceptNewAndExistingFolder(t *testing.T) {
  965. // New and existing folder
  966. id1 := srand.String(8)
  967. defer os.RemoveAll(filepath.Join("testdata", id1))
  968. id2 := srand.String(8)
  969. defer os.RemoveAll(filepath.Join("testdata", id2))
  970. tcfg := defaultAutoAcceptCfg.Copy()
  971. tcfg.Folders = []config.FolderConfiguration{
  972. {
  973. ID: id1,
  974. Path: filepath.Join("testdata", id1), // from previous test case, to verify that path doesn't get changed.
  975. },
  976. }
  977. wcfg, m := newState(tcfg)
  978. if _, ok := wcfg.Folder(id1); !ok || m.folderSharedWith(id1, device1) {
  979. t.Error("missing folder, or shared", id1)
  980. }
  981. m.ClusterConfig(device1, protocol.ClusterConfig{
  982. Folders: []protocol.Folder{
  983. {
  984. ID: id1,
  985. Label: id1,
  986. },
  987. {
  988. ID: id2,
  989. Label: id2,
  990. },
  991. },
  992. })
  993. for i, id := range []string{id1, id2} {
  994. if _, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) {
  995. t.Error("missing folder, or unshared", i, id)
  996. }
  997. }
  998. }
  999. func TestAutoAcceptAlreadyShared(t *testing.T) {
  1000. // Already shared
  1001. id := srand.String(8)
  1002. defer os.RemoveAll(filepath.Join("testdata", id))
  1003. tcfg := defaultAutoAcceptCfg.Copy()
  1004. tcfg.Folders = []config.FolderConfiguration{
  1005. {
  1006. ID: id,
  1007. Path: filepath.Join("testdata", id),
  1008. Devices: []config.FolderDeviceConfiguration{
  1009. {
  1010. DeviceID: device1,
  1011. },
  1012. },
  1013. },
  1014. }
  1015. wcfg, m := newState(tcfg)
  1016. if _, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) {
  1017. t.Error("missing folder, or not shared", id)
  1018. }
  1019. m.ClusterConfig(device1, protocol.ClusterConfig{
  1020. Folders: []protocol.Folder{
  1021. {
  1022. ID: id,
  1023. Label: id,
  1024. },
  1025. },
  1026. })
  1027. if _, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) {
  1028. t.Error("missing folder, or not shared", id)
  1029. }
  1030. }
  1031. func TestAutoAcceptNameConflict(t *testing.T) {
  1032. id := srand.String(8)
  1033. label := srand.String(8)
  1034. os.MkdirAll(filepath.Join("testdata", id), 0777)
  1035. os.MkdirAll(filepath.Join("testdata", label), 0777)
  1036. defer os.RemoveAll(filepath.Join("testdata", id))
  1037. defer os.RemoveAll(filepath.Join("testdata", label))
  1038. wcfg, m := newState(defaultAutoAcceptCfg)
  1039. m.ClusterConfig(device1, protocol.ClusterConfig{
  1040. Folders: []protocol.Folder{
  1041. {
  1042. ID: id,
  1043. Label: label,
  1044. },
  1045. },
  1046. })
  1047. if _, ok := wcfg.Folder(id); ok || m.folderSharedWith(id, device1) {
  1048. t.Error("unexpected folder", id)
  1049. }
  1050. }
  1051. func TestAutoAcceptPrefersLabel(t *testing.T) {
  1052. // Prefers label, falls back to ID.
  1053. wcfg, m := newState(defaultAutoAcceptCfg)
  1054. id := srand.String(8)
  1055. label := srand.String(8)
  1056. defer os.RemoveAll(filepath.Join("testdata", id))
  1057. defer os.RemoveAll(filepath.Join("testdata", label))
  1058. m.ClusterConfig(device1, protocol.ClusterConfig{
  1059. Folders: []protocol.Folder{
  1060. {
  1061. ID: id,
  1062. Label: label,
  1063. },
  1064. },
  1065. })
  1066. if fcfg, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) || !strings.HasSuffix(fcfg.Path, label) {
  1067. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1068. }
  1069. }
  1070. func TestAutoAcceptFallsBackToID(t *testing.T) {
  1071. // Prefers label, falls back to ID.
  1072. wcfg, m := newState(defaultAutoAcceptCfg)
  1073. id := srand.String(8)
  1074. label := srand.String(8)
  1075. os.MkdirAll(filepath.Join("testdata", label), 0777)
  1076. defer os.RemoveAll(filepath.Join("testdata", label))
  1077. defer os.RemoveAll(filepath.Join("testdata", id))
  1078. m.ClusterConfig(device1, protocol.ClusterConfig{
  1079. Folders: []protocol.Folder{
  1080. {
  1081. ID: id,
  1082. Label: label,
  1083. },
  1084. },
  1085. })
  1086. if fcfg, ok := wcfg.Folder(id); !ok || !m.folderSharedWith(id, device1) || !strings.HasSuffix(fcfg.Path, id) {
  1087. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1088. }
  1089. }
  1090. func TestAutoAcceptPausedWhenFolderConfigChanged(t *testing.T) {
  1091. // Existing folder
  1092. id := srand.String(8)
  1093. idOther := srand.String(8) // To check that path does not get changed.
  1094. defer os.RemoveAll(filepath.Join("testdata", id))
  1095. defer os.RemoveAll(filepath.Join("testdata", idOther))
  1096. tcfg := defaultAutoAcceptCfg.Copy()
  1097. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, id, "", fs.FilesystemTypeBasic, filepath.Join("testdata", idOther))
  1098. fcfg.Paused = true
  1099. // The order of devices here is wrong (cfg.clean() sorts them), which will cause the folder to restart.
  1100. // Because of the restart, folder gets removed from m.deviceFolder, which means that generateClusterConfig will not panic.
  1101. // This wasn't an issue before, yet keeping the test case to prove that it still isn't.
  1102. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1103. DeviceID: device1,
  1104. })
  1105. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1106. wcfg, m := newState(tcfg)
  1107. if _, ok := wcfg.Folder(id); !ok || m.folderSharedWith(id, device1) {
  1108. t.Error("missing folder, or shared", id)
  1109. }
  1110. if _, ok := m.folderRunners[id]; ok {
  1111. t.Fatal("folder running?")
  1112. }
  1113. m.ClusterConfig(device1, protocol.ClusterConfig{
  1114. Folders: []protocol.Folder{
  1115. {
  1116. ID: id,
  1117. Label: id,
  1118. },
  1119. },
  1120. })
  1121. m.generateClusterConfig(device1)
  1122. if fcfg, ok := wcfg.Folder(id); !ok {
  1123. t.Error("missing folder")
  1124. } else if fcfg.Path != filepath.Join("testdata", idOther) {
  1125. t.Error("folder path changed")
  1126. } else {
  1127. for _, dev := range fcfg.DeviceIDs() {
  1128. if dev == device1 {
  1129. return
  1130. }
  1131. }
  1132. t.Error("device missing")
  1133. }
  1134. if _, ok := m.folderDevices[id]; ok {
  1135. t.Error("folder started")
  1136. }
  1137. }
  1138. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1139. // Existing folder
  1140. id := srand.String(8)
  1141. idOther := srand.String(8) // To check that path does not get changed.
  1142. defer os.RemoveAll(filepath.Join("testdata", id))
  1143. defer os.RemoveAll(filepath.Join("testdata", idOther))
  1144. tcfg := defaultAutoAcceptCfg.Copy()
  1145. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, id, "", fs.FilesystemTypeBasic, filepath.Join("testdata", idOther))
  1146. fcfg.Paused = true
  1147. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1148. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1149. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1150. // did not have a file set.
  1151. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1152. {
  1153. DeviceID: device1,
  1154. },
  1155. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1156. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1157. wcfg, m := newState(tcfg)
  1158. if _, ok := wcfg.Folder(id); !ok || m.folderSharedWith(id, device1) {
  1159. t.Error("missing folder, or shared", id)
  1160. }
  1161. if _, ok := m.folderRunners[id]; ok {
  1162. t.Fatal("folder running?")
  1163. }
  1164. m.ClusterConfig(device1, protocol.ClusterConfig{
  1165. Folders: []protocol.Folder{
  1166. {
  1167. ID: id,
  1168. Label: id,
  1169. },
  1170. },
  1171. })
  1172. m.generateClusterConfig(device1)
  1173. if fcfg, ok := wcfg.Folder(id); !ok {
  1174. t.Error("missing folder")
  1175. } else if fcfg.Path != filepath.Join("testdata", idOther) {
  1176. t.Error("folder path changed")
  1177. } else {
  1178. for _, dev := range fcfg.DeviceIDs() {
  1179. if dev == device1 {
  1180. return
  1181. }
  1182. }
  1183. t.Error("device missing")
  1184. }
  1185. if _, ok := m.folderDevices[id]; ok {
  1186. t.Error("folder started")
  1187. }
  1188. }
  1189. func changeIgnores(t *testing.T, m *Model, expected []string) {
  1190. arrEqual := func(a, b []string) bool {
  1191. if len(a) != len(b) {
  1192. return false
  1193. }
  1194. for i := range a {
  1195. if a[i] != b[i] {
  1196. return false
  1197. }
  1198. }
  1199. return true
  1200. }
  1201. ignores, _, err := m.GetIgnores("default")
  1202. if err != nil {
  1203. t.Error(err)
  1204. }
  1205. if !arrEqual(ignores, expected) {
  1206. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1207. }
  1208. ignores = append(ignores, "pox")
  1209. err = m.SetIgnores("default", ignores)
  1210. if err != nil {
  1211. t.Error(err)
  1212. }
  1213. ignores2, _, err := m.GetIgnores("default")
  1214. if err != nil {
  1215. t.Error(err)
  1216. }
  1217. if !arrEqual(ignores, ignores2) {
  1218. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1219. }
  1220. if runtime.GOOS == "darwin" {
  1221. // see above
  1222. time.Sleep(time.Second)
  1223. } else {
  1224. time.Sleep(time.Millisecond)
  1225. }
  1226. err = m.SetIgnores("default", expected)
  1227. if err != nil {
  1228. t.Error(err)
  1229. }
  1230. ignores, _, err = m.GetIgnores("default")
  1231. if err != nil {
  1232. t.Error(err)
  1233. }
  1234. if !arrEqual(ignores, expected) {
  1235. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1236. }
  1237. }
  1238. func TestIgnores(t *testing.T) {
  1239. // Assure a clean start state
  1240. os.RemoveAll(filepath.Join("testdata", config.DefaultMarkerName))
  1241. os.MkdirAll(filepath.Join("testdata", config.DefaultMarkerName), 0644)
  1242. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  1243. db := db.OpenMemory()
  1244. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1245. m.ServeBackground()
  1246. defer m.Stop()
  1247. // m.cfg.SetFolder is not usable as it is non-blocking, and there is no
  1248. // way to know when the folder is actually added.
  1249. m.AddFolder(defaultFolderConfig)
  1250. m.StartFolder("default")
  1251. // Reach in and update the ignore matcher to one that always does
  1252. // reloads when asked to, instead of checking file mtimes. This is
  1253. // because we will be changing the files on disk often enough that the
  1254. // mtimes will be unreliable to determine change status.
  1255. m.fmut.Lock()
  1256. m.folderIgnores["default"] = ignore.New(defaultFs, ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  1257. m.fmut.Unlock()
  1258. // Make sure the initial scan has finished (ScanFolders is blocking)
  1259. m.ScanFolders()
  1260. expected := []string{
  1261. ".*",
  1262. "quux",
  1263. }
  1264. changeIgnores(t, m, expected)
  1265. _, _, err := m.GetIgnores("doesnotexist")
  1266. if err == nil {
  1267. t.Error("No error")
  1268. }
  1269. err = m.SetIgnores("doesnotexist", expected)
  1270. if err == nil {
  1271. t.Error("No error")
  1272. }
  1273. // Invalid path, marker should be missing, hence returns an error.
  1274. m.AddFolder(config.FolderConfiguration{ID: "fresh", Path: "XXX"})
  1275. _, _, err = m.GetIgnores("fresh")
  1276. if err == nil {
  1277. t.Error("No error")
  1278. }
  1279. // Repeat tests with paused folder
  1280. pausedDefaultFolderConfig := defaultFolderConfig
  1281. pausedDefaultFolderConfig.Paused = true
  1282. m.RestartFolder(pausedDefaultFolderConfig)
  1283. // Here folder initialization is not an issue as a paused folder isn't
  1284. // added to the model and thus there is no initial scan happening.
  1285. changeIgnores(t, m, expected)
  1286. // Make sure no .stignore file is considered valid
  1287. os.Rename("testdata/.stignore", "testdata/.stignore.bak")
  1288. changeIgnores(t, m, []string{})
  1289. os.Rename("testdata/.stignore.bak", "testdata/.stignore")
  1290. }
  1291. func TestROScanRecovery(t *testing.T) {
  1292. ldb := db.OpenMemory()
  1293. set := db.NewFileSet("default", defaultFs, ldb)
  1294. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1295. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1296. })
  1297. fcfg := config.FolderConfiguration{
  1298. ID: "default",
  1299. Path: "testdata/rotestfolder",
  1300. Type: config.FolderTypeSendOnly,
  1301. RescanIntervalS: 1,
  1302. MarkerName: config.DefaultMarkerName,
  1303. }
  1304. cfg := config.Wrap("/tmp/test", config.Configuration{
  1305. Folders: []config.FolderConfiguration{fcfg},
  1306. Devices: []config.DeviceConfiguration{
  1307. {
  1308. DeviceID: device1,
  1309. },
  1310. },
  1311. })
  1312. os.RemoveAll(fcfg.Path)
  1313. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1314. m.AddFolder(fcfg)
  1315. m.StartFolder("default")
  1316. m.ServeBackground()
  1317. defer m.Stop()
  1318. waitFor := func(status string) error {
  1319. timeout := time.Now().Add(2 * time.Second)
  1320. for {
  1321. _, _, err := m.State("default")
  1322. if err == nil && status == "" {
  1323. return nil
  1324. }
  1325. if err != nil && err.Error() == status {
  1326. return nil
  1327. }
  1328. if time.Now().After(timeout) {
  1329. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1330. }
  1331. time.Sleep(10 * time.Millisecond)
  1332. }
  1333. }
  1334. if err := waitFor("folder path missing"); err != nil {
  1335. t.Error(err)
  1336. return
  1337. }
  1338. os.Mkdir(fcfg.Path, 0700)
  1339. if err := waitFor("folder marker missing"); err != nil {
  1340. t.Error(err)
  1341. return
  1342. }
  1343. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1344. if err != nil {
  1345. t.Error(err)
  1346. return
  1347. }
  1348. fd.Close()
  1349. if err := waitFor(""); err != nil {
  1350. t.Error(err)
  1351. return
  1352. }
  1353. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1354. if err := waitFor("folder marker missing"); err != nil {
  1355. t.Error(err)
  1356. return
  1357. }
  1358. os.Remove(fcfg.Path)
  1359. if err := waitFor("folder path missing"); err != nil {
  1360. t.Error(err)
  1361. return
  1362. }
  1363. }
  1364. func TestRWScanRecovery(t *testing.T) {
  1365. ldb := db.OpenMemory()
  1366. set := db.NewFileSet("default", defaultFs, ldb)
  1367. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1368. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1369. })
  1370. fcfg := config.FolderConfiguration{
  1371. ID: "default",
  1372. Path: "testdata/rwtestfolder",
  1373. Type: config.FolderTypeSendReceive,
  1374. RescanIntervalS: 1,
  1375. MarkerName: config.DefaultMarkerName,
  1376. }
  1377. cfg := config.Wrap("/tmp/test", config.Configuration{
  1378. Folders: []config.FolderConfiguration{fcfg},
  1379. Devices: []config.DeviceConfiguration{
  1380. {
  1381. DeviceID: device1,
  1382. },
  1383. },
  1384. })
  1385. os.RemoveAll(fcfg.Path)
  1386. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1387. m.AddFolder(fcfg)
  1388. m.StartFolder("default")
  1389. m.ServeBackground()
  1390. defer m.Stop()
  1391. waitFor := func(status string) error {
  1392. timeout := time.Now().Add(2 * time.Second)
  1393. for {
  1394. _, _, err := m.State("default")
  1395. if err == nil && status == "" {
  1396. return nil
  1397. }
  1398. if err != nil && err.Error() == status {
  1399. return nil
  1400. }
  1401. if time.Now().After(timeout) {
  1402. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1403. }
  1404. time.Sleep(10 * time.Millisecond)
  1405. }
  1406. }
  1407. if err := waitFor("folder path missing"); err != nil {
  1408. t.Error(err)
  1409. return
  1410. }
  1411. os.Mkdir(fcfg.Path, 0700)
  1412. if err := waitFor("folder marker missing"); err != nil {
  1413. t.Error(err)
  1414. return
  1415. }
  1416. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1417. if err != nil {
  1418. t.Error(err)
  1419. return
  1420. }
  1421. fd.Close()
  1422. if err := waitFor(""); err != nil {
  1423. t.Error(err)
  1424. return
  1425. }
  1426. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1427. if err := waitFor("folder marker missing"); err != nil {
  1428. t.Error(err)
  1429. return
  1430. }
  1431. os.Remove(fcfg.Path)
  1432. if err := waitFor("folder path missing"); err != nil {
  1433. t.Error(err)
  1434. return
  1435. }
  1436. }
  1437. func TestGlobalDirectoryTree(t *testing.T) {
  1438. db := db.OpenMemory()
  1439. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1440. m.AddFolder(defaultFolderConfig)
  1441. m.ServeBackground()
  1442. defer m.Stop()
  1443. b := func(isfile bool, path ...string) protocol.FileInfo {
  1444. typ := protocol.FileInfoTypeDirectory
  1445. blocks := []protocol.BlockInfo{}
  1446. if isfile {
  1447. typ = protocol.FileInfoTypeFile
  1448. 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}}}
  1449. }
  1450. return protocol.FileInfo{
  1451. Name: filepath.Join(path...),
  1452. Type: typ,
  1453. ModifiedS: 0x666,
  1454. Blocks: blocks,
  1455. Size: 0xa,
  1456. }
  1457. }
  1458. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1459. testdata := []protocol.FileInfo{
  1460. b(false, "another"),
  1461. b(false, "another", "directory"),
  1462. b(true, "another", "directory", "afile"),
  1463. b(false, "another", "directory", "with"),
  1464. b(false, "another", "directory", "with", "a"),
  1465. b(true, "another", "directory", "with", "a", "file"),
  1466. b(true, "another", "directory", "with", "file"),
  1467. b(true, "another", "file"),
  1468. b(false, "other"),
  1469. b(false, "other", "rand"),
  1470. b(false, "other", "random"),
  1471. b(false, "other", "random", "dir"),
  1472. b(false, "other", "random", "dirx"),
  1473. b(false, "other", "randomx"),
  1474. b(false, "some"),
  1475. b(false, "some", "directory"),
  1476. b(false, "some", "directory", "with"),
  1477. b(false, "some", "directory", "with", "a"),
  1478. b(true, "some", "directory", "with", "a", "file"),
  1479. b(true, "rootfile"),
  1480. }
  1481. expectedResult := map[string]interface{}{
  1482. "another": map[string]interface{}{
  1483. "directory": map[string]interface{}{
  1484. "afile": filedata,
  1485. "with": map[string]interface{}{
  1486. "a": map[string]interface{}{
  1487. "file": filedata,
  1488. },
  1489. "file": filedata,
  1490. },
  1491. },
  1492. "file": filedata,
  1493. },
  1494. "other": map[string]interface{}{
  1495. "rand": map[string]interface{}{},
  1496. "random": map[string]interface{}{
  1497. "dir": map[string]interface{}{},
  1498. "dirx": map[string]interface{}{},
  1499. },
  1500. "randomx": map[string]interface{}{},
  1501. },
  1502. "some": map[string]interface{}{
  1503. "directory": map[string]interface{}{
  1504. "with": map[string]interface{}{
  1505. "a": map[string]interface{}{
  1506. "file": filedata,
  1507. },
  1508. },
  1509. },
  1510. },
  1511. "rootfile": filedata,
  1512. }
  1513. mm := func(data interface{}) string {
  1514. bytes, err := json.Marshal(data)
  1515. if err != nil {
  1516. panic(err)
  1517. }
  1518. return string(bytes)
  1519. }
  1520. m.Index(device1, "default", testdata)
  1521. result := m.GlobalDirectoryTree("default", "", -1, false)
  1522. if mm(result) != mm(expectedResult) {
  1523. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1524. }
  1525. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1526. if mm(result) != mm(expectedResult["another"]) {
  1527. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1528. }
  1529. result = m.GlobalDirectoryTree("default", "", 0, false)
  1530. currentResult := map[string]interface{}{
  1531. "another": map[string]interface{}{},
  1532. "other": map[string]interface{}{},
  1533. "some": map[string]interface{}{},
  1534. "rootfile": filedata,
  1535. }
  1536. if mm(result) != mm(currentResult) {
  1537. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1538. }
  1539. result = m.GlobalDirectoryTree("default", "", 1, false)
  1540. currentResult = map[string]interface{}{
  1541. "another": map[string]interface{}{
  1542. "directory": map[string]interface{}{},
  1543. "file": filedata,
  1544. },
  1545. "other": map[string]interface{}{
  1546. "rand": map[string]interface{}{},
  1547. "random": map[string]interface{}{},
  1548. "randomx": map[string]interface{}{},
  1549. },
  1550. "some": map[string]interface{}{
  1551. "directory": map[string]interface{}{},
  1552. },
  1553. "rootfile": filedata,
  1554. }
  1555. if mm(result) != mm(currentResult) {
  1556. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1557. }
  1558. result = m.GlobalDirectoryTree("default", "", -1, true)
  1559. currentResult = map[string]interface{}{
  1560. "another": map[string]interface{}{
  1561. "directory": map[string]interface{}{
  1562. "with": map[string]interface{}{
  1563. "a": map[string]interface{}{},
  1564. },
  1565. },
  1566. },
  1567. "other": map[string]interface{}{
  1568. "rand": map[string]interface{}{},
  1569. "random": map[string]interface{}{
  1570. "dir": map[string]interface{}{},
  1571. "dirx": map[string]interface{}{},
  1572. },
  1573. "randomx": map[string]interface{}{},
  1574. },
  1575. "some": map[string]interface{}{
  1576. "directory": map[string]interface{}{
  1577. "with": map[string]interface{}{
  1578. "a": map[string]interface{}{},
  1579. },
  1580. },
  1581. },
  1582. }
  1583. if mm(result) != mm(currentResult) {
  1584. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1585. }
  1586. result = m.GlobalDirectoryTree("default", "", 1, true)
  1587. currentResult = map[string]interface{}{
  1588. "another": map[string]interface{}{
  1589. "directory": map[string]interface{}{},
  1590. },
  1591. "other": map[string]interface{}{
  1592. "rand": map[string]interface{}{},
  1593. "random": map[string]interface{}{},
  1594. "randomx": map[string]interface{}{},
  1595. },
  1596. "some": map[string]interface{}{
  1597. "directory": map[string]interface{}{},
  1598. },
  1599. }
  1600. if mm(result) != mm(currentResult) {
  1601. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1602. }
  1603. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1604. currentResult = map[string]interface{}{
  1605. "directory": map[string]interface{}{},
  1606. "file": filedata,
  1607. }
  1608. if mm(result) != mm(currentResult) {
  1609. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1610. }
  1611. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1612. currentResult = map[string]interface{}{
  1613. "with": map[string]interface{}{},
  1614. }
  1615. if mm(result) != mm(currentResult) {
  1616. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1617. }
  1618. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1619. currentResult = map[string]interface{}{
  1620. "with": map[string]interface{}{
  1621. "a": map[string]interface{}{},
  1622. },
  1623. }
  1624. if mm(result) != mm(currentResult) {
  1625. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1626. }
  1627. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1628. currentResult = map[string]interface{}{
  1629. "with": map[string]interface{}{
  1630. "a": map[string]interface{}{
  1631. "file": filedata,
  1632. },
  1633. },
  1634. }
  1635. if mm(result) != mm(currentResult) {
  1636. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1637. }
  1638. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1639. currentResult = map[string]interface{}{
  1640. "directory": map[string]interface{}{
  1641. "with": map[string]interface{}{
  1642. "a": map[string]interface{}{},
  1643. },
  1644. },
  1645. }
  1646. if mm(result) != mm(currentResult) {
  1647. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1648. }
  1649. // No prefix matching!
  1650. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1651. currentResult = map[string]interface{}{}
  1652. if mm(result) != mm(currentResult) {
  1653. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1654. }
  1655. }
  1656. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1657. db := db.OpenMemory()
  1658. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1659. m.AddFolder(defaultFolderConfig)
  1660. m.ServeBackground()
  1661. b := func(isfile bool, path ...string) protocol.FileInfo {
  1662. typ := protocol.FileInfoTypeDirectory
  1663. blocks := []protocol.BlockInfo{}
  1664. if isfile {
  1665. typ = protocol.FileInfoTypeFile
  1666. 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}}}
  1667. }
  1668. return protocol.FileInfo{
  1669. Name: filepath.Join(path...),
  1670. Type: typ,
  1671. ModifiedS: 0x666,
  1672. Blocks: blocks,
  1673. Size: 0xa,
  1674. }
  1675. }
  1676. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1677. testdata := []protocol.FileInfo{
  1678. b(true, "another", "directory", "afile"),
  1679. b(true, "another", "directory", "with", "a", "file"),
  1680. b(true, "another", "directory", "with", "file"),
  1681. b(false, "other", "random", "dirx"),
  1682. b(false, "other", "randomx"),
  1683. b(false, "some", "directory", "with", "x"),
  1684. b(true, "some", "directory", "with", "a", "file"),
  1685. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1686. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1687. }
  1688. expectedResult := map[string]interface{}{
  1689. "another": map[string]interface{}{
  1690. "directory": map[string]interface{}{
  1691. "afile": filedata,
  1692. "with": map[string]interface{}{
  1693. "a": map[string]interface{}{
  1694. "file": filedata,
  1695. },
  1696. "file": filedata,
  1697. },
  1698. },
  1699. },
  1700. "other": map[string]interface{}{
  1701. "random": map[string]interface{}{
  1702. "dirx": map[string]interface{}{},
  1703. },
  1704. "randomx": map[string]interface{}{},
  1705. },
  1706. "some": map[string]interface{}{
  1707. "directory": map[string]interface{}{
  1708. "with": map[string]interface{}{
  1709. "a": map[string]interface{}{
  1710. "file": filedata,
  1711. },
  1712. "x": map[string]interface{}{},
  1713. },
  1714. },
  1715. },
  1716. "this": map[string]interface{}{
  1717. "is": map[string]interface{}{
  1718. "a": map[string]interface{}{
  1719. "deep": map[string]interface{}{
  1720. "invalid": map[string]interface{}{
  1721. "directory": map[string]interface{}{},
  1722. },
  1723. },
  1724. },
  1725. },
  1726. },
  1727. "xthis": map[string]interface{}{
  1728. "is": map[string]interface{}{
  1729. "a": map[string]interface{}{
  1730. "deep": map[string]interface{}{
  1731. "invalid": map[string]interface{}{
  1732. "file": filedata,
  1733. },
  1734. },
  1735. },
  1736. },
  1737. },
  1738. }
  1739. mm := func(data interface{}) string {
  1740. bytes, err := json.Marshal(data)
  1741. if err != nil {
  1742. panic(err)
  1743. }
  1744. return string(bytes)
  1745. }
  1746. m.Index(device1, "default", testdata)
  1747. result := m.GlobalDirectoryTree("default", "", -1, false)
  1748. if mm(result) != mm(expectedResult) {
  1749. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1750. }
  1751. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1752. currentResult := map[string]interface{}{
  1753. "invalid": map[string]interface{}{
  1754. "file": filedata,
  1755. },
  1756. }
  1757. if mm(result) != mm(currentResult) {
  1758. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1759. }
  1760. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1761. currentResult = map[string]interface{}{
  1762. "invalid": map[string]interface{}{},
  1763. }
  1764. if mm(result) != mm(currentResult) {
  1765. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1766. }
  1767. // !!! This is actually BAD, because we don't have enough level allowance
  1768. // to accept this file, hence the tree is left unbuilt !!!
  1769. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1770. currentResult = map[string]interface{}{}
  1771. if mm(result) != mm(currentResult) {
  1772. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1773. }
  1774. }
  1775. func genDeepFiles(n, d int) []protocol.FileInfo {
  1776. rand.Seed(int64(n))
  1777. files := make([]protocol.FileInfo, n)
  1778. t := time.Now().Unix()
  1779. for i := 0; i < n; i++ {
  1780. path := ""
  1781. for i := 0; i <= d; i++ {
  1782. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1783. }
  1784. sofar := ""
  1785. for _, path := range filepath.SplitList(path) {
  1786. sofar = filepath.Join(sofar, path)
  1787. files[i] = protocol.FileInfo{
  1788. Name: sofar,
  1789. }
  1790. i++
  1791. }
  1792. files[i].ModifiedS = t
  1793. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1794. }
  1795. return files
  1796. }
  1797. func BenchmarkTree_10000_50(b *testing.B) {
  1798. benchmarkTree(b, 10000, 50)
  1799. }
  1800. func BenchmarkTree_100_50(b *testing.B) {
  1801. benchmarkTree(b, 100, 50)
  1802. }
  1803. func BenchmarkTree_100_10(b *testing.B) {
  1804. benchmarkTree(b, 100, 10)
  1805. }
  1806. func benchmarkTree(b *testing.B, n1, n2 int) {
  1807. db := db.OpenMemory()
  1808. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1809. m.AddFolder(defaultFolderConfig)
  1810. m.ServeBackground()
  1811. m.ScanFolder("default")
  1812. files := genDeepFiles(n1, n2)
  1813. m.Index(device1, "default", files)
  1814. b.ResetTimer()
  1815. for i := 0; i < b.N; i++ {
  1816. m.GlobalDirectoryTree("default", "", -1, false)
  1817. }
  1818. b.ReportAllocs()
  1819. }
  1820. type unifySubsCase struct {
  1821. in []string // input to unifySubs
  1822. exists []string // paths that exist in the database
  1823. out []string // expected output
  1824. }
  1825. func unifySubsCases() []unifySubsCase {
  1826. cases := []unifySubsCase{
  1827. {
  1828. // 0. trailing slashes are cleaned, known paths are just passed on
  1829. []string{"foo/", "bar//"},
  1830. []string{"foo", "bar"},
  1831. []string{"bar", "foo"}, // the output is sorted
  1832. },
  1833. {
  1834. // 1. "foo/bar" gets trimmed as it's covered by foo
  1835. []string{"foo", "bar/", "foo/bar/"},
  1836. []string{"foo", "bar"},
  1837. []string{"bar", "foo"},
  1838. },
  1839. {
  1840. // 2. "" gets simplified to the empty list; ie scan all
  1841. []string{"foo", ""},
  1842. []string{"foo"},
  1843. nil,
  1844. },
  1845. {
  1846. // 3. "foo/bar" is unknown, but it's kept
  1847. // because its parent is known
  1848. []string{"foo/bar"},
  1849. []string{"foo"},
  1850. []string{"foo/bar"},
  1851. },
  1852. {
  1853. // 4. two independent known paths, both are kept
  1854. // "usr/lib" is not a prefix of "usr/libexec"
  1855. []string{"usr/lib", "usr/libexec"},
  1856. []string{"usr", "usr/lib", "usr/libexec"},
  1857. []string{"usr/lib", "usr/libexec"},
  1858. },
  1859. {
  1860. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1861. []string{"usr/lib", "usr/lib/exec"},
  1862. []string{"usr", "usr/lib", "usr/libexec"},
  1863. []string{"usr/lib"},
  1864. },
  1865. {
  1866. // 6. .stignore and .stfolder are special and are passed on
  1867. // verbatim even though they are unknown
  1868. []string{config.DefaultMarkerName, ".stignore"},
  1869. []string{},
  1870. []string{config.DefaultMarkerName, ".stignore"},
  1871. },
  1872. {
  1873. // 7. but the presence of something else unknown forces an actual
  1874. // scan
  1875. []string{config.DefaultMarkerName, ".stignore", "foo/bar"},
  1876. []string{},
  1877. []string{config.DefaultMarkerName, ".stignore", "foo"},
  1878. },
  1879. {
  1880. // 8. explicit request to scan all
  1881. nil,
  1882. []string{"foo"},
  1883. nil,
  1884. },
  1885. {
  1886. // 9. empty list of subs
  1887. []string{},
  1888. []string{"foo"},
  1889. nil,
  1890. },
  1891. }
  1892. if runtime.GOOS == "windows" {
  1893. // Fixup path separators
  1894. for i := range cases {
  1895. for j, p := range cases[i].in {
  1896. cases[i].in[j] = filepath.FromSlash(p)
  1897. }
  1898. for j, p := range cases[i].exists {
  1899. cases[i].exists[j] = filepath.FromSlash(p)
  1900. }
  1901. for j, p := range cases[i].out {
  1902. cases[i].out[j] = filepath.FromSlash(p)
  1903. }
  1904. }
  1905. }
  1906. return cases
  1907. }
  1908. func unifyExists(f string, tc unifySubsCase) bool {
  1909. for _, e := range tc.exists {
  1910. if f == e {
  1911. return true
  1912. }
  1913. }
  1914. return false
  1915. }
  1916. func TestUnifySubs(t *testing.T) {
  1917. cases := unifySubsCases()
  1918. for i, tc := range cases {
  1919. exists := func(f string) bool {
  1920. return unifyExists(f, tc)
  1921. }
  1922. out := unifySubs(tc.in, exists)
  1923. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1924. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1925. }
  1926. }
  1927. }
  1928. func BenchmarkUnifySubs(b *testing.B) {
  1929. cases := unifySubsCases()
  1930. b.ReportAllocs()
  1931. b.ResetTimer()
  1932. for i := 0; i < b.N; i++ {
  1933. for _, tc := range cases {
  1934. exists := func(f string) bool {
  1935. return unifyExists(f, tc)
  1936. }
  1937. unifySubs(tc.in, exists)
  1938. }
  1939. }
  1940. }
  1941. func TestIssue3028(t *testing.T) {
  1942. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1943. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1944. t.Fatal(err)
  1945. }
  1946. defer os.Remove("testdata/testrm")
  1947. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1948. t.Fatal(err)
  1949. }
  1950. defer os.Remove("testdata/testrm2")
  1951. // Create a model and default folder
  1952. db := db.OpenMemory()
  1953. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1954. defCfg := defaultFolderConfig.Copy()
  1955. defCfg.RescanIntervalS = 86400
  1956. m.AddFolder(defCfg)
  1957. m.StartFolder("default")
  1958. m.ServeBackground()
  1959. // Make sure the initial scan has finished (ScanFolders is blocking)
  1960. m.ScanFolders()
  1961. // Get a count of how many files are there now
  1962. locorigfiles := m.LocalSize("default").Files
  1963. globorigfiles := m.GlobalSize("default").Files
  1964. // Delete and rescan specifically these two
  1965. os.Remove("testdata/testrm")
  1966. os.Remove("testdata/testrm2")
  1967. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1968. // Verify that the number of files decreased by two and the number of
  1969. // deleted files increases by two
  1970. loc := m.LocalSize("default")
  1971. glob := m.GlobalSize("default")
  1972. if loc.Files != locorigfiles-2 {
  1973. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1974. }
  1975. if glob.Files != globorigfiles-2 {
  1976. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1977. }
  1978. if loc.Deleted != 2 {
  1979. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1980. }
  1981. if glob.Deleted != 2 {
  1982. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1983. }
  1984. }
  1985. func TestIssue4357(t *testing.T) {
  1986. db := db.OpenMemory()
  1987. cfg := defaultConfig.RawCopy()
  1988. // Create a separate wrapper not to pollute other tests.
  1989. wrapper := config.Wrap("/tmp/test", config.Configuration{})
  1990. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1991. m.ServeBackground()
  1992. defer m.Stop()
  1993. // Force the model to wire itself and add the folders
  1994. p, err := wrapper.Replace(cfg)
  1995. p.Wait()
  1996. if err != nil {
  1997. t.Error(err)
  1998. }
  1999. if _, ok := m.folderCfgs["default"]; !ok {
  2000. t.Error("Folder should be running")
  2001. }
  2002. newCfg := wrapper.RawCopy()
  2003. newCfg.Folders[0].Paused = true
  2004. p, err = wrapper.Replace(newCfg)
  2005. p.Wait()
  2006. if err != nil {
  2007. t.Error(err)
  2008. }
  2009. if _, ok := m.folderCfgs["default"]; ok {
  2010. t.Error("Folder should not be running")
  2011. }
  2012. if _, ok := m.cfg.Folder("default"); !ok {
  2013. t.Error("should still have folder in config")
  2014. }
  2015. p, err = wrapper.Replace(config.Configuration{})
  2016. p.Wait()
  2017. if err != nil {
  2018. t.Error(err)
  2019. }
  2020. if _, ok := m.cfg.Folder("default"); ok {
  2021. t.Error("should not have folder in config")
  2022. }
  2023. // Add the folder back, should be running
  2024. p, err = wrapper.Replace(cfg)
  2025. p.Wait()
  2026. if err != nil {
  2027. t.Error(err)
  2028. }
  2029. if _, ok := m.folderCfgs["default"]; !ok {
  2030. t.Error("Folder should be running")
  2031. }
  2032. if _, ok := m.cfg.Folder("default"); !ok {
  2033. t.Error("should still have folder in config")
  2034. }
  2035. // Should not panic when removing a running folder.
  2036. p, err = wrapper.Replace(config.Configuration{})
  2037. p.Wait()
  2038. if err != nil {
  2039. t.Error(err)
  2040. }
  2041. if _, ok := m.folderCfgs["default"]; ok {
  2042. t.Error("Folder should not be running")
  2043. }
  2044. if _, ok := m.cfg.Folder("default"); ok {
  2045. t.Error("should not have folder in config")
  2046. }
  2047. }
  2048. func TestScanNoDatabaseWrite(t *testing.T) {
  2049. // When scanning, nothing should be committed to database unless
  2050. // something actually changed.
  2051. db := db.OpenMemory()
  2052. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2053. m.AddFolder(defaultFolderConfig)
  2054. m.StartFolder("default")
  2055. m.ServeBackground()
  2056. // Start with no ignores, and restore the previous state when the test completes
  2057. curIgn, _, err := m.GetIgnores("default")
  2058. if err != nil {
  2059. t.Fatal(err)
  2060. }
  2061. defer m.SetIgnores("default", curIgn)
  2062. m.SetIgnores("default", nil)
  2063. fakeTime := time.Now().Add(5 * time.Second)
  2064. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  2065. // Scan the folder twice. The second scan should be a no-op database wise
  2066. m.ScanFolder("default")
  2067. c0 := db.Committed()
  2068. m.ScanFolder("default")
  2069. c1 := db.Committed()
  2070. if c1 != c0 {
  2071. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  2072. }
  2073. // Ignore a file we know exists. It'll be updated in the database.
  2074. m.SetIgnores("default", []string{"foo"})
  2075. fakeTime = time.Now().Add(10 * time.Second)
  2076. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  2077. m.ScanFolder("default")
  2078. c2 := db.Committed()
  2079. if c2 <= c1 {
  2080. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  2081. }
  2082. // Scan again. Nothing should happen.
  2083. m.ScanFolder("default")
  2084. c3 := db.Committed()
  2085. if c3 != c2 {
  2086. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  2087. }
  2088. }
  2089. func TestIssue2782(t *testing.T) {
  2090. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  2091. if runtime.GOOS == "windows" {
  2092. t.Skip("not reliable on Windows")
  2093. return
  2094. }
  2095. home := os.Getenv("HOME")
  2096. if home == "" {
  2097. t.Skip("no home")
  2098. }
  2099. // Create the test env. Needs to be based on $HOME as tilde expansion is
  2100. // part of the issue. Skip the test if any of this fails, as we are a
  2101. // bit outside of our stated domain here...
  2102. testName := ".syncthing-test." + srand.String(16)
  2103. testDir := filepath.Join(home, testName)
  2104. if err := os.RemoveAll(testDir); err != nil {
  2105. t.Skip(err)
  2106. }
  2107. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  2108. t.Skip(err)
  2109. }
  2110. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  2111. t.Skip(err)
  2112. }
  2113. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  2114. t.Skip(err)
  2115. }
  2116. defer os.RemoveAll(testDir)
  2117. db := db.OpenMemory()
  2118. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2119. m.AddFolder(config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  2120. m.StartFolder("default")
  2121. m.ServeBackground()
  2122. defer m.Stop()
  2123. if err := m.ScanFolder("default"); err != nil {
  2124. t.Error("scan error:", err)
  2125. }
  2126. m.fmut.Lock()
  2127. runner, _ := m.folderRunners["default"]
  2128. m.fmut.Unlock()
  2129. if err := runner.CheckHealth(); err != nil {
  2130. t.Error("health check error:", err)
  2131. }
  2132. }
  2133. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  2134. dbi := db.OpenMemory()
  2135. files := db.NewFileSet("default", defaultFs, dbi)
  2136. files.Drop(device1)
  2137. files.Update(device1, genFiles(1))
  2138. files.Drop(device2)
  2139. files.Update(device2, genFiles(1))
  2140. if len(files.ListDevices()) != 2 {
  2141. t.Error("expected two devices")
  2142. }
  2143. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2144. m.AddFolder(defaultFolderConfig)
  2145. m.StartFolder("default")
  2146. // Remote sequence is cached, hence need to recreated.
  2147. files = db.NewFileSet("default", defaultFs, dbi)
  2148. if len(files.ListDevices()) != 1 {
  2149. t.Error("Expected one device")
  2150. }
  2151. }
  2152. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  2153. dbi := db.OpenMemory()
  2154. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2155. fcfg.Devices = []config.FolderDeviceConfiguration{
  2156. {DeviceID: device1},
  2157. {DeviceID: device2},
  2158. }
  2159. cfg := config.Configuration{
  2160. Folders: []config.FolderConfiguration{fcfg},
  2161. Devices: []config.DeviceConfiguration{
  2162. config.NewDeviceConfiguration(device1, "device1"),
  2163. config.NewDeviceConfiguration(device2, "device2"),
  2164. },
  2165. Options: config.OptionsConfiguration{
  2166. // Don't remove temporaries directly on startup
  2167. KeepTemporariesH: 1,
  2168. },
  2169. }
  2170. wcfg := config.Wrap("/tmp/test", cfg)
  2171. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2172. m.AddFolder(fcfg)
  2173. m.StartFolder(fcfg.ID)
  2174. m.ServeBackground()
  2175. conn1 := &fakeConnection{id: device1}
  2176. m.AddConnection(conn1, protocol.HelloResult{})
  2177. conn2 := &fakeConnection{id: device2}
  2178. m.AddConnection(conn2, protocol.HelloResult{})
  2179. m.ClusterConfig(device1, protocol.ClusterConfig{
  2180. Folders: []protocol.Folder{
  2181. {
  2182. ID: "default",
  2183. Devices: []protocol.Device{
  2184. {ID: device1},
  2185. {ID: device2},
  2186. },
  2187. },
  2188. },
  2189. })
  2190. m.ClusterConfig(device2, protocol.ClusterConfig{
  2191. Folders: []protocol.Folder{
  2192. {
  2193. ID: "default",
  2194. Devices: []protocol.Device{
  2195. {ID: device1},
  2196. {ID: device2},
  2197. },
  2198. },
  2199. },
  2200. })
  2201. if !m.folderSharedWith("default", device1) {
  2202. t.Error("not shared with device1")
  2203. }
  2204. if !m.folderSharedWith("default", device2) {
  2205. t.Error("not shared with device2")
  2206. }
  2207. if conn2.Closed() {
  2208. t.Error("conn already closed")
  2209. }
  2210. cfg = cfg.Copy()
  2211. cfg.Devices = cfg.Devices[:1]
  2212. if _, err := wcfg.Replace(cfg); err != nil {
  2213. t.Error(err)
  2214. }
  2215. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  2216. if !m.folderSharedWith("default", device1) {
  2217. t.Error("not shared with device1")
  2218. }
  2219. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  2220. t.Error("shared with device2")
  2221. }
  2222. if !conn2.Closed() {
  2223. t.Error("connection not closed")
  2224. }
  2225. if _, ok := wcfg.Devices()[device2]; ok {
  2226. t.Error("device still in config")
  2227. }
  2228. fdevs, ok := m.folderDevices["default"]
  2229. if !ok {
  2230. t.Error("folder missing?")
  2231. }
  2232. for id := range fdevs {
  2233. if id == device2 {
  2234. t.Error("still there")
  2235. }
  2236. }
  2237. if _, ok := m.conn[device2]; !ok {
  2238. t.Error("conn missing early")
  2239. }
  2240. if _, ok := m.helloMessages[device2]; !ok {
  2241. t.Error("hello missing early")
  2242. }
  2243. if _, ok := m.deviceDownloads[device2]; !ok {
  2244. t.Error("downloads missing early")
  2245. }
  2246. m.Closed(conn2, fmt.Errorf("foo"))
  2247. if _, ok := m.conn[device2]; ok {
  2248. t.Error("conn not missing")
  2249. }
  2250. if _, ok := m.helloMessages[device2]; ok {
  2251. t.Error("hello not missing")
  2252. }
  2253. if _, ok := m.deviceDownloads[device2]; ok {
  2254. t.Error("downloads not missing")
  2255. }
  2256. }
  2257. func TestIssue3496(t *testing.T) {
  2258. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  2259. // It seems like lots of deleted files can cause negative completion
  2260. // percentages. Lets make sure that doesn't happen. Also do some general
  2261. // checks on the completion calculation stuff.
  2262. dbi := db.OpenMemory()
  2263. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2264. m.AddFolder(defaultFolderConfig)
  2265. m.StartFolder("default")
  2266. m.ServeBackground()
  2267. defer m.Stop()
  2268. m.ScanFolder("default")
  2269. addFakeConn(m, device1)
  2270. addFakeConn(m, device2)
  2271. // Reach into the model and grab the current file list...
  2272. m.fmut.RLock()
  2273. fs := m.folderFiles["default"]
  2274. m.fmut.RUnlock()
  2275. var localFiles []protocol.FileInfo
  2276. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  2277. localFiles = append(localFiles, i.(protocol.FileInfo))
  2278. return true
  2279. })
  2280. // Mark all files as deleted and fake it as update from device1
  2281. for i := range localFiles {
  2282. localFiles[i].Deleted = true
  2283. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  2284. localFiles[i].Blocks = nil
  2285. }
  2286. // Also add a small file that we're supposed to need, or the global size
  2287. // stuff will bail out early due to the entire folder being zero size.
  2288. localFiles = append(localFiles, protocol.FileInfo{
  2289. Name: "fake",
  2290. Size: 1234,
  2291. Type: protocol.FileInfoTypeFile,
  2292. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  2293. })
  2294. m.IndexUpdate(device1, "default", localFiles)
  2295. // Check that the completion percentage for us makes sense
  2296. comp := m.Completion(protocol.LocalDeviceID, "default")
  2297. if comp.NeedBytes > comp.GlobalBytes {
  2298. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  2299. }
  2300. if comp.CompletionPct < 0 {
  2301. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  2302. }
  2303. if comp.NeedBytes == 0 {
  2304. t.Error("Need no bytes even though some files are deleted")
  2305. }
  2306. if comp.CompletionPct == 100 {
  2307. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  2308. }
  2309. t.Log(comp)
  2310. // Check that NeedSize does the correct thing
  2311. need := m.NeedSize("default")
  2312. if need.Files != 1 || need.Bytes != 1234 {
  2313. // The one we added synthetically above
  2314. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  2315. }
  2316. if int(need.Deleted) != len(localFiles)-1 {
  2317. // The rest
  2318. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  2319. }
  2320. }
  2321. func TestIssue3804(t *testing.T) {
  2322. dbi := db.OpenMemory()
  2323. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2324. m.AddFolder(defaultFolderConfig)
  2325. m.StartFolder("default")
  2326. m.ServeBackground()
  2327. defer m.Stop()
  2328. // Subdirs ending in slash should be accepted
  2329. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  2330. t.Error("Unexpected error:", err)
  2331. }
  2332. }
  2333. func TestIssue3829(t *testing.T) {
  2334. dbi := db.OpenMemory()
  2335. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2336. m.AddFolder(defaultFolderConfig)
  2337. m.StartFolder("default")
  2338. m.ServeBackground()
  2339. defer m.Stop()
  2340. // Empty subdirs should be accepted
  2341. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  2342. t.Error("Unexpected error:", err)
  2343. }
  2344. }
  2345. func TestNoRequestsFromPausedDevices(t *testing.T) {
  2346. t.Skip("broken, fails randomly, #3843")
  2347. dbi := db.OpenMemory()
  2348. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2349. fcfg.Devices = []config.FolderDeviceConfiguration{
  2350. {DeviceID: device1},
  2351. {DeviceID: device2},
  2352. }
  2353. cfg := config.Configuration{
  2354. Folders: []config.FolderConfiguration{fcfg},
  2355. Devices: []config.DeviceConfiguration{
  2356. config.NewDeviceConfiguration(device1, "device1"),
  2357. config.NewDeviceConfiguration(device2, "device2"),
  2358. },
  2359. Options: config.OptionsConfiguration{
  2360. // Don't remove temporaries directly on startup
  2361. KeepTemporariesH: 1,
  2362. },
  2363. }
  2364. wcfg := config.Wrap("/tmp/test", cfg)
  2365. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2366. m.AddFolder(fcfg)
  2367. m.StartFolder(fcfg.ID)
  2368. m.ServeBackground()
  2369. file := testDataExpected["foo"]
  2370. files := m.folderFiles["default"]
  2371. files.Update(device1, []protocol.FileInfo{file})
  2372. files.Update(device2, []protocol.FileInfo{file})
  2373. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2374. if len(avail) != 0 {
  2375. t.Errorf("should not be available, no connections")
  2376. }
  2377. addFakeConn(m, device1)
  2378. addFakeConn(m, device2)
  2379. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2380. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2381. if len(avail) != 2 {
  2382. t.Errorf("should have two available")
  2383. }
  2384. cc := protocol.ClusterConfig{
  2385. Folders: []protocol.Folder{
  2386. {
  2387. ID: "default",
  2388. Devices: []protocol.Device{
  2389. {ID: device1},
  2390. {ID: device2},
  2391. },
  2392. },
  2393. },
  2394. }
  2395. m.ClusterConfig(device1, cc)
  2396. m.ClusterConfig(device2, cc)
  2397. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2398. if len(avail) != 2 {
  2399. t.Errorf("should have two available")
  2400. }
  2401. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2402. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2403. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2404. if len(avail) != 0 {
  2405. t.Errorf("should have no available")
  2406. }
  2407. // Test that remote paused folders are not used.
  2408. addFakeConn(m, device1)
  2409. addFakeConn(m, device2)
  2410. m.ClusterConfig(device1, cc)
  2411. ccp := cc
  2412. ccp.Folders[0].Paused = true
  2413. m.ClusterConfig(device1, ccp)
  2414. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2415. if len(avail) != 1 {
  2416. t.Errorf("should have one available")
  2417. }
  2418. }
  2419. // TestIssue2571 tests replacing a directory with content with a symlink
  2420. func TestIssue2571(t *testing.T) {
  2421. if runtime.GOOS == "windows" {
  2422. t.Skip("Scanning symlinks isn't supported on windows")
  2423. }
  2424. err := defaultFs.MkdirAll("replaceDir", 0755)
  2425. if err != nil {
  2426. t.Fatal(err)
  2427. }
  2428. defer func() {
  2429. defaultFs.RemoveAll("replaceDir")
  2430. }()
  2431. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "replaceDir"))
  2432. for _, dir := range []string{"toLink", "linkTarget"} {
  2433. err := testFs.MkdirAll(dir, 0775)
  2434. if err != nil {
  2435. t.Fatal(err)
  2436. }
  2437. fd, err := testFs.Create(filepath.Join(dir, "a"))
  2438. if err != nil {
  2439. t.Fatal(err)
  2440. }
  2441. fd.Close()
  2442. }
  2443. dbi := db.OpenMemory()
  2444. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2445. m.AddFolder(defaultFolderConfig)
  2446. m.StartFolder("default")
  2447. m.ServeBackground()
  2448. defer m.Stop()
  2449. m.ScanFolder("default")
  2450. if err = testFs.RemoveAll("toLink"); err != nil {
  2451. t.Fatal(err)
  2452. }
  2453. if err := osutil.DebugSymlinkForTestsOnly(filepath.Join(testFs.URI(), "linkTarget"), filepath.Join(testFs.URI(), "toLink")); err != nil {
  2454. t.Fatal(err)
  2455. }
  2456. m.ScanFolder("default")
  2457. if dir, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink")); !ok {
  2458. t.Fatalf("Dir missing in db")
  2459. } else if !dir.IsSymlink() {
  2460. t.Errorf("Dir wasn't changed to symlink")
  2461. }
  2462. if file, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink", "a")); !ok {
  2463. t.Fatalf("File missing in db")
  2464. } else if !file.Deleted {
  2465. t.Errorf("File below symlink has not been marked as deleted")
  2466. }
  2467. }
  2468. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  2469. func TestIssue4573(t *testing.T) {
  2470. if runtime.GOOS == "windows" {
  2471. t.Skip("Can't make the dir inaccessible on windows")
  2472. }
  2473. err := defaultFs.MkdirAll("inaccessible", 0755)
  2474. if err != nil {
  2475. t.Fatal(err)
  2476. }
  2477. defer func() {
  2478. defaultFs.Chmod("inaccessible", 0777)
  2479. defaultFs.RemoveAll("inaccessible")
  2480. }()
  2481. file := filepath.Join("inaccessible", "a")
  2482. fd, err := defaultFs.Create(file)
  2483. if err != nil {
  2484. t.Fatal(err)
  2485. }
  2486. fd.Close()
  2487. dbi := db.OpenMemory()
  2488. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2489. m.AddFolder(defaultFolderConfig)
  2490. m.StartFolder("default")
  2491. m.ServeBackground()
  2492. defer m.Stop()
  2493. m.ScanFolder("default")
  2494. err = defaultFs.Chmod("inaccessible", 0000)
  2495. if err != nil {
  2496. t.Fatal(err)
  2497. }
  2498. m.ScanFolder("default")
  2499. if file, ok := m.CurrentFolderFile("default", file); !ok {
  2500. t.Fatalf("File missing in db")
  2501. } else if file.Deleted {
  2502. t.Errorf("Inaccessible file has been marked as deleted.")
  2503. }
  2504. }
  2505. // TestInternalScan checks whether various fs operations are correctly represented
  2506. // in the db after scanning.
  2507. func TestInternalScan(t *testing.T) {
  2508. err := defaultFs.MkdirAll("internalScan", 0755)
  2509. if err != nil {
  2510. t.Fatal(err)
  2511. }
  2512. defer func() {
  2513. defaultFs.RemoveAll("internalScan")
  2514. }()
  2515. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "internalScan"))
  2516. testCases := map[string]func(protocol.FileInfo) bool{
  2517. "removeDir": func(f protocol.FileInfo) bool {
  2518. return !f.Deleted
  2519. },
  2520. "dirToFile": func(f protocol.FileInfo) bool {
  2521. return f.Deleted || f.IsDirectory()
  2522. },
  2523. }
  2524. baseDirs := []string{"dirToFile", "removeDir"}
  2525. for _, dir := range baseDirs {
  2526. sub := filepath.Join(dir, "subDir")
  2527. for _, dir := range []string{dir, sub} {
  2528. err := testFs.MkdirAll(dir, 0775)
  2529. if err != nil {
  2530. t.Fatalf("%v: %v", dir, err)
  2531. }
  2532. }
  2533. testCases[sub] = func(f protocol.FileInfo) bool {
  2534. return !f.Deleted
  2535. }
  2536. for _, dir := range []string{dir, sub} {
  2537. file := filepath.Join(dir, "a")
  2538. fd, err := testFs.Create(file)
  2539. if err != nil {
  2540. t.Fatal(err)
  2541. }
  2542. fd.Close()
  2543. testCases[file] = func(f protocol.FileInfo) bool {
  2544. return !f.Deleted
  2545. }
  2546. }
  2547. }
  2548. dbi := db.OpenMemory()
  2549. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2550. m.AddFolder(defaultFolderConfig)
  2551. m.StartFolder("default")
  2552. m.ServeBackground()
  2553. defer m.Stop()
  2554. m.ScanFolder("default")
  2555. for _, dir := range baseDirs {
  2556. if err = testFs.RemoveAll(dir); err != nil {
  2557. t.Fatal(err)
  2558. }
  2559. }
  2560. fd, err := testFs.Create("dirToFile")
  2561. if err != nil {
  2562. t.Fatal(err)
  2563. }
  2564. fd.Close()
  2565. m.ScanFolder("default")
  2566. for path, cond := range testCases {
  2567. if f, ok := m.CurrentFolderFile("default", filepath.Join("internalScan", path)); !ok {
  2568. t.Fatalf("%v missing in db", path)
  2569. } else if cond(f) {
  2570. t.Errorf("Incorrect db entry for %v", path)
  2571. }
  2572. }
  2573. }
  2574. func TestCustomMarkerName(t *testing.T) {
  2575. ldb := db.OpenMemory()
  2576. set := db.NewFileSet("default", defaultFs, ldb)
  2577. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2578. {Name: "dummyfile"},
  2579. })
  2580. fcfg := config.FolderConfiguration{
  2581. ID: "default",
  2582. Path: "testdata/rwtestfolder",
  2583. Type: config.FolderTypeSendReceive,
  2584. RescanIntervalS: 1,
  2585. MarkerName: "myfile",
  2586. }
  2587. cfg := config.Wrap("/tmp/test", config.Configuration{
  2588. Folders: []config.FolderConfiguration{fcfg},
  2589. Devices: []config.DeviceConfiguration{
  2590. {
  2591. DeviceID: device1,
  2592. },
  2593. },
  2594. })
  2595. os.RemoveAll(fcfg.Path)
  2596. defer os.RemoveAll(fcfg.Path)
  2597. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  2598. m.AddFolder(fcfg)
  2599. m.StartFolder("default")
  2600. m.ServeBackground()
  2601. defer m.Stop()
  2602. waitFor := func(status string) error {
  2603. timeout := time.Now().Add(2 * time.Second)
  2604. for {
  2605. _, _, err := m.State("default")
  2606. if err == nil && status == "" {
  2607. return nil
  2608. }
  2609. if err != nil && err.Error() == status {
  2610. return nil
  2611. }
  2612. if time.Now().After(timeout) {
  2613. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  2614. }
  2615. time.Sleep(10 * time.Millisecond)
  2616. }
  2617. }
  2618. if err := waitFor("folder path missing"); err != nil {
  2619. t.Error(err)
  2620. return
  2621. }
  2622. os.Mkdir(fcfg.Path, 0700)
  2623. fd, err := os.Create(filepath.Join(fcfg.Path, "myfile"))
  2624. if err != nil {
  2625. t.Error(err)
  2626. return
  2627. }
  2628. fd.Close()
  2629. if err := waitFor(""); err != nil {
  2630. t.Error(err)
  2631. return
  2632. }
  2633. }
  2634. func TestRemoveDirWithContent(t *testing.T) {
  2635. defer func() {
  2636. defaultFs.RemoveAll("dirwith")
  2637. }()
  2638. defaultFs.MkdirAll("dirwith", 0755)
  2639. content := filepath.Join("dirwith", "content")
  2640. fd, err := defaultFs.Create(content)
  2641. if err != nil {
  2642. t.Fatal(err)
  2643. return
  2644. }
  2645. fd.Close()
  2646. dbi := db.OpenMemory()
  2647. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2648. m.AddFolder(defaultFolderConfig)
  2649. m.StartFolder("default")
  2650. m.ServeBackground()
  2651. defer m.Stop()
  2652. m.ScanFolder("default")
  2653. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2654. if !ok {
  2655. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2656. }
  2657. dir.Deleted = true
  2658. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2659. file, ok := m.CurrentFolderFile("default", content)
  2660. if !ok {
  2661. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2662. }
  2663. file.Deleted = true
  2664. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2665. m.IndexUpdate(device1, "default", []protocol.FileInfo{dir, file})
  2666. // Is there something we could trigger on instead of just waiting?
  2667. timeout := time.NewTimer(5 * time.Second)
  2668. for {
  2669. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2670. if !ok {
  2671. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2672. }
  2673. file, ok := m.CurrentFolderFile("default", content)
  2674. if !ok {
  2675. t.Fatalf("Can't get file \"%v\" after index update", content)
  2676. }
  2677. if dir.Deleted && file.Deleted {
  2678. return
  2679. }
  2680. select {
  2681. case <-timeout.C:
  2682. if !dir.Deleted && !file.Deleted {
  2683. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2684. } else if !dir.Deleted {
  2685. t.Errorf("The dir was not deleted before timing out.")
  2686. } else {
  2687. t.Errorf("The content of the dir was not deleted before timing out.")
  2688. }
  2689. return
  2690. default:
  2691. time.Sleep(100 * time.Millisecond)
  2692. }
  2693. }
  2694. }
  2695. func TestIssue4475(t *testing.T) {
  2696. defer func() {
  2697. defaultFs.RemoveAll("delDir")
  2698. }()
  2699. err := defaultFs.MkdirAll("delDir", 0755)
  2700. if err != nil {
  2701. t.Fatal(err)
  2702. }
  2703. dbi := db.OpenMemory()
  2704. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2705. m.AddFolder(defaultFolderConfig)
  2706. m.StartFolder("default")
  2707. m.ServeBackground()
  2708. defer m.Stop()
  2709. m.ScanFolder("default")
  2710. // Scenario: Dir is deleted locally and before syncing/index exchange
  2711. // happens, a file is create in that dir on the remote.
  2712. // This should result in the directory being recreated and added to the
  2713. // db locally.
  2714. if err = defaultFs.RemoveAll("delDir"); err != nil {
  2715. t.Fatal(err)
  2716. }
  2717. m.ScanFolder("default")
  2718. conn := addFakeConn(m, device1)
  2719. conn.folder = "default"
  2720. if !m.folderSharedWith("default", device1) {
  2721. t.Fatal("not shared with device1")
  2722. }
  2723. fileName := filepath.Join("delDir", "file")
  2724. conn.addFile(fileName, 0644, protocol.FileInfoTypeFile, nil)
  2725. conn.sendIndexUpdate()
  2726. // Is there something we could trigger on instead of just waiting?
  2727. timeout := time.NewTimer(5 * time.Second)
  2728. created := false
  2729. for {
  2730. if !created {
  2731. if _, ok := m.CurrentFolderFile("default", fileName); ok {
  2732. created = true
  2733. }
  2734. } else {
  2735. dir, ok := m.CurrentFolderFile("default", "delDir")
  2736. if !ok {
  2737. t.Fatalf("can't get dir from db")
  2738. }
  2739. if !dir.Deleted {
  2740. return
  2741. }
  2742. }
  2743. select {
  2744. case <-timeout.C:
  2745. if created {
  2746. t.Errorf("Timed out before file from remote was created")
  2747. } else {
  2748. t.Errorf("Timed out before directory was resurrected in db")
  2749. }
  2750. return
  2751. default:
  2752. time.Sleep(100 * time.Millisecond)
  2753. }
  2754. }
  2755. }
  2756. func TestVersionRestore(t *testing.T) {
  2757. // We create a bunch of files which we restore
  2758. // In each file, we write the filename as the content
  2759. // We verify that the content matches at the expected filenames
  2760. // after the restore operation.
  2761. dir, err := ioutil.TempDir("", "")
  2762. if err != nil {
  2763. t.Fatal(err)
  2764. }
  2765. defer os.RemoveAll(dir)
  2766. dbi := db.OpenMemory()
  2767. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, dir)
  2768. fcfg.Versioning.Type = "simple"
  2769. fcfg.FSWatcherEnabled = false
  2770. filesystem := fcfg.Filesystem()
  2771. rawConfig := config.Configuration{
  2772. Folders: []config.FolderConfiguration{fcfg},
  2773. }
  2774. cfg := config.Wrap("/tmp/test", rawConfig)
  2775. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2776. m.AddFolder(fcfg)
  2777. m.StartFolder("default")
  2778. m.ServeBackground()
  2779. defer m.Stop()
  2780. m.ScanFolder("default")
  2781. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20200101-010101", locationLocal)
  2782. if err != nil {
  2783. t.Fatal(err)
  2784. }
  2785. sentinelTag := sentinel.Format(versioner.TimeFormat)
  2786. for _, file := range []string{
  2787. // Versions directory
  2788. ".stversions/file~20171210-040404.txt", // will be restored
  2789. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2790. ".stversions/something~20171210-040404", // will become directory, hence error
  2791. ".stversions/dir/file~20171210-040404.txt",
  2792. ".stversions/dir/file~20171210-040405.txt",
  2793. ".stversions/dir/file~20171210-040406.txt",
  2794. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2795. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2796. ".stversions/dir/file.txt~20171210-040405", // incorrect tag format, ignored.
  2797. ".stversions/dir/cat", // incorrect tag format, ignored.
  2798. // "file.txt" will be restored
  2799. "existing",
  2800. "something/file", // Becomes directory
  2801. "dir/file.txt",
  2802. "dir/existing.txt",
  2803. } {
  2804. if runtime.GOOS == "windows" {
  2805. file = filepath.FromSlash(file)
  2806. }
  2807. dir := filepath.Dir(file)
  2808. if err := filesystem.MkdirAll(dir, 0755); err != nil {
  2809. t.Fatal(err)
  2810. }
  2811. if fd, err := filesystem.Create(file); err != nil {
  2812. t.Fatal(err)
  2813. } else if _, err := fd.Write([]byte(file)); err != nil {
  2814. t.Fatal(err)
  2815. } else if err := fd.Close(); err != nil {
  2816. t.Fatal(err)
  2817. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2818. t.Fatal(err)
  2819. }
  2820. }
  2821. versions, err := m.GetFolderVersions("default")
  2822. if err != nil {
  2823. t.Fatal(err)
  2824. }
  2825. expectedVersions := map[string]int{
  2826. "file.txt": 1,
  2827. "existing": 1,
  2828. "something": 1,
  2829. "dir/file.txt": 3,
  2830. "dir/existing.txt": 1,
  2831. "very/very/deep/one.txt": 1,
  2832. }
  2833. for name, vers := range versions {
  2834. cnt, ok := expectedVersions[name]
  2835. if !ok {
  2836. t.Errorf("unexpected %s", name)
  2837. }
  2838. if len(vers) != cnt {
  2839. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2840. }
  2841. // Delete, so we can check if we didn't hit something we expect afterwards.
  2842. delete(expectedVersions, name)
  2843. }
  2844. for name := range expectedVersions {
  2845. t.Errorf("not found expected %s", name)
  2846. }
  2847. // Restoring non existing folder fails.
  2848. _, err = m.RestoreFolderVersions("does not exist", nil)
  2849. if err == nil {
  2850. t.Errorf("expected an error")
  2851. }
  2852. makeTime := func(s string) time.Time {
  2853. tm, err := time.ParseInLocation(versioner.TimeFormat, s, locationLocal)
  2854. if err != nil {
  2855. t.Error(err)
  2856. }
  2857. return tm.Truncate(time.Second)
  2858. }
  2859. restore := map[string]time.Time{
  2860. "file.txt": makeTime("20171210-040404"),
  2861. "existing": makeTime("20171210-040404"),
  2862. "something": makeTime("20171210-040404"),
  2863. "dir/file.txt": makeTime("20171210-040406"),
  2864. "dir/existing.txt": makeTime("20171210-040406"),
  2865. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2866. }
  2867. ferr, err := m.RestoreFolderVersions("default", restore)
  2868. if err != nil {
  2869. t.Fatal(err)
  2870. }
  2871. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || err != "cannot replace a non-file" {
  2872. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2873. }
  2874. // Failed items are not expected to be restored.
  2875. // Remove them from expectations
  2876. for name := range ferr {
  2877. delete(restore, name)
  2878. }
  2879. // Check that content of files matches to the version they've been restored.
  2880. for file, version := range restore {
  2881. if runtime.GOOS == "windows" {
  2882. file = filepath.FromSlash(file)
  2883. }
  2884. tag := version.In(locationLocal).Truncate(time.Second).Format(versioner.TimeFormat)
  2885. taggedName := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2886. fd, err := filesystem.Open(file)
  2887. if err != nil {
  2888. t.Error(err)
  2889. }
  2890. defer fd.Close()
  2891. content, err := ioutil.ReadAll(fd)
  2892. if err != nil {
  2893. t.Error(err)
  2894. }
  2895. if !bytes.Equal(content, []byte(taggedName)) {
  2896. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2897. }
  2898. }
  2899. // Simple versioner uses modtime for timestamp generation, so we can check
  2900. // if existing stuff was correctly archived as we restored.
  2901. expectArchived := map[string]struct{}{
  2902. "existing": {},
  2903. "dir/file.txt": {},
  2904. "dir/existing.txt": {},
  2905. }
  2906. // Even if they are at the archived path, content should have the non
  2907. // archived name.
  2908. for file := range expectArchived {
  2909. if runtime.GOOS == "windows" {
  2910. file = filepath.FromSlash(file)
  2911. }
  2912. taggedName := versioner.TagFilename(file, sentinelTag)
  2913. taggedArchivedName := filepath.Join(".stversions", taggedName)
  2914. fd, err := filesystem.Open(taggedArchivedName)
  2915. if err != nil {
  2916. t.Fatal(err)
  2917. }
  2918. defer fd.Close()
  2919. content, err := ioutil.ReadAll(fd)
  2920. if err != nil {
  2921. t.Error(err)
  2922. }
  2923. if !bytes.Equal(content, []byte(file)) {
  2924. t.Errorf("%s: %s != %s", file, string(content), file)
  2925. }
  2926. }
  2927. // Check for other unexpected things that are tagged.
  2928. filesystem.Walk(".", func(path string, f fs.FileInfo, err error) error {
  2929. if !f.IsRegular() {
  2930. return nil
  2931. }
  2932. if strings.Contains(path, sentinelTag) {
  2933. path = osutil.NormalizedFilename(path)
  2934. name, _ := versioner.UntagFilename(path)
  2935. name = strings.TrimPrefix(name, ".stversions/")
  2936. if _, ok := expectArchived[name]; !ok {
  2937. t.Errorf("unexpected file with sentinel tag: %s", name)
  2938. }
  2939. }
  2940. return nil
  2941. })
  2942. }
  2943. func TestPausedFolders(t *testing.T) {
  2944. // Create a separate wrapper not to pollute other tests.
  2945. cfg := defaultConfig.RawCopy()
  2946. wrapper := config.Wrap("/tmp/test", cfg)
  2947. db := db.OpenMemory()
  2948. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2949. m.AddFolder(defaultFolderConfig)
  2950. m.StartFolder("default")
  2951. m.ServeBackground()
  2952. defer m.Stop()
  2953. if err := m.ScanFolder("default"); err != nil {
  2954. t.Error(err)
  2955. }
  2956. pausedConfig := wrapper.RawCopy()
  2957. pausedConfig.Folders[0].Paused = true
  2958. w, err := m.cfg.Replace(pausedConfig)
  2959. if err != nil {
  2960. t.Fatal(err)
  2961. }
  2962. w.Wait()
  2963. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2964. t.Errorf("Expected folder paused error, received: %v", err)
  2965. }
  2966. if err := m.ScanFolder("nonexistent"); err != errFolderMissing {
  2967. t.Errorf("Expected missing folder error, received: %v", err)
  2968. }
  2969. }
  2970. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2971. fc := &fakeConnection{id: dev, model: m}
  2972. m.AddConnection(fc, protocol.HelloResult{})
  2973. m.ClusterConfig(dev, protocol.ClusterConfig{
  2974. Folders: []protocol.Folder{
  2975. {
  2976. ID: "default",
  2977. Devices: []protocol.Device{
  2978. {ID: device1},
  2979. {ID: device2},
  2980. },
  2981. },
  2982. },
  2983. })
  2984. return fc
  2985. }
  2986. type fakeAddr struct{}
  2987. func (fakeAddr) Network() string {
  2988. return "network"
  2989. }
  2990. func (fakeAddr) String() string {
  2991. return "address"
  2992. }
  2993. type alwaysChangedKey struct {
  2994. fs fs.Filesystem
  2995. name string
  2996. }
  2997. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  2998. type alwaysChanged struct {
  2999. seen map[alwaysChangedKey]struct{}
  3000. }
  3001. func newAlwaysChanged() *alwaysChanged {
  3002. return &alwaysChanged{
  3003. seen: make(map[alwaysChangedKey]struct{}),
  3004. }
  3005. }
  3006. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  3007. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  3008. }
  3009. func (c *alwaysChanged) Reset() {
  3010. c.seen = make(map[alwaysChangedKey]struct{})
  3011. }
  3012. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  3013. _, ok := c.seen[alwaysChangedKey{fs, name}]
  3014. return ok
  3015. }
  3016. func (c *alwaysChanged) Changed() bool {
  3017. return true
  3018. }