model_test.go 106 KB

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