model_test.go 88 KB

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