model_test.go 104 KB

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