model_test.go 111 KB

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