model_test.go 90 KB

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