model_test.go 94 KB

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