model_test.go 84 KB

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