model_test.go 90 KB

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