model_test.go 86 KB

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