model_test.go 113 KB

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