model_test.go 86 KB

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