model_test.go 109 KB

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