model_test.go 92 KB

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