model_test.go 98 KB

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