model_test.go 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511
  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. // 10. absolute path
  1893. []string{"/foo"},
  1894. []string{"foo"},
  1895. []string{"foo"},
  1896. },
  1897. }
  1898. if runtime.GOOS == "windows" {
  1899. // Fixup path separators
  1900. for i := range cases {
  1901. for j, p := range cases[i].in {
  1902. cases[i].in[j] = filepath.FromSlash(p)
  1903. }
  1904. for j, p := range cases[i].exists {
  1905. cases[i].exists[j] = filepath.FromSlash(p)
  1906. }
  1907. for j, p := range cases[i].out {
  1908. cases[i].out[j] = filepath.FromSlash(p)
  1909. }
  1910. }
  1911. }
  1912. return cases
  1913. }
  1914. func unifyExists(f string, tc unifySubsCase) bool {
  1915. for _, e := range tc.exists {
  1916. if f == e {
  1917. return true
  1918. }
  1919. }
  1920. return false
  1921. }
  1922. func TestUnifySubs(t *testing.T) {
  1923. cases := unifySubsCases()
  1924. for i, tc := range cases {
  1925. exists := func(f string) bool {
  1926. return unifyExists(f, tc)
  1927. }
  1928. out := unifySubs(tc.in, exists)
  1929. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1930. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1931. }
  1932. }
  1933. }
  1934. func BenchmarkUnifySubs(b *testing.B) {
  1935. cases := unifySubsCases()
  1936. b.ReportAllocs()
  1937. b.ResetTimer()
  1938. for i := 0; i < b.N; i++ {
  1939. for _, tc := range cases {
  1940. exists := func(f string) bool {
  1941. return unifyExists(f, tc)
  1942. }
  1943. unifySubs(tc.in, exists)
  1944. }
  1945. }
  1946. }
  1947. func TestIssue3028(t *testing.T) {
  1948. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1949. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1950. t.Fatal(err)
  1951. }
  1952. defer os.Remove("testdata/testrm")
  1953. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1954. t.Fatal(err)
  1955. }
  1956. defer os.Remove("testdata/testrm2")
  1957. // Create a model and default folder
  1958. db := db.OpenMemory()
  1959. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1960. defCfg := defaultFolderConfig.Copy()
  1961. defCfg.RescanIntervalS = 86400
  1962. m.AddFolder(defCfg)
  1963. m.StartFolder("default")
  1964. m.ServeBackground()
  1965. // Make sure the initial scan has finished (ScanFolders is blocking)
  1966. m.ScanFolders()
  1967. // Get a count of how many files are there now
  1968. locorigfiles := m.LocalSize("default").Files
  1969. globorigfiles := m.GlobalSize("default").Files
  1970. // Delete and rescan specifically these two
  1971. os.Remove("testdata/testrm")
  1972. os.Remove("testdata/testrm2")
  1973. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1974. // Verify that the number of files decreased by two and the number of
  1975. // deleted files increases by two
  1976. loc := m.LocalSize("default")
  1977. glob := m.GlobalSize("default")
  1978. if loc.Files != locorigfiles-2 {
  1979. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1980. }
  1981. if glob.Files != globorigfiles-2 {
  1982. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1983. }
  1984. if loc.Deleted != 2 {
  1985. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1986. }
  1987. if glob.Deleted != 2 {
  1988. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1989. }
  1990. }
  1991. func TestIssue4357(t *testing.T) {
  1992. db := db.OpenMemory()
  1993. cfg := defaultConfig.RawCopy()
  1994. // Create a separate wrapper not to pollute other tests.
  1995. wrapper := config.Wrap("/tmp/test", config.Configuration{})
  1996. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1997. m.ServeBackground()
  1998. defer m.Stop()
  1999. // Force the model to wire itself and add the folders
  2000. p, err := wrapper.Replace(cfg)
  2001. p.Wait()
  2002. if err != nil {
  2003. t.Error(err)
  2004. }
  2005. if _, ok := m.folderCfgs["default"]; !ok {
  2006. t.Error("Folder should be running")
  2007. }
  2008. newCfg := wrapper.RawCopy()
  2009. newCfg.Folders[0].Paused = true
  2010. p, err = wrapper.Replace(newCfg)
  2011. p.Wait()
  2012. if err != nil {
  2013. t.Error(err)
  2014. }
  2015. if _, ok := m.folderCfgs["default"]; ok {
  2016. t.Error("Folder should not be running")
  2017. }
  2018. if _, ok := m.cfg.Folder("default"); !ok {
  2019. t.Error("should still have folder in config")
  2020. }
  2021. p, err = wrapper.Replace(config.Configuration{})
  2022. p.Wait()
  2023. if err != nil {
  2024. t.Error(err)
  2025. }
  2026. if _, ok := m.cfg.Folder("default"); ok {
  2027. t.Error("should not have folder in config")
  2028. }
  2029. // Add the folder back, should be running
  2030. p, err = wrapper.Replace(cfg)
  2031. p.Wait()
  2032. if err != nil {
  2033. t.Error(err)
  2034. }
  2035. if _, ok := m.folderCfgs["default"]; !ok {
  2036. t.Error("Folder should be running")
  2037. }
  2038. if _, ok := m.cfg.Folder("default"); !ok {
  2039. t.Error("should still have folder in config")
  2040. }
  2041. // Should not panic when removing a running folder.
  2042. p, err = wrapper.Replace(config.Configuration{})
  2043. p.Wait()
  2044. if err != nil {
  2045. t.Error(err)
  2046. }
  2047. if _, ok := m.folderCfgs["default"]; ok {
  2048. t.Error("Folder should not be running")
  2049. }
  2050. if _, ok := m.cfg.Folder("default"); ok {
  2051. t.Error("should not have folder in config")
  2052. }
  2053. }
  2054. func TestScanNoDatabaseWrite(t *testing.T) {
  2055. // When scanning, nothing should be committed to database unless
  2056. // something actually changed.
  2057. db := db.OpenMemory()
  2058. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2059. m.AddFolder(defaultFolderConfig)
  2060. m.StartFolder("default")
  2061. m.ServeBackground()
  2062. // Start with no ignores, and restore the previous state when the test completes
  2063. curIgn, _, err := m.GetIgnores("default")
  2064. if err != nil {
  2065. t.Fatal(err)
  2066. }
  2067. defer m.SetIgnores("default", curIgn)
  2068. m.SetIgnores("default", nil)
  2069. fakeTime := time.Now().Add(5 * time.Second)
  2070. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  2071. // Scan the folder twice. The second scan should be a no-op database wise
  2072. m.ScanFolder("default")
  2073. c0 := db.Committed()
  2074. m.ScanFolder("default")
  2075. c1 := db.Committed()
  2076. if c1 != c0 {
  2077. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  2078. }
  2079. // Ignore a file we know exists. It'll be updated in the database.
  2080. m.SetIgnores("default", []string{"foo"})
  2081. fakeTime = time.Now().Add(10 * time.Second)
  2082. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  2083. m.ScanFolder("default")
  2084. c2 := db.Committed()
  2085. if c2 <= c1 {
  2086. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  2087. }
  2088. // Scan again. Nothing should happen.
  2089. m.ScanFolder("default")
  2090. c3 := db.Committed()
  2091. if c3 != c2 {
  2092. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  2093. }
  2094. }
  2095. func TestIssue2782(t *testing.T) {
  2096. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  2097. if runtime.GOOS == "windows" {
  2098. t.Skip("not reliable on Windows")
  2099. return
  2100. }
  2101. home := os.Getenv("HOME")
  2102. if home == "" {
  2103. t.Skip("no home")
  2104. }
  2105. // Create the test env. Needs to be based on $HOME as tilde expansion is
  2106. // part of the issue. Skip the test if any of this fails, as we are a
  2107. // bit outside of our stated domain here...
  2108. testName := ".syncthing-test." + srand.String(16)
  2109. testDir := filepath.Join(home, testName)
  2110. if err := os.RemoveAll(testDir); err != nil {
  2111. t.Skip(err)
  2112. }
  2113. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  2114. t.Skip(err)
  2115. }
  2116. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  2117. t.Skip(err)
  2118. }
  2119. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  2120. t.Skip(err)
  2121. }
  2122. defer os.RemoveAll(testDir)
  2123. db := db.OpenMemory()
  2124. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2125. m.AddFolder(config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  2126. m.StartFolder("default")
  2127. m.ServeBackground()
  2128. defer m.Stop()
  2129. if err := m.ScanFolder("default"); err != nil {
  2130. t.Error("scan error:", err)
  2131. }
  2132. m.fmut.Lock()
  2133. runner, _ := m.folderRunners["default"]
  2134. m.fmut.Unlock()
  2135. if err := runner.CheckHealth(); err != nil {
  2136. t.Error("health check error:", err)
  2137. }
  2138. }
  2139. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  2140. dbi := db.OpenMemory()
  2141. files := db.NewFileSet("default", defaultFs, dbi)
  2142. files.Drop(device1)
  2143. files.Update(device1, genFiles(1))
  2144. files.Drop(device2)
  2145. files.Update(device2, genFiles(1))
  2146. if len(files.ListDevices()) != 2 {
  2147. t.Error("expected two devices")
  2148. }
  2149. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2150. m.AddFolder(defaultFolderConfig)
  2151. m.StartFolder("default")
  2152. // Remote sequence is cached, hence need to recreated.
  2153. files = db.NewFileSet("default", defaultFs, dbi)
  2154. if len(files.ListDevices()) != 1 {
  2155. t.Error("Expected one device")
  2156. }
  2157. }
  2158. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  2159. dbi := db.OpenMemory()
  2160. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2161. fcfg.Devices = []config.FolderDeviceConfiguration{
  2162. {DeviceID: device1},
  2163. {DeviceID: device2},
  2164. }
  2165. cfg := config.Configuration{
  2166. Folders: []config.FolderConfiguration{fcfg},
  2167. Devices: []config.DeviceConfiguration{
  2168. config.NewDeviceConfiguration(device1, "device1"),
  2169. config.NewDeviceConfiguration(device2, "device2"),
  2170. },
  2171. Options: config.OptionsConfiguration{
  2172. // Don't remove temporaries directly on startup
  2173. KeepTemporariesH: 1,
  2174. },
  2175. }
  2176. wcfg := config.Wrap("/tmp/test", cfg)
  2177. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2178. m.AddFolder(fcfg)
  2179. m.StartFolder(fcfg.ID)
  2180. m.ServeBackground()
  2181. conn1 := &fakeConnection{id: device1}
  2182. m.AddConnection(conn1, protocol.HelloResult{})
  2183. conn2 := &fakeConnection{id: device2}
  2184. m.AddConnection(conn2, protocol.HelloResult{})
  2185. m.ClusterConfig(device1, protocol.ClusterConfig{
  2186. Folders: []protocol.Folder{
  2187. {
  2188. ID: "default",
  2189. Devices: []protocol.Device{
  2190. {ID: device1},
  2191. {ID: device2},
  2192. },
  2193. },
  2194. },
  2195. })
  2196. m.ClusterConfig(device2, protocol.ClusterConfig{
  2197. Folders: []protocol.Folder{
  2198. {
  2199. ID: "default",
  2200. Devices: []protocol.Device{
  2201. {ID: device1},
  2202. {ID: device2},
  2203. },
  2204. },
  2205. },
  2206. })
  2207. if !m.folderSharedWith("default", device1) {
  2208. t.Error("not shared with device1")
  2209. }
  2210. if !m.folderSharedWith("default", device2) {
  2211. t.Error("not shared with device2")
  2212. }
  2213. if conn2.Closed() {
  2214. t.Error("conn already closed")
  2215. }
  2216. cfg = cfg.Copy()
  2217. cfg.Devices = cfg.Devices[:1]
  2218. if _, err := wcfg.Replace(cfg); err != nil {
  2219. t.Error(err)
  2220. }
  2221. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  2222. if !m.folderSharedWith("default", device1) {
  2223. t.Error("not shared with device1")
  2224. }
  2225. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  2226. t.Error("shared with device2")
  2227. }
  2228. if !conn2.Closed() {
  2229. t.Error("connection not closed")
  2230. }
  2231. if _, ok := wcfg.Devices()[device2]; ok {
  2232. t.Error("device still in config")
  2233. }
  2234. fdevs, ok := m.folderDevices["default"]
  2235. if !ok {
  2236. t.Error("folder missing?")
  2237. }
  2238. for id := range fdevs {
  2239. if id == device2 {
  2240. t.Error("still there")
  2241. }
  2242. }
  2243. if _, ok := m.conn[device2]; !ok {
  2244. t.Error("conn missing early")
  2245. }
  2246. if _, ok := m.helloMessages[device2]; !ok {
  2247. t.Error("hello missing early")
  2248. }
  2249. if _, ok := m.deviceDownloads[device2]; !ok {
  2250. t.Error("downloads missing early")
  2251. }
  2252. m.Closed(conn2, fmt.Errorf("foo"))
  2253. if _, ok := m.conn[device2]; ok {
  2254. t.Error("conn not missing")
  2255. }
  2256. if _, ok := m.helloMessages[device2]; ok {
  2257. t.Error("hello not missing")
  2258. }
  2259. if _, ok := m.deviceDownloads[device2]; ok {
  2260. t.Error("downloads not missing")
  2261. }
  2262. }
  2263. func TestIssue3496(t *testing.T) {
  2264. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  2265. // It seems like lots of deleted files can cause negative completion
  2266. // percentages. Lets make sure that doesn't happen. Also do some general
  2267. // checks on the completion calculation stuff.
  2268. dbi := db.OpenMemory()
  2269. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2270. m.AddFolder(defaultFolderConfig)
  2271. m.StartFolder("default")
  2272. m.ServeBackground()
  2273. defer m.Stop()
  2274. m.ScanFolder("default")
  2275. addFakeConn(m, device1)
  2276. addFakeConn(m, device2)
  2277. // Reach into the model and grab the current file list...
  2278. m.fmut.RLock()
  2279. fs := m.folderFiles["default"]
  2280. m.fmut.RUnlock()
  2281. var localFiles []protocol.FileInfo
  2282. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  2283. localFiles = append(localFiles, i.(protocol.FileInfo))
  2284. return true
  2285. })
  2286. // Mark all files as deleted and fake it as update from device1
  2287. for i := range localFiles {
  2288. localFiles[i].Deleted = true
  2289. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  2290. localFiles[i].Blocks = nil
  2291. }
  2292. // Also add a small file that we're supposed to need, or the global size
  2293. // stuff will bail out early due to the entire folder being zero size.
  2294. localFiles = append(localFiles, protocol.FileInfo{
  2295. Name: "fake",
  2296. Size: 1234,
  2297. Type: protocol.FileInfoTypeFile,
  2298. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  2299. })
  2300. m.IndexUpdate(device1, "default", localFiles)
  2301. // Check that the completion percentage for us makes sense
  2302. comp := m.Completion(protocol.LocalDeviceID, "default")
  2303. if comp.NeedBytes > comp.GlobalBytes {
  2304. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  2305. }
  2306. if comp.CompletionPct < 0 {
  2307. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  2308. }
  2309. if comp.NeedBytes == 0 {
  2310. t.Error("Need no bytes even though some files are deleted")
  2311. }
  2312. if comp.CompletionPct == 100 {
  2313. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  2314. }
  2315. t.Log(comp)
  2316. // Check that NeedSize does the correct thing
  2317. need := m.NeedSize("default")
  2318. if need.Files != 1 || need.Bytes != 1234 {
  2319. // The one we added synthetically above
  2320. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  2321. }
  2322. if int(need.Deleted) != len(localFiles)-1 {
  2323. // The rest
  2324. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  2325. }
  2326. }
  2327. func TestIssue3804(t *testing.T) {
  2328. dbi := db.OpenMemory()
  2329. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2330. m.AddFolder(defaultFolderConfig)
  2331. m.StartFolder("default")
  2332. m.ServeBackground()
  2333. defer m.Stop()
  2334. // Subdirs ending in slash should be accepted
  2335. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  2336. t.Error("Unexpected error:", err)
  2337. }
  2338. }
  2339. func TestIssue3829(t *testing.T) {
  2340. dbi := db.OpenMemory()
  2341. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2342. m.AddFolder(defaultFolderConfig)
  2343. m.StartFolder("default")
  2344. m.ServeBackground()
  2345. defer m.Stop()
  2346. // Empty subdirs should be accepted
  2347. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  2348. t.Error("Unexpected error:", err)
  2349. }
  2350. }
  2351. func TestNoRequestsFromPausedDevices(t *testing.T) {
  2352. t.Skip("broken, fails randomly, #3843")
  2353. dbi := db.OpenMemory()
  2354. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2355. fcfg.Devices = []config.FolderDeviceConfiguration{
  2356. {DeviceID: device1},
  2357. {DeviceID: device2},
  2358. }
  2359. cfg := config.Configuration{
  2360. Folders: []config.FolderConfiguration{fcfg},
  2361. Devices: []config.DeviceConfiguration{
  2362. config.NewDeviceConfiguration(device1, "device1"),
  2363. config.NewDeviceConfiguration(device2, "device2"),
  2364. },
  2365. Options: config.OptionsConfiguration{
  2366. // Don't remove temporaries directly on startup
  2367. KeepTemporariesH: 1,
  2368. },
  2369. }
  2370. wcfg := config.Wrap("/tmp/test", cfg)
  2371. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2372. m.AddFolder(fcfg)
  2373. m.StartFolder(fcfg.ID)
  2374. m.ServeBackground()
  2375. file := testDataExpected["foo"]
  2376. files := m.folderFiles["default"]
  2377. files.Update(device1, []protocol.FileInfo{file})
  2378. files.Update(device2, []protocol.FileInfo{file})
  2379. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2380. if len(avail) != 0 {
  2381. t.Errorf("should not be available, no connections")
  2382. }
  2383. addFakeConn(m, device1)
  2384. addFakeConn(m, device2)
  2385. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2386. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2387. if len(avail) != 2 {
  2388. t.Errorf("should have two available")
  2389. }
  2390. cc := protocol.ClusterConfig{
  2391. Folders: []protocol.Folder{
  2392. {
  2393. ID: "default",
  2394. Devices: []protocol.Device{
  2395. {ID: device1},
  2396. {ID: device2},
  2397. },
  2398. },
  2399. },
  2400. }
  2401. m.ClusterConfig(device1, cc)
  2402. m.ClusterConfig(device2, cc)
  2403. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2404. if len(avail) != 2 {
  2405. t.Errorf("should have two available")
  2406. }
  2407. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2408. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2409. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2410. if len(avail) != 0 {
  2411. t.Errorf("should have no available")
  2412. }
  2413. // Test that remote paused folders are not used.
  2414. addFakeConn(m, device1)
  2415. addFakeConn(m, device2)
  2416. m.ClusterConfig(device1, cc)
  2417. ccp := cc
  2418. ccp.Folders[0].Paused = true
  2419. m.ClusterConfig(device1, ccp)
  2420. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2421. if len(avail) != 1 {
  2422. t.Errorf("should have one available")
  2423. }
  2424. }
  2425. // TestIssue2571 tests replacing a directory with content with a symlink
  2426. func TestIssue2571(t *testing.T) {
  2427. if runtime.GOOS == "windows" {
  2428. t.Skip("Scanning symlinks isn't supported on windows")
  2429. }
  2430. err := defaultFs.MkdirAll("replaceDir", 0755)
  2431. if err != nil {
  2432. t.Fatal(err)
  2433. }
  2434. defer func() {
  2435. defaultFs.RemoveAll("replaceDir")
  2436. }()
  2437. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "replaceDir"))
  2438. for _, dir := range []string{"toLink", "linkTarget"} {
  2439. err := testFs.MkdirAll(dir, 0775)
  2440. if err != nil {
  2441. t.Fatal(err)
  2442. }
  2443. fd, err := testFs.Create(filepath.Join(dir, "a"))
  2444. if err != nil {
  2445. t.Fatal(err)
  2446. }
  2447. fd.Close()
  2448. }
  2449. dbi := db.OpenMemory()
  2450. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2451. m.AddFolder(defaultFolderConfig)
  2452. m.StartFolder("default")
  2453. m.ServeBackground()
  2454. defer m.Stop()
  2455. m.ScanFolder("default")
  2456. if err = testFs.RemoveAll("toLink"); err != nil {
  2457. t.Fatal(err)
  2458. }
  2459. if err := osutil.DebugSymlinkForTestsOnly(filepath.Join(testFs.URI(), "linkTarget"), filepath.Join(testFs.URI(), "toLink")); err != nil {
  2460. t.Fatal(err)
  2461. }
  2462. m.ScanFolder("default")
  2463. if dir, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink")); !ok {
  2464. t.Fatalf("Dir missing in db")
  2465. } else if !dir.IsSymlink() {
  2466. t.Errorf("Dir wasn't changed to symlink")
  2467. }
  2468. if file, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink", "a")); !ok {
  2469. t.Fatalf("File missing in db")
  2470. } else if !file.Deleted {
  2471. t.Errorf("File below symlink has not been marked as deleted")
  2472. }
  2473. }
  2474. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  2475. func TestIssue4573(t *testing.T) {
  2476. if runtime.GOOS == "windows" {
  2477. t.Skip("Can't make the dir inaccessible on windows")
  2478. }
  2479. err := defaultFs.MkdirAll("inaccessible", 0755)
  2480. if err != nil {
  2481. t.Fatal(err)
  2482. }
  2483. defer func() {
  2484. defaultFs.Chmod("inaccessible", 0777)
  2485. defaultFs.RemoveAll("inaccessible")
  2486. }()
  2487. file := filepath.Join("inaccessible", "a")
  2488. fd, err := defaultFs.Create(file)
  2489. if err != nil {
  2490. t.Fatal(err)
  2491. }
  2492. fd.Close()
  2493. dbi := db.OpenMemory()
  2494. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2495. m.AddFolder(defaultFolderConfig)
  2496. m.StartFolder("default")
  2497. m.ServeBackground()
  2498. defer m.Stop()
  2499. m.ScanFolder("default")
  2500. err = defaultFs.Chmod("inaccessible", 0000)
  2501. if err != nil {
  2502. t.Fatal(err)
  2503. }
  2504. m.ScanFolder("default")
  2505. if file, ok := m.CurrentFolderFile("default", file); !ok {
  2506. t.Fatalf("File missing in db")
  2507. } else if file.Deleted {
  2508. t.Errorf("Inaccessible file has been marked as deleted.")
  2509. }
  2510. }
  2511. // TestInternalScan checks whether various fs operations are correctly represented
  2512. // in the db after scanning.
  2513. func TestInternalScan(t *testing.T) {
  2514. err := defaultFs.MkdirAll("internalScan", 0755)
  2515. if err != nil {
  2516. t.Fatal(err)
  2517. }
  2518. defer func() {
  2519. defaultFs.RemoveAll("internalScan")
  2520. }()
  2521. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "internalScan"))
  2522. testCases := map[string]func(protocol.FileInfo) bool{
  2523. "removeDir": func(f protocol.FileInfo) bool {
  2524. return !f.Deleted
  2525. },
  2526. "dirToFile": func(f protocol.FileInfo) bool {
  2527. return f.Deleted || f.IsDirectory()
  2528. },
  2529. }
  2530. baseDirs := []string{"dirToFile", "removeDir"}
  2531. for _, dir := range baseDirs {
  2532. sub := filepath.Join(dir, "subDir")
  2533. for _, dir := range []string{dir, sub} {
  2534. err := testFs.MkdirAll(dir, 0775)
  2535. if err != nil {
  2536. t.Fatalf("%v: %v", dir, err)
  2537. }
  2538. }
  2539. testCases[sub] = func(f protocol.FileInfo) bool {
  2540. return !f.Deleted
  2541. }
  2542. for _, dir := range []string{dir, sub} {
  2543. file := filepath.Join(dir, "a")
  2544. fd, err := testFs.Create(file)
  2545. if err != nil {
  2546. t.Fatal(err)
  2547. }
  2548. fd.Close()
  2549. testCases[file] = func(f protocol.FileInfo) bool {
  2550. return !f.Deleted
  2551. }
  2552. }
  2553. }
  2554. dbi := db.OpenMemory()
  2555. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2556. m.AddFolder(defaultFolderConfig)
  2557. m.StartFolder("default")
  2558. m.ServeBackground()
  2559. defer m.Stop()
  2560. m.ScanFolder("default")
  2561. for _, dir := range baseDirs {
  2562. if err = testFs.RemoveAll(dir); err != nil {
  2563. t.Fatal(err)
  2564. }
  2565. }
  2566. fd, err := testFs.Create("dirToFile")
  2567. if err != nil {
  2568. t.Fatal(err)
  2569. }
  2570. fd.Close()
  2571. m.ScanFolder("default")
  2572. for path, cond := range testCases {
  2573. if f, ok := m.CurrentFolderFile("default", filepath.Join("internalScan", path)); !ok {
  2574. t.Fatalf("%v missing in db", path)
  2575. } else if cond(f) {
  2576. t.Errorf("Incorrect db entry for %v", path)
  2577. }
  2578. }
  2579. }
  2580. func TestCustomMarkerName(t *testing.T) {
  2581. ldb := db.OpenMemory()
  2582. set := db.NewFileSet("default", defaultFs, ldb)
  2583. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2584. {Name: "dummyfile"},
  2585. })
  2586. fcfg := config.FolderConfiguration{
  2587. ID: "default",
  2588. Path: "testdata/rwtestfolder",
  2589. Type: config.FolderTypeSendReceive,
  2590. RescanIntervalS: 1,
  2591. MarkerName: "myfile",
  2592. }
  2593. cfg := config.Wrap("/tmp/test", config.Configuration{
  2594. Folders: []config.FolderConfiguration{fcfg},
  2595. Devices: []config.DeviceConfiguration{
  2596. {
  2597. DeviceID: device1,
  2598. },
  2599. },
  2600. })
  2601. os.RemoveAll(fcfg.Path)
  2602. defer os.RemoveAll(fcfg.Path)
  2603. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  2604. m.AddFolder(fcfg)
  2605. m.StartFolder("default")
  2606. m.ServeBackground()
  2607. defer m.Stop()
  2608. waitFor := func(status string) error {
  2609. timeout := time.Now().Add(2 * time.Second)
  2610. for {
  2611. _, _, err := m.State("default")
  2612. if err == nil && status == "" {
  2613. return nil
  2614. }
  2615. if err != nil && err.Error() == status {
  2616. return nil
  2617. }
  2618. if time.Now().After(timeout) {
  2619. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  2620. }
  2621. time.Sleep(10 * time.Millisecond)
  2622. }
  2623. }
  2624. if err := waitFor("folder path missing"); err != nil {
  2625. t.Error(err)
  2626. return
  2627. }
  2628. os.Mkdir(fcfg.Path, 0700)
  2629. fd, err := os.Create(filepath.Join(fcfg.Path, "myfile"))
  2630. if err != nil {
  2631. t.Error(err)
  2632. return
  2633. }
  2634. fd.Close()
  2635. if err := waitFor(""); err != nil {
  2636. t.Error(err)
  2637. return
  2638. }
  2639. }
  2640. func TestRemoveDirWithContent(t *testing.T) {
  2641. defer func() {
  2642. defaultFs.RemoveAll("dirwith")
  2643. }()
  2644. defaultFs.MkdirAll("dirwith", 0755)
  2645. content := filepath.Join("dirwith", "content")
  2646. fd, err := defaultFs.Create(content)
  2647. if err != nil {
  2648. t.Fatal(err)
  2649. return
  2650. }
  2651. fd.Close()
  2652. dbi := db.OpenMemory()
  2653. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2654. m.AddFolder(defaultFolderConfig)
  2655. m.StartFolder("default")
  2656. m.ServeBackground()
  2657. defer m.Stop()
  2658. m.ScanFolder("default")
  2659. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2660. if !ok {
  2661. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2662. }
  2663. dir.Deleted = true
  2664. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2665. file, ok := m.CurrentFolderFile("default", content)
  2666. if !ok {
  2667. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2668. }
  2669. file.Deleted = true
  2670. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2671. m.IndexUpdate(device1, "default", []protocol.FileInfo{dir, file})
  2672. // Is there something we could trigger on instead of just waiting?
  2673. timeout := time.NewTimer(5 * time.Second)
  2674. for {
  2675. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2676. if !ok {
  2677. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2678. }
  2679. file, ok := m.CurrentFolderFile("default", content)
  2680. if !ok {
  2681. t.Fatalf("Can't get file \"%v\" after index update", content)
  2682. }
  2683. if dir.Deleted && file.Deleted {
  2684. return
  2685. }
  2686. select {
  2687. case <-timeout.C:
  2688. if !dir.Deleted && !file.Deleted {
  2689. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2690. } else if !dir.Deleted {
  2691. t.Errorf("The dir was not deleted before timing out.")
  2692. } else {
  2693. t.Errorf("The content of the dir was not deleted before timing out.")
  2694. }
  2695. return
  2696. default:
  2697. time.Sleep(100 * time.Millisecond)
  2698. }
  2699. }
  2700. }
  2701. func TestIssue4475(t *testing.T) {
  2702. defer func() {
  2703. defaultFs.RemoveAll("delDir")
  2704. }()
  2705. err := defaultFs.MkdirAll("delDir", 0755)
  2706. if err != nil {
  2707. t.Fatal(err)
  2708. }
  2709. dbi := db.OpenMemory()
  2710. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2711. m.AddFolder(defaultFolderConfig)
  2712. m.StartFolder("default")
  2713. m.ServeBackground()
  2714. defer m.Stop()
  2715. m.ScanFolder("default")
  2716. // Scenario: Dir is deleted locally and before syncing/index exchange
  2717. // happens, a file is create in that dir on the remote.
  2718. // This should result in the directory being recreated and added to the
  2719. // db locally.
  2720. if err = defaultFs.RemoveAll("delDir"); err != nil {
  2721. t.Fatal(err)
  2722. }
  2723. m.ScanFolder("default")
  2724. conn := addFakeConn(m, device1)
  2725. conn.folder = "default"
  2726. if !m.folderSharedWith("default", device1) {
  2727. t.Fatal("not shared with device1")
  2728. }
  2729. fileName := filepath.Join("delDir", "file")
  2730. conn.addFile(fileName, 0644, protocol.FileInfoTypeFile, nil)
  2731. conn.sendIndexUpdate()
  2732. // Is there something we could trigger on instead of just waiting?
  2733. timeout := time.NewTimer(5 * time.Second)
  2734. created := false
  2735. for {
  2736. if !created {
  2737. if _, ok := m.CurrentFolderFile("default", fileName); ok {
  2738. created = true
  2739. }
  2740. } else {
  2741. dir, ok := m.CurrentFolderFile("default", "delDir")
  2742. if !ok {
  2743. t.Fatalf("can't get dir from db")
  2744. }
  2745. if !dir.Deleted {
  2746. return
  2747. }
  2748. }
  2749. select {
  2750. case <-timeout.C:
  2751. if created {
  2752. t.Errorf("Timed out before file from remote was created")
  2753. } else {
  2754. t.Errorf("Timed out before directory was resurrected in db")
  2755. }
  2756. return
  2757. default:
  2758. time.Sleep(100 * time.Millisecond)
  2759. }
  2760. }
  2761. }
  2762. func TestVersionRestore(t *testing.T) {
  2763. // We create a bunch of files which we restore
  2764. // In each file, we write the filename as the content
  2765. // We verify that the content matches at the expected filenames
  2766. // after the restore operation.
  2767. dir, err := ioutil.TempDir("", "")
  2768. if err != nil {
  2769. t.Fatal(err)
  2770. }
  2771. defer os.RemoveAll(dir)
  2772. dbi := db.OpenMemory()
  2773. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, dir)
  2774. fcfg.Versioning.Type = "simple"
  2775. fcfg.FSWatcherEnabled = false
  2776. filesystem := fcfg.Filesystem()
  2777. rawConfig := config.Configuration{
  2778. Folders: []config.FolderConfiguration{fcfg},
  2779. }
  2780. cfg := config.Wrap("/tmp/test", rawConfig)
  2781. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2782. m.AddFolder(fcfg)
  2783. m.StartFolder("default")
  2784. m.ServeBackground()
  2785. defer m.Stop()
  2786. m.ScanFolder("default")
  2787. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20200101-010101", locationLocal)
  2788. if err != nil {
  2789. t.Fatal(err)
  2790. }
  2791. sentinelTag := sentinel.Format(versioner.TimeFormat)
  2792. for _, file := range []string{
  2793. // Versions directory
  2794. ".stversions/file~20171210-040404.txt", // will be restored
  2795. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2796. ".stversions/something~20171210-040404", // will become directory, hence error
  2797. ".stversions/dir/file~20171210-040404.txt",
  2798. ".stversions/dir/file~20171210-040405.txt",
  2799. ".stversions/dir/file~20171210-040406.txt",
  2800. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2801. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2802. ".stversions/dir/file.txt~20171210-040405", // incorrect tag format, ignored.
  2803. ".stversions/dir/cat", // incorrect tag format, ignored.
  2804. // "file.txt" will be restored
  2805. "existing",
  2806. "something/file", // Becomes directory
  2807. "dir/file.txt",
  2808. "dir/existing.txt",
  2809. } {
  2810. if runtime.GOOS == "windows" {
  2811. file = filepath.FromSlash(file)
  2812. }
  2813. dir := filepath.Dir(file)
  2814. if err := filesystem.MkdirAll(dir, 0755); err != nil {
  2815. t.Fatal(err)
  2816. }
  2817. if fd, err := filesystem.Create(file); err != nil {
  2818. t.Fatal(err)
  2819. } else if _, err := fd.Write([]byte(file)); err != nil {
  2820. t.Fatal(err)
  2821. } else if err := fd.Close(); err != nil {
  2822. t.Fatal(err)
  2823. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2824. t.Fatal(err)
  2825. }
  2826. }
  2827. versions, err := m.GetFolderVersions("default")
  2828. if err != nil {
  2829. t.Fatal(err)
  2830. }
  2831. expectedVersions := map[string]int{
  2832. "file.txt": 1,
  2833. "existing": 1,
  2834. "something": 1,
  2835. "dir/file.txt": 3,
  2836. "dir/existing.txt": 1,
  2837. "very/very/deep/one.txt": 1,
  2838. }
  2839. for name, vers := range versions {
  2840. cnt, ok := expectedVersions[name]
  2841. if !ok {
  2842. t.Errorf("unexpected %s", name)
  2843. }
  2844. if len(vers) != cnt {
  2845. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2846. }
  2847. // Delete, so we can check if we didn't hit something we expect afterwards.
  2848. delete(expectedVersions, name)
  2849. }
  2850. for name := range expectedVersions {
  2851. t.Errorf("not found expected %s", name)
  2852. }
  2853. // Restoring non existing folder fails.
  2854. _, err = m.RestoreFolderVersions("does not exist", nil)
  2855. if err == nil {
  2856. t.Errorf("expected an error")
  2857. }
  2858. makeTime := func(s string) time.Time {
  2859. tm, err := time.ParseInLocation(versioner.TimeFormat, s, locationLocal)
  2860. if err != nil {
  2861. t.Error(err)
  2862. }
  2863. return tm.Truncate(time.Second)
  2864. }
  2865. restore := map[string]time.Time{
  2866. "file.txt": makeTime("20171210-040404"),
  2867. "existing": makeTime("20171210-040404"),
  2868. "something": makeTime("20171210-040404"),
  2869. "dir/file.txt": makeTime("20171210-040406"),
  2870. "dir/existing.txt": makeTime("20171210-040406"),
  2871. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2872. }
  2873. ferr, err := m.RestoreFolderVersions("default", restore)
  2874. if err != nil {
  2875. t.Fatal(err)
  2876. }
  2877. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || err != "cannot replace a non-file" {
  2878. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2879. }
  2880. // Failed items are not expected to be restored.
  2881. // Remove them from expectations
  2882. for name := range ferr {
  2883. delete(restore, name)
  2884. }
  2885. // Check that content of files matches to the version they've been restored.
  2886. for file, version := range restore {
  2887. if runtime.GOOS == "windows" {
  2888. file = filepath.FromSlash(file)
  2889. }
  2890. tag := version.In(locationLocal).Truncate(time.Second).Format(versioner.TimeFormat)
  2891. taggedName := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2892. fd, err := filesystem.Open(file)
  2893. if err != nil {
  2894. t.Error(err)
  2895. }
  2896. defer fd.Close()
  2897. content, err := ioutil.ReadAll(fd)
  2898. if err != nil {
  2899. t.Error(err)
  2900. }
  2901. if !bytes.Equal(content, []byte(taggedName)) {
  2902. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2903. }
  2904. }
  2905. // Simple versioner uses modtime for timestamp generation, so we can check
  2906. // if existing stuff was correctly archived as we restored.
  2907. expectArchived := map[string]struct{}{
  2908. "existing": {},
  2909. "dir/file.txt": {},
  2910. "dir/existing.txt": {},
  2911. }
  2912. // Even if they are at the archived path, content should have the non
  2913. // archived name.
  2914. for file := range expectArchived {
  2915. if runtime.GOOS == "windows" {
  2916. file = filepath.FromSlash(file)
  2917. }
  2918. taggedName := versioner.TagFilename(file, sentinelTag)
  2919. taggedArchivedName := filepath.Join(".stversions", taggedName)
  2920. fd, err := filesystem.Open(taggedArchivedName)
  2921. if err != nil {
  2922. t.Fatal(err)
  2923. }
  2924. defer fd.Close()
  2925. content, err := ioutil.ReadAll(fd)
  2926. if err != nil {
  2927. t.Error(err)
  2928. }
  2929. if !bytes.Equal(content, []byte(file)) {
  2930. t.Errorf("%s: %s != %s", file, string(content), file)
  2931. }
  2932. }
  2933. // Check for other unexpected things that are tagged.
  2934. filesystem.Walk(".", func(path string, f fs.FileInfo, err error) error {
  2935. if !f.IsRegular() {
  2936. return nil
  2937. }
  2938. if strings.Contains(path, sentinelTag) {
  2939. path = osutil.NormalizedFilename(path)
  2940. name, _ := versioner.UntagFilename(path)
  2941. name = strings.TrimPrefix(name, ".stversions/")
  2942. if _, ok := expectArchived[name]; !ok {
  2943. t.Errorf("unexpected file with sentinel tag: %s", name)
  2944. }
  2945. }
  2946. return nil
  2947. })
  2948. }
  2949. func TestPausedFolders(t *testing.T) {
  2950. // Create a separate wrapper not to pollute other tests.
  2951. cfg := defaultConfig.RawCopy()
  2952. wrapper := config.Wrap("/tmp/test", cfg)
  2953. db := db.OpenMemory()
  2954. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2955. m.AddFolder(defaultFolderConfig)
  2956. m.StartFolder("default")
  2957. m.ServeBackground()
  2958. defer m.Stop()
  2959. if err := m.ScanFolder("default"); err != nil {
  2960. t.Error(err)
  2961. }
  2962. pausedConfig := wrapper.RawCopy()
  2963. pausedConfig.Folders[0].Paused = true
  2964. w, err := m.cfg.Replace(pausedConfig)
  2965. if err != nil {
  2966. t.Fatal(err)
  2967. }
  2968. w.Wait()
  2969. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2970. t.Errorf("Expected folder paused error, received: %v", err)
  2971. }
  2972. if err := m.ScanFolder("nonexistent"); err != errFolderMissing {
  2973. t.Errorf("Expected missing folder error, received: %v", err)
  2974. }
  2975. }
  2976. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2977. fc := &fakeConnection{id: dev, model: m}
  2978. m.AddConnection(fc, protocol.HelloResult{})
  2979. m.ClusterConfig(dev, protocol.ClusterConfig{
  2980. Folders: []protocol.Folder{
  2981. {
  2982. ID: "default",
  2983. Devices: []protocol.Device{
  2984. {ID: device1},
  2985. {ID: device2},
  2986. },
  2987. },
  2988. },
  2989. })
  2990. return fc
  2991. }
  2992. type fakeAddr struct{}
  2993. func (fakeAddr) Network() string {
  2994. return "network"
  2995. }
  2996. func (fakeAddr) String() string {
  2997. return "address"
  2998. }
  2999. type alwaysChangedKey struct {
  3000. fs fs.Filesystem
  3001. name string
  3002. }
  3003. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  3004. type alwaysChanged struct {
  3005. seen map[alwaysChangedKey]struct{}
  3006. }
  3007. func newAlwaysChanged() *alwaysChanged {
  3008. return &alwaysChanged{
  3009. seen: make(map[alwaysChangedKey]struct{}),
  3010. }
  3011. }
  3012. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  3013. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  3014. }
  3015. func (c *alwaysChanged) Reset() {
  3016. c.seen = make(map[alwaysChangedKey]struct{})
  3017. }
  3018. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  3019. _, ok := c.seen[alwaysChangedKey{fs, name}]
  3020. return ok
  3021. }
  3022. func (c *alwaysChanged) Changed() bool {
  3023. return true
  3024. }