model_test.go 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057
  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. "sort"
  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. for _, dev := range fcfg.DeviceIDs() {
  1120. if dev == device1 {
  1121. return
  1122. }
  1123. }
  1124. t.Error("device missing")
  1125. }
  1126. if _, ok := m.folderRunners.Get(id); ok {
  1127. t.Error("folder started")
  1128. }
  1129. }
  1130. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1131. // Existing folder
  1132. id := srand.String(8)
  1133. idOther := srand.String(8) // To check that path does not get changed.
  1134. tcfg := defaultAutoAcceptCfg.Copy()
  1135. fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", config.FilesystemTypeFake, idOther)
  1136. fcfg.Paused = true
  1137. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1138. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1139. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1140. // did not have a file set.
  1141. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1142. {
  1143. DeviceID: device1,
  1144. },
  1145. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1146. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1147. m, cancel := newState(t, tcfg)
  1148. defer cleanupModel(m)
  1149. defer cancel()
  1150. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1151. t.Error("missing folder, or not shared", id)
  1152. }
  1153. if _, ok := m.folderRunners.Get(id); ok {
  1154. t.Fatal("folder running?")
  1155. }
  1156. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  1157. m.generateClusterConfig(device1)
  1158. if fcfg, ok := m.cfg.Folder(id); !ok {
  1159. t.Error("missing folder")
  1160. } else if fcfg.Path != idOther {
  1161. t.Error("folder path changed")
  1162. } else {
  1163. for _, dev := range fcfg.DeviceIDs() {
  1164. if dev == device1 {
  1165. return
  1166. }
  1167. }
  1168. t.Error("device missing")
  1169. }
  1170. if _, ok := m.folderRunners.Get(id); ok {
  1171. t.Error("folder started")
  1172. }
  1173. }
  1174. func TestAutoAcceptEnc(t *testing.T) {
  1175. tcfg := defaultAutoAcceptCfg.Copy()
  1176. m, cancel := newState(t, tcfg)
  1177. defer cleanupModel(m)
  1178. defer cancel()
  1179. id := srand.String(8)
  1180. defer os.RemoveAll(id)
  1181. token := []byte("token")
  1182. basicCC := func() *protocol.ClusterConfig {
  1183. return &protocol.ClusterConfig{
  1184. Folders: []protocol.Folder{{
  1185. ID: id,
  1186. Label: id,
  1187. }},
  1188. }
  1189. }
  1190. // Earlier tests might cause the connection to get closed, thus ClusterConfig
  1191. // would panic.
  1192. clusterConfig := func(deviceID protocol.DeviceID, cm *protocol.ClusterConfig) {
  1193. conn := newFakeConnection(deviceID, m)
  1194. m.AddConnection(conn, protocol.Hello{})
  1195. m.ClusterConfig(conn, cm)
  1196. }
  1197. clusterConfig(device1, basicCC())
  1198. if _, ok := m.cfg.Folder(id); ok {
  1199. t.Fatal("unexpected added")
  1200. }
  1201. cc := basicCC()
  1202. cc.Folders[0].Devices = []protocol.Device{{ID: device1}}
  1203. clusterConfig(device1, cc)
  1204. if _, ok := m.cfg.Folder(id); ok {
  1205. t.Fatal("unexpected added")
  1206. }
  1207. cc = basicCC()
  1208. cc.Folders[0].Devices = []protocol.Device{{ID: myID}}
  1209. clusterConfig(device1, cc)
  1210. if _, ok := m.cfg.Folder(id); ok {
  1211. t.Fatal("unexpected added")
  1212. }
  1213. // New folder, encrypted -> add as enc
  1214. cc = createClusterConfig(device1, id)
  1215. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1216. clusterConfig(device1, cc)
  1217. if cfg, ok := m.cfg.Folder(id); !ok {
  1218. t.Fatal("unexpected unadded")
  1219. } else {
  1220. if !cfg.SharedWith(device1) {
  1221. t.Fatal("unexpected unshared")
  1222. }
  1223. if cfg.Type != config.FolderTypeReceiveEncrypted {
  1224. t.Fatal("Folder not added as receiveEncrypted")
  1225. }
  1226. }
  1227. // New device, unencrypted on encrypted folder -> reject
  1228. clusterConfig(device2, createClusterConfig(device2, id))
  1229. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1230. t.Fatal("unexpected shared")
  1231. }
  1232. // New device, encrypted on encrypted folder -> share
  1233. cc = createClusterConfig(device2, id)
  1234. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1235. clusterConfig(device2, cc)
  1236. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1237. t.Fatal("unexpected unshared")
  1238. }
  1239. // New folder, no encrypted -> add "normal"
  1240. id = srand.String(8)
  1241. defer os.RemoveAll(id)
  1242. clusterConfig(device1, createClusterConfig(device1, id))
  1243. if cfg, ok := m.cfg.Folder(id); !ok {
  1244. t.Fatal("unexpected unadded")
  1245. } else {
  1246. if !cfg.SharedWith(device1) {
  1247. t.Fatal("unexpected unshared")
  1248. }
  1249. if cfg.Type != config.FolderTypeSendReceive {
  1250. t.Fatal("Folder not added as send-receive")
  1251. }
  1252. }
  1253. // New device, encrypted on unencrypted folder -> reject
  1254. cc = createClusterConfig(device2, id)
  1255. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1256. clusterConfig(device2, cc)
  1257. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1258. t.Fatal("unexpected shared")
  1259. }
  1260. // New device, unencrypted on unencrypted folder -> share
  1261. clusterConfig(device2, createClusterConfig(device2, id))
  1262. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1263. t.Fatal("unexpected unshared")
  1264. }
  1265. }
  1266. func changeIgnores(t *testing.T, m *testModel, expected []string) {
  1267. arrEqual := func(a, b []string) bool {
  1268. if len(a) != len(b) {
  1269. return false
  1270. }
  1271. for i := range a {
  1272. if a[i] != b[i] {
  1273. return false
  1274. }
  1275. }
  1276. return true
  1277. }
  1278. ignores, _, err := m.LoadIgnores("default")
  1279. if err != nil {
  1280. t.Error(err)
  1281. }
  1282. if !arrEqual(ignores, expected) {
  1283. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1284. }
  1285. ignores = append(ignores, "pox")
  1286. err = m.SetIgnores("default", ignores)
  1287. if err != nil {
  1288. t.Error(err)
  1289. }
  1290. ignores2, _, err := m.LoadIgnores("default")
  1291. if err != nil {
  1292. t.Error(err)
  1293. }
  1294. if !arrEqual(ignores, ignores2) {
  1295. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1296. }
  1297. if build.IsDarwin {
  1298. // see above
  1299. time.Sleep(time.Second)
  1300. } else {
  1301. time.Sleep(time.Millisecond)
  1302. }
  1303. err = m.SetIgnores("default", expected)
  1304. if err != nil {
  1305. t.Error(err)
  1306. }
  1307. ignores, _, err = m.LoadIgnores("default")
  1308. if err != nil {
  1309. t.Error(err)
  1310. }
  1311. if !arrEqual(ignores, expected) {
  1312. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1313. }
  1314. }
  1315. func TestIgnores(t *testing.T) {
  1316. w, cancel := newConfigWrapper(defaultCfg)
  1317. defer cancel()
  1318. ffs := w.FolderList()[0].Filesystem()
  1319. m := setupModel(t, w)
  1320. defer cleanupModel(m)
  1321. // Assure a clean start state
  1322. must(t, ffs.MkdirAll(config.DefaultMarkerName, 0o644))
  1323. writeFile(t, ffs, ".stignore", []byte(".*\nquux\n"))
  1324. folderIgnoresAlwaysReload(t, m, defaultFolderConfig)
  1325. // Make sure the initial scan has finished (ScanFolders is blocking)
  1326. m.ScanFolders()
  1327. expected := []string{
  1328. ".*",
  1329. "quux",
  1330. }
  1331. changeIgnores(t, m, expected)
  1332. _, _, err := m.LoadIgnores("doesnotexist")
  1333. if err == nil {
  1334. t.Error("No error")
  1335. }
  1336. err = m.SetIgnores("doesnotexist", expected)
  1337. if err == nil {
  1338. t.Error("No error")
  1339. }
  1340. // Invalid path, treated like no patterns at all.
  1341. fcfg := config.FolderConfiguration{
  1342. ID: "fresh", Path: "XXX",
  1343. FilesystemType: config.FilesystemTypeFake,
  1344. }
  1345. ignores := ignore.New(fcfg.Filesystem(), ignore.WithCache(m.cfg.Options().CacheIgnoredFiles))
  1346. m.mut.Lock()
  1347. m.folderCfgs[fcfg.ID] = fcfg
  1348. m.folderIgnores[fcfg.ID] = ignores
  1349. m.mut.Unlock()
  1350. _, _, err = m.LoadIgnores("fresh")
  1351. if err != nil {
  1352. t.Error("Got error for inexistent folder path")
  1353. }
  1354. // Repeat tests with paused folder
  1355. pausedDefaultFolderConfig := defaultFolderConfig
  1356. pausedDefaultFolderConfig.Paused = true
  1357. m.restartFolder(defaultFolderConfig, pausedDefaultFolderConfig, false)
  1358. // Here folder initialization is not an issue as a paused folder isn't
  1359. // added to the model and thus there is no initial scan happening.
  1360. changeIgnores(t, m, expected)
  1361. // Make sure no .stignore file is considered valid
  1362. defer func() {
  1363. must(t, ffs.Rename(".stignore.bak", ".stignore"))
  1364. }()
  1365. must(t, ffs.Rename(".stignore", ".stignore.bak"))
  1366. changeIgnores(t, m, []string{})
  1367. }
  1368. func TestEmptyIgnores(t *testing.T) {
  1369. w, cancel := newConfigWrapper(defaultCfg)
  1370. defer cancel()
  1371. ffs := w.FolderList()[0].Filesystem()
  1372. m := setupModel(t, w)
  1373. defer cleanupModel(m)
  1374. if err := m.SetIgnores("default", []string{}); err != nil {
  1375. t.Error(err)
  1376. }
  1377. if _, err := ffs.Stat(".stignore"); err == nil {
  1378. t.Error(".stignore was created despite being empty")
  1379. }
  1380. if err := m.SetIgnores("default", []string{".*", "quux"}); err != nil {
  1381. t.Error(err)
  1382. }
  1383. if _, err := ffs.Stat(".stignore"); os.IsNotExist(err) {
  1384. t.Error(".stignore does not exist")
  1385. }
  1386. if err := m.SetIgnores("default", []string{}); err != nil {
  1387. t.Error(err)
  1388. }
  1389. if _, err := ffs.Stat(".stignore"); err == nil {
  1390. t.Error(".stignore should have been deleted because it is empty")
  1391. }
  1392. }
  1393. func waitForState(t *testing.T, sub events.Subscription, folder, expected string) {
  1394. t.Helper()
  1395. timeout := time.After(5 * time.Second)
  1396. var err string
  1397. for {
  1398. select {
  1399. case ev := <-sub.C():
  1400. data := ev.Data.(map[string]interface{})
  1401. if data["folder"].(string) == folder {
  1402. if data["error"] == nil {
  1403. err = ""
  1404. } else {
  1405. err = data["error"].(string)
  1406. }
  1407. if err == expected {
  1408. return
  1409. } else {
  1410. t.Error(ev)
  1411. }
  1412. }
  1413. case <-timeout:
  1414. t.Fatalf("Timed out waiting for status: %s, current status: %v", expected, err)
  1415. }
  1416. }
  1417. }
  1418. func TestROScanRecovery(t *testing.T) {
  1419. fcfg := config.FolderConfiguration{
  1420. FilesystemType: config.FilesystemTypeFake,
  1421. ID: "default",
  1422. Path: srand.String(32),
  1423. Type: config.FolderTypeSendOnly,
  1424. RescanIntervalS: 1,
  1425. MarkerName: config.DefaultMarkerName,
  1426. }
  1427. cfg, cancel := newConfigWrapper(config.Configuration{
  1428. Version: config.CurrentVersion,
  1429. Folders: []config.FolderConfiguration{fcfg},
  1430. Devices: []config.DeviceConfiguration{
  1431. {
  1432. DeviceID: device1,
  1433. },
  1434. },
  1435. })
  1436. defer cancel()
  1437. m := newModel(t, cfg, myID, nil)
  1438. m.sdb.Update("default", protocol.LocalDeviceID, []protocol.FileInfo{
  1439. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1440. })
  1441. ffs := fcfg.Filesystem()
  1442. // Remove marker to generate an error
  1443. ffs.Remove(fcfg.MarkerName)
  1444. sub := m.evLogger.Subscribe(events.StateChanged)
  1445. defer sub.Unsubscribe()
  1446. m.ServeBackground()
  1447. defer cleanupModel(m)
  1448. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1449. fd, err := ffs.Create(config.DefaultMarkerName)
  1450. if err != nil {
  1451. t.Fatal(err)
  1452. }
  1453. fd.Close()
  1454. waitForState(t, sub, "default", "")
  1455. }
  1456. func TestRWScanRecovery(t *testing.T) {
  1457. fcfg := config.FolderConfiguration{
  1458. FilesystemType: config.FilesystemTypeFake,
  1459. ID: "default",
  1460. Path: srand.String(32),
  1461. Type: config.FolderTypeSendReceive,
  1462. RescanIntervalS: 1,
  1463. MarkerName: config.DefaultMarkerName,
  1464. }
  1465. cfg, cancel := newConfigWrapper(config.Configuration{
  1466. Version: config.CurrentVersion,
  1467. Folders: []config.FolderConfiguration{fcfg},
  1468. Devices: []config.DeviceConfiguration{
  1469. {
  1470. DeviceID: device1,
  1471. },
  1472. },
  1473. })
  1474. defer cancel()
  1475. m := newModel(t, cfg, myID, nil)
  1476. m.sdb.Update("default", protocol.LocalDeviceID, []protocol.FileInfo{
  1477. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1478. })
  1479. ffs := fcfg.Filesystem()
  1480. // Generate error
  1481. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  1482. t.Fatal(err)
  1483. }
  1484. sub := m.evLogger.Subscribe(events.StateChanged)
  1485. defer sub.Unsubscribe()
  1486. m.ServeBackground()
  1487. defer cleanupModel(m)
  1488. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1489. fd, err := ffs.Create(config.DefaultMarkerName)
  1490. if err != nil {
  1491. t.Error(err)
  1492. }
  1493. fd.Close()
  1494. waitForState(t, sub, "default", "")
  1495. }
  1496. func TestGlobalDirectoryTree(t *testing.T) {
  1497. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  1498. defer wCancel()
  1499. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  1500. var seq int64
  1501. b := func(isfile bool, path ...string) protocol.FileInfo {
  1502. typ := protocol.FileInfoTypeDirectory
  1503. var blocks []protocol.BlockInfo
  1504. if isfile {
  1505. typ = protocol.FileInfoTypeFile
  1506. 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}}}
  1507. }
  1508. seq++
  1509. return protocol.FileInfo{
  1510. Name: filepath.Join(path...),
  1511. Type: typ,
  1512. ModifiedS: 0x666,
  1513. Blocks: blocks,
  1514. Size: 0xa,
  1515. Sequence: seq,
  1516. }
  1517. }
  1518. f := func(name string) *TreeEntry {
  1519. return &TreeEntry{
  1520. Name: name,
  1521. ModTime: time.Unix(0x666, 0),
  1522. Size: 0xa,
  1523. Type: protocol.FileInfoTypeFile.String(),
  1524. }
  1525. }
  1526. d := func(name string, entries ...*TreeEntry) *TreeEntry {
  1527. return &TreeEntry{
  1528. Name: name,
  1529. ModTime: time.Unix(0x666, 0),
  1530. Size: 128,
  1531. Type: protocol.FileInfoTypeDirectory.String(),
  1532. Children: entries,
  1533. }
  1534. }
  1535. testdata := []protocol.FileInfo{
  1536. b(false, "another"),
  1537. b(false, "another", "directory"),
  1538. b(true, "another", "directory", "afile"),
  1539. b(false, "another", "directory", "with"),
  1540. b(false, "another", "directory", "with", "a"),
  1541. b(true, "another", "directory", "with", "a", "file"),
  1542. b(true, "another", "directory", "with", "file"),
  1543. b(true, "another", "file"),
  1544. b(false, "other"),
  1545. b(false, "other", "rand"),
  1546. b(false, "other", "random"),
  1547. b(false, "other", "random", "dir"),
  1548. b(false, "other", "random", "dirx"),
  1549. b(false, "other", "randomx"),
  1550. b(false, "some"),
  1551. b(false, "some", "directory"),
  1552. b(false, "some", "directory", "with"),
  1553. b(false, "some", "directory", "with", "a"),
  1554. b(true, "some", "directory", "with", "a", "file"),
  1555. b(true, "zzrootfile"),
  1556. }
  1557. expectedResult := []*TreeEntry{
  1558. d("another",
  1559. d("directory",
  1560. f("afile"),
  1561. d("with",
  1562. d("a",
  1563. f("file"),
  1564. ),
  1565. f("file"),
  1566. ),
  1567. ),
  1568. f("file"),
  1569. ),
  1570. d("other",
  1571. d("rand"),
  1572. d("random",
  1573. d("dir"),
  1574. d("dirx"),
  1575. ),
  1576. d("randomx"),
  1577. ),
  1578. d("some",
  1579. d("directory",
  1580. d("with",
  1581. d("a",
  1582. f("file"),
  1583. ),
  1584. ),
  1585. ),
  1586. ),
  1587. f("zzrootfile"),
  1588. }
  1589. mm := func(data interface{}) string {
  1590. bytes, err := json.MarshalIndent(data, "", " ")
  1591. if err != nil {
  1592. panic(err)
  1593. }
  1594. return string(bytes)
  1595. }
  1596. must(t, m.Index(conn, &protocol.Index{Folder: "default", Files: testdata}))
  1597. result, _ := m.GlobalDirectoryTree("default", "", -1, false)
  1598. if mm(result) != mm(expectedResult) {
  1599. t.Fatalf("Does not match:\n%s\n============\n%s", mm(result), mm(expectedResult))
  1600. }
  1601. result, _ = m.GlobalDirectoryTree("default", "another", -1, false)
  1602. if mm(result) != mm(findByName(expectedResult, "another").Children) {
  1603. t.Fatalf("Does not match:\n%s\n============\n%s", mm(result), mm(findByName(expectedResult, "another").Children))
  1604. }
  1605. result, _ = m.GlobalDirectoryTree("default", "", 0, false)
  1606. currentResult := []*TreeEntry{
  1607. d("another"),
  1608. d("other"),
  1609. d("some"),
  1610. f("zzrootfile"),
  1611. }
  1612. if mm(result) != mm(currentResult) {
  1613. t.Fatalf("Does not match:\n%s\n============\n%s", mm(result), mm(currentResult))
  1614. }
  1615. result, _ = m.GlobalDirectoryTree("default", "", 1, false)
  1616. currentResult = []*TreeEntry{
  1617. d("another",
  1618. d("directory"),
  1619. f("file"),
  1620. ),
  1621. d("other",
  1622. d("rand"),
  1623. d("random"),
  1624. d("randomx"),
  1625. ),
  1626. d("some",
  1627. d("directory"),
  1628. ),
  1629. f("zzrootfile"),
  1630. }
  1631. if mm(result) != mm(currentResult) {
  1632. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1633. }
  1634. result, _ = m.GlobalDirectoryTree("default", "", -1, true)
  1635. currentResult = []*TreeEntry{
  1636. d("another",
  1637. d("directory",
  1638. d("with",
  1639. d("a"),
  1640. ),
  1641. ),
  1642. ),
  1643. d("other",
  1644. d("rand"),
  1645. d("random",
  1646. d("dir"),
  1647. d("dirx"),
  1648. ),
  1649. d("randomx"),
  1650. ),
  1651. d("some",
  1652. d("directory",
  1653. d("with",
  1654. d("a"),
  1655. ),
  1656. ),
  1657. ),
  1658. }
  1659. if mm(result) != mm(currentResult) {
  1660. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1661. }
  1662. result, _ = m.GlobalDirectoryTree("default", "", 1, true)
  1663. currentResult = []*TreeEntry{
  1664. d("another",
  1665. d("directory"),
  1666. ),
  1667. d("other",
  1668. d("rand"),
  1669. d("random"),
  1670. d("randomx"),
  1671. ),
  1672. d("some",
  1673. d("directory"),
  1674. ),
  1675. }
  1676. if mm(result) != mm(currentResult) {
  1677. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1678. }
  1679. result, _ = m.GlobalDirectoryTree("default", "another", 0, false)
  1680. currentResult = []*TreeEntry{
  1681. d("directory"),
  1682. f("file"),
  1683. }
  1684. if mm(result) != mm(currentResult) {
  1685. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1686. }
  1687. result, _ = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1688. currentResult = []*TreeEntry{
  1689. d("with"),
  1690. }
  1691. if mm(result) != mm(currentResult) {
  1692. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1693. }
  1694. result, _ = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1695. currentResult = []*TreeEntry{
  1696. d("with",
  1697. d("a"),
  1698. ),
  1699. }
  1700. if mm(result) != mm(currentResult) {
  1701. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1702. }
  1703. result, _ = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1704. currentResult = []*TreeEntry{
  1705. d("with",
  1706. d("a",
  1707. f("file"),
  1708. ),
  1709. ),
  1710. }
  1711. if mm(result) != mm(currentResult) {
  1712. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1713. }
  1714. result, _ = m.GlobalDirectoryTree("default", "another", -1, true)
  1715. currentResult = []*TreeEntry{
  1716. d("directory",
  1717. d("with",
  1718. d("a"),
  1719. ),
  1720. ),
  1721. }
  1722. if mm(result) != mm(currentResult) {
  1723. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1724. }
  1725. // No prefix matching!
  1726. result, _ = m.GlobalDirectoryTree("default", "som", -1, false)
  1727. currentResult = []*TreeEntry{}
  1728. if mm(result) != mm(currentResult) {
  1729. t.Fatalf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1730. }
  1731. }
  1732. func genDeepFiles(n, d int) []protocol.FileInfo {
  1733. mrand.Seed(int64(n))
  1734. files := make([]protocol.FileInfo, n)
  1735. t := time.Now().Unix()
  1736. for i := 0; i < n; i++ {
  1737. path := ""
  1738. for i := 0; i <= d; i++ {
  1739. path = filepath.Join(path, strconv.Itoa(mrand.Int()))
  1740. }
  1741. sofar := ""
  1742. for _, path := range filepath.SplitList(path) {
  1743. sofar = filepath.Join(sofar, path)
  1744. files[i] = protocol.FileInfo{
  1745. Name: sofar,
  1746. }
  1747. i++
  1748. }
  1749. files[i].ModifiedS = t
  1750. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1751. }
  1752. return files
  1753. }
  1754. func BenchmarkTree_10000_50(b *testing.B) {
  1755. benchmarkTree(b, 10000, 50)
  1756. }
  1757. func BenchmarkTree_100_50(b *testing.B) {
  1758. benchmarkTree(b, 100, 50)
  1759. }
  1760. func BenchmarkTree_100_10(b *testing.B) {
  1761. benchmarkTree(b, 100, 10)
  1762. }
  1763. func benchmarkTree(b *testing.B, n1, n2 int) {
  1764. m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
  1765. defer wcfgCancel()
  1766. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  1767. m.ScanFolder(fcfg.ID)
  1768. files := genDeepFiles(n1, n2)
  1769. must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
  1770. b.ResetTimer()
  1771. for i := 0; i < b.N; i++ {
  1772. m.GlobalDirectoryTree(fcfg.ID, "", -1, false)
  1773. }
  1774. b.ReportAllocs()
  1775. }
  1776. func TestIssue3028(t *testing.T) {
  1777. w, cancel := newConfigWrapper(defaultCfg)
  1778. defer cancel()
  1779. ffs := w.FolderList()[0].Filesystem()
  1780. m := setupModel(t, w)
  1781. defer cleanupModel(m)
  1782. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1783. writeFile(t, ffs, "testrm", []byte("Hello"))
  1784. writeFile(t, ffs, "testrm2", []byte("Hello"))
  1785. // Scan, and get a count of how many files are there now
  1786. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1787. locorigfiles := mustV(m.LocalSize("default", protocol.LocalDeviceID)).Files
  1788. globorigfiles := mustV(m.GlobalSize("default")).Files
  1789. // Delete
  1790. must(t, ffs.Remove("testrm"))
  1791. must(t, ffs.Remove("testrm2"))
  1792. // Verify that the number of files decreased by two and the number of
  1793. // deleted files increases by two
  1794. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1795. loc := mustV(m.LocalSize("default", protocol.LocalDeviceID))
  1796. glob := mustV(m.GlobalSize("default"))
  1797. if loc.Files != locorigfiles-2 {
  1798. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1799. }
  1800. if glob.Files != globorigfiles-2 {
  1801. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1802. }
  1803. if loc.Deleted != 2 {
  1804. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1805. }
  1806. if glob.Deleted != 2 {
  1807. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1808. }
  1809. }
  1810. func TestIssue4357(t *testing.T) {
  1811. cfg := defaultCfgWrapper.RawCopy()
  1812. // Create a separate wrapper not to pollute other tests.
  1813. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  1814. defer cancel()
  1815. m := newModel(t, wrapper, myID, nil)
  1816. m.ServeBackground()
  1817. defer cleanupModel(m)
  1818. // Force the model to wire itself and add the folders
  1819. replace(t, wrapper, cfg)
  1820. if _, ok := m.folderCfgs["default"]; !ok {
  1821. t.Error("Folder should be running")
  1822. }
  1823. newCfg := wrapper.RawCopy()
  1824. newCfg.Folders[0].Paused = true
  1825. replace(t, wrapper, newCfg)
  1826. if _, ok := m.folderCfgs["default"]; ok {
  1827. t.Error("Folder should not be running")
  1828. }
  1829. if _, ok := m.cfg.Folder("default"); !ok {
  1830. t.Error("should still have folder in config")
  1831. }
  1832. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1833. if _, ok := m.cfg.Folder("default"); ok {
  1834. t.Error("should not have folder in config")
  1835. }
  1836. // Add the folder back, should be running
  1837. replace(t, wrapper, cfg)
  1838. if _, ok := m.folderCfgs["default"]; !ok {
  1839. t.Error("Folder should be running")
  1840. }
  1841. if _, ok := m.cfg.Folder("default"); !ok {
  1842. t.Error("should still have folder in config")
  1843. }
  1844. // Should not panic when removing a running folder.
  1845. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1846. if _, ok := m.folderCfgs["default"]; ok {
  1847. t.Error("Folder should not be running")
  1848. }
  1849. if _, ok := m.cfg.Folder("default"); ok {
  1850. t.Error("should not have folder in config")
  1851. }
  1852. }
  1853. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1854. m := newModel(t, defaultCfgWrapper, myID, nil)
  1855. m.sdb.DropAllFiles("default", device1)
  1856. m.sdb.Update("default", device1, genFiles(1))
  1857. m.sdb.DropAllFiles("default", device2)
  1858. m.sdb.Update("default", device2, genFiles(1))
  1859. if devs, err := m.sdb.ListDevicesForFolder("default"); err != nil || len(devs) != 2 {
  1860. t.Log(devs, err)
  1861. t.Error("expected two devices")
  1862. }
  1863. m.newFolder(defaultFolderConfig, false)
  1864. defer cleanupModel(m)
  1865. if devs, err := m.sdb.ListDevicesForFolder("default"); err != nil || len(devs) != 1 {
  1866. t.Log(devs, err)
  1867. t.Error("expected one device")
  1868. }
  1869. }
  1870. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1871. wcfg, cancel := newConfigWrapper(defaultCfg)
  1872. defer cancel()
  1873. addDevice2(t, wcfg, wcfg.FolderList()[0])
  1874. m := setupModel(t, wcfg)
  1875. defer cleanupModel(m)
  1876. conn1 := newFakeConnection(device1, m)
  1877. m.AddConnection(conn1, protocol.Hello{})
  1878. conn2 := newFakeConnection(device2, m)
  1879. m.AddConnection(conn2, protocol.Hello{})
  1880. m.ClusterConfig(conn1, &protocol.ClusterConfig{
  1881. Folders: []protocol.Folder{
  1882. {
  1883. ID: "default",
  1884. Devices: []protocol.Device{
  1885. {ID: myID},
  1886. {ID: device1},
  1887. {ID: device2},
  1888. },
  1889. },
  1890. },
  1891. })
  1892. m.ClusterConfig(conn2, &protocol.ClusterConfig{
  1893. Folders: []protocol.Folder{
  1894. {
  1895. ID: "default",
  1896. Devices: []protocol.Device{
  1897. {ID: myID},
  1898. {ID: device1},
  1899. {ID: device2},
  1900. },
  1901. },
  1902. },
  1903. })
  1904. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  1905. t.Error("not shared with device1")
  1906. }
  1907. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
  1908. t.Error("not shared with device2")
  1909. }
  1910. select {
  1911. case <-conn2.Closed():
  1912. t.Error("conn already closed")
  1913. default:
  1914. }
  1915. if _, err := wcfg.RemoveDevice(device2); err != nil {
  1916. t.Error(err)
  1917. }
  1918. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1919. fcfg, ok := m.cfg.Folder("default")
  1920. if !ok {
  1921. t.Fatal("default folder missing")
  1922. }
  1923. if !fcfg.SharedWith(device1) {
  1924. t.Error("not shared with device1")
  1925. }
  1926. if fcfg.SharedWith(device2) {
  1927. t.Error("shared with device2")
  1928. }
  1929. for _, dev := range fcfg.Devices {
  1930. if dev.DeviceID == device2 {
  1931. t.Error("still there")
  1932. }
  1933. }
  1934. select {
  1935. case <-conn2.Closed():
  1936. default:
  1937. t.Error("connection not closed")
  1938. }
  1939. if _, ok := wcfg.Devices()[device2]; ok {
  1940. t.Error("device still in config")
  1941. }
  1942. if _, ok := m.deviceConnIDs[device2]; ok {
  1943. t.Error("conn not missing")
  1944. }
  1945. if _, ok := m.helloMessages[device2]; ok {
  1946. t.Error("hello not missing")
  1947. }
  1948. if _, ok := m.deviceDownloads[device2]; ok {
  1949. t.Error("downloads not missing")
  1950. }
  1951. }
  1952. func TestIssue3804(t *testing.T) {
  1953. m := setupModel(t, defaultCfgWrapper)
  1954. defer cleanupModel(m)
  1955. // Subdirs ending in slash should be accepted
  1956. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1957. t.Error("Unexpected error:", err)
  1958. }
  1959. }
  1960. func TestIssue3829(t *testing.T) {
  1961. m := setupModel(t, defaultCfgWrapper)
  1962. defer cleanupModel(m)
  1963. // Empty subdirs should be accepted
  1964. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1965. t.Error("Unexpected error:", err)
  1966. }
  1967. }
  1968. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  1969. func TestIssue4573(t *testing.T) {
  1970. w, fcfg, wCancel := newDefaultCfgWrapper()
  1971. defer wCancel()
  1972. testFs := fcfg.Filesystem()
  1973. defer os.RemoveAll(testFs.URI())
  1974. must(t, testFs.MkdirAll("inaccessible", 0o755))
  1975. defer testFs.Chmod("inaccessible", 0o777)
  1976. file := filepath.Join("inaccessible", "a")
  1977. fd, err := testFs.Create(file)
  1978. must(t, err)
  1979. fd.Close()
  1980. m := setupModel(t, w)
  1981. defer cleanupModel(m)
  1982. must(t, testFs.Chmod("inaccessible", 0o000))
  1983. m.ScanFolder("default")
  1984. if file, ok := m.testCurrentFolderFile("default", file); !ok {
  1985. t.Fatalf("File missing in db")
  1986. } else if file.Deleted {
  1987. t.Errorf("Inaccessible file has been marked as deleted.")
  1988. }
  1989. }
  1990. // TestInternalScan checks whether various fs operations are correctly represented
  1991. // in the db after scanning.
  1992. func TestInternalScan(t *testing.T) {
  1993. w, fcfg, wCancel := newDefaultCfgWrapper()
  1994. defer wCancel()
  1995. testFs := fcfg.Filesystem()
  1996. defer os.RemoveAll(testFs.URI())
  1997. testCases := map[string]func(protocol.FileInfo) bool{
  1998. "removeDir": func(f protocol.FileInfo) bool {
  1999. return !f.Deleted
  2000. },
  2001. "dirToFile": func(f protocol.FileInfo) bool {
  2002. return f.Deleted || f.IsDirectory()
  2003. },
  2004. }
  2005. baseDirs := []string{"dirToFile", "removeDir"}
  2006. for _, dir := range baseDirs {
  2007. sub := filepath.Join(dir, "subDir")
  2008. for _, dir := range []string{dir, sub} {
  2009. if err := testFs.MkdirAll(dir, 0o775); err != nil {
  2010. t.Fatalf("%v: %v", dir, err)
  2011. }
  2012. }
  2013. testCases[sub] = func(f protocol.FileInfo) bool {
  2014. return !f.Deleted
  2015. }
  2016. for _, dir := range []string{dir, sub} {
  2017. file := filepath.Join(dir, "a")
  2018. fd, err := testFs.Create(file)
  2019. must(t, err)
  2020. fd.Close()
  2021. testCases[file] = func(f protocol.FileInfo) bool {
  2022. return !f.Deleted
  2023. }
  2024. }
  2025. }
  2026. m := setupModel(t, w)
  2027. defer cleanupModel(m)
  2028. for _, dir := range baseDirs {
  2029. must(t, testFs.RemoveAll(dir))
  2030. }
  2031. fd, err := testFs.Create("dirToFile")
  2032. must(t, err)
  2033. fd.Close()
  2034. m.ScanFolder("default")
  2035. for path, cond := range testCases {
  2036. if f, ok := m.testCurrentFolderFile("default", path); !ok {
  2037. t.Fatalf("%v missing in db", path)
  2038. } else if cond(f) {
  2039. t.Errorf("Incorrect db entry for %v", path)
  2040. }
  2041. }
  2042. }
  2043. func TestCustomMarkerName(t *testing.T) {
  2044. fcfg := newFolderConfig()
  2045. fcfg.ID = "default"
  2046. fcfg.RescanIntervalS = 1
  2047. fcfg.MarkerName = "myfile"
  2048. cfg, cancel := newConfigWrapper(config.Configuration{
  2049. Version: config.CurrentVersion,
  2050. Folders: []config.FolderConfiguration{fcfg},
  2051. Devices: []config.DeviceConfiguration{
  2052. {
  2053. DeviceID: device1,
  2054. },
  2055. },
  2056. })
  2057. defer cancel()
  2058. ffs := fcfg.Filesystem()
  2059. m := newModel(t, cfg, myID, nil)
  2060. m.sdb.Update("default", protocol.LocalDeviceID, []protocol.FileInfo{
  2061. {Name: "dummyfile"},
  2062. })
  2063. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  2064. t.Fatal(err)
  2065. }
  2066. sub := m.evLogger.Subscribe(events.StateChanged)
  2067. defer sub.Unsubscribe()
  2068. m.ServeBackground()
  2069. defer cleanupModel(m)
  2070. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  2071. fd, _ := ffs.Create("myfile")
  2072. fd.Close()
  2073. waitForState(t, sub, "default", "")
  2074. }
  2075. func TestRemoveDirWithContent(t *testing.T) {
  2076. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2077. defer wcfgCancel()
  2078. tfs := fcfg.Filesystem()
  2079. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2080. tfs.MkdirAll("dirwith", 0o755)
  2081. content := filepath.Join("dirwith", "content")
  2082. fd, err := tfs.Create(content)
  2083. must(t, err)
  2084. fd.Close()
  2085. must(t, m.ScanFolder(fcfg.ID))
  2086. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2087. if !ok {
  2088. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2089. }
  2090. dir.Deleted = true
  2091. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2092. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2093. if !ok {
  2094. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2095. }
  2096. file.Deleted = true
  2097. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2098. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{dir, file}}))
  2099. // Is there something we could trigger on instead of just waiting?
  2100. timeout := time.NewTimer(5 * time.Second)
  2101. for {
  2102. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2103. if !ok {
  2104. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2105. }
  2106. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2107. if !ok {
  2108. t.Fatalf("Can't get file \"%v\" after index update", content)
  2109. }
  2110. if dir.Deleted && file.Deleted {
  2111. return
  2112. }
  2113. select {
  2114. case <-timeout.C:
  2115. if !dir.Deleted && !file.Deleted {
  2116. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2117. } else if !dir.Deleted {
  2118. t.Errorf("The dir was not deleted before timing out.")
  2119. } else {
  2120. t.Errorf("The content of the dir was not deleted before timing out.")
  2121. }
  2122. return
  2123. default:
  2124. time.Sleep(100 * time.Millisecond)
  2125. }
  2126. }
  2127. }
  2128. func TestIssue4475(t *testing.T) {
  2129. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2130. defer wcfgCancel()
  2131. defer cleanupModel(m)
  2132. testFs := fcfg.Filesystem()
  2133. // Scenario: Dir is deleted locally and before syncing/index exchange
  2134. // happens, a file is create in that dir on the remote.
  2135. // This should result in the directory being recreated and added to the
  2136. // db locally.
  2137. must(t, testFs.MkdirAll("delDir", 0o755))
  2138. m.ScanFolder("default")
  2139. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2140. t.Fatal("not shared with device1")
  2141. }
  2142. fileName := filepath.Join("delDir", "file")
  2143. conn.addFile(fileName, 0o644, protocol.FileInfoTypeFile, nil)
  2144. conn.sendIndexUpdate()
  2145. // Is there something we could trigger on instead of just waiting?
  2146. timeout := time.NewTimer(5 * time.Second)
  2147. created := false
  2148. for {
  2149. if !created {
  2150. if _, ok := m.testCurrentFolderFile("default", fileName); ok {
  2151. created = true
  2152. }
  2153. } else {
  2154. dir, ok := m.testCurrentFolderFile("default", "delDir")
  2155. if !ok {
  2156. t.Fatalf("can't get dir from db")
  2157. }
  2158. if !dir.Deleted {
  2159. return
  2160. }
  2161. }
  2162. select {
  2163. case <-timeout.C:
  2164. if created {
  2165. t.Errorf("Timed out before file from remote was created")
  2166. } else {
  2167. t.Errorf("Timed out before directory was resurrected in db")
  2168. }
  2169. return
  2170. default:
  2171. time.Sleep(100 * time.Millisecond)
  2172. }
  2173. }
  2174. }
  2175. func TestVersionRestore(t *testing.T) {
  2176. t.Skip("incompatible with fakefs")
  2177. // We create a bunch of files which we restore
  2178. // In each file, we write the filename as the content
  2179. // We verify that the content matches at the expected filenames
  2180. // after the restore operation.
  2181. fcfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", config.FilesystemTypeFake, srand.String(32))
  2182. fcfg.Versioning.Type = "simple"
  2183. fcfg.FSWatcherEnabled = false
  2184. filesystem := fcfg.Filesystem()
  2185. rawConfig := config.Configuration{
  2186. Version: config.CurrentVersion,
  2187. Folders: []config.FolderConfiguration{fcfg},
  2188. }
  2189. cfg, cancel := newConfigWrapper(rawConfig)
  2190. defer cancel()
  2191. m := setupModel(t, cfg)
  2192. defer cleanupModel(m)
  2193. m.ScanFolder("default")
  2194. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20180101-010101", time.Local)
  2195. if err != nil {
  2196. t.Fatal(err)
  2197. }
  2198. for _, file := range []string{
  2199. // Versions directory
  2200. ".stversions/file~20171210-040404.txt", // will be restored
  2201. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2202. ".stversions/something~20171210-040404", // will become directory, hence error
  2203. ".stversions/dir/file~20171210-040404.txt",
  2204. ".stversions/dir/file~20171210-040405.txt",
  2205. ".stversions/dir/file~20171210-040406.txt",
  2206. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2207. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2208. ".stversions/dir/cat", // untagged which was used by trashcan, supported
  2209. // "file.txt" will be restored
  2210. "existing",
  2211. "something/file", // Becomes directory
  2212. "dir/file.txt",
  2213. "dir/existing.txt",
  2214. } {
  2215. if build.IsWindows {
  2216. file = filepath.FromSlash(file)
  2217. }
  2218. dir := filepath.Dir(file)
  2219. must(t, filesystem.MkdirAll(dir, 0o755))
  2220. if fd, err := filesystem.Create(file); err != nil {
  2221. t.Fatal(err)
  2222. } else if _, err := fd.Write([]byte(file)); err != nil {
  2223. t.Fatal(err)
  2224. } else if err := fd.Close(); err != nil {
  2225. t.Fatal(err)
  2226. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2227. t.Fatal(err)
  2228. }
  2229. }
  2230. versions, err := m.GetFolderVersions("default")
  2231. must(t, err)
  2232. expectedVersions := map[string]int{
  2233. "file.txt": 1,
  2234. "existing": 1,
  2235. "something": 1,
  2236. "dir/file.txt": 3,
  2237. "dir/existing.txt": 1,
  2238. "very/very/deep/one.txt": 1,
  2239. "dir/cat": 1,
  2240. }
  2241. for name, vers := range versions {
  2242. cnt, ok := expectedVersions[name]
  2243. if !ok {
  2244. t.Errorf("unexpected %s", name)
  2245. }
  2246. if len(vers) != cnt {
  2247. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2248. }
  2249. // Delete, so we can check if we didn't hit something we expect afterwards.
  2250. delete(expectedVersions, name)
  2251. }
  2252. for name := range expectedVersions {
  2253. t.Errorf("not found expected %s", name)
  2254. }
  2255. // Restoring non existing folder fails.
  2256. _, err = m.RestoreFolderVersions("does not exist", nil)
  2257. if err == nil {
  2258. t.Errorf("expected an error")
  2259. }
  2260. makeTime := func(s string) time.Time {
  2261. tm, err := time.ParseInLocation(versioner.TimeFormat, s, time.Local)
  2262. if err != nil {
  2263. t.Error(err)
  2264. }
  2265. return tm.Truncate(time.Second)
  2266. }
  2267. restore := map[string]time.Time{
  2268. "file.txt": makeTime("20171210-040404"),
  2269. "existing": makeTime("20171210-040404"),
  2270. "something": makeTime("20171210-040404"),
  2271. "dir/file.txt": makeTime("20171210-040406"),
  2272. "dir/existing.txt": makeTime("20171210-040406"),
  2273. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2274. }
  2275. beforeRestore := time.Now().Truncate(time.Second)
  2276. ferr, err := m.RestoreFolderVersions("default", restore)
  2277. must(t, err)
  2278. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || !errors.Is(err, versioner.ErrDirectory) {
  2279. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2280. }
  2281. // Failed items are not expected to be restored.
  2282. // Remove them from expectations
  2283. for name := range ferr {
  2284. delete(restore, name)
  2285. }
  2286. // Check that content of files matches to the version they've been restored.
  2287. for file, version := range restore {
  2288. if build.IsWindows {
  2289. file = filepath.FromSlash(file)
  2290. }
  2291. tag := version.In(time.Local).Truncate(time.Second).Format(versioner.TimeFormat)
  2292. taggedName := filepath.Join(versioner.DefaultPath, versioner.TagFilename(file, tag))
  2293. fd, err := filesystem.Open(file)
  2294. if err != nil {
  2295. t.Error(err)
  2296. }
  2297. defer fd.Close()
  2298. content, err := io.ReadAll(fd)
  2299. if err != nil {
  2300. t.Error(err)
  2301. }
  2302. if !bytes.Equal(content, []byte(taggedName)) {
  2303. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2304. }
  2305. }
  2306. // Simple versioner uses now for timestamp generation, so we can check
  2307. // if existing stuff was correctly archived as we restored (oppose to deleteD), and version time as after beforeRestore
  2308. expectArchived := map[string]struct{}{
  2309. "existing": {},
  2310. "dir/file.txt": {},
  2311. "dir/existing.txt": {},
  2312. }
  2313. allFileVersions, err := m.GetFolderVersions("default")
  2314. must(t, err)
  2315. for file, versions := range allFileVersions {
  2316. key := file
  2317. if build.IsWindows {
  2318. file = filepath.FromSlash(file)
  2319. }
  2320. for _, version := range versions {
  2321. if version.VersionTime.Equal(beforeRestore) || version.VersionTime.After(beforeRestore) {
  2322. fd, err := filesystem.Open(versioner.DefaultPath + "/" + versioner.TagFilename(file, version.VersionTime.Format(versioner.TimeFormat)))
  2323. must(t, err)
  2324. defer fd.Close()
  2325. content, err := io.ReadAll(fd)
  2326. if err != nil {
  2327. t.Error(err)
  2328. }
  2329. // Even if they are at the archived path, content should have the non
  2330. // archived name.
  2331. if !bytes.Equal(content, []byte(file)) {
  2332. t.Errorf("%s (%s): %s != %s", file, fd.Name(), string(content), file)
  2333. }
  2334. _, ok := expectArchived[key]
  2335. if !ok {
  2336. t.Error("unexpected archived file with future timestamp", file, version.VersionTime)
  2337. }
  2338. delete(expectArchived, key)
  2339. }
  2340. }
  2341. }
  2342. if len(expectArchived) != 0 {
  2343. t.Fatal("missed some archived files", expectArchived)
  2344. }
  2345. }
  2346. func TestPausedFolders(t *testing.T) {
  2347. // Create a separate wrapper not to pollute other tests.
  2348. wrapper, cancel := newConfigWrapper(defaultCfgWrapper.RawCopy())
  2349. defer cancel()
  2350. m := setupModel(t, wrapper)
  2351. defer cleanupModel(m)
  2352. if err := m.ScanFolder("default"); err != nil {
  2353. t.Error(err)
  2354. }
  2355. pausedConfig := wrapper.RawCopy()
  2356. pausedConfig.Folders[0].Paused = true
  2357. replace(t, wrapper, pausedConfig)
  2358. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2359. t.Errorf("Expected folder paused error, received: %v", err)
  2360. }
  2361. if err := m.ScanFolder("nonexistent"); err != ErrFolderMissing {
  2362. t.Errorf("Expected missing folder error, received: %v", err)
  2363. }
  2364. }
  2365. func TestIssue4094(t *testing.T) {
  2366. // Create a separate wrapper not to pollute other tests.
  2367. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2368. defer cancel()
  2369. m := newModel(t, wrapper, myID, nil)
  2370. m.ServeBackground()
  2371. defer cleanupModel(m)
  2372. // Force the model to wire itself and add the folders
  2373. folderPath := "nonexistent"
  2374. cfg := defaultCfgWrapper.RawCopy()
  2375. fcfg := config.FolderConfiguration{
  2376. FilesystemType: config.FilesystemTypeFake,
  2377. ID: "folder1",
  2378. Path: folderPath,
  2379. Paused: true,
  2380. Devices: []config.FolderDeviceConfiguration{
  2381. {DeviceID: device1},
  2382. },
  2383. }
  2384. cfg.Folders = []config.FolderConfiguration{fcfg}
  2385. replace(t, wrapper, cfg)
  2386. if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
  2387. t.Fatalf("failed setting ignores: %v", err)
  2388. }
  2389. if _, err := fcfg.Filesystem().Lstat(".stignore"); err != nil {
  2390. t.Fatalf("failed stating .stignore: %v", err)
  2391. }
  2392. }
  2393. func TestIssue4903(t *testing.T) {
  2394. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2395. defer cancel()
  2396. m := setupModel(t, wrapper)
  2397. defer cleanupModel(m)
  2398. // Force the model to wire itself and add the folders
  2399. folderPath := "nonexistent"
  2400. cfg := defaultCfgWrapper.RawCopy()
  2401. fcfg := config.FolderConfiguration{
  2402. ID: "folder1",
  2403. Path: folderPath,
  2404. Paused: true,
  2405. Devices: []config.FolderDeviceConfiguration{
  2406. {DeviceID: device1},
  2407. },
  2408. }
  2409. cfg.Folders = []config.FolderConfiguration{fcfg}
  2410. replace(t, wrapper, cfg)
  2411. if err := fcfg.CheckPath(); err != config.ErrPathMissing {
  2412. t.Fatalf("expected path missing error, got: %v, debug: %s", err, fcfg.CheckPath())
  2413. }
  2414. if _, err := fcfg.Filesystem().Lstat("."); !fs.IsNotExist(err) {
  2415. t.Fatalf("Expected missing path error, got: %v", err)
  2416. }
  2417. }
  2418. func TestIssue5002(t *testing.T) {
  2419. // recheckFile should not panic when given an index equal to the number of blocks
  2420. w, fcfg, wCancel := newDefaultCfgWrapper()
  2421. defer wCancel()
  2422. ffs := fcfg.Filesystem()
  2423. fd, err := ffs.Create("foo")
  2424. must(t, err)
  2425. _, err = fd.Write([]byte("foobar"))
  2426. must(t, err)
  2427. fd.Close()
  2428. m := setupModel(t, w)
  2429. defer cleanupModel(m)
  2430. if err := m.ScanFolder("default"); err != nil {
  2431. t.Error(err)
  2432. }
  2433. file, ok := m.testCurrentFolderFile("default", "foo")
  2434. if !ok {
  2435. t.Fatal("test file should exist")
  2436. }
  2437. blockSize := int32(file.BlockSize())
  2438. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size-int64(blockSize), []byte{1, 2, 3, 4})
  2439. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size, []byte{1, 2, 3, 4}) // panic
  2440. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size+int64(blockSize), []byte{1, 2, 3, 4})
  2441. }
  2442. func TestParentOfUnignored(t *testing.T) {
  2443. w, fcfg, wCancel := newDefaultCfgWrapper()
  2444. defer wCancel()
  2445. ffs := fcfg.Filesystem()
  2446. must(t, ffs.Mkdir("bar", 0o755))
  2447. must(t, ffs.Mkdir("baz", 0o755))
  2448. must(t, ffs.Mkdir("baz/quux", 0o755))
  2449. m := setupModel(t, w)
  2450. defer cleanupModel(m)
  2451. m.SetIgnores("default", []string{"!quux", "*"})
  2452. m.ScanFolder("default")
  2453. if bar, ok := m.testCurrentFolderFile("default", "bar"); !ok {
  2454. t.Error(`Directory "bar" missing in db`)
  2455. } else if !bar.IsIgnored() {
  2456. t.Error(`Directory "bar" is not ignored`)
  2457. }
  2458. if baz, ok := m.testCurrentFolderFile("default", "baz"); !ok {
  2459. t.Error(`Directory "baz" missing in db`)
  2460. } else if baz.IsIgnored() {
  2461. t.Error(`Directory "baz" is ignored`)
  2462. }
  2463. }
  2464. // TestFolderRestartZombies reproduces issue 5233, where multiple concurrent folder
  2465. // restarts would leave more than one folder runner alive.
  2466. func TestFolderRestartZombies(t *testing.T) {
  2467. wrapper, cancel := newConfigWrapper(defaultCfg.Copy())
  2468. defer cancel()
  2469. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2470. cfg.Options.RawMaxFolderConcurrency = -1
  2471. _, i, _ := cfg.Folder("default")
  2472. cfg.Folders[i].FilesystemType = config.FilesystemTypeFake
  2473. })
  2474. must(t, err)
  2475. waiter.Wait()
  2476. folderCfg, _ := wrapper.Folder("default")
  2477. m := setupModel(t, wrapper)
  2478. defer cleanupModel(m)
  2479. // Make sure the folder is up and running, because we want to count it.
  2480. m.ScanFolder("default")
  2481. // Check how many running folders we have running before the test.
  2482. if r := m.foldersRunning.Load(); r != 1 {
  2483. t.Error("Expected one running folder, not", r)
  2484. }
  2485. // Run a few parallel configuration changers for one second. Each waits
  2486. // for the commit to complete, but there are many of them.
  2487. var wg sync.WaitGroup
  2488. for i := 0; i < 25; i++ {
  2489. wg.Add(1)
  2490. go func() {
  2491. defer wg.Done()
  2492. t0 := time.Now()
  2493. for time.Since(t0) < time.Second {
  2494. fcfg := folderCfg.Copy()
  2495. fcfg.MaxConflicts = mrand.Int() // safe change that should cause a folder restart
  2496. setFolder(t, wrapper, fcfg)
  2497. }
  2498. }()
  2499. }
  2500. // Wait for the above to complete and check how many folders we have
  2501. // running now. It should not have increased.
  2502. wg.Wait()
  2503. // Make sure the folder is up and running, because we want to count it.
  2504. m.ScanFolder("default")
  2505. if r := m.foldersRunning.Load(); r != 1 {
  2506. t.Error("Expected one running folder, not", r)
  2507. }
  2508. }
  2509. func TestRequestLimit(t *testing.T) {
  2510. wrapper, fcfg, cancel := newDefaultCfgWrapper()
  2511. ffs := fcfg.Filesystem()
  2512. file := "tmpfile"
  2513. fd, err := ffs.Create(file)
  2514. must(t, err)
  2515. fd.Close()
  2516. defer cancel()
  2517. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2518. _, i, _ := cfg.Device(device1)
  2519. cfg.Devices[i].MaxRequestKiB = 1
  2520. })
  2521. must(t, err)
  2522. waiter.Wait()
  2523. m, conn := setupModelWithConnectionFromWrapper(t, wrapper)
  2524. defer cleanupModel(m)
  2525. m.ScanFolder("default")
  2526. befReq := time.Now()
  2527. first, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
  2528. if err != nil {
  2529. t.Fatalf("First request failed: %v", err)
  2530. }
  2531. reqDur := time.Since(befReq)
  2532. returned := make(chan struct{})
  2533. go func() {
  2534. second, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
  2535. if err != nil {
  2536. t.Errorf("Second request failed: %v", err)
  2537. }
  2538. close(returned)
  2539. second.Close()
  2540. }()
  2541. time.Sleep(10 * reqDur)
  2542. select {
  2543. case <-returned:
  2544. t.Fatalf("Second request returned before first was done")
  2545. default:
  2546. }
  2547. first.Close()
  2548. select {
  2549. case <-returned:
  2550. case <-time.After(time.Second):
  2551. t.Fatalf("Second request did not return after first was done")
  2552. }
  2553. }
  2554. // TestConnCloseOnRestart checks that there is no deadlock when calling Close
  2555. // on a protocol connection that has a blocking reader (blocking writer can't
  2556. // be done as the test requires clusterconfigs to go through).
  2557. func TestConnCloseOnRestart(t *testing.T) {
  2558. oldCloseTimeout := protocol.CloseTimeout
  2559. protocol.CloseTimeout = 100 * time.Millisecond
  2560. defer func() {
  2561. protocol.CloseTimeout = oldCloseTimeout
  2562. }()
  2563. w, fcfg, wCancel := newDefaultCfgWrapper()
  2564. defer wCancel()
  2565. m := setupModel(t, w)
  2566. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  2567. br := &testutil.BlockingRW{}
  2568. nw := &testutil.NoopRW{}
  2569. ci := &protocolmocks.ConnectionInfo{}
  2570. ci.ConnectionIDReturns(srand.String(16))
  2571. m.AddConnection(protocol.NewConnection(device1, br, nw, testutil.NoopCloser{}, m, ci, protocol.CompressionNever, nil, m.keyGen), protocol.Hello{})
  2572. m.mut.RLock()
  2573. if len(m.closed) != 1 {
  2574. t.Fatalf("Expected just one conn (len(m.closed) == %v)", len(m.closed))
  2575. }
  2576. var closed chan struct{}
  2577. for _, c := range m.closed {
  2578. closed = c
  2579. }
  2580. m.mut.RUnlock()
  2581. waiter, err := w.RemoveDevice(device1)
  2582. if err != nil {
  2583. t.Fatal(err)
  2584. }
  2585. done := make(chan struct{})
  2586. go func() {
  2587. waiter.Wait()
  2588. close(done)
  2589. }()
  2590. select {
  2591. case <-done:
  2592. case <-time.After(5 * time.Second):
  2593. t.Fatal("Timed out before config took effect")
  2594. }
  2595. select {
  2596. case <-closed:
  2597. case <-time.After(5 * time.Second):
  2598. t.Fatal("Timed out before connection was closed")
  2599. }
  2600. }
  2601. func TestModTimeWindow(t *testing.T) {
  2602. w, fcfg, wCancel := newDefaultCfgWrapper()
  2603. defer wCancel()
  2604. tfs := modtimeTruncatingFS{
  2605. trunc: 0,
  2606. Filesystem: fcfg.Filesystem(),
  2607. }
  2608. // fcfg.RawModTimeWindowS = 2
  2609. setFolder(t, w, fcfg)
  2610. m := setupModel(t, w)
  2611. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2612. name := "foo"
  2613. fd, err := tfs.Create(name)
  2614. must(t, err)
  2615. stat, err := fd.Stat()
  2616. must(t, err)
  2617. modTime := stat.ModTime()
  2618. fd.Close()
  2619. m.ScanFolders()
  2620. // Get current version
  2621. fi, ok := m.testCurrentFolderFile("default", name)
  2622. if !ok {
  2623. t.Fatal("File missing")
  2624. }
  2625. v := fi.Version
  2626. // Change the filesystem to only return modtimes to the closest two
  2627. // seconds, like FAT.
  2628. tfs.trunc = 2 * time.Second
  2629. // Scan again
  2630. m.ScanFolders()
  2631. // No change due to within window
  2632. fi, _ = m.testCurrentFolderFile("default", name)
  2633. if !fi.Version.Equal(v) {
  2634. t.Fatalf("Got version %v, expected %v", fi.Version, v)
  2635. }
  2636. // Update to be outside window
  2637. err = tfs.Chtimes(name, time.Now(), modTime.Add(2*time.Second))
  2638. must(t, err)
  2639. m.ScanFolders()
  2640. // Version should have updated
  2641. fi, _ = m.testCurrentFolderFile("default", name)
  2642. if fi.Version.Compare(v) != protocol.Greater {
  2643. t.Fatalf("Got result %v, expected %v", fi.Version.Compare(v), protocol.Greater)
  2644. }
  2645. }
  2646. func TestDevicePause(t *testing.T) {
  2647. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2648. defer wcfgCancel()
  2649. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  2650. sub := m.evLogger.Subscribe(events.DevicePaused)
  2651. defer sub.Unsubscribe()
  2652. m.mut.RLock()
  2653. var closed chan struct{}
  2654. for _, c := range m.closed {
  2655. closed = c
  2656. }
  2657. m.mut.RUnlock()
  2658. pauseDevice(t, m.cfg, device1, true)
  2659. timeout := time.NewTimer(5 * time.Second)
  2660. select {
  2661. case <-sub.C():
  2662. select {
  2663. case <-closed:
  2664. case <-timeout.C:
  2665. t.Fatal("Timed out before connection was closed")
  2666. }
  2667. case <-timeout.C:
  2668. t.Fatal("Timed out before device was paused")
  2669. }
  2670. }
  2671. func TestDeviceWasSeen(t *testing.T) {
  2672. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2673. defer wcfgCancel()
  2674. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  2675. m.deviceWasSeen(device1)
  2676. stats, err := m.DeviceStatistics()
  2677. if err != nil {
  2678. t.Error("Unexpected error:", err)
  2679. }
  2680. entry := stats[device1]
  2681. if time.Since(entry.LastSeen) > time.Second {
  2682. t.Error("device should have been seen now")
  2683. }
  2684. }
  2685. func TestNewLimitedRequestResponse(t *testing.T) {
  2686. l0 := semaphore.New(0)
  2687. l1 := semaphore.New(1024)
  2688. l2 := (*semaphore.Semaphore)(nil)
  2689. // Should take 500 bytes from any non-unlimited non-nil limiters.
  2690. res := newLimitedRequestResponse(500, l0, l1, l2)
  2691. if l1.Available() != 1024-500 {
  2692. t.Error("should have taken bytes from limited limiter")
  2693. }
  2694. // Closing the result should return the bytes.
  2695. res.Close()
  2696. // Try to take 1024 bytes to make sure the bytes were returned.
  2697. done := make(chan struct{})
  2698. go func() {
  2699. l1.Take(1024)
  2700. close(done)
  2701. }()
  2702. select {
  2703. case <-done:
  2704. case <-time.After(time.Second):
  2705. t.Error("Bytes weren't returned in a timely fashion")
  2706. }
  2707. }
  2708. func TestSummaryPausedNoError(t *testing.T) {
  2709. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2710. defer wcfgCancel()
  2711. pauseFolder(t, wcfg, fcfg.ID, true)
  2712. m := setupModel(t, wcfg)
  2713. defer cleanupModel(m)
  2714. fss := NewFolderSummaryService(wcfg, m, myID, events.NoopLogger)
  2715. if _, err := fss.Summary(fcfg.ID); err != nil {
  2716. t.Error("Expected no error getting a summary for a paused folder:", err)
  2717. }
  2718. }
  2719. func TestFolderAPIErrors(t *testing.T) {
  2720. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2721. defer wcfgCancel()
  2722. pauseFolder(t, wcfg, fcfg.ID, true)
  2723. m := setupModel(t, wcfg)
  2724. defer cleanupModel(m)
  2725. methods := []func(folder string) error{
  2726. m.ScanFolder,
  2727. func(folder string) error {
  2728. return m.ScanFolderSubdirs(folder, nil)
  2729. },
  2730. func(folder string) error {
  2731. _, err := m.GetFolderVersions(folder)
  2732. return err
  2733. },
  2734. func(folder string) error {
  2735. _, err := m.RestoreFolderVersions(folder, nil)
  2736. return err
  2737. },
  2738. }
  2739. for i, method := range methods {
  2740. if err := method(fcfg.ID); err != ErrFolderPaused {
  2741. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderPaused, err, i)
  2742. }
  2743. if err := method("notexisting"); err != ErrFolderMissing {
  2744. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderMissing, err, i)
  2745. }
  2746. }
  2747. }
  2748. func TestRenameSequenceOrder(t *testing.T) {
  2749. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2750. defer wcfgCancel()
  2751. m := setupModel(t, wcfg)
  2752. defer cleanupModel(m)
  2753. numFiles := 20
  2754. ffs := fcfg.Filesystem()
  2755. for i := 0; i < numFiles; i++ {
  2756. v := fmt.Sprintf("%d", i)
  2757. writeFile(t, ffs, v, []byte(v))
  2758. }
  2759. m.ScanFolders()
  2760. count := countIterator[protocol.FileInfo](t)(m.LocalFiles("default", protocol.LocalDeviceID))
  2761. if count != numFiles {
  2762. t.Errorf("Unexpected count: %d != %d", count, numFiles)
  2763. }
  2764. // Modify all the files, other than the ones we expect to rename
  2765. for i := 0; i < numFiles; i++ {
  2766. if i == 3 || i == 17 || i == 16 || i == 4 {
  2767. continue
  2768. }
  2769. v := fmt.Sprintf("%d", i)
  2770. writeFile(t, ffs, v, []byte(v+"-new"))
  2771. }
  2772. // Rename
  2773. must(t, ffs.Rename("3", "17"))
  2774. must(t, ffs.Rename("16", "4"))
  2775. // Scan
  2776. m.ScanFolders()
  2777. var firstExpectedSequence int64
  2778. var secondExpectedSequence int64
  2779. failed := false
  2780. it, errFn := m.LocalFilesSequenced("default", protocol.LocalDeviceID, 0)
  2781. for i := range it {
  2782. t.Log(i)
  2783. if i.FileName() == "17" {
  2784. firstExpectedSequence = i.SequenceNo() + 1
  2785. }
  2786. if i.FileName() == "4" {
  2787. secondExpectedSequence = i.SequenceNo() + 1
  2788. }
  2789. if i.FileName() == "3" {
  2790. failed = i.SequenceNo() != firstExpectedSequence || failed
  2791. }
  2792. if i.FileName() == "16" {
  2793. failed = i.SequenceNo() != secondExpectedSequence || failed
  2794. }
  2795. }
  2796. if err := errFn(); err != nil {
  2797. t.Fatal(err)
  2798. }
  2799. if failed {
  2800. t.Fail()
  2801. }
  2802. }
  2803. func TestRenameSameFile(t *testing.T) {
  2804. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2805. defer wcfgCancel()
  2806. m := setupModel(t, wcfg)
  2807. defer cleanupModel(m)
  2808. ffs := fcfg.Filesystem()
  2809. writeFile(t, ffs, "file", []byte("file"))
  2810. m.ScanFolders()
  2811. count := countIterator[protocol.FileInfo](t)(m.LocalFiles("default", protocol.LocalDeviceID))
  2812. if count != 1 {
  2813. t.Errorf("Unexpected count: %d != %d", count, 1)
  2814. }
  2815. must(t, ffs.Rename("file", "file1"))
  2816. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file0"))
  2817. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file2"))
  2818. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file3"))
  2819. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file4"))
  2820. m.ScanFolders()
  2821. prevSeq := int64(0)
  2822. seen := false
  2823. it, errFn := m.LocalFilesSequenced("default", protocol.LocalDeviceID, 0)
  2824. for i := range it {
  2825. if i.SequenceNo() <= prevSeq {
  2826. t.Fatalf("non-increasing sequences: %d <= %d", i.SequenceNo(), prevSeq)
  2827. }
  2828. if i.FileName() == "file" {
  2829. if seen {
  2830. t.Fatal("already seen file")
  2831. }
  2832. seen = true
  2833. }
  2834. prevSeq = i.SequenceNo()
  2835. }
  2836. if err := errFn(); err != nil {
  2837. t.Fatal(err)
  2838. }
  2839. }
  2840. func TestBlockListMap(t *testing.T) {
  2841. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2842. defer wcfgCancel()
  2843. m := setupModel(t, wcfg)
  2844. defer cleanupModel(m)
  2845. ffs := fcfg.Filesystem()
  2846. writeFile(t, ffs, "one", []byte("content"))
  2847. writeFile(t, ffs, "two", []byte("content"))
  2848. writeFile(t, ffs, "three", []byte("content"))
  2849. writeFile(t, ffs, "four", []byte("content"))
  2850. writeFile(t, ffs, "five", []byte("content"))
  2851. m.ScanFolders()
  2852. fi, ok, err := m.model.CurrentFolderFile("default", "one")
  2853. if err != nil {
  2854. t.Fatal(err)
  2855. }
  2856. if !ok {
  2857. t.Error("failed to find existing file")
  2858. }
  2859. var paths []string
  2860. for fi, err := range itererr.Zip(m.model.AllForBlocksHash(fcfg.ID, fi.BlocksHash)) {
  2861. if err != nil {
  2862. t.Fatal(err)
  2863. }
  2864. paths = append(paths, fi.Name)
  2865. }
  2866. expected := []string{"one", "two", "three", "four", "five"}
  2867. if !equalStringsInAnyOrder(paths, expected) {
  2868. t.Fatalf("expected %q got %q", expected, paths)
  2869. }
  2870. // Fudge the files around
  2871. // Remove
  2872. must(t, ffs.Remove("one"))
  2873. // Modify
  2874. must(t, ffs.Remove("two"))
  2875. writeFile(t, ffs, "two", []byte("mew-content"))
  2876. // Rename
  2877. must(t, ffs.Rename("three", "new-three"))
  2878. // Change type
  2879. must(t, ffs.Remove("four"))
  2880. must(t, ffs.Mkdir("four", 0o644))
  2881. m.ScanFolders()
  2882. // Check we're left with 2 of the 5
  2883. paths = paths[:0]
  2884. for fi, err := range itererr.Zip(m.model.AllForBlocksHash(fcfg.ID, fi.BlocksHash)) {
  2885. if err != nil {
  2886. t.Fatal(err)
  2887. }
  2888. paths = append(paths, fi.Name)
  2889. }
  2890. expected = []string{"new-three", "five"}
  2891. if !equalStringsInAnyOrder(paths, expected) {
  2892. t.Fatalf("expected %q got %q", expected, paths)
  2893. }
  2894. }
  2895. func TestScanRenameCaseOnly(t *testing.T) {
  2896. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2897. defer wcfgCancel()
  2898. m := setupModel(t, wcfg)
  2899. defer cleanupModel(m)
  2900. ffs := fcfg.Filesystem()
  2901. name := "foo"
  2902. writeFile(t, ffs, name, []byte("contents"))
  2903. m.ScanFolders()
  2904. found := false
  2905. for i, err := range itererr.Zip(m.LocalFiles(fcfg.ID, protocol.LocalDeviceID)) {
  2906. if err != nil {
  2907. t.Fatal(err)
  2908. }
  2909. if found {
  2910. t.Fatal("got more than one file")
  2911. }
  2912. if i.FileName() != name {
  2913. t.Fatalf("got file %v, expected %v", i.FileName(), name)
  2914. }
  2915. found = true
  2916. }
  2917. upper := strings.ToUpper(name)
  2918. must(t, ffs.Rename(name, upper))
  2919. m.ScanFolders()
  2920. found = false
  2921. for i, err := range itererr.Zip(m.LocalFiles(fcfg.ID, protocol.LocalDeviceID)) {
  2922. if err != nil {
  2923. t.Fatal(err)
  2924. }
  2925. if i.FileName() == name {
  2926. if i.IsDeleted() {
  2927. continue
  2928. }
  2929. t.Fatal("renamed file not deleted")
  2930. }
  2931. if i.FileName() != upper {
  2932. t.Fatalf("got file %v, expected %v", i.FileName(), upper)
  2933. }
  2934. if found {
  2935. t.Fatal("got more than the expected files")
  2936. }
  2937. found = true
  2938. }
  2939. }
  2940. func TestClusterConfigOnFolderAdd(t *testing.T) {
  2941. testConfigChangeTriggersClusterConfigs(t, false, true, nil, func(wrapper config.Wrapper) {
  2942. fcfg := newFolderConfig()
  2943. fcfg.ID = "second"
  2944. fcfg.Label = "second"
  2945. fcfg.Devices = []config.FolderDeviceConfiguration{{
  2946. DeviceID: device2,
  2947. IntroducedBy: protocol.EmptyDeviceID,
  2948. }}
  2949. setFolder(t, wrapper, fcfg)
  2950. })
  2951. }
  2952. func TestClusterConfigOnFolderShare(t *testing.T) {
  2953. testConfigChangeTriggersClusterConfigs(t, true, true, nil, func(cfg config.Wrapper) {
  2954. fcfg := cfg.FolderList()[0]
  2955. fcfg.Devices = []config.FolderDeviceConfiguration{{
  2956. DeviceID: device2,
  2957. IntroducedBy: protocol.EmptyDeviceID,
  2958. }}
  2959. setFolder(t, cfg, fcfg)
  2960. })
  2961. }
  2962. func TestClusterConfigOnFolderUnshare(t *testing.T) {
  2963. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  2964. fcfg := cfg.FolderList()[0]
  2965. fcfg.Devices = nil
  2966. setFolder(t, cfg, fcfg)
  2967. })
  2968. }
  2969. func TestClusterConfigOnFolderRemove(t *testing.T) {
  2970. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  2971. rcfg := cfg.RawCopy()
  2972. rcfg.Folders = nil
  2973. replace(t, cfg, rcfg)
  2974. })
  2975. }
  2976. func TestClusterConfigOnFolderPause(t *testing.T) {
  2977. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  2978. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  2979. })
  2980. }
  2981. func TestClusterConfigOnFolderUnpause(t *testing.T) {
  2982. testConfigChangeTriggersClusterConfigs(t, true, false, func(cfg config.Wrapper) {
  2983. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  2984. }, func(cfg config.Wrapper) {
  2985. pauseFolder(t, cfg, cfg.FolderList()[0].ID, false)
  2986. })
  2987. }
  2988. func TestAddFolderCompletion(t *testing.T) {
  2989. // Empty folders are always 100% complete.
  2990. comp := newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderValid)
  2991. comp.add(newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderPaused))
  2992. if comp.CompletionPct != 100 {
  2993. t.Error(comp.CompletionPct)
  2994. }
  2995. // Completion is of the whole
  2996. comp = newFolderCompletion(db.Counts{Bytes: 100}, db.Counts{}, 0, remoteFolderValid) // 100% complete
  2997. comp.add(newFolderCompletion(db.Counts{Bytes: 400}, db.Counts{Bytes: 50}, 0, remoteFolderValid)) // 82.5% complete
  2998. if comp.CompletionPct != 90 { // 100 * (1 - 50/500)
  2999. t.Error(comp.CompletionPct)
  3000. }
  3001. }
  3002. func TestScanDeletedROChangedOnSR(t *testing.T) {
  3003. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  3004. ffs := fcfg.Filesystem()
  3005. defer wCancel()
  3006. defer cleanupModelAndRemoveDir(m, ffs.URI())
  3007. fcfg.Type = config.FolderTypeReceiveOnly
  3008. setFolder(t, m.cfg, fcfg)
  3009. name := "foo"
  3010. writeFile(t, ffs, name, []byte(name))
  3011. m.ScanFolders()
  3012. file, ok := m.testCurrentFolderFile(fcfg.ID, name)
  3013. if !ok {
  3014. t.Fatal("file missing in db")
  3015. }
  3016. // A remote must have the file, otherwise the deletion below is
  3017. // automatically resolved as not a ro-changed item.
  3018. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{file}}))
  3019. must(t, ffs.Remove(name))
  3020. m.ScanFolders()
  3021. if mustV(m.ReceiveOnlySize(fcfg.ID)).Deleted != 1 {
  3022. t.Fatal("expected one receive only changed deleted item")
  3023. }
  3024. fcfg.Type = config.FolderTypeSendReceive
  3025. setFolder(t, m.cfg, fcfg)
  3026. m.ScanFolders()
  3027. if mustV(m.ReceiveOnlySize(fcfg.ID)).Deleted != 0 {
  3028. t.Fatal("expected no receive only changed deleted item")
  3029. }
  3030. if mustV(m.LocalSize(fcfg.ID, protocol.LocalDeviceID)).Deleted != 1 {
  3031. t.Fatal("expected one local deleted item")
  3032. }
  3033. }
  3034. func testConfigChangeTriggersClusterConfigs(t *testing.T, expectFirst, expectSecond bool, pre func(config.Wrapper), fn func(config.Wrapper)) {
  3035. t.Helper()
  3036. wcfg, _, wcfgCancel := newDefaultCfgWrapper()
  3037. defer wcfgCancel()
  3038. m := setupModel(t, wcfg)
  3039. defer cleanupModel(m)
  3040. setDevice(t, wcfg, newDeviceConfiguration(wcfg.DefaultDevice(), device2, "device2"))
  3041. if pre != nil {
  3042. pre(wcfg)
  3043. }
  3044. cc1 := make(chan struct{}, 1)
  3045. cc2 := make(chan struct{}, 1)
  3046. fc1 := newFakeConnection(device1, m)
  3047. fc1.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
  3048. cc1 <- struct{}{}
  3049. })
  3050. fc2 := newFakeConnection(device2, m)
  3051. fc2.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
  3052. cc2 <- struct{}{}
  3053. })
  3054. m.AddConnection(fc1, protocol.Hello{})
  3055. m.AddConnection(fc2, protocol.Hello{})
  3056. m.promoteConnections()
  3057. // Initial CCs
  3058. select {
  3059. case <-cc1:
  3060. default:
  3061. t.Fatal("missing initial CC from device1")
  3062. }
  3063. select {
  3064. case <-cc2:
  3065. default:
  3066. t.Fatal("missing initial CC from device2")
  3067. }
  3068. t.Log("Applying config change")
  3069. fn(wcfg)
  3070. timeout := time.NewTimer(time.Second)
  3071. if expectFirst {
  3072. select {
  3073. case <-cc1:
  3074. case <-timeout.C:
  3075. t.Errorf("timed out before receiving cluste rconfig for first device")
  3076. }
  3077. }
  3078. if expectSecond {
  3079. select {
  3080. case <-cc2:
  3081. case <-timeout.C:
  3082. t.Errorf("timed out before receiving cluste rconfig for second device")
  3083. }
  3084. }
  3085. }
  3086. // The end result of the tested scenario is that the global version entry has an
  3087. // empty version vector and is not deleted, while everything is actually deleted.
  3088. // That then causes these files to be considered as needed, while they are not.
  3089. // https://github.com/syncthing/syncthing/issues/6961
  3090. func TestIssue6961(t *testing.T) {
  3091. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  3092. defer wcfgCancel()
  3093. tfs := fcfg.Filesystem()
  3094. waiter, err := wcfg.Modify(func(cfg *config.Configuration) {
  3095. cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device2, "device2"))
  3096. fcfg.Type = config.FolderTypeReceiveOnly
  3097. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  3098. cfg.SetFolder(fcfg)
  3099. })
  3100. must(t, err)
  3101. waiter.Wait()
  3102. // Always recalc/repair when opening a fileset.
  3103. m := newModel(t, wcfg, myID, nil)
  3104. m.ServeBackground()
  3105. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3106. conn1 := addFakeConn(m, device1, fcfg.ID)
  3107. conn2 := addFakeConn(m, device2, fcfg.ID)
  3108. m.ScanFolders()
  3109. name := "foo"
  3110. version := protocol.Vector{}.Update(device1.Short())
  3111. // Remote, valid and existing file
  3112. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, Version: version, Sequence: 1}}}))
  3113. // Remote, invalid (receive-only) and existing file
  3114. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, RawInvalid: true, Sequence: 1}}}))
  3115. // Create a local file
  3116. if fd, err := tfs.OpenFile(name, fs.OptCreate, 0o666); err != nil {
  3117. t.Fatal(err)
  3118. } else {
  3119. fd.Close()
  3120. }
  3121. if info, err := tfs.Lstat(name); err != nil {
  3122. t.Fatal(err)
  3123. } else {
  3124. l.Infoln("intest", info.Mode)
  3125. }
  3126. m.ScanFolders()
  3127. // Get rid of valid global
  3128. waiter, err = wcfg.RemoveDevice(device1)
  3129. if err != nil {
  3130. t.Fatal(err)
  3131. }
  3132. waiter.Wait()
  3133. // Delete the local file
  3134. must(t, tfs.Remove(name))
  3135. m.ScanFolders()
  3136. // Drop the remote index, add some other file.
  3137. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: "bar", RawInvalid: true, Sequence: 1}}}))
  3138. // Pause and unpause folder to create new db.FileSet and thus recalculate everything
  3139. pauseFolder(t, wcfg, fcfg.ID, true)
  3140. pauseFolder(t, wcfg, fcfg.ID, false)
  3141. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedDeletes != 0 {
  3142. t.Error("Expected 0 needed deletes, got", comp.NeedDeletes)
  3143. } else {
  3144. t.Log(comp)
  3145. }
  3146. }
  3147. func TestCompletionEmptyGlobal(t *testing.T) {
  3148. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  3149. defer wcfgCancel()
  3150. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  3151. files := []protocol.FileInfo{{Name: "foo", Version: protocol.Vector{}.Update(myID.Short()), Sequence: 1}}
  3152. m.sdb.Update(fcfg.ID, protocol.LocalDeviceID, files)
  3153. files[0].Deleted = true
  3154. files[0].Version = files[0].Version.Update(device1.Short())
  3155. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3156. comp := m.testCompletion(protocol.LocalDeviceID, fcfg.ID)
  3157. if comp.CompletionPct != 95 {
  3158. t.Error("Expected completion of 95%, got", comp.CompletionPct)
  3159. }
  3160. }
  3161. func TestNeedMetaAfterIndexReset(t *testing.T) {
  3162. w, fcfg, wCancel := newDefaultCfgWrapper()
  3163. defer wCancel()
  3164. addDevice2(t, w, fcfg)
  3165. m := setupModel(t, w)
  3166. defer cleanupModelAndRemoveDir(m, fcfg.Path)
  3167. conn1 := addFakeConn(m, device1, fcfg.ID)
  3168. conn2 := addFakeConn(m, device2, fcfg.ID)
  3169. var seq int64 = 1
  3170. files := []protocol.FileInfo{{Name: "foo", Size: 10, Version: protocol.Vector{}.Update(device1.Short()), Sequence: seq}}
  3171. // Start with two remotes having one file, then both deleting it, then
  3172. // only one adding it again.
  3173. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3174. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3175. seq++
  3176. files[0].SetDeleted(device2.Short())
  3177. files[0].Sequence = seq
  3178. must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3179. must(t, m.IndexUpdate(conn2, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3180. seq++
  3181. files[0].Deleted = false
  3182. files[0].Size = 20
  3183. files[0].Version = files[0].Version.Update(device1.Short())
  3184. files[0].Sequence = seq
  3185. must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3186. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
  3187. t.Error("Expected one needed item for device2, got", comp.NeedItems)
  3188. }
  3189. // Pretend we had an index reset on device 1
  3190. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3191. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
  3192. t.Error("Expected one needed item for device2, got", comp.NeedItems)
  3193. }
  3194. }
  3195. func TestCcCheckEncryption(t *testing.T) {
  3196. if testing.Short() {
  3197. t.Skip("skipping on short testing - generating encryption tokens is slow")
  3198. }
  3199. w, fcfg, wCancel := newDefaultCfgWrapper()
  3200. defer wCancel()
  3201. m := setupModel(t, w)
  3202. m.cancel()
  3203. defer cleanupModel(m)
  3204. pw := "foo"
  3205. token := protocol.PasswordToken(m.keyGen, fcfg.ID, pw)
  3206. m.folderEncryptionPasswordTokens[fcfg.ID] = token
  3207. testCases := []struct {
  3208. tokenRemote, tokenLocal []byte
  3209. isEncryptedRemote, isEncryptedLocal bool
  3210. expectedErr error
  3211. }{
  3212. {
  3213. tokenRemote: token,
  3214. tokenLocal: token,
  3215. expectedErr: errEncryptionInvConfigRemote,
  3216. },
  3217. {
  3218. isEncryptedRemote: true,
  3219. isEncryptedLocal: true,
  3220. expectedErr: errEncryptionInvConfigLocal,
  3221. },
  3222. {
  3223. tokenRemote: token,
  3224. tokenLocal: nil,
  3225. isEncryptedRemote: false,
  3226. isEncryptedLocal: false,
  3227. expectedErr: errEncryptionNotEncryptedLocal,
  3228. },
  3229. {
  3230. tokenRemote: token,
  3231. tokenLocal: nil,
  3232. isEncryptedRemote: true,
  3233. isEncryptedLocal: false,
  3234. expectedErr: nil,
  3235. },
  3236. {
  3237. tokenRemote: token,
  3238. tokenLocal: nil,
  3239. isEncryptedRemote: false,
  3240. isEncryptedLocal: true,
  3241. expectedErr: nil,
  3242. },
  3243. {
  3244. tokenRemote: nil,
  3245. tokenLocal: token,
  3246. isEncryptedRemote: true,
  3247. isEncryptedLocal: false,
  3248. expectedErr: nil,
  3249. },
  3250. {
  3251. tokenRemote: nil,
  3252. tokenLocal: token,
  3253. isEncryptedRemote: false,
  3254. isEncryptedLocal: true,
  3255. expectedErr: nil,
  3256. },
  3257. {
  3258. tokenRemote: nil,
  3259. tokenLocal: token,
  3260. isEncryptedRemote: false,
  3261. isEncryptedLocal: false,
  3262. expectedErr: errEncryptionNotEncryptedLocal,
  3263. },
  3264. {
  3265. tokenRemote: nil,
  3266. tokenLocal: nil,
  3267. isEncryptedRemote: true,
  3268. isEncryptedLocal: false,
  3269. expectedErr: errEncryptionPlainForRemoteEncrypted,
  3270. },
  3271. {
  3272. tokenRemote: nil,
  3273. tokenLocal: nil,
  3274. isEncryptedRemote: false,
  3275. isEncryptedLocal: true,
  3276. expectedErr: errEncryptionPlainForReceiveEncrypted,
  3277. },
  3278. {
  3279. tokenRemote: nil,
  3280. tokenLocal: nil,
  3281. isEncryptedRemote: false,
  3282. isEncryptedLocal: false,
  3283. expectedErr: nil,
  3284. },
  3285. }
  3286. for i, tc := range testCases {
  3287. tfcfg := fcfg.Copy()
  3288. if tc.isEncryptedLocal {
  3289. tfcfg.Type = config.FolderTypeReceiveEncrypted
  3290. m.folderEncryptionPasswordTokens[fcfg.ID] = token
  3291. }
  3292. dcfg := config.FolderDeviceConfiguration{DeviceID: device1}
  3293. if tc.isEncryptedRemote {
  3294. dcfg.EncryptionPassword = pw
  3295. }
  3296. deviceInfos := &clusterConfigDeviceInfo{
  3297. remote: protocol.Device{ID: device1, EncryptionPasswordToken: tc.tokenRemote},
  3298. local: protocol.Device{ID: myID, EncryptionPasswordToken: tc.tokenLocal},
  3299. }
  3300. err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
  3301. if err != tc.expectedErr {
  3302. t.Errorf("Testcase %v: Expected error %v, got %v", i, tc.expectedErr, err)
  3303. }
  3304. if tc.expectedErr == nil {
  3305. err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, true)
  3306. if tc.isEncryptedRemote || tc.isEncryptedLocal {
  3307. if err != nil {
  3308. t.Errorf("Testcase %v: Expected no error, got %v", i, err)
  3309. }
  3310. } else {
  3311. if err != errEncryptionNotEncryptedUntrusted {
  3312. t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionNotEncryptedUntrusted, err)
  3313. }
  3314. }
  3315. }
  3316. if err != nil || (!tc.isEncryptedRemote && !tc.isEncryptedLocal) {
  3317. continue
  3318. }
  3319. if tc.isEncryptedLocal {
  3320. m.folderEncryptionPasswordTokens[fcfg.ID] = []byte("notAMatch")
  3321. } else {
  3322. dcfg.EncryptionPassword = "notAMatch"
  3323. }
  3324. err = m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
  3325. if err != errEncryptionPassword {
  3326. t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionPassword, err)
  3327. }
  3328. }
  3329. }
  3330. func TestCCFolderNotRunning(t *testing.T) {
  3331. // Create the folder, but don't start it.
  3332. w, fcfg, wCancel := newDefaultCfgWrapper()
  3333. defer wCancel()
  3334. tfs := fcfg.Filesystem()
  3335. m := newModel(t, w, myID, nil)
  3336. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3337. // A connection can happen before all the folders are started.
  3338. cc, _ := m.generateClusterConfig(device1)
  3339. if l := len(cc.Folders); l != 1 {
  3340. t.Fatalf("Expected 1 folder in CC, got %v", l)
  3341. }
  3342. folder := cc.Folders[0]
  3343. if id := folder.ID; id != fcfg.ID {
  3344. t.Fatalf("Expected folder %v, got %v", fcfg.ID, id)
  3345. }
  3346. if l := len(folder.Devices); l != 2 {
  3347. t.Fatalf("Expected 2 devices in CC, got %v", l)
  3348. }
  3349. local := folder.Devices[1]
  3350. if local.ID != myID {
  3351. local = folder.Devices[0]
  3352. }
  3353. if !folder.Paused && local.IndexID == 0 {
  3354. t.Errorf("Folder isn't paused, but index-id is zero")
  3355. }
  3356. }
  3357. func TestPendingFolder(t *testing.T) {
  3358. w, _, wCancel := newDefaultCfgWrapper()
  3359. defer wCancel()
  3360. m := setupModel(t, w)
  3361. defer cleanupModel(m)
  3362. setDevice(t, w, config.DeviceConfiguration{DeviceID: device2})
  3363. pfolder := "default"
  3364. of := db.ObservedFolder{
  3365. Time: time.Now().Truncate(time.Second),
  3366. Label: pfolder,
  3367. }
  3368. if err := m.observed.AddOrUpdatePendingFolder(pfolder, of, device2); err != nil {
  3369. t.Fatal(err)
  3370. }
  3371. deviceFolders, err := m.PendingFolders(protocol.EmptyDeviceID)
  3372. if err != nil {
  3373. t.Fatal(err)
  3374. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3375. t.Errorf("folder %v not pending", pfolder)
  3376. } else if _, ok := pf.OfferedBy[device2]; !ok {
  3377. t.Errorf("folder %v not pending for device %v", pfolder, device2)
  3378. } else if len(pf.OfferedBy) > 1 {
  3379. t.Errorf("folder %v pending for too many devices %v", pfolder, pf.OfferedBy)
  3380. }
  3381. device3, err := protocol.DeviceIDFromString("AIBAEAQ-CAIBAEC-AQCAIBA-EAQCAIA-BAEAQCA-IBAEAQC-CAIBAEA-QCAIBA7")
  3382. if err != nil {
  3383. t.Fatal(err)
  3384. }
  3385. setDevice(t, w, config.DeviceConfiguration{DeviceID: device3})
  3386. if err := m.observed.AddOrUpdatePendingFolder(pfolder, of, device3); err != nil {
  3387. t.Fatal(err)
  3388. }
  3389. deviceFolders, err = m.PendingFolders(device2)
  3390. if err != nil {
  3391. t.Fatal(err)
  3392. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3393. t.Errorf("folder %v not pending when filtered", pfolder)
  3394. } else if _, ok := pf.OfferedBy[device2]; !ok {
  3395. t.Errorf("folder %v not pending for device %v when filtered", pfolder, device2)
  3396. } else if _, ok := pf.OfferedBy[device3]; ok {
  3397. t.Errorf("folder %v pending for device %v, but not filtered out", pfolder, device3)
  3398. }
  3399. waiter, err := w.RemoveDevice(device3)
  3400. if err != nil {
  3401. t.Fatal(err)
  3402. }
  3403. waiter.Wait()
  3404. deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
  3405. if err != nil {
  3406. t.Fatal(err)
  3407. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3408. t.Errorf("folder %v not pending", pfolder)
  3409. } else if _, ok := pf.OfferedBy[device3]; ok {
  3410. t.Errorf("folder %v pending for removed device %v", pfolder, device3)
  3411. }
  3412. waiter, err = w.RemoveFolder(pfolder)
  3413. if err != nil {
  3414. t.Fatal(err)
  3415. }
  3416. waiter.Wait()
  3417. deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
  3418. if err != nil {
  3419. t.Fatal(err)
  3420. } else if _, ok := deviceFolders[pfolder]; ok {
  3421. t.Errorf("folder %v still pending after local removal", pfolder)
  3422. }
  3423. }
  3424. func TestDeletedNotLocallyChangedReceiveOnly(t *testing.T) {
  3425. deletedNotLocallyChanged(t, config.FolderTypeReceiveOnly)
  3426. }
  3427. func TestDeletedNotLocallyChangedReceiveEncrypted(t *testing.T) {
  3428. deletedNotLocallyChanged(t, config.FolderTypeReceiveEncrypted)
  3429. }
  3430. func deletedNotLocallyChanged(t *testing.T, ft config.FolderType) {
  3431. w, fcfg, wCancel := newDefaultCfgWrapper()
  3432. tfs := fcfg.Filesystem()
  3433. fcfg.Type = ft
  3434. setFolder(t, w, fcfg)
  3435. defer wCancel()
  3436. m := setupModel(t, w)
  3437. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3438. name := "foo"
  3439. writeFile(t, tfs, name, nil)
  3440. must(t, m.ScanFolder(fcfg.ID))
  3441. fi, ok, err := m.CurrentFolderFile(fcfg.ID, name)
  3442. must(t, err)
  3443. if !ok {
  3444. t.Fatal("File hasn't been added")
  3445. }
  3446. if !fi.IsReceiveOnlyChanged() {
  3447. t.Fatal("File isn't receive-only-changed")
  3448. }
  3449. must(t, tfs.Remove(name))
  3450. must(t, m.ScanFolder(fcfg.ID))
  3451. _, ok, err = m.CurrentFolderFile(fcfg.ID, name)
  3452. must(t, err)
  3453. if ok {
  3454. t.Error("Expected file to be removed from db")
  3455. }
  3456. }
  3457. func equalStringsInAnyOrder(a, b []string) bool {
  3458. if len(a) != len(b) {
  3459. return false
  3460. }
  3461. sort.Strings(a)
  3462. sort.Strings(b)
  3463. for i := range a {
  3464. if a[i] != b[i] {
  3465. return false
  3466. }
  3467. }
  3468. return true
  3469. }
  3470. // modtimeTruncatingFS is a FileSystem that returns modification times only
  3471. // to the closest two `trunc` interval.
  3472. type modtimeTruncatingFS struct {
  3473. trunc time.Duration
  3474. fs.Filesystem
  3475. }
  3476. func (f modtimeTruncatingFS) Lstat(name string) (fs.FileInfo, error) {
  3477. fmt.Println("lstat", name)
  3478. info, err := f.Filesystem.Lstat(name)
  3479. return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
  3480. }
  3481. func (f modtimeTruncatingFS) Stat(name string) (fs.FileInfo, error) {
  3482. fmt.Println("stat", name)
  3483. info, err := f.Filesystem.Stat(name)
  3484. return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
  3485. }
  3486. func (f modtimeTruncatingFS) Walk(root string, walkFn fs.WalkFunc) error {
  3487. return f.Filesystem.Walk(root, func(path string, info fs.FileInfo, err error) error {
  3488. if err != nil {
  3489. return walkFn(path, nil, err)
  3490. }
  3491. fmt.Println("walk", info.Name())
  3492. return walkFn(path, modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, nil)
  3493. })
  3494. }
  3495. type modtimeTruncatingFileInfo struct {
  3496. trunc time.Duration
  3497. fs.FileInfo
  3498. }
  3499. func (fi modtimeTruncatingFileInfo) ModTime() time.Time {
  3500. return fi.FileInfo.ModTime().Truncate(fi.trunc)
  3501. }
  3502. func countIterator[T any](t *testing.T) func(it iter.Seq[T], errFn func() error) int {
  3503. return func(it iter.Seq[T], errFn func() error) int {
  3504. t.Helper()
  3505. count := 0
  3506. for range it {
  3507. count++
  3508. }
  3509. if err := errFn(); err != nil {
  3510. t.Fatal(err)
  3511. }
  3512. return count
  3513. }
  3514. }