model_test.go 109 KB

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