model_test.go 95 KB

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