model_test.go 87 KB

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