model_test.go 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "io"
  14. mrand "math/rand"
  15. "os"
  16. "path/filepath"
  17. "runtime/pprof"
  18. "slices"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "testing"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/build"
  25. "github.com/syncthing/syncthing/lib/config"
  26. "github.com/syncthing/syncthing/lib/db"
  27. "github.com/syncthing/syncthing/lib/db/backend"
  28. "github.com/syncthing/syncthing/lib/events"
  29. "github.com/syncthing/syncthing/lib/fs"
  30. "github.com/syncthing/syncthing/lib/ignore"
  31. "github.com/syncthing/syncthing/lib/osutil"
  32. "github.com/syncthing/syncthing/lib/protocol"
  33. protocolmocks "github.com/syncthing/syncthing/lib/protocol/mocks"
  34. srand "github.com/syncthing/syncthing/lib/rand"
  35. "github.com/syncthing/syncthing/lib/semaphore"
  36. "github.com/syncthing/syncthing/lib/testutil"
  37. "github.com/syncthing/syncthing/lib/versioner"
  38. )
  39. func newState(t testing.TB, cfg config.Configuration) (*testModel, context.CancelFunc) {
  40. wcfg, cancel := newConfigWrapper(cfg)
  41. m := setupModel(t, wcfg)
  42. for _, dev := range cfg.Devices {
  43. m.AddConnection(newFakeConnection(dev.DeviceID, m), protocol.Hello{})
  44. }
  45. return m, cancel
  46. }
  47. func createClusterConfig(remote protocol.DeviceID, ids ...string) *protocol.ClusterConfig {
  48. cc := &protocol.ClusterConfig{
  49. Folders: make([]protocol.Folder, len(ids)),
  50. }
  51. for i, id := range ids {
  52. cc.Folders[i] = protocol.Folder{
  53. ID: id,
  54. Label: id,
  55. }
  56. }
  57. return addFolderDevicesToClusterConfig(cc, remote)
  58. }
  59. func addFolderDevicesToClusterConfig(cc *protocol.ClusterConfig, remote protocol.DeviceID) *protocol.ClusterConfig {
  60. for i := range cc.Folders {
  61. cc.Folders[i].Devices = []protocol.Device{
  62. {ID: myID},
  63. {ID: remote},
  64. }
  65. }
  66. return cc
  67. }
  68. func TestRequest(t *testing.T) {
  69. wrapper, fcfg, cancel := newDefaultCfgWrapper()
  70. ffs := fcfg.Filesystem(nil)
  71. defer cancel()
  72. m := setupModel(t, wrapper)
  73. defer cleanupModel(m)
  74. fd, err := ffs.Create("foo")
  75. if err != nil {
  76. t.Fatal(err)
  77. }
  78. if _, err := fd.Write([]byte("foobar")); err != nil {
  79. t.Fatal(err)
  80. }
  81. fd.Close()
  82. m.ScanFolder("default")
  83. // Existing, shared file
  84. res, err := m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 6})
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. bs := res.Data()
  89. if !bytes.Equal(bs, []byte("foobar")) {
  90. t.Errorf("Incorrect data from request: %q", string(bs))
  91. }
  92. // Existing, nonshared file
  93. _, err = m.Request(device2Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 6})
  94. if err == nil {
  95. t.Error("Unexpected nil error on insecure file read")
  96. }
  97. // Nonexistent file
  98. _, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "nonexistent", Size: 6})
  99. if err == nil {
  100. t.Error("Unexpected nil error on insecure file read")
  101. }
  102. // Shared folder, but disallowed file name
  103. _, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "../walk.go", Size: 6})
  104. if err == nil {
  105. t.Error("Unexpected nil error on insecure file read")
  106. }
  107. // Negative size
  108. _, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: -4})
  109. if err == nil {
  110. t.Error("Unexpected nil error on insecure file read")
  111. }
  112. // Larger block than available
  113. _, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 42, Hash: []byte("hash necessary but not checked")})
  114. if err == nil {
  115. t.Error("Unexpected nil error on read past end of file")
  116. }
  117. _, err = m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "foo", Size: 42})
  118. if err != nil {
  119. t.Error("Unexpected error when large read should be permitted")
  120. }
  121. }
  122. func genFiles(n int) []protocol.FileInfo {
  123. files := make([]protocol.FileInfo, n)
  124. t := time.Now().Unix()
  125. for i := 0; i < n; i++ {
  126. files[i] = protocol.FileInfo{
  127. Name: fmt.Sprintf("file%d", i),
  128. ModifiedS: t,
  129. Sequence: int64(i + 1),
  130. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  131. Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}},
  132. }
  133. }
  134. return files
  135. }
  136. func BenchmarkIndex_10000(b *testing.B) {
  137. benchmarkIndex(b, 10000)
  138. }
  139. func BenchmarkIndex_100(b *testing.B) {
  140. benchmarkIndex(b, 100)
  141. }
  142. func benchmarkIndex(b *testing.B, nfiles int) {
  143. m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
  144. defer wcfgCancel()
  145. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  146. files := genFiles(nfiles)
  147. must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
  148. b.ResetTimer()
  149. for i := 0; i < b.N; i++ {
  150. must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
  151. }
  152. b.ReportAllocs()
  153. }
  154. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  155. benchmarkIndexUpdate(b, 10000, 10000)
  156. }
  157. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  158. benchmarkIndexUpdate(b, 10000, 100)
  159. }
  160. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  161. benchmarkIndexUpdate(b, 10000, 1)
  162. }
  163. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  164. m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
  165. defer wcfgCancel()
  166. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  167. files := genFiles(nfiles)
  168. ufiles := genFiles(nufiles)
  169. must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
  170. b.ResetTimer()
  171. for i := 0; i < b.N; i++ {
  172. must(b, m.IndexUpdate(device1Conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: ufiles}))
  173. }
  174. b.ReportAllocs()
  175. }
  176. func BenchmarkRequestOut(b *testing.B) {
  177. m := setupModel(b, defaultCfgWrapper)
  178. defer cleanupModel(m)
  179. const n = 1000
  180. files := genFiles(n)
  181. fc := newFakeConnection(device1, m)
  182. for _, f := range files {
  183. fc.addFile(f.Name, 0o644, protocol.FileInfoTypeFile, []byte("some data to return"))
  184. }
  185. m.AddConnection(fc, protocol.Hello{})
  186. must(b, m.Index(device1Conn, &protocol.Index{Folder: "default", Files: files}))
  187. b.ResetTimer()
  188. for i := 0; i < b.N; i++ {
  189. data, err := m.RequestGlobal(context.Background(), device1, "default", files[i%n].Name, 0, 0, 32, nil, 0, false)
  190. if err != nil {
  191. b.Error(err)
  192. }
  193. if data == nil {
  194. b.Error("nil data")
  195. }
  196. }
  197. }
  198. func BenchmarkRequestInSingleFile(b *testing.B) {
  199. w, cancel := newConfigWrapper(defaultCfg)
  200. defer cancel()
  201. ffs := w.FolderList()[0].Filesystem(nil)
  202. m := setupModel(b, w)
  203. defer cleanupModel(m)
  204. buf := make([]byte, 128<<10)
  205. srand.Read(buf)
  206. must(b, ffs.MkdirAll("request/for/a/file/in/a/couple/of/dirs", 0o755))
  207. writeFile(b, ffs, "request/for/a/file/in/a/couple/of/dirs/128k", buf)
  208. b.ResetTimer()
  209. for i := 0; i < b.N; i++ {
  210. if _, err := m.Request(device1Conn, &protocol.Request{Folder: "default", Name: "request/for/a/file/in/a/couple/of/dirs/128k", Size: 128 << 10}); err != nil {
  211. b.Error(err)
  212. }
  213. }
  214. b.SetBytes(128 << 10)
  215. }
  216. func TestDeviceRename(t *testing.T) {
  217. hello := protocol.Hello{
  218. ClientName: "syncthing",
  219. ClientVersion: "v0.9.4",
  220. }
  221. rawCfg := config.New(device1)
  222. rawCfg.Devices = []config.DeviceConfiguration{
  223. {
  224. DeviceID: device1,
  225. },
  226. }
  227. cfg, cfgCancel := newConfigWrapper(rawCfg)
  228. defer cfgCancel()
  229. m := newModel(t, cfg, myID, nil)
  230. if cfg.Devices()[device1].Name != "" {
  231. t.Errorf("Device already has a name")
  232. }
  233. conn := newFakeConnection(device1, m)
  234. m.AddConnection(conn, hello)
  235. m.ServeBackground()
  236. defer cleanupModel(m)
  237. if cfg.Devices()[device1].Name != "" {
  238. t.Errorf("Device already has a name")
  239. }
  240. m.Closed(conn, protocol.ErrTimeout)
  241. hello.DeviceName = "tester"
  242. m.AddConnection(conn, hello)
  243. if cfg.Devices()[device1].Name != "tester" {
  244. t.Errorf("Device did not get a name")
  245. }
  246. m.Closed(conn, protocol.ErrTimeout)
  247. hello.DeviceName = "tester2"
  248. m.AddConnection(conn, hello)
  249. if cfg.Devices()[device1].Name != "tester" {
  250. t.Errorf("Device name got overwritten")
  251. }
  252. ffs := fs.NewFilesystem(fs.FilesystemTypeFake, srand.String(32)+"?content=true")
  253. path := "someConfigfile"
  254. must(t, saveConfig(ffs, path, cfg.RawCopy()))
  255. cfgw, _, err := loadConfig(ffs, path, myID, events.NoopLogger)
  256. if err != nil {
  257. t.Error(err)
  258. return
  259. }
  260. if cfgw.Devices()[device1].Name != "tester" {
  261. t.Errorf("Device name not saved in config")
  262. }
  263. m.Closed(conn, protocol.ErrTimeout)
  264. waiter, err := cfg.Modify(func(cfg *config.Configuration) {
  265. cfg.Options.OverwriteRemoteDevNames = true
  266. })
  267. must(t, err)
  268. waiter.Wait()
  269. hello.DeviceName = "tester2"
  270. m.AddConnection(conn, hello)
  271. if cfg.Devices()[device1].Name != "tester2" {
  272. t.Errorf("Device name not overwritten")
  273. }
  274. }
  275. // Adjusted copy of the original function for testing purposes
  276. func saveConfig(ffs fs.Filesystem, path string, cfg config.Configuration) error {
  277. fd, err := ffs.Create(path)
  278. if err != nil {
  279. l.Debugln("Create:", err)
  280. return err
  281. }
  282. if err := cfg.WriteXML(osutil.LineEndingsWriter(fd)); err != nil {
  283. l.Debugln("WriteXML:", err)
  284. fd.Close()
  285. return err
  286. }
  287. if err := fd.Close(); err != nil {
  288. l.Debugln("Close:", err)
  289. return err
  290. }
  291. if _, err := ffs.Lstat(path); err != nil {
  292. return err
  293. }
  294. return nil
  295. }
  296. // Adjusted copy of the original function for testing purposes
  297. func loadConfig(ffs fs.Filesystem, path string, myID protocol.DeviceID, evLogger events.Logger) (config.Wrapper, int, error) {
  298. if _, err := ffs.Lstat(path); err != nil {
  299. return nil, 0, err
  300. }
  301. fd, err := ffs.OpenFile(path, fs.OptReadWrite, 0o666)
  302. if err != nil {
  303. return nil, 0, err
  304. }
  305. defer fd.Close()
  306. cfg, originalVersion, err := config.ReadXML(fd, myID)
  307. if err != nil {
  308. return nil, 0, err
  309. }
  310. return config.Wrap(path, cfg, myID, evLogger), originalVersion, nil
  311. }
  312. func TestClusterConfig(t *testing.T) {
  313. cfg := config.New(device1)
  314. cfg.Options.MinHomeDiskFree.Value = 0 // avoids unnecessary free space checks
  315. cfg.Devices = []config.DeviceConfiguration{
  316. {
  317. DeviceID: device1,
  318. Introducer: true,
  319. },
  320. {
  321. DeviceID: device2,
  322. },
  323. }
  324. cfg.Folders = []config.FolderConfiguration{
  325. {
  326. FilesystemType: config.FilesystemTypeFake,
  327. ID: "folder1",
  328. Path: "testdata1",
  329. Devices: []config.FolderDeviceConfiguration{
  330. {DeviceID: device1},
  331. {DeviceID: device2},
  332. },
  333. },
  334. {
  335. FilesystemType: config.FilesystemTypeFake,
  336. ID: "folder2",
  337. Path: "testdata2",
  338. Paused: true, // should still be included
  339. Devices: []config.FolderDeviceConfiguration{
  340. {DeviceID: device1},
  341. {DeviceID: device2},
  342. },
  343. },
  344. {
  345. FilesystemType: config.FilesystemTypeFake,
  346. ID: "folder3",
  347. Path: "testdata3",
  348. Devices: []config.FolderDeviceConfiguration{
  349. {DeviceID: device1},
  350. // should not be included, does not include device2
  351. },
  352. },
  353. }
  354. wrapper, cancel := newConfigWrapper(cfg)
  355. defer cancel()
  356. m := newModel(t, wrapper, myID, nil)
  357. m.ServeBackground()
  358. defer cleanupModel(m)
  359. cm, _ := m.generateClusterConfig(device2)
  360. if l := len(cm.Folders); l != 2 {
  361. t.Fatalf("Incorrect number of folders %d != 2", l)
  362. }
  363. r := cm.Folders[0]
  364. if r.ID != "folder1" {
  365. t.Errorf("Incorrect folder %q != folder1", r.ID)
  366. }
  367. if l := len(r.Devices); l != 2 {
  368. t.Errorf("Incorrect number of devices %d != 2", l)
  369. }
  370. if id := r.Devices[0].ID; id != device1 {
  371. t.Errorf("Incorrect device ID %s != %s", id, device1)
  372. }
  373. if !r.Devices[0].Introducer {
  374. t.Error("Device1 should be flagged as Introducer")
  375. }
  376. if id := r.Devices[1].ID; id != device2 {
  377. t.Errorf("Incorrect device ID %s != %s", id, device2)
  378. }
  379. if r.Devices[1].Introducer {
  380. t.Error("Device2 should not be flagged as Introducer")
  381. }
  382. r = cm.Folders[1]
  383. if r.ID != "folder2" {
  384. t.Errorf("Incorrect folder %q != folder2", r.ID)
  385. }
  386. if l := len(r.Devices); l != 2 {
  387. t.Errorf("Incorrect number of devices %d != 2", l)
  388. }
  389. if id := r.Devices[0].ID; id != device1 {
  390. t.Errorf("Incorrect device ID %s != %s", id, device1)
  391. }
  392. if !r.Devices[0].Introducer {
  393. t.Error("Device1 should be flagged as Introducer")
  394. }
  395. if id := r.Devices[1].ID; id != device2 {
  396. t.Errorf("Incorrect device ID %s != %s", id, device2)
  397. }
  398. if r.Devices[1].Introducer {
  399. t.Error("Device2 should not be flagged as Introducer")
  400. }
  401. }
  402. func TestIntroducer(t *testing.T) {
  403. var introducedByAnyone protocol.DeviceID
  404. // LocalDeviceID is a magic value meaning don't check introducer
  405. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  406. for _, dev := range cfg.Devices {
  407. if dev.DeviceID.Equals(id) {
  408. if introducedBy.Equals(introducedByAnyone) {
  409. return true
  410. }
  411. return dev.IntroducedBy.Equals(introducedBy)
  412. }
  413. }
  414. return false
  415. }
  416. m, cancel := newState(t, config.Configuration{
  417. Version: config.CurrentVersion,
  418. Devices: []config.DeviceConfiguration{
  419. {
  420. DeviceID: device1,
  421. Introducer: true,
  422. },
  423. },
  424. Folders: []config.FolderConfiguration{
  425. {
  426. FilesystemType: config.FilesystemTypeFake,
  427. ID: "folder1",
  428. Path: "testdata",
  429. Devices: []config.FolderDeviceConfiguration{
  430. {DeviceID: device1},
  431. },
  432. },
  433. {
  434. FilesystemType: config.FilesystemTypeFake,
  435. ID: "folder2",
  436. Path: "testdata",
  437. Devices: []config.FolderDeviceConfiguration{
  438. {DeviceID: device1},
  439. },
  440. },
  441. },
  442. })
  443. cc := basicClusterConfig(myID, device1, "folder1", "folder2")
  444. cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
  445. ID: device2,
  446. Introducer: true,
  447. SkipIntroductionRemovals: true,
  448. })
  449. cc.Folders[1].Devices = append(cc.Folders[1].Devices, protocol.Device{
  450. ID: device2,
  451. Introducer: true,
  452. SkipIntroductionRemovals: true,
  453. EncryptionPasswordToken: []byte("faketoken"),
  454. })
  455. m.ClusterConfig(device1Conn, cc)
  456. if newDev, ok := m.cfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  457. t.Error("device 2 missing or wrong flags")
  458. }
  459. if !contains(m.cfg.Folders()["folder1"], device2, device1) {
  460. t.Error("expected folder 1 to have device2 introduced by device 1")
  461. }
  462. for _, devCfg := range m.cfg.Folders()["folder2"].Devices {
  463. if devCfg.DeviceID == device2 {
  464. t.Error("Device was added even though it's untrusted")
  465. }
  466. }
  467. cleanupModel(m)
  468. cancel()
  469. m, cancel = newState(t, config.Configuration{
  470. Version: config.CurrentVersion,
  471. Devices: []config.DeviceConfiguration{
  472. {
  473. DeviceID: device1,
  474. Introducer: true,
  475. },
  476. {
  477. DeviceID: device2,
  478. IntroducedBy: device1,
  479. },
  480. },
  481. Folders: []config.FolderConfiguration{
  482. {
  483. FilesystemType: config.FilesystemTypeFake,
  484. ID: "folder1",
  485. Path: "testdata",
  486. Devices: []config.FolderDeviceConfiguration{
  487. {DeviceID: device1},
  488. {DeviceID: device2, IntroducedBy: device1},
  489. },
  490. },
  491. {
  492. FilesystemType: config.FilesystemTypeFake,
  493. ID: "folder2",
  494. Path: "testdata",
  495. Devices: []config.FolderDeviceConfiguration{
  496. {DeviceID: device1},
  497. },
  498. },
  499. },
  500. })
  501. cc = basicClusterConfig(myID, device1, "folder2")
  502. cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
  503. ID: device2,
  504. Introducer: true,
  505. SkipIntroductionRemovals: true,
  506. })
  507. m.ClusterConfig(device1Conn, cc)
  508. // Should not get introducer, as it's already unset, and it's an existing device.
  509. if newDev, ok := m.cfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  510. t.Error("device 2 missing or changed flags")
  511. }
  512. if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
  513. t.Error("expected device 2 to be removed from folder 1")
  514. }
  515. if !contains(m.cfg.Folders()["folder2"], device2, device1) {
  516. t.Error("expected device 2 to be added to folder 2")
  517. }
  518. cleanupModel(m)
  519. cancel()
  520. m, cancel = newState(t, config.Configuration{
  521. Version: config.CurrentVersion,
  522. Devices: []config.DeviceConfiguration{
  523. {
  524. DeviceID: device1,
  525. Introducer: true,
  526. },
  527. {
  528. DeviceID: device2,
  529. IntroducedBy: device1,
  530. },
  531. },
  532. Folders: []config.FolderConfiguration{
  533. {
  534. FilesystemType: config.FilesystemTypeFake,
  535. ID: "folder1",
  536. Path: "testdata",
  537. Devices: []config.FolderDeviceConfiguration{
  538. {DeviceID: device1},
  539. {DeviceID: device2, IntroducedBy: device1},
  540. },
  541. },
  542. {
  543. FilesystemType: config.FilesystemTypeFake,
  544. ID: "folder2",
  545. Path: "testdata",
  546. Devices: []config.FolderDeviceConfiguration{
  547. {DeviceID: device1},
  548. {DeviceID: device2, IntroducedBy: device1},
  549. },
  550. },
  551. },
  552. })
  553. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
  554. if _, ok := m.cfg.Device(device2); ok {
  555. t.Error("device 2 should have been removed")
  556. }
  557. if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
  558. t.Error("expected device 2 to be removed from folder 1")
  559. }
  560. if contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
  561. t.Error("expected device 2 to be removed from folder 2")
  562. }
  563. // Two cases when removals should not happen
  564. // 1. Introducer flag no longer set on device
  565. cleanupModel(m)
  566. cancel()
  567. m, cancel = newState(t, config.Configuration{
  568. Version: config.CurrentVersion,
  569. Devices: []config.DeviceConfiguration{
  570. {
  571. DeviceID: device1,
  572. Introducer: false,
  573. },
  574. {
  575. DeviceID: device2,
  576. IntroducedBy: device1,
  577. },
  578. },
  579. Folders: []config.FolderConfiguration{
  580. {
  581. FilesystemType: config.FilesystemTypeFake,
  582. ID: "folder1",
  583. Path: "testdata",
  584. Devices: []config.FolderDeviceConfiguration{
  585. {DeviceID: device1},
  586. {DeviceID: device2, IntroducedBy: device1},
  587. },
  588. },
  589. {
  590. FilesystemType: config.FilesystemTypeFake,
  591. ID: "folder2",
  592. Path: "testdata",
  593. Devices: []config.FolderDeviceConfiguration{
  594. {DeviceID: device1},
  595. {DeviceID: device2, IntroducedBy: device1},
  596. },
  597. },
  598. },
  599. })
  600. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
  601. if _, ok := m.cfg.Device(device2); !ok {
  602. t.Error("device 2 should not have been removed")
  603. }
  604. if !contains(m.cfg.Folders()["folder1"], device2, device1) {
  605. t.Error("expected device 2 not to be removed from folder 1")
  606. }
  607. if !contains(m.cfg.Folders()["folder2"], device2, device1) {
  608. t.Error("expected device 2 not to be removed from folder 2")
  609. }
  610. // 2. SkipIntroductionRemovals is set
  611. cleanupModel(m)
  612. cancel()
  613. m, cancel = newState(t, config.Configuration{
  614. Version: config.CurrentVersion,
  615. Devices: []config.DeviceConfiguration{
  616. {
  617. DeviceID: device1,
  618. Introducer: true,
  619. SkipIntroductionRemovals: true,
  620. },
  621. {
  622. DeviceID: device2,
  623. IntroducedBy: device1,
  624. },
  625. },
  626. Folders: []config.FolderConfiguration{
  627. {
  628. FilesystemType: config.FilesystemTypeFake,
  629. ID: "folder1",
  630. Path: "testdata",
  631. Devices: []config.FolderDeviceConfiguration{
  632. {DeviceID: device1},
  633. {DeviceID: device2, IntroducedBy: device1},
  634. },
  635. },
  636. {
  637. FilesystemType: config.FilesystemTypeFake,
  638. ID: "folder2",
  639. Path: "testdata",
  640. Devices: []config.FolderDeviceConfiguration{
  641. {DeviceID: device1},
  642. },
  643. },
  644. },
  645. })
  646. cc = basicClusterConfig(myID, device1, "folder2")
  647. cc.Folders[0].Devices = append(cc.Folders[0].Devices, protocol.Device{
  648. ID: device2,
  649. Introducer: true,
  650. SkipIntroductionRemovals: true,
  651. })
  652. m.ClusterConfig(device1Conn, cc)
  653. if _, ok := m.cfg.Device(device2); !ok {
  654. t.Error("device 2 should not have been removed")
  655. }
  656. if !contains(m.cfg.Folders()["folder1"], device2, device1) {
  657. t.Error("expected device 2 not to be removed from folder 1")
  658. }
  659. if !contains(m.cfg.Folders()["folder2"], device2, device1) {
  660. t.Error("expected device 2 not to be added to folder 2")
  661. }
  662. // Test device not being removed as it's shared without an introducer.
  663. cleanupModel(m)
  664. cancel()
  665. m, cancel = newState(t, config.Configuration{
  666. Version: config.CurrentVersion,
  667. Devices: []config.DeviceConfiguration{
  668. {
  669. DeviceID: device1,
  670. Introducer: true,
  671. },
  672. {
  673. DeviceID: device2,
  674. IntroducedBy: device1,
  675. },
  676. },
  677. Folders: []config.FolderConfiguration{
  678. {
  679. FilesystemType: config.FilesystemTypeFake,
  680. ID: "folder1",
  681. Path: "testdata",
  682. Devices: []config.FolderDeviceConfiguration{
  683. {DeviceID: device1},
  684. {DeviceID: device2, IntroducedBy: device1},
  685. },
  686. },
  687. {
  688. FilesystemType: config.FilesystemTypeFake,
  689. ID: "folder2",
  690. Path: "testdata",
  691. Devices: []config.FolderDeviceConfiguration{
  692. {DeviceID: device1},
  693. {DeviceID: device2},
  694. },
  695. },
  696. },
  697. })
  698. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
  699. if _, ok := m.cfg.Device(device2); !ok {
  700. t.Error("device 2 should not have been removed")
  701. }
  702. if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
  703. t.Error("expected device 2 to be removed from folder 1")
  704. }
  705. if !contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
  706. t.Error("expected device 2 not to be removed from folder 2")
  707. }
  708. // Test device not being removed as it's shared by a different introducer.
  709. cleanupModel(m)
  710. cancel()
  711. m, cancel = newState(t, config.Configuration{
  712. Version: config.CurrentVersion,
  713. Devices: []config.DeviceConfiguration{
  714. {
  715. DeviceID: device1,
  716. Introducer: true,
  717. },
  718. {
  719. DeviceID: device2,
  720. IntroducedBy: device1,
  721. },
  722. },
  723. Folders: []config.FolderConfiguration{
  724. {
  725. FilesystemType: config.FilesystemTypeFake,
  726. ID: "folder1",
  727. Path: "testdata",
  728. Devices: []config.FolderDeviceConfiguration{
  729. {DeviceID: device1},
  730. {DeviceID: device2, IntroducedBy: device1},
  731. },
  732. },
  733. {
  734. FilesystemType: config.FilesystemTypeFake,
  735. ID: "folder2",
  736. Path: "testdata",
  737. Devices: []config.FolderDeviceConfiguration{
  738. {DeviceID: device1},
  739. {DeviceID: device2, IntroducedBy: myID},
  740. },
  741. },
  742. },
  743. })
  744. defer cleanupModel(m)
  745. defer cancel()
  746. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{})
  747. if _, ok := m.cfg.Device(device2); !ok {
  748. t.Error("device 2 should not have been removed")
  749. }
  750. if contains(m.cfg.Folders()["folder1"], device2, introducedByAnyone) {
  751. t.Error("expected device 2 to be removed from folder 1")
  752. }
  753. if !contains(m.cfg.Folders()["folder2"], device2, introducedByAnyone) {
  754. t.Error("expected device 2 not to be removed from folder 2")
  755. }
  756. }
  757. func TestIssue4897(t *testing.T) {
  758. m, cancel := newState(t, config.Configuration{
  759. Version: config.CurrentVersion,
  760. Devices: []config.DeviceConfiguration{
  761. {
  762. DeviceID: device1,
  763. Introducer: true,
  764. },
  765. },
  766. Folders: []config.FolderConfiguration{
  767. {
  768. FilesystemType: config.FilesystemTypeFake,
  769. ID: "folder1",
  770. Path: "testdata",
  771. Devices: []config.FolderDeviceConfiguration{
  772. {DeviceID: device1},
  773. },
  774. Paused: true,
  775. },
  776. },
  777. })
  778. defer cleanupModel(m)
  779. cancel()
  780. cm, _ := m.generateClusterConfig(device1)
  781. if l := len(cm.Folders); l != 1 {
  782. t.Errorf("Cluster config contains %v folders, expected 1", l)
  783. }
  784. }
  785. // TestIssue5063 is about a panic in connection with modifying config in quick
  786. // succession, related with auto accepted folders. It's unclear what exactly, a
  787. // relevant bit seems to be here:
  788. // PR-comments: https://github.com/syncthing/syncthing/pull/5069/files#r203146546
  789. // Issue: https://github.com/syncthing/syncthing/pull/5509
  790. func TestIssue5063(t *testing.T) {
  791. m, cancel := newState(t, defaultAutoAcceptCfg)
  792. defer cleanupModel(m)
  793. defer cancel()
  794. m.mut.Lock()
  795. for _, c := range m.connections {
  796. conn := c.(*fakeConnection)
  797. conn.CloseCalls(func(_ error) {})
  798. defer m.Closed(c, errStopped) // to unblock deferred m.Stop()
  799. }
  800. m.mut.Unlock()
  801. wg := sync.WaitGroup{}
  802. addAndVerify := func(id string) {
  803. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  804. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  805. t.Error("expected shared", id)
  806. }
  807. wg.Done()
  808. }
  809. reps := 10
  810. ids := make([]string, reps)
  811. for i := 0; i < reps; i++ {
  812. wg.Add(1)
  813. ids[i] = srand.String(8)
  814. go addAndVerify(ids[i])
  815. }
  816. finished := make(chan struct{})
  817. go func() {
  818. wg.Wait()
  819. close(finished)
  820. }()
  821. select {
  822. case <-finished:
  823. case <-time.After(10 * time.Second):
  824. pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
  825. t.Fatal("Timed out before all devices were added")
  826. }
  827. }
  828. func TestAutoAcceptRejected(t *testing.T) {
  829. // Nothing happens if AutoAcceptFolders not set
  830. tcfg := defaultAutoAcceptCfg.Copy()
  831. for i := range tcfg.Devices {
  832. tcfg.Devices[i].AutoAcceptFolders = false
  833. }
  834. m, cancel := newState(t, tcfg)
  835. // defer cleanupModel(m)
  836. defer cancel()
  837. id := srand.String(8)
  838. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  839. if cfg, ok := m.cfg.Folder(id); ok && cfg.SharedWith(device1) {
  840. t.Error("unexpected shared", id)
  841. }
  842. }
  843. func TestAutoAcceptNewFolder(t *testing.T) {
  844. // New folder
  845. m, cancel := newState(t, defaultAutoAcceptCfg)
  846. defer cleanupModel(m)
  847. defer cancel()
  848. id := srand.String(8)
  849. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  850. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  851. t.Error("expected shared", id)
  852. }
  853. }
  854. func TestAutoAcceptNewFolderFromTwoDevices(t *testing.T) {
  855. m, cancel := newState(t, defaultAutoAcceptCfg)
  856. defer cleanupModel(m)
  857. defer cancel()
  858. id := srand.String(8)
  859. defer os.RemoveAll(id)
  860. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  861. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  862. t.Error("expected shared", id)
  863. }
  864. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  865. t.Error("unexpected expected shared", id)
  866. }
  867. m.ClusterConfig(device2Conn, createClusterConfig(device2, id))
  868. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device2) {
  869. t.Error("expected shared", id)
  870. }
  871. }
  872. func TestAutoAcceptNewFolderFromOnlyOneDevice(t *testing.T) {
  873. modifiedCfg := defaultAutoAcceptCfg.Copy()
  874. modifiedCfg.Devices[2].AutoAcceptFolders = false
  875. m, cancel := newState(t, modifiedCfg)
  876. id := srand.String(8)
  877. defer os.RemoveAll(id)
  878. defer cleanupModel(m)
  879. defer cancel()
  880. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  881. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  882. t.Error("expected shared", id)
  883. }
  884. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  885. t.Error("unexpected expected shared", id)
  886. }
  887. m.ClusterConfig(device2Conn, createClusterConfig(device2, id))
  888. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  889. t.Error("unexpected shared", id)
  890. }
  891. }
  892. func TestAutoAcceptNewFolderPremutationsNoPanic(t *testing.T) {
  893. if testing.Short() {
  894. t.Skip("short tests only")
  895. }
  896. id := srand.String(8)
  897. label := srand.String(8)
  898. premutations := []protocol.Folder{
  899. {ID: id, Label: id},
  900. {ID: id, Label: label},
  901. {ID: label, Label: id},
  902. {ID: label, Label: label},
  903. }
  904. localFolders := append(premutations, protocol.Folder{})
  905. for _, localFolder := range localFolders {
  906. for _, localFolderPaused := range []bool{false, true} {
  907. for _, dev1folder := range premutations {
  908. for _, dev2folder := range premutations {
  909. cfg := defaultAutoAcceptCfg.Copy()
  910. if localFolder.Label != "" {
  911. fcfg := newFolderConfiguration(defaultCfgWrapper, localFolder.ID, localFolder.Label, config.FilesystemTypeFake, localFolder.ID)
  912. fcfg.Paused = localFolderPaused
  913. cfg.Folders = append(cfg.Folders, fcfg)
  914. }
  915. m, cancel := newState(t, cfg)
  916. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{
  917. Folders: []protocol.Folder{dev1folder},
  918. })
  919. m.ClusterConfig(device2Conn, &protocol.ClusterConfig{
  920. Folders: []protocol.Folder{dev2folder},
  921. })
  922. cleanupModel(m)
  923. cancel()
  924. }
  925. }
  926. }
  927. }
  928. }
  929. func TestAutoAcceptMultipleFolders(t *testing.T) {
  930. // Multiple new folders
  931. id1 := srand.String(8)
  932. defer os.RemoveAll(id1)
  933. id2 := srand.String(8)
  934. defer os.RemoveAll(id2)
  935. m, cancel := newState(t, defaultAutoAcceptCfg)
  936. defer cleanupModel(m)
  937. defer cancel()
  938. m.ClusterConfig(device1Conn, createClusterConfig(device1, id1, id2))
  939. if fcfg, ok := m.cfg.Folder(id1); !ok || !fcfg.SharedWith(device1) {
  940. t.Error("expected shared", id1)
  941. }
  942. if fcfg, ok := m.cfg.Folder(id2); !ok || !fcfg.SharedWith(device1) {
  943. t.Error("expected shared", id2)
  944. }
  945. }
  946. func TestAutoAcceptExistingFolder(t *testing.T) {
  947. // Existing folder
  948. id := srand.String(8)
  949. idOther := srand.String(8) // To check that path does not get changed.
  950. tcfg := defaultAutoAcceptCfg.Copy()
  951. tcfg.Folders = []config.FolderConfiguration{
  952. {
  953. FilesystemType: config.FilesystemTypeFake,
  954. ID: id,
  955. Path: idOther, // To check that path does not get changed.
  956. },
  957. }
  958. m, cancel := newState(t, tcfg)
  959. defer cleanupModel(m)
  960. defer cancel()
  961. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device1) {
  962. t.Error("missing folder, or shared", id)
  963. }
  964. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  965. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || fcfg.Path != idOther {
  966. t.Error("missing folder, or unshared, or path changed", id)
  967. }
  968. }
  969. func TestAutoAcceptNewAndExistingFolder(t *testing.T) {
  970. // New and existing folder
  971. id1 := srand.String(8)
  972. id2 := srand.String(8)
  973. tcfg := defaultAutoAcceptCfg.Copy()
  974. tcfg.Folders = []config.FolderConfiguration{
  975. {
  976. FilesystemType: config.FilesystemTypeFake,
  977. ID: id1,
  978. Path: id1, // from previous test case, to verify that path doesn't get changed.
  979. },
  980. }
  981. m, cancel := newState(t, tcfg)
  982. defer cleanupModel(m)
  983. defer cancel()
  984. if fcfg, ok := m.cfg.Folder(id1); !ok || fcfg.SharedWith(device1) {
  985. t.Error("missing folder, or shared", id1)
  986. }
  987. m.ClusterConfig(device1Conn, createClusterConfig(device1, id1, id2))
  988. for i, id := range []string{id1, id2} {
  989. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  990. t.Error("missing folder, or unshared", i, id)
  991. }
  992. }
  993. }
  994. func TestAutoAcceptAlreadyShared(t *testing.T) {
  995. // Already shared
  996. id := srand.String(8)
  997. tcfg := defaultAutoAcceptCfg.Copy()
  998. tcfg.Folders = []config.FolderConfiguration{
  999. {
  1000. FilesystemType: config.FilesystemTypeFake,
  1001. ID: id,
  1002. Path: id,
  1003. Devices: []config.FolderDeviceConfiguration{
  1004. {
  1005. DeviceID: device1,
  1006. },
  1007. },
  1008. },
  1009. }
  1010. m, cancel := newState(t, tcfg)
  1011. defer cleanupModel(m)
  1012. defer cancel()
  1013. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1014. t.Error("missing folder, or not shared", id)
  1015. }
  1016. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  1017. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1018. t.Error("missing folder, or not shared", id)
  1019. }
  1020. }
  1021. func TestAutoAcceptNameConflict(t *testing.T) {
  1022. ffs := fs.NewFilesystem(fs.FilesystemTypeFake, srand.String(32))
  1023. id := srand.String(8)
  1024. label := srand.String(8)
  1025. ffs.MkdirAll(id, 0o777)
  1026. ffs.MkdirAll(label, 0o777)
  1027. m, cancel := newState(t, defaultAutoAcceptCfg)
  1028. defer cleanupModel(m)
  1029. defer cancel()
  1030. m.ClusterConfig(device1Conn, &protocol.ClusterConfig{
  1031. Folders: []protocol.Folder{
  1032. {
  1033. ID: id,
  1034. Label: label,
  1035. },
  1036. },
  1037. })
  1038. if fcfg, ok := m.cfg.Folder(id); ok && fcfg.SharedWith(device1) {
  1039. t.Error("unexpected folder", id)
  1040. }
  1041. }
  1042. func TestAutoAcceptPrefersLabel(t *testing.T) {
  1043. // Prefers label, falls back to ID.
  1044. m, cancel := newState(t, defaultAutoAcceptCfg)
  1045. id := srand.String(8)
  1046. label := srand.String(8)
  1047. defer cleanupModel(m)
  1048. defer cancel()
  1049. m.ClusterConfig(device1Conn, addFolderDevicesToClusterConfig(&protocol.ClusterConfig{
  1050. Folders: []protocol.Folder{
  1051. {
  1052. ID: id,
  1053. Label: label,
  1054. },
  1055. },
  1056. }, device1))
  1057. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, label) {
  1058. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1059. }
  1060. }
  1061. func TestAutoAcceptFallsBackToID(t *testing.T) {
  1062. // Prefers label, falls back to ID.
  1063. m, cancel := newState(t, defaultAutoAcceptCfg)
  1064. ffs := defaultFolderConfig.Filesystem(nil)
  1065. id := srand.String(8)
  1066. label := srand.String(8)
  1067. if err := ffs.MkdirAll(label, 0o777); err != nil {
  1068. t.Error(err)
  1069. }
  1070. defer cleanupModel(m)
  1071. defer cancel()
  1072. m.ClusterConfig(device1Conn, addFolderDevicesToClusterConfig(&protocol.ClusterConfig{
  1073. Folders: []protocol.Folder{
  1074. {
  1075. ID: id,
  1076. Label: label,
  1077. },
  1078. },
  1079. }, device1))
  1080. fcfg, ok := m.cfg.Folder(id)
  1081. if !ok {
  1082. t.Error("folder configuration missing")
  1083. }
  1084. if !fcfg.SharedWith(device1) {
  1085. t.Error("folder is not shared with device1")
  1086. }
  1087. }
  1088. func TestAutoAcceptPausedWhenFolderConfigChanged(t *testing.T) {
  1089. // Existing folder
  1090. id := srand.String(8)
  1091. idOther := srand.String(8) // To check that path does not get changed.
  1092. tcfg := defaultAutoAcceptCfg.Copy()
  1093. fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", config.FilesystemTypeFake, idOther)
  1094. fcfg.Paused = true
  1095. // The order of devices here is wrong (cfg.clean() sorts them), which will cause the folder to restart.
  1096. // Because of the restart, folder gets removed from m.deviceFolder, which means that generateClusterConfig will not panic.
  1097. // This wasn't an issue before, yet keeping the test case to prove that it still isn't.
  1098. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1099. DeviceID: device1,
  1100. })
  1101. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1102. m, cancel := newState(t, tcfg)
  1103. defer cleanupModel(m)
  1104. defer cancel()
  1105. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1106. t.Error("missing folder, or not shared", id)
  1107. }
  1108. if _, ok := m.folderRunners.Get(id); ok {
  1109. t.Fatal("folder running?")
  1110. }
  1111. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  1112. m.generateClusterConfig(device1)
  1113. if fcfg, ok := m.cfg.Folder(id); !ok {
  1114. t.Error("missing folder")
  1115. } else if fcfg.Path != idOther {
  1116. t.Error("folder path changed")
  1117. } else {
  1118. if slices.Contains(fcfg.DeviceIDs(), device1) {
  1119. return
  1120. }
  1121. t.Error("device missing")
  1122. }
  1123. if _, ok := m.folderRunners.Get(id); ok {
  1124. t.Error("folder started")
  1125. }
  1126. }
  1127. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1128. // Existing folder
  1129. id := srand.String(8)
  1130. idOther := srand.String(8) // To check that path does not get changed.
  1131. tcfg := defaultAutoAcceptCfg.Copy()
  1132. fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", config.FilesystemTypeFake, idOther)
  1133. fcfg.Paused = true
  1134. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1135. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1136. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1137. // did not have a file set.
  1138. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1139. {
  1140. DeviceID: device1,
  1141. },
  1142. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1143. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1144. m, cancel := newState(t, tcfg)
  1145. defer cleanupModel(m)
  1146. defer cancel()
  1147. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1148. t.Error("missing folder, or not shared", id)
  1149. }
  1150. if _, ok := m.folderRunners.Get(id); ok {
  1151. t.Fatal("folder running?")
  1152. }
  1153. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  1154. m.generateClusterConfig(device1)
  1155. if fcfg, ok := m.cfg.Folder(id); !ok {
  1156. t.Error("missing folder")
  1157. } else if fcfg.Path != idOther {
  1158. t.Error("folder path changed")
  1159. } else {
  1160. if slices.Contains(fcfg.DeviceIDs(), device1) {
  1161. return
  1162. }
  1163. t.Error("device missing")
  1164. }
  1165. if _, ok := m.folderRunners.Get(id); ok {
  1166. t.Error("folder started")
  1167. }
  1168. }
  1169. func TestAutoAcceptEnc(t *testing.T) {
  1170. tcfg := defaultAutoAcceptCfg.Copy()
  1171. m, cancel := newState(t, tcfg)
  1172. defer cleanupModel(m)
  1173. defer cancel()
  1174. id := srand.String(8)
  1175. defer os.RemoveAll(id)
  1176. token := []byte("token")
  1177. basicCC := func() *protocol.ClusterConfig {
  1178. return &protocol.ClusterConfig{
  1179. Folders: []protocol.Folder{{
  1180. ID: id,
  1181. Label: id,
  1182. }},
  1183. }
  1184. }
  1185. // Earlier tests might cause the connection to get closed, thus ClusterConfig
  1186. // would panic.
  1187. clusterConfig := func(deviceID protocol.DeviceID, cm *protocol.ClusterConfig) {
  1188. conn := newFakeConnection(deviceID, m)
  1189. m.AddConnection(conn, protocol.Hello{})
  1190. m.ClusterConfig(conn, cm)
  1191. }
  1192. clusterConfig(device1, basicCC())
  1193. if _, ok := m.cfg.Folder(id); ok {
  1194. t.Fatal("unexpected added")
  1195. }
  1196. cc := basicCC()
  1197. cc.Folders[0].Devices = []protocol.Device{{ID: device1}}
  1198. clusterConfig(device1, cc)
  1199. if _, ok := m.cfg.Folder(id); ok {
  1200. t.Fatal("unexpected added")
  1201. }
  1202. cc = basicCC()
  1203. cc.Folders[0].Devices = []protocol.Device{{ID: myID}}
  1204. clusterConfig(device1, cc)
  1205. if _, ok := m.cfg.Folder(id); ok {
  1206. t.Fatal("unexpected added")
  1207. }
  1208. // New folder, encrypted -> add as enc
  1209. cc = createClusterConfig(device1, id)
  1210. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1211. clusterConfig(device1, cc)
  1212. if cfg, ok := m.cfg.Folder(id); !ok {
  1213. t.Fatal("unexpected unadded")
  1214. } else {
  1215. if !cfg.SharedWith(device1) {
  1216. t.Fatal("unexpected unshared")
  1217. }
  1218. if cfg.Type != config.FolderTypeReceiveEncrypted {
  1219. t.Fatal("Folder not added as receiveEncrypted")
  1220. }
  1221. }
  1222. // New device, unencrypted on encrypted folder -> reject
  1223. clusterConfig(device2, createClusterConfig(device2, id))
  1224. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1225. t.Fatal("unexpected shared")
  1226. }
  1227. // New device, encrypted on encrypted folder -> share
  1228. cc = createClusterConfig(device2, id)
  1229. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1230. clusterConfig(device2, cc)
  1231. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1232. t.Fatal("unexpected unshared")
  1233. }
  1234. // New folder, no encrypted -> add "normal"
  1235. id = srand.String(8)
  1236. defer os.RemoveAll(id)
  1237. clusterConfig(device1, createClusterConfig(device1, id))
  1238. if cfg, ok := m.cfg.Folder(id); !ok {
  1239. t.Fatal("unexpected unadded")
  1240. } else {
  1241. if !cfg.SharedWith(device1) {
  1242. t.Fatal("unexpected unshared")
  1243. }
  1244. if cfg.Type != config.FolderTypeSendReceive {
  1245. t.Fatal("Folder not added as send-receive")
  1246. }
  1247. }
  1248. // New device, encrypted on unencrypted folder -> reject
  1249. cc = createClusterConfig(device2, id)
  1250. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1251. clusterConfig(device2, cc)
  1252. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1253. t.Fatal("unexpected shared")
  1254. }
  1255. // New device, unencrypted on unencrypted folder -> share
  1256. clusterConfig(device2, createClusterConfig(device2, id))
  1257. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1258. t.Fatal("unexpected unshared")
  1259. }
  1260. }
  1261. func changeIgnores(t *testing.T, m *testModel, expected []string) {
  1262. arrEqual := func(a, b []string) bool {
  1263. if len(a) != len(b) {
  1264. return false
  1265. }
  1266. for i := range a {
  1267. if a[i] != b[i] {
  1268. return false
  1269. }
  1270. }
  1271. return true
  1272. }
  1273. ignores, _, err := m.LoadIgnores("default")
  1274. if err != nil {
  1275. t.Error(err)
  1276. }
  1277. if !arrEqual(ignores, expected) {
  1278. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1279. }
  1280. ignores = append(ignores, "pox")
  1281. err = m.SetIgnores("default", ignores)
  1282. if err != nil {
  1283. t.Error(err)
  1284. }
  1285. ignores2, _, err := m.LoadIgnores("default")
  1286. if err != nil {
  1287. t.Error(err)
  1288. }
  1289. if !arrEqual(ignores, ignores2) {
  1290. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1291. }
  1292. if build.IsDarwin {
  1293. // see above
  1294. time.Sleep(time.Second)
  1295. } else {
  1296. time.Sleep(time.Millisecond)
  1297. }
  1298. err = m.SetIgnores("default", expected)
  1299. if err != nil {
  1300. t.Error(err)
  1301. }
  1302. ignores, _, err = m.LoadIgnores("default")
  1303. if err != nil {
  1304. t.Error(err)
  1305. }
  1306. if !arrEqual(ignores, expected) {
  1307. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1308. }
  1309. }
  1310. func TestIgnores(t *testing.T) {
  1311. w, cancel := newConfigWrapper(defaultCfg)
  1312. defer cancel()
  1313. ffs := w.FolderList()[0].Filesystem(nil)
  1314. m := setupModel(t, w)
  1315. defer cleanupModel(m)
  1316. // Assure a clean start state
  1317. must(t, ffs.MkdirAll(config.DefaultMarkerName, 0o644))
  1318. writeFile(t, ffs, ".stignore", []byte(".*\nquux\n"))
  1319. folderIgnoresAlwaysReload(t, m, defaultFolderConfig)
  1320. // Make sure the initial scan has finished (ScanFolders is blocking)
  1321. m.ScanFolders()
  1322. expected := []string{
  1323. ".*",
  1324. "quux",
  1325. }
  1326. changeIgnores(t, m, expected)
  1327. _, _, err := m.LoadIgnores("doesnotexist")
  1328. if err == nil {
  1329. t.Error("No error")
  1330. }
  1331. err = m.SetIgnores("doesnotexist", expected)
  1332. if err == nil {
  1333. t.Error("No error")
  1334. }
  1335. // Invalid path, treated like no patterns at all.
  1336. fcfg := config.FolderConfiguration{
  1337. ID: "fresh", Path: "XXX",
  1338. FilesystemType: config.FilesystemTypeFake,
  1339. }
  1340. ignores := ignore.New(fcfg.Filesystem(nil), ignore.WithCache(m.cfg.Options().CacheIgnoredFiles))
  1341. m.mut.Lock()
  1342. m.folderCfgs[fcfg.ID] = fcfg
  1343. m.folderIgnores[fcfg.ID] = ignores
  1344. m.mut.Unlock()
  1345. _, _, err = m.LoadIgnores("fresh")
  1346. if err != nil {
  1347. t.Error("Got error for inexistent folder path")
  1348. }
  1349. // Repeat tests with paused folder
  1350. pausedDefaultFolderConfig := defaultFolderConfig
  1351. pausedDefaultFolderConfig.Paused = true
  1352. m.restartFolder(defaultFolderConfig, pausedDefaultFolderConfig, false)
  1353. // Here folder initialization is not an issue as a paused folder isn't
  1354. // added to the model and thus there is no initial scan happening.
  1355. changeIgnores(t, m, expected)
  1356. // Make sure no .stignore file is considered valid
  1357. defer func() {
  1358. must(t, ffs.Rename(".stignore.bak", ".stignore"))
  1359. }()
  1360. must(t, ffs.Rename(".stignore", ".stignore.bak"))
  1361. changeIgnores(t, m, []string{})
  1362. }
  1363. func TestEmptyIgnores(t *testing.T) {
  1364. w, cancel := newConfigWrapper(defaultCfg)
  1365. defer cancel()
  1366. ffs := w.FolderList()[0].Filesystem(nil)
  1367. m := setupModel(t, w)
  1368. defer cleanupModel(m)
  1369. if err := m.SetIgnores("default", []string{}); err != nil {
  1370. t.Error(err)
  1371. }
  1372. if _, err := ffs.Stat(".stignore"); err == nil {
  1373. t.Error(".stignore was created despite being empty")
  1374. }
  1375. if err := m.SetIgnores("default", []string{".*", "quux"}); err != nil {
  1376. t.Error(err)
  1377. }
  1378. if _, err := ffs.Stat(".stignore"); os.IsNotExist(err) {
  1379. t.Error(".stignore does not exist")
  1380. }
  1381. if err := m.SetIgnores("default", []string{}); err != nil {
  1382. t.Error(err)
  1383. }
  1384. if _, err := ffs.Stat(".stignore"); err == nil {
  1385. t.Error(".stignore should have been deleted because it is empty")
  1386. }
  1387. }
  1388. func waitForState(t *testing.T, sub events.Subscription, folder, expected string) {
  1389. t.Helper()
  1390. timeout := time.After(5 * time.Second)
  1391. var err string
  1392. for {
  1393. select {
  1394. case ev := <-sub.C():
  1395. data := ev.Data.(map[string]interface{})
  1396. if data["folder"].(string) == folder {
  1397. if data["error"] == nil {
  1398. err = ""
  1399. } else {
  1400. err = data["error"].(string)
  1401. }
  1402. if err == expected {
  1403. return
  1404. } else {
  1405. t.Error(ev)
  1406. }
  1407. }
  1408. case <-timeout:
  1409. t.Fatalf("Timed out waiting for status: %s, current status: %v", expected, err)
  1410. }
  1411. }
  1412. }
  1413. func TestROScanRecovery(t *testing.T) {
  1414. fcfg := config.FolderConfiguration{
  1415. FilesystemType: config.FilesystemTypeFake,
  1416. ID: "default",
  1417. Path: srand.String(32),
  1418. Type: config.FolderTypeSendOnly,
  1419. RescanIntervalS: 1,
  1420. MarkerName: config.DefaultMarkerName,
  1421. }
  1422. cfg, cancel := newConfigWrapper(config.Configuration{
  1423. Version: config.CurrentVersion,
  1424. Folders: []config.FolderConfiguration{fcfg},
  1425. Devices: []config.DeviceConfiguration{
  1426. {
  1427. DeviceID: device1,
  1428. },
  1429. },
  1430. })
  1431. defer cancel()
  1432. m := newModel(t, cfg, myID, nil)
  1433. set := newFileSet(t, "default", m.db)
  1434. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1435. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1436. })
  1437. ffs := fcfg.Filesystem(nil)
  1438. // Remove marker to generate an error
  1439. ffs.Remove(fcfg.MarkerName)
  1440. sub := m.evLogger.Subscribe(events.StateChanged)
  1441. defer sub.Unsubscribe()
  1442. m.ServeBackground()
  1443. defer cleanupModel(m)
  1444. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1445. fd, err := ffs.Create(config.DefaultMarkerName)
  1446. if err != nil {
  1447. t.Fatal(err)
  1448. }
  1449. fd.Close()
  1450. waitForState(t, sub, "default", "")
  1451. }
  1452. func TestRWScanRecovery(t *testing.T) {
  1453. fcfg := config.FolderConfiguration{
  1454. FilesystemType: config.FilesystemTypeFake,
  1455. ID: "default",
  1456. Path: srand.String(32),
  1457. Type: config.FolderTypeSendReceive,
  1458. RescanIntervalS: 1,
  1459. MarkerName: config.DefaultMarkerName,
  1460. }
  1461. cfg, cancel := newConfigWrapper(config.Configuration{
  1462. Version: config.CurrentVersion,
  1463. Folders: []config.FolderConfiguration{fcfg},
  1464. Devices: []config.DeviceConfiguration{
  1465. {
  1466. DeviceID: device1,
  1467. },
  1468. },
  1469. })
  1470. defer cancel()
  1471. m := newModel(t, cfg, myID, nil)
  1472. set := newFileSet(t, "default", m.db)
  1473. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1474. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1475. })
  1476. ffs := fcfg.Filesystem(nil)
  1477. // Generate error
  1478. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  1479. t.Fatal(err)
  1480. }
  1481. sub := m.evLogger.Subscribe(events.StateChanged)
  1482. defer sub.Unsubscribe()
  1483. m.ServeBackground()
  1484. defer cleanupModel(m)
  1485. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1486. fd, err := ffs.Create(config.DefaultMarkerName)
  1487. if err != nil {
  1488. t.Error(err)
  1489. }
  1490. fd.Close()
  1491. waitForState(t, sub, "default", "")
  1492. }
  1493. func TestGlobalDirectoryTree(t *testing.T) {
  1494. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  1495. defer wCancel()
  1496. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  1497. b := func(isfile bool, path ...string) protocol.FileInfo {
  1498. typ := protocol.FileInfoTypeDirectory
  1499. var blocks []protocol.BlockInfo
  1500. if isfile {
  1501. typ = protocol.FileInfoTypeFile
  1502. 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}}}
  1503. }
  1504. return protocol.FileInfo{
  1505. Name: filepath.Join(path...),
  1506. Type: typ,
  1507. ModifiedS: 0x666,
  1508. Blocks: blocks,
  1509. Size: 0xa,
  1510. }
  1511. }
  1512. f := func(name string) *TreeEntry {
  1513. return &TreeEntry{
  1514. Name: name,
  1515. ModTime: time.Unix(0x666, 0),
  1516. Size: 0xa,
  1517. Type: protocol.FileInfoTypeFile.String(),
  1518. }
  1519. }
  1520. d := func(name string, entries ...*TreeEntry) *TreeEntry {
  1521. return &TreeEntry{
  1522. Name: name,
  1523. ModTime: time.Unix(0x666, 0),
  1524. Size: 128,
  1525. Type: protocol.FileInfoTypeDirectory.String(),
  1526. Children: entries,
  1527. }
  1528. }
  1529. testdata := []protocol.FileInfo{
  1530. b(false, "another"),
  1531. b(false, "another", "directory"),
  1532. b(true, "another", "directory", "afile"),
  1533. b(false, "another", "directory", "with"),
  1534. b(false, "another", "directory", "with", "a"),
  1535. b(true, "another", "directory", "with", "a", "file"),
  1536. b(true, "another", "directory", "with", "file"),
  1537. b(true, "another", "file"),
  1538. b(false, "other"),
  1539. b(false, "other", "rand"),
  1540. b(false, "other", "random"),
  1541. b(false, "other", "random", "dir"),
  1542. b(false, "other", "random", "dirx"),
  1543. b(false, "other", "randomx"),
  1544. b(false, "some"),
  1545. b(false, "some", "directory"),
  1546. b(false, "some", "directory", "with"),
  1547. b(false, "some", "directory", "with", "a"),
  1548. b(true, "some", "directory", "with", "a", "file"),
  1549. b(true, "zzrootfile"),
  1550. }
  1551. expectedResult := []*TreeEntry{
  1552. d("another",
  1553. d("directory",
  1554. f("afile"),
  1555. d("with",
  1556. d("a",
  1557. f("file"),
  1558. ),
  1559. f("file"),
  1560. ),
  1561. ),
  1562. f("file"),
  1563. ),
  1564. d("other",
  1565. d("rand"),
  1566. d("random",
  1567. d("dir"),
  1568. d("dirx"),
  1569. ),
  1570. d("randomx"),
  1571. ),
  1572. d("some",
  1573. d("directory",
  1574. d("with",
  1575. d("a",
  1576. f("file"),
  1577. ),
  1578. ),
  1579. ),
  1580. ),
  1581. f("zzrootfile"),
  1582. }
  1583. mm := func(data interface{}) string {
  1584. bytes, err := json.MarshalIndent(data, "", " ")
  1585. if err != nil {
  1586. panic(err)
  1587. }
  1588. return string(bytes)
  1589. }
  1590. must(t, m.Index(conn, &protocol.Index{Folder: "default", Files: testdata}))
  1591. result, _ := m.GlobalDirectoryTree("default", "", -1, false)
  1592. if mm(result) != mm(expectedResult) {
  1593. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(expectedResult))
  1594. }
  1595. result, _ = m.GlobalDirectoryTree("default", "another", -1, false)
  1596. if mm(result) != mm(findByName(expectedResult, "another").Children) {
  1597. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(findByName(expectedResult, "another").Children))
  1598. }
  1599. result, _ = m.GlobalDirectoryTree("default", "", 0, false)
  1600. currentResult := []*TreeEntry{
  1601. d("another"),
  1602. d("other"),
  1603. d("some"),
  1604. f("zzrootfile"),
  1605. }
  1606. if mm(result) != mm(currentResult) {
  1607. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(currentResult))
  1608. }
  1609. result, _ = m.GlobalDirectoryTree("default", "", 1, false)
  1610. currentResult = []*TreeEntry{
  1611. d("another",
  1612. d("directory"),
  1613. f("file"),
  1614. ),
  1615. d("other",
  1616. d("rand"),
  1617. d("random"),
  1618. d("randomx"),
  1619. ),
  1620. d("some",
  1621. d("directory"),
  1622. ),
  1623. f("zzrootfile"),
  1624. }
  1625. if mm(result) != mm(currentResult) {
  1626. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1627. }
  1628. result, _ = m.GlobalDirectoryTree("default", "", -1, true)
  1629. currentResult = []*TreeEntry{
  1630. d("another",
  1631. d("directory",
  1632. d("with",
  1633. d("a"),
  1634. ),
  1635. ),
  1636. ),
  1637. d("other",
  1638. d("rand"),
  1639. d("random",
  1640. d("dir"),
  1641. d("dirx"),
  1642. ),
  1643. d("randomx"),
  1644. ),
  1645. d("some",
  1646. d("directory",
  1647. d("with",
  1648. d("a"),
  1649. ),
  1650. ),
  1651. ),
  1652. }
  1653. if mm(result) != mm(currentResult) {
  1654. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1655. }
  1656. result, _ = m.GlobalDirectoryTree("default", "", 1, true)
  1657. currentResult = []*TreeEntry{
  1658. d("another",
  1659. d("directory"),
  1660. ),
  1661. d("other",
  1662. d("rand"),
  1663. d("random"),
  1664. d("randomx"),
  1665. ),
  1666. d("some",
  1667. d("directory"),
  1668. ),
  1669. }
  1670. if mm(result) != mm(currentResult) {
  1671. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1672. }
  1673. result, _ = m.GlobalDirectoryTree("default", "another", 0, false)
  1674. currentResult = []*TreeEntry{
  1675. d("directory"),
  1676. f("file"),
  1677. }
  1678. if mm(result) != mm(currentResult) {
  1679. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1680. }
  1681. result, _ = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1682. currentResult = []*TreeEntry{
  1683. d("with"),
  1684. }
  1685. if mm(result) != mm(currentResult) {
  1686. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1687. }
  1688. result, _ = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1689. currentResult = []*TreeEntry{
  1690. d("with",
  1691. d("a"),
  1692. ),
  1693. }
  1694. if mm(result) != mm(currentResult) {
  1695. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1696. }
  1697. result, _ = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1698. currentResult = []*TreeEntry{
  1699. d("with",
  1700. d("a",
  1701. f("file"),
  1702. ),
  1703. ),
  1704. }
  1705. if mm(result) != mm(currentResult) {
  1706. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1707. }
  1708. result, _ = m.GlobalDirectoryTree("default", "another", -1, true)
  1709. currentResult = []*TreeEntry{
  1710. d("directory",
  1711. d("with",
  1712. d("a"),
  1713. ),
  1714. ),
  1715. }
  1716. if mm(result) != mm(currentResult) {
  1717. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1718. }
  1719. // No prefix matching!
  1720. result, _ = m.GlobalDirectoryTree("default", "som", -1, false)
  1721. currentResult = []*TreeEntry{}
  1722. if mm(result) != mm(currentResult) {
  1723. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1724. }
  1725. }
  1726. func genDeepFiles(n, d int) []protocol.FileInfo {
  1727. mrand.Seed(int64(n))
  1728. files := make([]protocol.FileInfo, n)
  1729. t := time.Now().Unix()
  1730. for i := 0; i < n; i++ {
  1731. path := ""
  1732. for i := 0; i <= d; i++ {
  1733. path = filepath.Join(path, strconv.Itoa(mrand.Int()))
  1734. }
  1735. sofar := ""
  1736. for _, path := range filepath.SplitList(path) {
  1737. sofar = filepath.Join(sofar, path)
  1738. files[i] = protocol.FileInfo{
  1739. Name: sofar,
  1740. }
  1741. i++
  1742. }
  1743. files[i].ModifiedS = t
  1744. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1745. }
  1746. return files
  1747. }
  1748. func BenchmarkTree_10000_50(b *testing.B) {
  1749. benchmarkTree(b, 10000, 50)
  1750. }
  1751. func BenchmarkTree_100_50(b *testing.B) {
  1752. benchmarkTree(b, 100, 50)
  1753. }
  1754. func BenchmarkTree_100_10(b *testing.B) {
  1755. benchmarkTree(b, 100, 10)
  1756. }
  1757. func benchmarkTree(b *testing.B, n1, n2 int) {
  1758. m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
  1759. defer wcfgCancel()
  1760. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  1761. m.ScanFolder(fcfg.ID)
  1762. files := genDeepFiles(n1, n2)
  1763. must(b, m.Index(device1Conn, &protocol.Index{Folder: fcfg.ID, Files: files}))
  1764. b.ResetTimer()
  1765. for i := 0; i < b.N; i++ {
  1766. m.GlobalDirectoryTree(fcfg.ID, "", -1, false)
  1767. }
  1768. b.ReportAllocs()
  1769. }
  1770. func TestIssue3028(t *testing.T) {
  1771. w, cancel := newConfigWrapper(defaultCfg)
  1772. defer cancel()
  1773. ffs := w.FolderList()[0].Filesystem(nil)
  1774. m := setupModel(t, w)
  1775. defer cleanupModel(m)
  1776. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1777. writeFile(t, ffs, "testrm", []byte("Hello"))
  1778. writeFile(t, ffs, "testrm2", []byte("Hello"))
  1779. // Scan, and get a count of how many files are there now
  1780. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1781. locorigfiles := localSize(t, m, "default").Files
  1782. globorigfiles := globalSize(t, m, "default").Files
  1783. // Delete
  1784. must(t, ffs.Remove("testrm"))
  1785. must(t, ffs.Remove("testrm2"))
  1786. // Verify that the number of files decreased by two and the number of
  1787. // deleted files increases by two
  1788. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1789. loc := localSize(t, m, "default")
  1790. glob := globalSize(t, m, "default")
  1791. if loc.Files != locorigfiles-2 {
  1792. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1793. }
  1794. if glob.Files != globorigfiles-2 {
  1795. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1796. }
  1797. if loc.Deleted != 2 {
  1798. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1799. }
  1800. if glob.Deleted != 2 {
  1801. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1802. }
  1803. }
  1804. func TestIssue4357(t *testing.T) {
  1805. cfg := defaultCfgWrapper.RawCopy()
  1806. // Create a separate wrapper not to pollute other tests.
  1807. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  1808. defer cancel()
  1809. m := newModel(t, wrapper, myID, nil)
  1810. m.ServeBackground()
  1811. defer cleanupModel(m)
  1812. // Force the model to wire itself and add the folders
  1813. replace(t, wrapper, cfg)
  1814. if _, ok := m.folderCfgs["default"]; !ok {
  1815. t.Error("Folder should be running")
  1816. }
  1817. newCfg := wrapper.RawCopy()
  1818. newCfg.Folders[0].Paused = true
  1819. replace(t, wrapper, newCfg)
  1820. if _, ok := m.folderCfgs["default"]; ok {
  1821. t.Error("Folder should not be running")
  1822. }
  1823. if _, ok := m.cfg.Folder("default"); !ok {
  1824. t.Error("should still have folder in config")
  1825. }
  1826. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1827. if _, ok := m.cfg.Folder("default"); ok {
  1828. t.Error("should not have folder in config")
  1829. }
  1830. // Add the folder back, should be running
  1831. replace(t, wrapper, cfg)
  1832. if _, ok := m.folderCfgs["default"]; !ok {
  1833. t.Error("Folder should be running")
  1834. }
  1835. if _, ok := m.cfg.Folder("default"); !ok {
  1836. t.Error("should still have folder in config")
  1837. }
  1838. // Should not panic when removing a running folder.
  1839. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1840. if _, ok := m.folderCfgs["default"]; ok {
  1841. t.Error("Folder should not be running")
  1842. }
  1843. if _, ok := m.cfg.Folder("default"); ok {
  1844. t.Error("should not have folder in config")
  1845. }
  1846. }
  1847. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1848. m := newModel(t, defaultCfgWrapper, myID, nil)
  1849. files := newFileSet(t, "default", m.db)
  1850. files.Drop(device1)
  1851. files.Update(device1, genFiles(1))
  1852. files.Drop(device2)
  1853. files.Update(device2, genFiles(1))
  1854. if len(files.ListDevices()) != 2 {
  1855. t.Error("expected two devices")
  1856. }
  1857. m.newFolder(defaultFolderConfig, false)
  1858. defer cleanupModel(m)
  1859. // Remote sequence is cached, hence need to recreated.
  1860. files = newFileSet(t, "default", m.db)
  1861. if l := len(files.ListDevices()); l != 1 {
  1862. t.Errorf("Expected one device got %v", l)
  1863. }
  1864. }
  1865. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1866. wcfg, cancel := newConfigWrapper(defaultCfg)
  1867. defer cancel()
  1868. addDevice2(t, wcfg, wcfg.FolderList()[0])
  1869. m := setupModel(t, wcfg)
  1870. defer cleanupModel(m)
  1871. conn1 := newFakeConnection(device1, m)
  1872. m.AddConnection(conn1, protocol.Hello{})
  1873. conn2 := newFakeConnection(device2, m)
  1874. m.AddConnection(conn2, protocol.Hello{})
  1875. m.ClusterConfig(conn1, &protocol.ClusterConfig{
  1876. Folders: []protocol.Folder{
  1877. {
  1878. ID: "default",
  1879. Devices: []protocol.Device{
  1880. {ID: myID},
  1881. {ID: device1},
  1882. {ID: device2},
  1883. },
  1884. },
  1885. },
  1886. })
  1887. m.ClusterConfig(conn2, &protocol.ClusterConfig{
  1888. Folders: []protocol.Folder{
  1889. {
  1890. ID: "default",
  1891. Devices: []protocol.Device{
  1892. {ID: myID},
  1893. {ID: device1},
  1894. {ID: device2},
  1895. },
  1896. },
  1897. },
  1898. })
  1899. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  1900. t.Error("not shared with device1")
  1901. }
  1902. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
  1903. t.Error("not shared with device2")
  1904. }
  1905. select {
  1906. case <-conn2.Closed():
  1907. t.Error("conn already closed")
  1908. default:
  1909. }
  1910. if _, err := wcfg.RemoveDevice(device2); err != nil {
  1911. t.Error(err)
  1912. }
  1913. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1914. fcfg, ok := m.cfg.Folder("default")
  1915. if !ok {
  1916. t.Fatal("default folder missing")
  1917. }
  1918. if !fcfg.SharedWith(device1) {
  1919. t.Error("not shared with device1")
  1920. }
  1921. if fcfg.SharedWith(device2) {
  1922. t.Error("shared with device2")
  1923. }
  1924. for _, dev := range fcfg.Devices {
  1925. if dev.DeviceID == device2 {
  1926. t.Error("still there")
  1927. }
  1928. }
  1929. select {
  1930. case <-conn2.Closed():
  1931. default:
  1932. t.Error("connection not closed")
  1933. }
  1934. if _, ok := wcfg.Devices()[device2]; ok {
  1935. t.Error("device still in config")
  1936. }
  1937. if _, ok := m.deviceConnIDs[device2]; ok {
  1938. t.Error("conn not missing")
  1939. }
  1940. if _, ok := m.helloMessages[device2]; ok {
  1941. t.Error("hello not missing")
  1942. }
  1943. if _, ok := m.deviceDownloads[device2]; ok {
  1944. t.Error("downloads not missing")
  1945. }
  1946. }
  1947. func TestIssue3804(t *testing.T) {
  1948. m := setupModel(t, defaultCfgWrapper)
  1949. defer cleanupModel(m)
  1950. // Subdirs ending in slash should be accepted
  1951. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1952. t.Error("Unexpected error:", err)
  1953. }
  1954. }
  1955. func TestIssue3829(t *testing.T) {
  1956. m := setupModel(t, defaultCfgWrapper)
  1957. defer cleanupModel(m)
  1958. // Empty subdirs should be accepted
  1959. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1960. t.Error("Unexpected error:", err)
  1961. }
  1962. }
  1963. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  1964. func TestIssue4573(t *testing.T) {
  1965. w, fcfg, wCancel := newDefaultCfgWrapper()
  1966. defer wCancel()
  1967. testFs := fcfg.Filesystem(nil)
  1968. defer os.RemoveAll(testFs.URI())
  1969. must(t, testFs.MkdirAll("inaccessible", 0o755))
  1970. defer testFs.Chmod("inaccessible", 0o777)
  1971. file := filepath.Join("inaccessible", "a")
  1972. fd, err := testFs.Create(file)
  1973. must(t, err)
  1974. fd.Close()
  1975. m := setupModel(t, w)
  1976. defer cleanupModel(m)
  1977. must(t, testFs.Chmod("inaccessible", 0o000))
  1978. m.ScanFolder("default")
  1979. if file, ok := m.testCurrentFolderFile("default", file); !ok {
  1980. t.Fatalf("File missing in db")
  1981. } else if file.Deleted {
  1982. t.Errorf("Inaccessible file has been marked as deleted.")
  1983. }
  1984. }
  1985. // TestInternalScan checks whether various fs operations are correctly represented
  1986. // in the db after scanning.
  1987. func TestInternalScan(t *testing.T) {
  1988. w, fcfg, wCancel := newDefaultCfgWrapper()
  1989. defer wCancel()
  1990. testFs := fcfg.Filesystem(nil)
  1991. defer os.RemoveAll(testFs.URI())
  1992. testCases := map[string]func(protocol.FileInfo) bool{
  1993. "removeDir": func(f protocol.FileInfo) bool {
  1994. return !f.Deleted
  1995. },
  1996. "dirToFile": func(f protocol.FileInfo) bool {
  1997. return f.Deleted || f.IsDirectory()
  1998. },
  1999. }
  2000. baseDirs := []string{"dirToFile", "removeDir"}
  2001. for _, dir := range baseDirs {
  2002. sub := filepath.Join(dir, "subDir")
  2003. for _, dir := range []string{dir, sub} {
  2004. if err := testFs.MkdirAll(dir, 0o775); err != nil {
  2005. t.Fatalf("%v: %v", dir, err)
  2006. }
  2007. }
  2008. testCases[sub] = func(f protocol.FileInfo) bool {
  2009. return !f.Deleted
  2010. }
  2011. for _, dir := range []string{dir, sub} {
  2012. file := filepath.Join(dir, "a")
  2013. fd, err := testFs.Create(file)
  2014. must(t, err)
  2015. fd.Close()
  2016. testCases[file] = func(f protocol.FileInfo) bool {
  2017. return !f.Deleted
  2018. }
  2019. }
  2020. }
  2021. m := setupModel(t, w)
  2022. defer cleanupModel(m)
  2023. for _, dir := range baseDirs {
  2024. must(t, testFs.RemoveAll(dir))
  2025. }
  2026. fd, err := testFs.Create("dirToFile")
  2027. must(t, err)
  2028. fd.Close()
  2029. m.ScanFolder("default")
  2030. for path, cond := range testCases {
  2031. if f, ok := m.testCurrentFolderFile("default", path); !ok {
  2032. t.Fatalf("%v missing in db", path)
  2033. } else if cond(f) {
  2034. t.Errorf("Incorrect db entry for %v", path)
  2035. }
  2036. }
  2037. }
  2038. func TestCustomMarkerName(t *testing.T) {
  2039. fcfg := newFolderConfig()
  2040. fcfg.ID = "default"
  2041. fcfg.RescanIntervalS = 1
  2042. fcfg.MarkerName = "myfile"
  2043. cfg, cancel := newConfigWrapper(config.Configuration{
  2044. Version: config.CurrentVersion,
  2045. Folders: []config.FolderConfiguration{fcfg},
  2046. Devices: []config.DeviceConfiguration{
  2047. {
  2048. DeviceID: device1,
  2049. },
  2050. },
  2051. })
  2052. defer cancel()
  2053. ffs := fcfg.Filesystem(nil)
  2054. m := newModel(t, cfg, myID, nil)
  2055. set := newFileSet(t, "default", m.db)
  2056. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2057. {Name: "dummyfile"},
  2058. })
  2059. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  2060. t.Fatal(err)
  2061. }
  2062. sub := m.evLogger.Subscribe(events.StateChanged)
  2063. defer sub.Unsubscribe()
  2064. m.ServeBackground()
  2065. defer cleanupModel(m)
  2066. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  2067. fd, _ := ffs.Create("myfile")
  2068. fd.Close()
  2069. waitForState(t, sub, "default", "")
  2070. }
  2071. func TestRemoveDirWithContent(t *testing.T) {
  2072. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2073. defer wcfgCancel()
  2074. tfs := fcfg.Filesystem(nil)
  2075. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2076. tfs.MkdirAll("dirwith", 0o755)
  2077. content := filepath.Join("dirwith", "content")
  2078. fd, err := tfs.Create(content)
  2079. must(t, err)
  2080. fd.Close()
  2081. must(t, m.ScanFolder(fcfg.ID))
  2082. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2083. if !ok {
  2084. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2085. }
  2086. dir.Deleted = true
  2087. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2088. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2089. if !ok {
  2090. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2091. }
  2092. file.Deleted = true
  2093. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2094. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{dir, file}}))
  2095. // Is there something we could trigger on instead of just waiting?
  2096. timeout := time.NewTimer(5 * time.Second)
  2097. for {
  2098. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2099. if !ok {
  2100. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2101. }
  2102. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2103. if !ok {
  2104. t.Fatalf("Can't get file \"%v\" after index update", content)
  2105. }
  2106. if dir.Deleted && file.Deleted {
  2107. return
  2108. }
  2109. select {
  2110. case <-timeout.C:
  2111. if !dir.Deleted && !file.Deleted {
  2112. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2113. } else if !dir.Deleted {
  2114. t.Errorf("The dir was not deleted before timing out.")
  2115. } else {
  2116. t.Errorf("The content of the dir was not deleted before timing out.")
  2117. }
  2118. return
  2119. default:
  2120. time.Sleep(100 * time.Millisecond)
  2121. }
  2122. }
  2123. }
  2124. func TestIssue4475(t *testing.T) {
  2125. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2126. defer wcfgCancel()
  2127. defer cleanupModel(m)
  2128. testFs := fcfg.Filesystem(nil)
  2129. // Scenario: Dir is deleted locally and before syncing/index exchange
  2130. // happens, a file is create in that dir on the remote.
  2131. // This should result in the directory being recreated and added to the
  2132. // db locally.
  2133. must(t, testFs.MkdirAll("delDir", 0o755))
  2134. m.ScanFolder("default")
  2135. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2136. t.Fatal("not shared with device1")
  2137. }
  2138. fileName := filepath.Join("delDir", "file")
  2139. conn.addFile(fileName, 0o644, protocol.FileInfoTypeFile, nil)
  2140. conn.sendIndexUpdate()
  2141. // Is there something we could trigger on instead of just waiting?
  2142. timeout := time.NewTimer(5 * time.Second)
  2143. created := false
  2144. for {
  2145. if !created {
  2146. if _, ok := m.testCurrentFolderFile("default", fileName); ok {
  2147. created = true
  2148. }
  2149. } else {
  2150. dir, ok := m.testCurrentFolderFile("default", "delDir")
  2151. if !ok {
  2152. t.Fatalf("can't get dir from db")
  2153. }
  2154. if !dir.Deleted {
  2155. return
  2156. }
  2157. }
  2158. select {
  2159. case <-timeout.C:
  2160. if created {
  2161. t.Errorf("Timed out before file from remote was created")
  2162. } else {
  2163. t.Errorf("Timed out before directory was resurrected in db")
  2164. }
  2165. return
  2166. default:
  2167. time.Sleep(100 * time.Millisecond)
  2168. }
  2169. }
  2170. }
  2171. func TestVersionRestore(t *testing.T) {
  2172. t.Skip("incompatible with fakefs")
  2173. // We create a bunch of files which we restore
  2174. // In each file, we write the filename as the content
  2175. // We verify that the content matches at the expected filenames
  2176. // after the restore operation.
  2177. fcfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", config.FilesystemTypeFake, srand.String(32))
  2178. fcfg.Versioning.Type = "simple"
  2179. fcfg.FSWatcherEnabled = false
  2180. filesystem := fcfg.Filesystem(nil)
  2181. rawConfig := config.Configuration{
  2182. Version: config.CurrentVersion,
  2183. Folders: []config.FolderConfiguration{fcfg},
  2184. }
  2185. cfg, cancel := newConfigWrapper(rawConfig)
  2186. defer cancel()
  2187. m := setupModel(t, cfg)
  2188. defer cleanupModel(m)
  2189. m.ScanFolder("default")
  2190. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20180101-010101", time.Local)
  2191. if err != nil {
  2192. t.Fatal(err)
  2193. }
  2194. for _, file := range []string{
  2195. // Versions directory
  2196. ".stversions/file~20171210-040404.txt", // will be restored
  2197. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2198. ".stversions/something~20171210-040404", // will become directory, hence error
  2199. ".stversions/dir/file~20171210-040404.txt",
  2200. ".stversions/dir/file~20171210-040405.txt",
  2201. ".stversions/dir/file~20171210-040406.txt",
  2202. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2203. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2204. ".stversions/dir/cat", // untagged which was used by trashcan, supported
  2205. // "file.txt" will be restored
  2206. "existing",
  2207. "something/file", // Becomes directory
  2208. "dir/file.txt",
  2209. "dir/existing.txt",
  2210. } {
  2211. if build.IsWindows {
  2212. file = filepath.FromSlash(file)
  2213. }
  2214. dir := filepath.Dir(file)
  2215. must(t, filesystem.MkdirAll(dir, 0o755))
  2216. if fd, err := filesystem.Create(file); err != nil {
  2217. t.Fatal(err)
  2218. } else if _, err := fd.Write([]byte(file)); err != nil {
  2219. t.Fatal(err)
  2220. } else if err := fd.Close(); err != nil {
  2221. t.Fatal(err)
  2222. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2223. t.Fatal(err)
  2224. }
  2225. }
  2226. versions, err := m.GetFolderVersions("default")
  2227. must(t, err)
  2228. expectedVersions := map[string]int{
  2229. "file.txt": 1,
  2230. "existing": 1,
  2231. "something": 1,
  2232. "dir/file.txt": 3,
  2233. "dir/existing.txt": 1,
  2234. "very/very/deep/one.txt": 1,
  2235. "dir/cat": 1,
  2236. }
  2237. for name, vers := range versions {
  2238. cnt, ok := expectedVersions[name]
  2239. if !ok {
  2240. t.Errorf("unexpected %s", name)
  2241. }
  2242. if len(vers) != cnt {
  2243. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2244. }
  2245. // Delete, so we can check if we didn't hit something we expect afterwards.
  2246. delete(expectedVersions, name)
  2247. }
  2248. for name := range expectedVersions {
  2249. t.Errorf("not found expected %s", name)
  2250. }
  2251. // Restoring non existing folder fails.
  2252. _, err = m.RestoreFolderVersions("does not exist", nil)
  2253. if err == nil {
  2254. t.Errorf("expected an error")
  2255. }
  2256. makeTime := func(s string) time.Time {
  2257. tm, err := time.ParseInLocation(versioner.TimeFormat, s, time.Local)
  2258. if err != nil {
  2259. t.Error(err)
  2260. }
  2261. return tm.Truncate(time.Second)
  2262. }
  2263. restore := map[string]time.Time{
  2264. "file.txt": makeTime("20171210-040404"),
  2265. "existing": makeTime("20171210-040404"),
  2266. "something": makeTime("20171210-040404"),
  2267. "dir/file.txt": makeTime("20171210-040406"),
  2268. "dir/existing.txt": makeTime("20171210-040406"),
  2269. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2270. }
  2271. beforeRestore := time.Now().Truncate(time.Second)
  2272. ferr, err := m.RestoreFolderVersions("default", restore)
  2273. must(t, err)
  2274. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || !errors.Is(err, versioner.ErrDirectory) {
  2275. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2276. }
  2277. // Failed items are not expected to be restored.
  2278. // Remove them from expectations
  2279. for name := range ferr {
  2280. delete(restore, name)
  2281. }
  2282. // Check that content of files matches to the version they've been restored.
  2283. for file, version := range restore {
  2284. if build.IsWindows {
  2285. file = filepath.FromSlash(file)
  2286. }
  2287. tag := version.In(time.Local).Truncate(time.Second).Format(versioner.TimeFormat)
  2288. taggedName := filepath.Join(versioner.DefaultPath, versioner.TagFilename(file, tag))
  2289. fd, err := filesystem.Open(file)
  2290. if err != nil {
  2291. t.Error(err)
  2292. }
  2293. defer fd.Close()
  2294. content, err := io.ReadAll(fd)
  2295. if err != nil {
  2296. t.Error(err)
  2297. }
  2298. if !bytes.Equal(content, []byte(taggedName)) {
  2299. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2300. }
  2301. }
  2302. // Simple versioner uses now for timestamp generation, so we can check
  2303. // if existing stuff was correctly archived as we restored (oppose to deleteD), and version time as after beforeRestore
  2304. expectArchived := map[string]struct{}{
  2305. "existing": {},
  2306. "dir/file.txt": {},
  2307. "dir/existing.txt": {},
  2308. }
  2309. allFileVersions, err := m.GetFolderVersions("default")
  2310. must(t, err)
  2311. for file, versions := range allFileVersions {
  2312. key := file
  2313. if build.IsWindows {
  2314. file = filepath.FromSlash(file)
  2315. }
  2316. for _, version := range versions {
  2317. if version.VersionTime.Equal(beforeRestore) || version.VersionTime.After(beforeRestore) {
  2318. fd, err := filesystem.Open(versioner.DefaultPath + "/" + versioner.TagFilename(file, version.VersionTime.Format(versioner.TimeFormat)))
  2319. must(t, err)
  2320. defer fd.Close()
  2321. content, err := io.ReadAll(fd)
  2322. if err != nil {
  2323. t.Error(err)
  2324. }
  2325. // Even if they are at the archived path, content should have the non
  2326. // archived name.
  2327. if !bytes.Equal(content, []byte(file)) {
  2328. t.Errorf("%s (%s): %s != %s", file, fd.Name(), string(content), file)
  2329. }
  2330. _, ok := expectArchived[key]
  2331. if !ok {
  2332. t.Error("unexpected archived file with future timestamp", file, version.VersionTime)
  2333. }
  2334. delete(expectArchived, key)
  2335. }
  2336. }
  2337. }
  2338. if len(expectArchived) != 0 {
  2339. t.Fatal("missed some archived files", expectArchived)
  2340. }
  2341. }
  2342. func TestPausedFolders(t *testing.T) {
  2343. // Create a separate wrapper not to pollute other tests.
  2344. wrapper, cancel := newConfigWrapper(defaultCfgWrapper.RawCopy())
  2345. defer cancel()
  2346. m := setupModel(t, wrapper)
  2347. defer cleanupModel(m)
  2348. if err := m.ScanFolder("default"); err != nil {
  2349. t.Error(err)
  2350. }
  2351. pausedConfig := wrapper.RawCopy()
  2352. pausedConfig.Folders[0].Paused = true
  2353. replace(t, wrapper, pausedConfig)
  2354. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2355. t.Errorf("Expected folder paused error, received: %v", err)
  2356. }
  2357. if err := m.ScanFolder("nonexistent"); err != ErrFolderMissing {
  2358. t.Errorf("Expected missing folder error, received: %v", err)
  2359. }
  2360. }
  2361. func TestIssue4094(t *testing.T) {
  2362. // Create a separate wrapper not to pollute other tests.
  2363. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2364. defer cancel()
  2365. m := newModel(t, wrapper, myID, nil)
  2366. m.ServeBackground()
  2367. defer cleanupModel(m)
  2368. // Force the model to wire itself and add the folders
  2369. folderPath := "nonexistent"
  2370. cfg := defaultCfgWrapper.RawCopy()
  2371. fcfg := config.FolderConfiguration{
  2372. FilesystemType: config.FilesystemTypeFake,
  2373. ID: "folder1",
  2374. Path: folderPath,
  2375. Paused: true,
  2376. Devices: []config.FolderDeviceConfiguration{
  2377. {DeviceID: device1},
  2378. },
  2379. }
  2380. cfg.Folders = []config.FolderConfiguration{fcfg}
  2381. replace(t, wrapper, cfg)
  2382. if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
  2383. t.Fatalf("failed setting ignores: %v", err)
  2384. }
  2385. if _, err := fcfg.Filesystem(nil).Lstat(".stignore"); err != nil {
  2386. t.Fatalf("failed stating .stignore: %v", err)
  2387. }
  2388. }
  2389. func TestIssue4903(t *testing.T) {
  2390. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2391. defer cancel()
  2392. m := setupModel(t, wrapper)
  2393. defer cleanupModel(m)
  2394. // Force the model to wire itself and add the folders
  2395. folderPath := "nonexistent"
  2396. cfg := defaultCfgWrapper.RawCopy()
  2397. fcfg := config.FolderConfiguration{
  2398. ID: "folder1",
  2399. Path: folderPath,
  2400. FilesystemType: config.FilesystemTypeBasic,
  2401. Paused: true,
  2402. Devices: []config.FolderDeviceConfiguration{
  2403. {DeviceID: device1},
  2404. },
  2405. }
  2406. cfg.Folders = []config.FolderConfiguration{fcfg}
  2407. replace(t, wrapper, cfg)
  2408. if err := fcfg.CheckPath(); err != config.ErrPathMissing {
  2409. t.Fatalf("expected path missing error, got: %v, debug: %s", err, fcfg.CheckPath())
  2410. }
  2411. if _, err := fcfg.Filesystem(nil).Lstat("."); !fs.IsNotExist(err) {
  2412. t.Fatalf("Expected missing path error, got: %v", err)
  2413. }
  2414. }
  2415. func TestIssue5002(t *testing.T) {
  2416. // recheckFile should not panic when given an index equal to the number of blocks
  2417. w, fcfg, wCancel := newDefaultCfgWrapper()
  2418. defer wCancel()
  2419. ffs := fcfg.Filesystem(nil)
  2420. fd, err := ffs.Create("foo")
  2421. must(t, err)
  2422. _, err = fd.Write([]byte("foobar"))
  2423. must(t, err)
  2424. fd.Close()
  2425. m := setupModel(t, w)
  2426. defer cleanupModel(m)
  2427. if err := m.ScanFolder("default"); err != nil {
  2428. t.Error(err)
  2429. }
  2430. file, ok := m.testCurrentFolderFile("default", "foo")
  2431. if !ok {
  2432. t.Fatal("test file should exist")
  2433. }
  2434. blockSize := int32(file.BlockSize())
  2435. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size-int64(blockSize), []byte{1, 2, 3, 4}, 0)
  2436. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size, []byte{1, 2, 3, 4}, 0) // panic
  2437. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size+int64(blockSize), []byte{1, 2, 3, 4}, 0)
  2438. }
  2439. func TestParentOfUnignored(t *testing.T) {
  2440. w, fcfg, wCancel := newDefaultCfgWrapper()
  2441. defer wCancel()
  2442. ffs := fcfg.Filesystem(nil)
  2443. must(t, ffs.Mkdir("bar", 0o755))
  2444. must(t, ffs.Mkdir("baz", 0o755))
  2445. must(t, ffs.Mkdir("baz/quux", 0o755))
  2446. m := setupModel(t, w)
  2447. defer cleanupModel(m)
  2448. m.SetIgnores("default", []string{"!quux", "*"})
  2449. m.ScanFolder("default")
  2450. if bar, ok := m.testCurrentFolderFile("default", "bar"); !ok {
  2451. t.Error(`Directory "bar" missing in db`)
  2452. } else if !bar.IsIgnored() {
  2453. t.Error(`Directory "bar" is not ignored`)
  2454. }
  2455. if baz, ok := m.testCurrentFolderFile("default", "baz"); !ok {
  2456. t.Error(`Directory "baz" missing in db`)
  2457. } else if baz.IsIgnored() {
  2458. t.Error(`Directory "baz" is ignored`)
  2459. }
  2460. }
  2461. // TestFolderRestartZombies reproduces issue 5233, where multiple concurrent folder
  2462. // restarts would leave more than one folder runner alive.
  2463. func TestFolderRestartZombies(t *testing.T) {
  2464. wrapper, cancel := newConfigWrapper(defaultCfg.Copy())
  2465. defer cancel()
  2466. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2467. cfg.Options.RawMaxFolderConcurrency = -1
  2468. _, i, _ := cfg.Folder("default")
  2469. cfg.Folders[i].FilesystemType = config.FilesystemTypeFake
  2470. })
  2471. must(t, err)
  2472. waiter.Wait()
  2473. folderCfg, _ := wrapper.Folder("default")
  2474. m := setupModel(t, wrapper)
  2475. defer cleanupModel(m)
  2476. // Make sure the folder is up and running, because we want to count it.
  2477. m.ScanFolder("default")
  2478. // Check how many running folders we have running before the test.
  2479. if r := m.foldersRunning.Load(); r != 1 {
  2480. t.Error("Expected one running folder, not", r)
  2481. }
  2482. // Run a few parallel configuration changers for one second. Each waits
  2483. // for the commit to complete, but there are many of them.
  2484. var wg sync.WaitGroup
  2485. for i := 0; i < 25; i++ {
  2486. wg.Add(1)
  2487. go func() {
  2488. defer wg.Done()
  2489. t0 := time.Now()
  2490. for time.Since(t0) < time.Second {
  2491. fcfg := folderCfg.Copy()
  2492. fcfg.MaxConflicts = mrand.Int() // safe change that should cause a folder restart
  2493. setFolder(t, wrapper, fcfg)
  2494. }
  2495. }()
  2496. }
  2497. // Wait for the above to complete and check how many folders we have
  2498. // running now. It should not have increased.
  2499. wg.Wait()
  2500. // Make sure the folder is up and running, because we want to count it.
  2501. m.ScanFolder("default")
  2502. if r := m.foldersRunning.Load(); r != 1 {
  2503. t.Error("Expected one running folder, not", r)
  2504. }
  2505. }
  2506. func TestRequestLimit(t *testing.T) {
  2507. wrapper, fcfg, cancel := newDefaultCfgWrapper()
  2508. ffs := fcfg.Filesystem(nil)
  2509. file := "tmpfile"
  2510. fd, err := ffs.Create(file)
  2511. must(t, err)
  2512. fd.Close()
  2513. defer cancel()
  2514. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2515. _, i, _ := cfg.Device(device1)
  2516. cfg.Devices[i].MaxRequestKiB = 1
  2517. })
  2518. must(t, err)
  2519. waiter.Wait()
  2520. m, conn := setupModelWithConnectionFromWrapper(t, wrapper)
  2521. defer cleanupModel(m)
  2522. m.ScanFolder("default")
  2523. befReq := time.Now()
  2524. first, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
  2525. if err != nil {
  2526. t.Fatalf("First request failed: %v", err)
  2527. }
  2528. reqDur := time.Since(befReq)
  2529. returned := make(chan struct{})
  2530. go func() {
  2531. second, err := m.Request(conn, &protocol.Request{Folder: "default", Name: file, Size: 2000})
  2532. if err != nil {
  2533. t.Errorf("Second request failed: %v", err)
  2534. }
  2535. close(returned)
  2536. second.Close()
  2537. }()
  2538. time.Sleep(10 * reqDur)
  2539. select {
  2540. case <-returned:
  2541. t.Fatalf("Second request returned before first was done")
  2542. default:
  2543. }
  2544. first.Close()
  2545. select {
  2546. case <-returned:
  2547. case <-time.After(time.Second):
  2548. t.Fatalf("Second request did not return after first was done")
  2549. }
  2550. }
  2551. // TestConnCloseOnRestart checks that there is no deadlock when calling Close
  2552. // on a protocol connection that has a blocking reader (blocking writer can't
  2553. // be done as the test requires clusterconfigs to go through).
  2554. func TestConnCloseOnRestart(t *testing.T) {
  2555. oldCloseTimeout := protocol.CloseTimeout
  2556. protocol.CloseTimeout = 100 * time.Millisecond
  2557. defer func() {
  2558. protocol.CloseTimeout = oldCloseTimeout
  2559. }()
  2560. w, fcfg, wCancel := newDefaultCfgWrapper()
  2561. defer wCancel()
  2562. m := setupModel(t, w)
  2563. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2564. br := &testutil.BlockingRW{}
  2565. nw := &testutil.NoopRW{}
  2566. ci := &protocolmocks.ConnectionInfo{}
  2567. ci.ConnectionIDReturns(srand.String(16))
  2568. m.AddConnection(protocol.NewConnection(device1, br, nw, testutil.NoopCloser{}, m, ci, protocol.CompressionNever, nil, m.keyGen), protocol.Hello{})
  2569. m.mut.RLock()
  2570. if len(m.closed) != 1 {
  2571. t.Fatalf("Expected just one conn (len(m.closed) == %v)", len(m.closed))
  2572. }
  2573. var closed chan struct{}
  2574. for _, c := range m.closed {
  2575. closed = c
  2576. }
  2577. m.mut.RUnlock()
  2578. waiter, err := w.RemoveDevice(device1)
  2579. if err != nil {
  2580. t.Fatal(err)
  2581. }
  2582. done := make(chan struct{})
  2583. go func() {
  2584. waiter.Wait()
  2585. close(done)
  2586. }()
  2587. select {
  2588. case <-done:
  2589. case <-time.After(5 * time.Second):
  2590. t.Fatal("Timed out before config took effect")
  2591. }
  2592. select {
  2593. case <-closed:
  2594. case <-time.After(5 * time.Second):
  2595. t.Fatal("Timed out before connection was closed")
  2596. }
  2597. }
  2598. func TestModTimeWindow(t *testing.T) {
  2599. w, fcfg, wCancel := newDefaultCfgWrapper()
  2600. defer wCancel()
  2601. tfs := modtimeTruncatingFS{
  2602. trunc: 0,
  2603. Filesystem: fcfg.Filesystem(nil),
  2604. }
  2605. // fcfg.RawModTimeWindowS = 2
  2606. setFolder(t, w, fcfg)
  2607. m := setupModel(t, w)
  2608. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2609. name := "foo"
  2610. fd, err := tfs.Create(name)
  2611. must(t, err)
  2612. stat, err := fd.Stat()
  2613. must(t, err)
  2614. modTime := stat.ModTime()
  2615. fd.Close()
  2616. m.ScanFolders()
  2617. // Get current version
  2618. fi, ok := m.testCurrentFolderFile("default", name)
  2619. if !ok {
  2620. t.Fatal("File missing")
  2621. }
  2622. v := fi.Version
  2623. // Change the filesystem to only return modtimes to the closest two
  2624. // seconds, like FAT.
  2625. tfs.trunc = 2 * time.Second
  2626. // Scan again
  2627. m.ScanFolders()
  2628. // No change due to within window
  2629. fi, _ = m.testCurrentFolderFile("default", name)
  2630. if !fi.Version.Equal(v) {
  2631. t.Fatalf("Got version %v, expected %v", fi.Version, v)
  2632. }
  2633. // Update to be outside window
  2634. err = tfs.Chtimes(name, time.Now(), modTime.Add(2*time.Second))
  2635. must(t, err)
  2636. m.ScanFolders()
  2637. // Version should have updated
  2638. fi, _ = m.testCurrentFolderFile("default", name)
  2639. if fi.Version.Compare(v) != protocol.Greater {
  2640. t.Fatalf("Got result %v, expected %v", fi.Version.Compare(v), protocol.Greater)
  2641. }
  2642. }
  2643. func TestDevicePause(t *testing.T) {
  2644. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2645. defer wcfgCancel()
  2646. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2647. sub := m.evLogger.Subscribe(events.DevicePaused)
  2648. defer sub.Unsubscribe()
  2649. m.mut.RLock()
  2650. var closed chan struct{}
  2651. for _, c := range m.closed {
  2652. closed = c
  2653. }
  2654. m.mut.RUnlock()
  2655. pauseDevice(t, m.cfg, device1, true)
  2656. timeout := time.NewTimer(5 * time.Second)
  2657. select {
  2658. case <-sub.C():
  2659. select {
  2660. case <-closed:
  2661. case <-timeout.C:
  2662. t.Fatal("Timed out before connection was closed")
  2663. }
  2664. case <-timeout.C:
  2665. t.Fatal("Timed out before device was paused")
  2666. }
  2667. }
  2668. func TestDeviceWasSeen(t *testing.T) {
  2669. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2670. defer wcfgCancel()
  2671. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2672. m.deviceWasSeen(device1)
  2673. stats, err := m.DeviceStatistics()
  2674. if err != nil {
  2675. t.Error("Unexpected error:", err)
  2676. }
  2677. entry := stats[device1]
  2678. if time.Since(entry.LastSeen) > time.Second {
  2679. t.Error("device should have been seen now")
  2680. }
  2681. }
  2682. func TestNewLimitedRequestResponse(t *testing.T) {
  2683. l0 := semaphore.New(0)
  2684. l1 := semaphore.New(1024)
  2685. l2 := (*semaphore.Semaphore)(nil)
  2686. // Should take 500 bytes from any non-unlimited non-nil limiters.
  2687. res := newLimitedRequestResponse(500, l0, l1, l2)
  2688. if l1.Available() != 1024-500 {
  2689. t.Error("should have taken bytes from limited limiter")
  2690. }
  2691. // Closing the result should return the bytes.
  2692. res.Close()
  2693. // Try to take 1024 bytes to make sure the bytes were returned.
  2694. done := make(chan struct{})
  2695. go func() {
  2696. l1.Take(1024)
  2697. close(done)
  2698. }()
  2699. select {
  2700. case <-done:
  2701. case <-time.After(time.Second):
  2702. t.Error("Bytes weren't returned in a timely fashion")
  2703. }
  2704. }
  2705. func TestSummaryPausedNoError(t *testing.T) {
  2706. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2707. defer wcfgCancel()
  2708. pauseFolder(t, wcfg, fcfg.ID, true)
  2709. m := setupModel(t, wcfg)
  2710. defer cleanupModel(m)
  2711. fss := NewFolderSummaryService(wcfg, m, myID, events.NoopLogger)
  2712. if _, err := fss.Summary(fcfg.ID); err != nil {
  2713. t.Error("Expected no error getting a summary for a paused folder:", err)
  2714. }
  2715. }
  2716. func TestFolderAPIErrors(t *testing.T) {
  2717. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2718. defer wcfgCancel()
  2719. pauseFolder(t, wcfg, fcfg.ID, true)
  2720. m := setupModel(t, wcfg)
  2721. defer cleanupModel(m)
  2722. methods := []func(folder string) error{
  2723. m.ScanFolder,
  2724. func(folder string) error {
  2725. return m.ScanFolderSubdirs(folder, nil)
  2726. },
  2727. func(folder string) error {
  2728. _, err := m.GetFolderVersions(folder)
  2729. return err
  2730. },
  2731. func(folder string) error {
  2732. _, err := m.RestoreFolderVersions(folder, nil)
  2733. return err
  2734. },
  2735. }
  2736. for i, method := range methods {
  2737. if err := method(fcfg.ID); err != ErrFolderPaused {
  2738. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderPaused, err, i)
  2739. }
  2740. if err := method("notexisting"); err != ErrFolderMissing {
  2741. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderMissing, err, i)
  2742. }
  2743. }
  2744. }
  2745. func TestRenameSequenceOrder(t *testing.T) {
  2746. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2747. defer wcfgCancel()
  2748. m := setupModel(t, wcfg)
  2749. defer cleanupModel(m)
  2750. numFiles := 20
  2751. ffs := fcfg.Filesystem(nil)
  2752. for i := 0; i < numFiles; i++ {
  2753. v := fmt.Sprintf("%d", i)
  2754. writeFile(t, ffs, v, []byte(v))
  2755. }
  2756. m.ScanFolders()
  2757. count := 0
  2758. snap := dbSnapshot(t, m, "default")
  2759. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
  2760. count++
  2761. return true
  2762. })
  2763. snap.Release()
  2764. if count != numFiles {
  2765. t.Errorf("Unexpected count: %d != %d", count, numFiles)
  2766. }
  2767. // Modify all the files, other than the ones we expect to rename
  2768. for i := 0; i < numFiles; i++ {
  2769. if i == 3 || i == 17 || i == 16 || i == 4 {
  2770. continue
  2771. }
  2772. v := fmt.Sprintf("%d", i)
  2773. writeFile(t, ffs, v, []byte(v+"-new"))
  2774. }
  2775. // Rename
  2776. must(t, ffs.Rename("3", "17"))
  2777. must(t, ffs.Rename("16", "4"))
  2778. // Scan
  2779. m.ScanFolders()
  2780. // Verify sequence of a appearing is followed by c disappearing.
  2781. snap = dbSnapshot(t, m, "default")
  2782. defer snap.Release()
  2783. var firstExpectedSequence int64
  2784. var secondExpectedSequence int64
  2785. failed := false
  2786. snap.WithHaveSequence(0, func(i protocol.FileInfo) bool {
  2787. t.Log(i)
  2788. if i.FileName() == "17" {
  2789. firstExpectedSequence = i.SequenceNo() + 1
  2790. }
  2791. if i.FileName() == "4" {
  2792. secondExpectedSequence = i.SequenceNo() + 1
  2793. }
  2794. if i.FileName() == "3" {
  2795. failed = i.SequenceNo() != firstExpectedSequence || failed
  2796. }
  2797. if i.FileName() == "16" {
  2798. failed = i.SequenceNo() != secondExpectedSequence || failed
  2799. }
  2800. return true
  2801. })
  2802. if failed {
  2803. t.Fail()
  2804. }
  2805. }
  2806. func TestRenameSameFile(t *testing.T) {
  2807. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2808. defer wcfgCancel()
  2809. m := setupModel(t, wcfg)
  2810. defer cleanupModel(m)
  2811. ffs := fcfg.Filesystem(nil)
  2812. writeFile(t, ffs, "file", []byte("file"))
  2813. m.ScanFolders()
  2814. count := 0
  2815. snap := dbSnapshot(t, m, "default")
  2816. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
  2817. count++
  2818. return true
  2819. })
  2820. snap.Release()
  2821. if count != 1 {
  2822. t.Errorf("Unexpected count: %d != %d", count, 1)
  2823. }
  2824. must(t, ffs.Rename("file", "file1"))
  2825. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file0"))
  2826. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file2"))
  2827. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file3"))
  2828. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file4"))
  2829. m.ScanFolders()
  2830. snap = dbSnapshot(t, m, "default")
  2831. defer snap.Release()
  2832. prevSeq := int64(0)
  2833. seen := false
  2834. snap.WithHaveSequence(0, func(i protocol.FileInfo) bool {
  2835. if i.SequenceNo() <= prevSeq {
  2836. t.Fatalf("non-increasing sequences: %d <= %d", i.SequenceNo(), prevSeq)
  2837. }
  2838. if i.FileName() == "file" {
  2839. if seen {
  2840. t.Fatal("already seen file")
  2841. }
  2842. seen = true
  2843. }
  2844. prevSeq = i.SequenceNo()
  2845. return true
  2846. })
  2847. }
  2848. func TestRenameEmptyFile(t *testing.T) {
  2849. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2850. defer wcfgCancel()
  2851. m := setupModel(t, wcfg)
  2852. defer cleanupModel(m)
  2853. ffs := fcfg.Filesystem(nil)
  2854. writeFile(t, ffs, "file", []byte("data"))
  2855. writeFile(t, ffs, "empty", nil)
  2856. m.ScanFolders()
  2857. snap := dbSnapshot(t, m, "default")
  2858. defer snap.Release()
  2859. empty, eok := snap.Get(protocol.LocalDeviceID, "empty")
  2860. if !eok {
  2861. t.Fatal("failed to find empty file")
  2862. }
  2863. file, fok := snap.Get(protocol.LocalDeviceID, "file")
  2864. if !fok {
  2865. t.Fatal("failed to find non-empty file")
  2866. }
  2867. count := 0
  2868. snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileInfo) bool {
  2869. count++
  2870. return true
  2871. })
  2872. if count != 0 {
  2873. t.Fatalf("Found %d entries for empty file, expected 0", count)
  2874. }
  2875. count = 0
  2876. snap.WithBlocksHash(file.BlocksHash, func(_ protocol.FileInfo) bool {
  2877. count++
  2878. return true
  2879. })
  2880. if count != 1 {
  2881. t.Fatalf("Found %d entries for non-empty file, expected 1", count)
  2882. }
  2883. must(t, ffs.Rename("file", "new-file"))
  2884. must(t, ffs.Rename("empty", "new-empty"))
  2885. // Scan
  2886. m.ScanFolders()
  2887. snap = dbSnapshot(t, m, "default")
  2888. defer snap.Release()
  2889. count = 0
  2890. snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileInfo) bool {
  2891. count++
  2892. return true
  2893. })
  2894. if count != 0 {
  2895. t.Fatalf("Found %d entries for empty file, expected 0", count)
  2896. }
  2897. count = 0
  2898. snap.WithBlocksHash(file.BlocksHash, func(i protocol.FileInfo) bool {
  2899. count++
  2900. if i.FileName() != "new-file" {
  2901. t.Fatalf("unexpected file name %s, expected new-file", i.FileName())
  2902. }
  2903. return true
  2904. })
  2905. if count != 1 {
  2906. t.Fatalf("Found %d entries for non-empty file, expected 1", count)
  2907. }
  2908. }
  2909. func TestBlockListMap(t *testing.T) {
  2910. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2911. defer wcfgCancel()
  2912. m := setupModel(t, wcfg)
  2913. defer cleanupModel(m)
  2914. ffs := fcfg.Filesystem(nil)
  2915. writeFile(t, ffs, "one", []byte("content"))
  2916. writeFile(t, ffs, "two", []byte("content"))
  2917. writeFile(t, ffs, "three", []byte("content"))
  2918. writeFile(t, ffs, "four", []byte("content"))
  2919. writeFile(t, ffs, "five", []byte("content"))
  2920. m.ScanFolders()
  2921. snap := dbSnapshot(t, m, "default")
  2922. defer snap.Release()
  2923. fi, ok := snap.Get(protocol.LocalDeviceID, "one")
  2924. if !ok {
  2925. t.Error("failed to find existing file")
  2926. }
  2927. var paths []string
  2928. snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileInfo) bool {
  2929. paths = append(paths, fi.FileName())
  2930. return true
  2931. })
  2932. snap.Release()
  2933. expected := []string{"one", "two", "three", "four", "five"}
  2934. if !equalStringsInAnyOrder(paths, expected) {
  2935. t.Errorf("expected %q got %q", expected, paths)
  2936. }
  2937. // Fudge the files around
  2938. // Remove
  2939. must(t, ffs.Remove("one"))
  2940. // Modify
  2941. must(t, ffs.Remove("two"))
  2942. writeFile(t, ffs, "two", []byte("mew-content"))
  2943. // Rename
  2944. must(t, ffs.Rename("three", "new-three"))
  2945. // Change type
  2946. must(t, ffs.Remove("four"))
  2947. must(t, ffs.Mkdir("four", 0o644))
  2948. m.ScanFolders()
  2949. // Check we're left with 2 of the 5
  2950. snap = dbSnapshot(t, m, "default")
  2951. defer snap.Release()
  2952. paths = paths[:0]
  2953. snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileInfo) bool {
  2954. paths = append(paths, fi.FileName())
  2955. return true
  2956. })
  2957. snap.Release()
  2958. expected = []string{"new-three", "five"}
  2959. if !equalStringsInAnyOrder(paths, expected) {
  2960. t.Errorf("expected %q got %q", expected, paths)
  2961. }
  2962. }
  2963. func TestScanRenameCaseOnly(t *testing.T) {
  2964. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2965. defer wcfgCancel()
  2966. m := setupModel(t, wcfg)
  2967. defer cleanupModel(m)
  2968. ffs := fcfg.Filesystem(nil)
  2969. name := "foo"
  2970. writeFile(t, ffs, name, []byte("contents"))
  2971. m.ScanFolders()
  2972. snap := dbSnapshot(t, m, fcfg.ID)
  2973. defer snap.Release()
  2974. found := false
  2975. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
  2976. if found {
  2977. t.Fatal("got more than one file")
  2978. }
  2979. if i.FileName() != name {
  2980. t.Fatalf("got file %v, expected %v", i.FileName(), name)
  2981. }
  2982. found = true
  2983. return true
  2984. })
  2985. snap.Release()
  2986. upper := strings.ToUpper(name)
  2987. must(t, ffs.Rename(name, upper))
  2988. m.ScanFolders()
  2989. snap = dbSnapshot(t, m, fcfg.ID)
  2990. defer snap.Release()
  2991. found = false
  2992. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileInfo) bool {
  2993. if i.FileName() == name {
  2994. if i.IsDeleted() {
  2995. return true
  2996. }
  2997. t.Fatal("renamed file not deleted")
  2998. }
  2999. if i.FileName() != upper {
  3000. t.Fatalf("got file %v, expected %v", i.FileName(), upper)
  3001. }
  3002. if found {
  3003. t.Fatal("got more than the expected files")
  3004. }
  3005. found = true
  3006. return true
  3007. })
  3008. }
  3009. func TestClusterConfigOnFolderAdd(t *testing.T) {
  3010. testConfigChangeTriggersClusterConfigs(t, false, true, nil, func(wrapper config.Wrapper) {
  3011. fcfg := newFolderConfig()
  3012. fcfg.ID = "second"
  3013. fcfg.Label = "second"
  3014. fcfg.Devices = []config.FolderDeviceConfiguration{{
  3015. DeviceID: device2,
  3016. IntroducedBy: protocol.EmptyDeviceID,
  3017. }}
  3018. setFolder(t, wrapper, fcfg)
  3019. })
  3020. }
  3021. func TestClusterConfigOnFolderShare(t *testing.T) {
  3022. testConfigChangeTriggersClusterConfigs(t, true, true, nil, func(cfg config.Wrapper) {
  3023. fcfg := cfg.FolderList()[0]
  3024. fcfg.Devices = []config.FolderDeviceConfiguration{{
  3025. DeviceID: device2,
  3026. IntroducedBy: protocol.EmptyDeviceID,
  3027. }}
  3028. setFolder(t, cfg, fcfg)
  3029. })
  3030. }
  3031. func TestClusterConfigOnFolderUnshare(t *testing.T) {
  3032. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3033. fcfg := cfg.FolderList()[0]
  3034. fcfg.Devices = nil
  3035. setFolder(t, cfg, fcfg)
  3036. })
  3037. }
  3038. func TestClusterConfigOnFolderRemove(t *testing.T) {
  3039. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3040. rcfg := cfg.RawCopy()
  3041. rcfg.Folders = nil
  3042. replace(t, cfg, rcfg)
  3043. })
  3044. }
  3045. func TestClusterConfigOnFolderPause(t *testing.T) {
  3046. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3047. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  3048. })
  3049. }
  3050. func TestClusterConfigOnFolderUnpause(t *testing.T) {
  3051. testConfigChangeTriggersClusterConfigs(t, true, false, func(cfg config.Wrapper) {
  3052. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  3053. }, func(cfg config.Wrapper) {
  3054. pauseFolder(t, cfg, cfg.FolderList()[0].ID, false)
  3055. })
  3056. }
  3057. func TestAddFolderCompletion(t *testing.T) {
  3058. // Empty folders are always 100% complete.
  3059. comp := newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderValid)
  3060. comp.add(newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderPaused))
  3061. if comp.CompletionPct != 100 {
  3062. t.Error(comp.CompletionPct)
  3063. }
  3064. // Completion is of the whole
  3065. comp = newFolderCompletion(db.Counts{Bytes: 100}, db.Counts{}, 0, remoteFolderValid) // 100% complete
  3066. comp.add(newFolderCompletion(db.Counts{Bytes: 400}, db.Counts{Bytes: 50}, 0, remoteFolderValid)) // 82.5% complete
  3067. if comp.CompletionPct != 90 { // 100 * (1 - 50/500)
  3068. t.Error(comp.CompletionPct)
  3069. }
  3070. }
  3071. func TestScanDeletedROChangedOnSR(t *testing.T) {
  3072. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  3073. ffs := fcfg.Filesystem(nil)
  3074. defer wCancel()
  3075. defer cleanupModelAndRemoveDir(m, ffs.URI())
  3076. fcfg.Type = config.FolderTypeReceiveOnly
  3077. setFolder(t, m.cfg, fcfg)
  3078. name := "foo"
  3079. writeFile(t, ffs, name, []byte(name))
  3080. m.ScanFolders()
  3081. file, ok := m.testCurrentFolderFile(fcfg.ID, name)
  3082. if !ok {
  3083. t.Fatal("file missing in db")
  3084. }
  3085. // A remote must have the file, otherwise the deletion below is
  3086. // automatically resolved as not a ro-changed item.
  3087. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: []protocol.FileInfo{file}}))
  3088. must(t, ffs.Remove(name))
  3089. m.ScanFolders()
  3090. if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 1 {
  3091. t.Fatal("expected one receive only changed deleted item")
  3092. }
  3093. fcfg.Type = config.FolderTypeSendReceive
  3094. setFolder(t, m.cfg, fcfg)
  3095. m.ScanFolders()
  3096. if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 0 {
  3097. t.Fatal("expected no receive only changed deleted item")
  3098. }
  3099. if localSize(t, m, fcfg.ID).Deleted != 1 {
  3100. t.Fatal("expected one local deleted item")
  3101. }
  3102. }
  3103. func testConfigChangeTriggersClusterConfigs(t *testing.T, expectFirst, expectSecond bool, pre func(config.Wrapper), fn func(config.Wrapper)) {
  3104. t.Helper()
  3105. wcfg, _, wcfgCancel := newDefaultCfgWrapper()
  3106. defer wcfgCancel()
  3107. m := setupModel(t, wcfg)
  3108. defer cleanupModel(m)
  3109. setDevice(t, wcfg, newDeviceConfiguration(wcfg.DefaultDevice(), device2, "device2"))
  3110. if pre != nil {
  3111. pre(wcfg)
  3112. }
  3113. cc1 := make(chan struct{}, 1)
  3114. cc2 := make(chan struct{}, 1)
  3115. fc1 := newFakeConnection(device1, m)
  3116. fc1.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
  3117. cc1 <- struct{}{}
  3118. })
  3119. fc2 := newFakeConnection(device2, m)
  3120. fc2.ClusterConfigCalls(func(_ *protocol.ClusterConfig) {
  3121. cc2 <- struct{}{}
  3122. })
  3123. m.AddConnection(fc1, protocol.Hello{})
  3124. m.AddConnection(fc2, protocol.Hello{})
  3125. m.promoteConnections()
  3126. // Initial CCs
  3127. select {
  3128. case <-cc1:
  3129. default:
  3130. t.Fatal("missing initial CC from device1")
  3131. }
  3132. select {
  3133. case <-cc2:
  3134. default:
  3135. t.Fatal("missing initial CC from device2")
  3136. }
  3137. t.Log("Applying config change")
  3138. fn(wcfg)
  3139. timeout := time.NewTimer(time.Second)
  3140. if expectFirst {
  3141. select {
  3142. case <-cc1:
  3143. case <-timeout.C:
  3144. t.Errorf("timed out before receiving cluste rconfig for first device")
  3145. }
  3146. }
  3147. if expectSecond {
  3148. select {
  3149. case <-cc2:
  3150. case <-timeout.C:
  3151. t.Errorf("timed out before receiving cluste rconfig for second device")
  3152. }
  3153. }
  3154. }
  3155. // The end result of the tested scenario is that the global version entry has an
  3156. // empty version vector and is not deleted, while everything is actually deleted.
  3157. // That then causes these files to be considered as needed, while they are not.
  3158. // https://github.com/syncthing/syncthing/issues/6961
  3159. func TestIssue6961(t *testing.T) {
  3160. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  3161. defer wcfgCancel()
  3162. tfs := fcfg.Filesystem(nil)
  3163. waiter, err := wcfg.Modify(func(cfg *config.Configuration) {
  3164. cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device2, "device2"))
  3165. fcfg.Type = config.FolderTypeReceiveOnly
  3166. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  3167. cfg.SetFolder(fcfg)
  3168. })
  3169. must(t, err)
  3170. waiter.Wait()
  3171. // Always recalc/repair when opening a fileset.
  3172. m := newModel(t, wcfg, myID, nil)
  3173. m.db.Close()
  3174. m.db, err = db.NewLowlevel(backend.OpenMemory(), m.evLogger, db.WithRecheckInterval(time.Millisecond))
  3175. if err != nil {
  3176. t.Fatal(err)
  3177. }
  3178. m.ServeBackground()
  3179. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3180. conn1 := addFakeConn(m, device1, fcfg.ID)
  3181. conn2 := addFakeConn(m, device2, fcfg.ID)
  3182. m.ScanFolders()
  3183. name := "foo"
  3184. version := protocol.Vector{}.Update(device1.Short())
  3185. // Remote, valid and existing file
  3186. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, Version: version, Sequence: 1}}}))
  3187. // Remote, invalid (receive-only) and existing file
  3188. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: name, RawInvalid: true, Sequence: 1}}}))
  3189. // Create a local file
  3190. if fd, err := tfs.OpenFile(name, fs.OptCreate, 0o666); err != nil {
  3191. t.Fatal(err)
  3192. } else {
  3193. fd.Close()
  3194. }
  3195. if info, err := tfs.Lstat(name); err != nil {
  3196. t.Fatal(err)
  3197. } else {
  3198. l.Infoln("intest", info.Mode)
  3199. }
  3200. m.ScanFolders()
  3201. // Get rid of valid global
  3202. waiter, err = wcfg.RemoveDevice(device1)
  3203. if err != nil {
  3204. t.Fatal(err)
  3205. }
  3206. waiter.Wait()
  3207. // Delete the local file
  3208. must(t, tfs.Remove(name))
  3209. m.ScanFolders()
  3210. // Drop the remote index, add some other file.
  3211. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: []protocol.FileInfo{{Name: "bar", RawInvalid: true, Sequence: 1}}}))
  3212. // Pause and unpause folder to create new db.FileSet and thus recalculate everything
  3213. pauseFolder(t, wcfg, fcfg.ID, true)
  3214. pauseFolder(t, wcfg, fcfg.ID, false)
  3215. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedDeletes != 0 {
  3216. t.Error("Expected 0 needed deletes, got", comp.NeedDeletes)
  3217. } else {
  3218. t.Log(comp)
  3219. }
  3220. }
  3221. func TestCompletionEmptyGlobal(t *testing.T) {
  3222. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  3223. defer wcfgCancel()
  3224. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  3225. files := []protocol.FileInfo{{Name: "foo", Version: protocol.Vector{}.Update(myID.Short()), Sequence: 1}}
  3226. m.mut.Lock()
  3227. m.folderFiles[fcfg.ID].Update(protocol.LocalDeviceID, files)
  3228. m.mut.Unlock()
  3229. files[0].Deleted = true
  3230. files[0].Version = files[0].Version.Update(device1.Short())
  3231. must(t, m.IndexUpdate(conn, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3232. comp := m.testCompletion(protocol.LocalDeviceID, fcfg.ID)
  3233. if comp.CompletionPct != 95 {
  3234. t.Error("Expected completion of 95%, got", comp.CompletionPct)
  3235. }
  3236. }
  3237. func TestNeedMetaAfterIndexReset(t *testing.T) {
  3238. w, fcfg, wCancel := newDefaultCfgWrapper()
  3239. defer wCancel()
  3240. addDevice2(t, w, fcfg)
  3241. m := setupModel(t, w)
  3242. defer cleanupModelAndRemoveDir(m, fcfg.Path)
  3243. conn1 := addFakeConn(m, device1, fcfg.ID)
  3244. conn2 := addFakeConn(m, device2, fcfg.ID)
  3245. var seq int64 = 1
  3246. files := []protocol.FileInfo{{Name: "foo", Size: 10, Version: protocol.Vector{}.Update(device1.Short()), Sequence: seq}}
  3247. // Start with two remotes having one file, then both deleting it, then
  3248. // only one adding it again.
  3249. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3250. must(t, m.Index(conn2, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3251. seq++
  3252. files[0].SetDeleted(device2.Short())
  3253. files[0].Sequence = seq
  3254. must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3255. must(t, m.IndexUpdate(conn2, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3256. seq++
  3257. files[0].Deleted = false
  3258. files[0].Size = 20
  3259. files[0].Version = files[0].Version.Update(device1.Short())
  3260. files[0].Sequence = seq
  3261. must(t, m.IndexUpdate(conn1, &protocol.IndexUpdate{Folder: fcfg.ID, Files: files}))
  3262. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
  3263. t.Error("Expected one needed item for device2, got", comp.NeedItems)
  3264. }
  3265. // Pretend we had an index reset on device 1
  3266. must(t, m.Index(conn1, &protocol.Index{Folder: fcfg.ID, Files: files}))
  3267. if comp := m.testCompletion(device2, fcfg.ID); comp.NeedItems != 1 {
  3268. t.Error("Expected one needed item for device2, got", comp.NeedItems)
  3269. }
  3270. }
  3271. func TestCcCheckEncryption(t *testing.T) {
  3272. if testing.Short() {
  3273. t.Skip("skipping on short testing - generating encryption tokens is slow")
  3274. }
  3275. w, fcfg, wCancel := newDefaultCfgWrapper()
  3276. defer wCancel()
  3277. m := setupModel(t, w)
  3278. m.cancel()
  3279. defer cleanupModel(m)
  3280. pw := "foo"
  3281. token := protocol.PasswordToken(m.keyGen, fcfg.ID, pw)
  3282. m.folderEncryptionPasswordTokens[fcfg.ID] = token
  3283. testCases := []struct {
  3284. tokenRemote, tokenLocal []byte
  3285. isEncryptedRemote, isEncryptedLocal bool
  3286. expectedErr error
  3287. }{
  3288. {
  3289. tokenRemote: token,
  3290. tokenLocal: token,
  3291. expectedErr: errEncryptionInvConfigRemote,
  3292. },
  3293. {
  3294. isEncryptedRemote: true,
  3295. isEncryptedLocal: true,
  3296. expectedErr: errEncryptionInvConfigLocal,
  3297. },
  3298. {
  3299. tokenRemote: token,
  3300. tokenLocal: nil,
  3301. isEncryptedRemote: false,
  3302. isEncryptedLocal: false,
  3303. expectedErr: errEncryptionNotEncryptedLocal,
  3304. },
  3305. {
  3306. tokenRemote: token,
  3307. tokenLocal: nil,
  3308. isEncryptedRemote: true,
  3309. isEncryptedLocal: false,
  3310. expectedErr: nil,
  3311. },
  3312. {
  3313. tokenRemote: token,
  3314. tokenLocal: nil,
  3315. isEncryptedRemote: false,
  3316. isEncryptedLocal: true,
  3317. expectedErr: nil,
  3318. },
  3319. {
  3320. tokenRemote: nil,
  3321. tokenLocal: token,
  3322. isEncryptedRemote: true,
  3323. isEncryptedLocal: false,
  3324. expectedErr: nil,
  3325. },
  3326. {
  3327. tokenRemote: nil,
  3328. tokenLocal: token,
  3329. isEncryptedRemote: false,
  3330. isEncryptedLocal: true,
  3331. expectedErr: nil,
  3332. },
  3333. {
  3334. tokenRemote: nil,
  3335. tokenLocal: token,
  3336. isEncryptedRemote: false,
  3337. isEncryptedLocal: false,
  3338. expectedErr: errEncryptionNotEncryptedLocal,
  3339. },
  3340. {
  3341. tokenRemote: nil,
  3342. tokenLocal: nil,
  3343. isEncryptedRemote: true,
  3344. isEncryptedLocal: false,
  3345. expectedErr: errEncryptionPlainForRemoteEncrypted,
  3346. },
  3347. {
  3348. tokenRemote: nil,
  3349. tokenLocal: nil,
  3350. isEncryptedRemote: false,
  3351. isEncryptedLocal: true,
  3352. expectedErr: errEncryptionPlainForReceiveEncrypted,
  3353. },
  3354. {
  3355. tokenRemote: nil,
  3356. tokenLocal: nil,
  3357. isEncryptedRemote: false,
  3358. isEncryptedLocal: false,
  3359. expectedErr: nil,
  3360. },
  3361. }
  3362. for i, tc := range testCases {
  3363. tfcfg := fcfg.Copy()
  3364. if tc.isEncryptedLocal {
  3365. tfcfg.Type = config.FolderTypeReceiveEncrypted
  3366. m.folderEncryptionPasswordTokens[fcfg.ID] = token
  3367. }
  3368. dcfg := config.FolderDeviceConfiguration{DeviceID: device1}
  3369. if tc.isEncryptedRemote {
  3370. dcfg.EncryptionPassword = pw
  3371. }
  3372. deviceInfos := &clusterConfigDeviceInfo{
  3373. remote: protocol.Device{ID: device1, EncryptionPasswordToken: tc.tokenRemote},
  3374. local: protocol.Device{ID: myID, EncryptionPasswordToken: tc.tokenLocal},
  3375. }
  3376. err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
  3377. if err != tc.expectedErr {
  3378. t.Errorf("Testcase %v: Expected error %v, got %v", i, tc.expectedErr, err)
  3379. }
  3380. if tc.expectedErr == nil {
  3381. err := m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, true)
  3382. if tc.isEncryptedRemote || tc.isEncryptedLocal {
  3383. if err != nil {
  3384. t.Errorf("Testcase %v: Expected no error, got %v", i, err)
  3385. }
  3386. } else {
  3387. if err != errEncryptionNotEncryptedUntrusted {
  3388. t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionNotEncryptedUntrusted, err)
  3389. }
  3390. }
  3391. }
  3392. if err != nil || (!tc.isEncryptedRemote && !tc.isEncryptedLocal) {
  3393. continue
  3394. }
  3395. if tc.isEncryptedLocal {
  3396. m.folderEncryptionPasswordTokens[fcfg.ID] = []byte("notAMatch")
  3397. } else {
  3398. dcfg.EncryptionPassword = "notAMatch"
  3399. }
  3400. err = m.ccCheckEncryption(tfcfg, dcfg, deviceInfos, false)
  3401. if err != errEncryptionPassword {
  3402. t.Errorf("Testcase %v: Expected error %v, got %v", i, errEncryptionPassword, err)
  3403. }
  3404. }
  3405. }
  3406. func TestCCFolderNotRunning(t *testing.T) {
  3407. // Create the folder, but don't start it.
  3408. w, fcfg, wCancel := newDefaultCfgWrapper()
  3409. defer wCancel()
  3410. tfs := fcfg.Filesystem(nil)
  3411. m := newModel(t, w, myID, nil)
  3412. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3413. // A connection can happen before all the folders are started.
  3414. cc, _ := m.generateClusterConfig(device1)
  3415. if l := len(cc.Folders); l != 1 {
  3416. t.Fatalf("Expected 1 folder in CC, got %v", l)
  3417. }
  3418. folder := cc.Folders[0]
  3419. if id := folder.ID; id != fcfg.ID {
  3420. t.Fatalf("Expected folder %v, got %v", fcfg.ID, id)
  3421. }
  3422. if l := len(folder.Devices); l != 2 {
  3423. t.Fatalf("Expected 2 devices in CC, got %v", l)
  3424. }
  3425. local := folder.Devices[1]
  3426. if local.ID != myID {
  3427. local = folder.Devices[0]
  3428. }
  3429. if !folder.Paused && local.IndexID == 0 {
  3430. t.Errorf("Folder isn't paused, but index-id is zero")
  3431. }
  3432. }
  3433. func TestPendingFolder(t *testing.T) {
  3434. w, _, wCancel := newDefaultCfgWrapper()
  3435. defer wCancel()
  3436. m := setupModel(t, w)
  3437. defer cleanupModel(m)
  3438. setDevice(t, w, config.DeviceConfiguration{DeviceID: device2})
  3439. pfolder := "default"
  3440. of := db.ObservedFolder{
  3441. Time: time.Now().Truncate(time.Second),
  3442. Label: pfolder,
  3443. }
  3444. if err := m.db.AddOrUpdatePendingFolder(pfolder, of, device2); err != nil {
  3445. t.Fatal(err)
  3446. }
  3447. deviceFolders, err := m.PendingFolders(protocol.EmptyDeviceID)
  3448. if err != nil {
  3449. t.Fatal(err)
  3450. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3451. t.Errorf("folder %v not pending", pfolder)
  3452. } else if _, ok := pf.OfferedBy[device2]; !ok {
  3453. t.Errorf("folder %v not pending for device %v", pfolder, device2)
  3454. } else if len(pf.OfferedBy) > 1 {
  3455. t.Errorf("folder %v pending for too many devices %v", pfolder, pf.OfferedBy)
  3456. }
  3457. device3, err := protocol.DeviceIDFromString("AIBAEAQ-CAIBAEC-AQCAIBA-EAQCAIA-BAEAQCA-IBAEAQC-CAIBAEA-QCAIBA7")
  3458. if err != nil {
  3459. t.Fatal(err)
  3460. }
  3461. setDevice(t, w, config.DeviceConfiguration{DeviceID: device3})
  3462. if err := m.db.AddOrUpdatePendingFolder(pfolder, of, device3); err != nil {
  3463. t.Fatal(err)
  3464. }
  3465. deviceFolders, err = m.PendingFolders(device2)
  3466. if err != nil {
  3467. t.Fatal(err)
  3468. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3469. t.Errorf("folder %v not pending when filtered", pfolder)
  3470. } else if _, ok := pf.OfferedBy[device2]; !ok {
  3471. t.Errorf("folder %v not pending for device %v when filtered", pfolder, device2)
  3472. } else if _, ok := pf.OfferedBy[device3]; ok {
  3473. t.Errorf("folder %v pending for device %v, but not filtered out", pfolder, device3)
  3474. }
  3475. waiter, err := w.RemoveDevice(device3)
  3476. if err != nil {
  3477. t.Fatal(err)
  3478. }
  3479. waiter.Wait()
  3480. deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
  3481. if err != nil {
  3482. t.Fatal(err)
  3483. } else if pf, ok := deviceFolders[pfolder]; !ok {
  3484. t.Errorf("folder %v not pending", pfolder)
  3485. } else if _, ok := pf.OfferedBy[device3]; ok {
  3486. t.Errorf("folder %v pending for removed device %v", pfolder, device3)
  3487. }
  3488. waiter, err = w.RemoveFolder(pfolder)
  3489. if err != nil {
  3490. t.Fatal(err)
  3491. }
  3492. waiter.Wait()
  3493. deviceFolders, err = m.PendingFolders(protocol.EmptyDeviceID)
  3494. if err != nil {
  3495. t.Fatal(err)
  3496. } else if _, ok := deviceFolders[pfolder]; ok {
  3497. t.Errorf("folder %v still pending after local removal", pfolder)
  3498. }
  3499. }
  3500. func TestDeletedNotLocallyChangedReceiveOnly(t *testing.T) {
  3501. deletedNotLocallyChanged(t, config.FolderTypeReceiveOnly)
  3502. }
  3503. func TestDeletedNotLocallyChangedReceiveEncrypted(t *testing.T) {
  3504. deletedNotLocallyChanged(t, config.FolderTypeReceiveEncrypted)
  3505. }
  3506. func deletedNotLocallyChanged(t *testing.T, ft config.FolderType) {
  3507. w, fcfg, wCancel := newDefaultCfgWrapper()
  3508. tfs := fcfg.Filesystem(nil)
  3509. fcfg.Type = ft
  3510. setFolder(t, w, fcfg)
  3511. defer wCancel()
  3512. m := setupModel(t, w)
  3513. defer cleanupModelAndRemoveDir(m, tfs.URI())
  3514. name := "foo"
  3515. writeFile(t, tfs, name, nil)
  3516. must(t, m.ScanFolder(fcfg.ID))
  3517. fi, ok, err := m.CurrentFolderFile(fcfg.ID, name)
  3518. must(t, err)
  3519. if !ok {
  3520. t.Fatal("File hasn't been added")
  3521. }
  3522. if !fi.IsReceiveOnlyChanged() {
  3523. t.Fatal("File isn't receive-only-changed")
  3524. }
  3525. must(t, tfs.Remove(name))
  3526. must(t, m.ScanFolder(fcfg.ID))
  3527. _, ok, err = m.CurrentFolderFile(fcfg.ID, name)
  3528. must(t, err)
  3529. if ok {
  3530. t.Error("Expected file to be removed from db")
  3531. }
  3532. }
  3533. func equalStringsInAnyOrder(a, b []string) bool {
  3534. if len(a) != len(b) {
  3535. return false
  3536. }
  3537. slices.Sort(a)
  3538. slices.Sort(b)
  3539. for i := range a {
  3540. if a[i] != b[i] {
  3541. return false
  3542. }
  3543. }
  3544. return true
  3545. }
  3546. // modtimeTruncatingFS is a FileSystem that returns modification times only
  3547. // to the closest two `trunc` interval.
  3548. type modtimeTruncatingFS struct {
  3549. trunc time.Duration
  3550. fs.Filesystem
  3551. }
  3552. func (f modtimeTruncatingFS) Lstat(name string) (fs.FileInfo, error) {
  3553. fmt.Println("lstat", name)
  3554. info, err := f.Filesystem.Lstat(name)
  3555. return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
  3556. }
  3557. func (f modtimeTruncatingFS) Stat(name string) (fs.FileInfo, error) {
  3558. fmt.Println("stat", name)
  3559. info, err := f.Filesystem.Stat(name)
  3560. return modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, err
  3561. }
  3562. func (f modtimeTruncatingFS) Walk(root string, walkFn fs.WalkFunc) error {
  3563. return f.Filesystem.Walk(root, func(path string, info fs.FileInfo, err error) error {
  3564. if err != nil {
  3565. return walkFn(path, nil, err)
  3566. }
  3567. fmt.Println("walk", info.Name())
  3568. return walkFn(path, modtimeTruncatingFileInfo{trunc: f.trunc, FileInfo: info}, nil)
  3569. })
  3570. }
  3571. type modtimeTruncatingFileInfo struct {
  3572. trunc time.Duration
  3573. fs.FileInfo
  3574. }
  3575. func (fi modtimeTruncatingFileInfo) ModTime() time.Time {
  3576. return fi.FileInfo.ModTime().Truncate(fi.trunc)
  3577. }