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. "sort"
  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/testutils"
  36. "github.com/syncthing/syncthing/lib/util"
  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, "default", "foo", 0, 6, 0, nil, 0, false)
  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, "default", "foo", 0, 6, 0, nil, 0, false)
  94. if err == nil {
  95. t.Error("Unexpected nil error on insecure file read")
  96. }
  97. // Nonexistent file
  98. _, err = m.Request(device1Conn, "default", "nonexistent", 0, 6, 0, nil, 0, false)
  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, "default", "../walk.go", 0, 6, 0, nil, 0, false)
  104. if err == nil {
  105. t.Error("Unexpected nil error on insecure file read")
  106. }
  107. // Negative offset
  108. _, err = m.Request(device1Conn, "default", "foo", 0, -4, 0, nil, 0, false)
  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, "default", "foo", 0, 42, 0, []byte("hash necessary but not checked"), 0, false)
  114. if err == nil {
  115. t.Error("Unexpected nil error on read past end of file")
  116. }
  117. _, err = m.Request(device1Conn, "default", "foo", 0, 42, 0, nil, 0, false)
  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, fcfg.ID, files))
  148. b.ResetTimer()
  149. for i := 0; i < b.N; i++ {
  150. must(b, m.Index(device1Conn, fcfg.ID, 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, fcfg.ID, files))
  170. b.ResetTimer()
  171. for i := 0; i < b.N; i++ {
  172. must(b, m.IndexUpdate(device1Conn, fcfg.ID, 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, "default", 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, "default", "request/for/a/file/in/a/couple/of/dirs/128k", 0, 128<<10, 0, nil, 0, false); 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, "syncthing", "dev", 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: fs.FilesystemTypeFake,
  327. ID: "folder1",
  328. Path: "testdata1",
  329. Devices: []config.FolderDeviceConfiguration{
  330. {DeviceID: device1},
  331. {DeviceID: device2},
  332. },
  333. },
  334. {
  335. FilesystemType: fs.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: fs.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, "syncthing", "dev", 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: fs.FilesystemTypeFake,
  427. ID: "folder1",
  428. Path: "testdata",
  429. Devices: []config.FolderDeviceConfiguration{
  430. {DeviceID: device1},
  431. },
  432. },
  433. {
  434. FilesystemType: fs.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: fs.FilesystemTypeFake,
  484. ID: "folder1",
  485. Path: "testdata",
  486. Devices: []config.FolderDeviceConfiguration{
  487. {DeviceID: device1},
  488. {DeviceID: device2, IntroducedBy: device1},
  489. },
  490. },
  491. {
  492. FilesystemType: fs.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: fs.FilesystemTypeFake,
  535. ID: "folder1",
  536. Path: "testdata",
  537. Devices: []config.FolderDeviceConfiguration{
  538. {DeviceID: device1},
  539. {DeviceID: device2, IntroducedBy: device1},
  540. },
  541. },
  542. {
  543. FilesystemType: fs.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: fs.FilesystemTypeFake,
  582. ID: "folder1",
  583. Path: "testdata",
  584. Devices: []config.FolderDeviceConfiguration{
  585. {DeviceID: device1},
  586. {DeviceID: device2, IntroducedBy: device1},
  587. },
  588. },
  589. {
  590. FilesystemType: fs.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: fs.FilesystemTypeFake,
  629. ID: "folder1",
  630. Path: "testdata",
  631. Devices: []config.FolderDeviceConfiguration{
  632. {DeviceID: device1},
  633. {DeviceID: device2, IntroducedBy: device1},
  634. },
  635. },
  636. {
  637. FilesystemType: fs.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: fs.FilesystemTypeFake,
  680. ID: "folder1",
  681. Path: "testdata",
  682. Devices: []config.FolderDeviceConfiguration{
  683. {DeviceID: device1},
  684. {DeviceID: device2, IntroducedBy: device1},
  685. },
  686. },
  687. {
  688. FilesystemType: fs.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: fs.FilesystemTypeFake,
  726. ID: "folder1",
  727. Path: "testdata",
  728. Devices: []config.FolderDeviceConfiguration{
  729. {DeviceID: device1},
  730. {DeviceID: device2, IntroducedBy: device1},
  731. },
  732. },
  733. {
  734. FilesystemType: fs.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: fs.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.pmut.Lock()
  795. for _, c := range m.conn {
  796. conn := c.(*fakeConnection)
  797. conn.CloseCalls(func(_ error) {})
  798. defer m.Closed(c, errStopped) // to unblock deferred m.Stop()
  799. }
  800. m.pmut.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, fs.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: fs.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: fs.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: fs.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, "", fs.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[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. for _, dev := range fcfg.DeviceIDs() {
  1119. if dev == device1 {
  1120. return
  1121. }
  1122. }
  1123. t.Error("device missing")
  1124. }
  1125. if _, ok := m.folderRunners[id]; ok {
  1126. t.Error("folder started")
  1127. }
  1128. }
  1129. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1130. // Existing folder
  1131. id := srand.String(8)
  1132. idOther := srand.String(8) // To check that path does not get changed.
  1133. tcfg := defaultAutoAcceptCfg.Copy()
  1134. fcfg := newFolderConfiguration(defaultCfgWrapper, id, "", fs.FilesystemTypeFake, idOther)
  1135. fcfg.Paused = true
  1136. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1137. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1138. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1139. // did not have a file set.
  1140. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1141. {
  1142. DeviceID: device1,
  1143. },
  1144. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1145. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1146. m, cancel := newState(t, tcfg)
  1147. defer cleanupModel(m)
  1148. defer cancel()
  1149. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1150. t.Error("missing folder, or not shared", id)
  1151. }
  1152. if _, ok := m.folderRunners[id]; ok {
  1153. t.Fatal("folder running?")
  1154. }
  1155. m.ClusterConfig(device1Conn, createClusterConfig(device1, id))
  1156. m.generateClusterConfig(device1)
  1157. if fcfg, ok := m.cfg.Folder(id); !ok {
  1158. t.Error("missing folder")
  1159. } else if fcfg.Path != idOther {
  1160. t.Error("folder path changed")
  1161. } else {
  1162. for _, dev := range fcfg.DeviceIDs() {
  1163. if dev == device1 {
  1164. return
  1165. }
  1166. }
  1167. t.Error("device missing")
  1168. }
  1169. if _, ok := m.folderRunners[id]; ok {
  1170. t.Error("folder started")
  1171. }
  1172. }
  1173. func TestAutoAcceptEnc(t *testing.T) {
  1174. tcfg := defaultAutoAcceptCfg.Copy()
  1175. m, cancel := newState(t, tcfg)
  1176. defer cleanupModel(m)
  1177. defer cancel()
  1178. id := srand.String(8)
  1179. defer os.RemoveAll(id)
  1180. token := []byte("token")
  1181. basicCC := func() protocol.ClusterConfig {
  1182. return protocol.ClusterConfig{
  1183. Folders: []protocol.Folder{{
  1184. ID: id,
  1185. Label: id,
  1186. }},
  1187. }
  1188. }
  1189. // Earlier tests might cause the connection to get closed, thus ClusterConfig
  1190. // would panic.
  1191. clusterConfig := func(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  1192. m.AddConnection(newFakeConnection(deviceID, m), protocol.Hello{})
  1193. m.ClusterConfig(&protocolmocks.Connection{DeviceIDStub: func() protocol.DeviceID { return deviceID }}, cm)
  1194. }
  1195. clusterConfig(device1, basicCC())
  1196. if _, ok := m.cfg.Folder(id); ok {
  1197. t.Fatal("unexpected added")
  1198. }
  1199. cc := basicCC()
  1200. cc.Folders[0].Devices = []protocol.Device{{ID: device1}}
  1201. clusterConfig(device1, cc)
  1202. if _, ok := m.cfg.Folder(id); ok {
  1203. t.Fatal("unexpected added")
  1204. }
  1205. cc = basicCC()
  1206. cc.Folders[0].Devices = []protocol.Device{{ID: myID}}
  1207. clusterConfig(device1, cc)
  1208. if _, ok := m.cfg.Folder(id); ok {
  1209. t.Fatal("unexpected added")
  1210. }
  1211. // New folder, encrypted -> add as enc
  1212. cc = createClusterConfig(device1, id)
  1213. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1214. clusterConfig(device1, cc)
  1215. if cfg, ok := m.cfg.Folder(id); !ok {
  1216. t.Fatal("unexpected unadded")
  1217. } else {
  1218. if !cfg.SharedWith(device1) {
  1219. t.Fatal("unexpected unshared")
  1220. }
  1221. if cfg.Type != config.FolderTypeReceiveEncrypted {
  1222. t.Fatal("Folder not added as receiveEncrypted")
  1223. }
  1224. }
  1225. // New device, unencrypted on encrypted folder -> reject
  1226. clusterConfig(device2, createClusterConfig(device2, id))
  1227. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1228. t.Fatal("unexpected shared")
  1229. }
  1230. // New device, encrypted on encrypted folder -> share
  1231. cc = createClusterConfig(device2, id)
  1232. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1233. clusterConfig(device2, cc)
  1234. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1235. t.Fatal("unexpected unshared")
  1236. }
  1237. // New folder, no encrypted -> add "normal"
  1238. id = srand.String(8)
  1239. defer os.RemoveAll(id)
  1240. clusterConfig(device1, createClusterConfig(device1, id))
  1241. if cfg, ok := m.cfg.Folder(id); !ok {
  1242. t.Fatal("unexpected unadded")
  1243. } else {
  1244. if !cfg.SharedWith(device1) {
  1245. t.Fatal("unexpected unshared")
  1246. }
  1247. if cfg.Type != config.FolderTypeSendReceive {
  1248. t.Fatal("Folder not added as send-receive")
  1249. }
  1250. }
  1251. // New device, encrypted on unencrypted folder -> reject
  1252. cc = createClusterConfig(device2, id)
  1253. cc.Folders[0].Devices[1].EncryptionPasswordToken = token
  1254. clusterConfig(device2, cc)
  1255. if cfg, _ := m.cfg.Folder(id); cfg.SharedWith(device2) {
  1256. t.Fatal("unexpected shared")
  1257. }
  1258. // New device, unencrypted on unencrypted folder -> share
  1259. clusterConfig(device2, createClusterConfig(device2, id))
  1260. if cfg, _ := m.cfg.Folder(id); !cfg.SharedWith(device2) {
  1261. t.Fatal("unexpected unshared")
  1262. }
  1263. }
  1264. func changeIgnores(t *testing.T, m *testModel, expected []string) {
  1265. arrEqual := func(a, b []string) bool {
  1266. if len(a) != len(b) {
  1267. return false
  1268. }
  1269. for i := range a {
  1270. if a[i] != b[i] {
  1271. return false
  1272. }
  1273. }
  1274. return true
  1275. }
  1276. ignores, _, err := m.LoadIgnores("default")
  1277. if err != nil {
  1278. t.Error(err)
  1279. }
  1280. if !arrEqual(ignores, expected) {
  1281. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1282. }
  1283. ignores = append(ignores, "pox")
  1284. err = m.SetIgnores("default", ignores)
  1285. if err != nil {
  1286. t.Error(err)
  1287. }
  1288. ignores2, _, err := m.LoadIgnores("default")
  1289. if err != nil {
  1290. t.Error(err)
  1291. }
  1292. if !arrEqual(ignores, ignores2) {
  1293. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1294. }
  1295. if build.IsDarwin {
  1296. // see above
  1297. time.Sleep(time.Second)
  1298. } else {
  1299. time.Sleep(time.Millisecond)
  1300. }
  1301. err = m.SetIgnores("default", expected)
  1302. if err != nil {
  1303. t.Error(err)
  1304. }
  1305. ignores, _, err = m.LoadIgnores("default")
  1306. if err != nil {
  1307. t.Error(err)
  1308. }
  1309. if !arrEqual(ignores, expected) {
  1310. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1311. }
  1312. }
  1313. func TestIgnores(t *testing.T) {
  1314. w, cancel := newConfigWrapper(defaultCfg)
  1315. defer cancel()
  1316. ffs := w.FolderList()[0].Filesystem(nil)
  1317. m := setupModel(t, w)
  1318. defer cleanupModel(m)
  1319. // Assure a clean start state
  1320. must(t, ffs.MkdirAll(config.DefaultMarkerName, 0o644))
  1321. writeFile(t, ffs, ".stignore", []byte(".*\nquux\n"))
  1322. folderIgnoresAlwaysReload(t, m, defaultFolderConfig)
  1323. // Make sure the initial scan has finished (ScanFolders is blocking)
  1324. m.ScanFolders()
  1325. expected := []string{
  1326. ".*",
  1327. "quux",
  1328. }
  1329. changeIgnores(t, m, expected)
  1330. _, _, err := m.LoadIgnores("doesnotexist")
  1331. if err == nil {
  1332. t.Error("No error")
  1333. }
  1334. err = m.SetIgnores("doesnotexist", expected)
  1335. if err == nil {
  1336. t.Error("No error")
  1337. }
  1338. // Invalid path, treated like no patterns at all.
  1339. fcfg := config.FolderConfiguration{
  1340. ID: "fresh", Path: "XXX",
  1341. FilesystemType: fs.FilesystemTypeFake,
  1342. }
  1343. ignores := ignore.New(fcfg.Filesystem(nil), ignore.WithCache(m.cfg.Options().CacheIgnoredFiles))
  1344. m.fmut.Lock()
  1345. m.folderCfgs[fcfg.ID] = fcfg
  1346. m.folderIgnores[fcfg.ID] = ignores
  1347. m.fmut.Unlock()
  1348. _, _, err = m.LoadIgnores("fresh")
  1349. if err != nil {
  1350. t.Error("Got error for inexistent folder path")
  1351. }
  1352. // Repeat tests with paused folder
  1353. pausedDefaultFolderConfig := defaultFolderConfig
  1354. pausedDefaultFolderConfig.Paused = true
  1355. m.restartFolder(defaultFolderConfig, pausedDefaultFolderConfig, false)
  1356. // Here folder initialization is not an issue as a paused folder isn't
  1357. // added to the model and thus there is no initial scan happening.
  1358. changeIgnores(t, m, expected)
  1359. // Make sure no .stignore file is considered valid
  1360. defer func() {
  1361. must(t, ffs.Rename(".stignore.bak", ".stignore"))
  1362. }()
  1363. must(t, ffs.Rename(".stignore", ".stignore.bak"))
  1364. changeIgnores(t, m, []string{})
  1365. }
  1366. func TestEmptyIgnores(t *testing.T) {
  1367. w, cancel := newConfigWrapper(defaultCfg)
  1368. defer cancel()
  1369. ffs := w.FolderList()[0].Filesystem(nil)
  1370. m := setupModel(t, w)
  1371. defer cleanupModel(m)
  1372. if err := m.SetIgnores("default", []string{}); err != nil {
  1373. t.Error(err)
  1374. }
  1375. if _, err := ffs.Stat(".stignore"); err == nil {
  1376. t.Error(".stignore was created despite being empty")
  1377. }
  1378. if err := m.SetIgnores("default", []string{".*", "quux"}); err != nil {
  1379. t.Error(err)
  1380. }
  1381. if _, err := ffs.Stat(".stignore"); os.IsNotExist(err) {
  1382. t.Error(".stignore does not exist")
  1383. }
  1384. if err := m.SetIgnores("default", []string{}); err != nil {
  1385. t.Error(err)
  1386. }
  1387. if _, err := ffs.Stat(".stignore"); err == nil {
  1388. t.Error(".stignore should have been deleted because it is empty")
  1389. }
  1390. }
  1391. func waitForState(t *testing.T, sub events.Subscription, folder, expected string) {
  1392. t.Helper()
  1393. timeout := time.After(5 * time.Second)
  1394. var err string
  1395. for {
  1396. select {
  1397. case ev := <-sub.C():
  1398. data := ev.Data.(map[string]interface{})
  1399. if data["folder"].(string) == folder {
  1400. if data["error"] == nil {
  1401. err = ""
  1402. } else {
  1403. err = data["error"].(string)
  1404. }
  1405. if err == expected {
  1406. return
  1407. } else {
  1408. t.Error(ev)
  1409. }
  1410. }
  1411. case <-timeout:
  1412. t.Fatalf("Timed out waiting for status: %s, current status: %v", expected, err)
  1413. }
  1414. }
  1415. }
  1416. func TestROScanRecovery(t *testing.T) {
  1417. fcfg := config.FolderConfiguration{
  1418. FilesystemType: fs.FilesystemTypeFake,
  1419. ID: "default",
  1420. Path: srand.String(32),
  1421. Type: config.FolderTypeSendOnly,
  1422. RescanIntervalS: 1,
  1423. MarkerName: config.DefaultMarkerName,
  1424. }
  1425. cfg, cancel := newConfigWrapper(config.Configuration{
  1426. Version: config.CurrentVersion,
  1427. Folders: []config.FolderConfiguration{fcfg},
  1428. Devices: []config.DeviceConfiguration{
  1429. {
  1430. DeviceID: device1,
  1431. },
  1432. },
  1433. })
  1434. defer cancel()
  1435. m := newModel(t, cfg, myID, "syncthing", "dev", nil)
  1436. set := newFileSet(t, "default", m.db)
  1437. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1438. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1439. })
  1440. ffs := fcfg.Filesystem(nil)
  1441. // Remove marker to generate an error
  1442. ffs.Remove(fcfg.MarkerName)
  1443. sub := m.evLogger.Subscribe(events.StateChanged)
  1444. defer sub.Unsubscribe()
  1445. m.ServeBackground()
  1446. defer cleanupModel(m)
  1447. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1448. fd, err := ffs.Create(config.DefaultMarkerName)
  1449. if err != nil {
  1450. t.Fatal(err)
  1451. }
  1452. fd.Close()
  1453. waitForState(t, sub, "default", "")
  1454. }
  1455. func TestRWScanRecovery(t *testing.T) {
  1456. fcfg := config.FolderConfiguration{
  1457. FilesystemType: fs.FilesystemTypeFake,
  1458. ID: "default",
  1459. Path: srand.String(32),
  1460. Type: config.FolderTypeSendReceive,
  1461. RescanIntervalS: 1,
  1462. MarkerName: config.DefaultMarkerName,
  1463. }
  1464. cfg, cancel := newConfigWrapper(config.Configuration{
  1465. Version: config.CurrentVersion,
  1466. Folders: []config.FolderConfiguration{fcfg},
  1467. Devices: []config.DeviceConfiguration{
  1468. {
  1469. DeviceID: device1,
  1470. },
  1471. },
  1472. })
  1473. defer cancel()
  1474. m := newModel(t, cfg, myID, "syncthing", "dev", nil)
  1475. set := newFileSet(t, "default", m.db)
  1476. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1477. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1478. })
  1479. ffs := fcfg.Filesystem(nil)
  1480. // Generate error
  1481. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  1482. t.Fatal(err)
  1483. }
  1484. sub := m.evLogger.Subscribe(events.StateChanged)
  1485. defer sub.Unsubscribe()
  1486. m.ServeBackground()
  1487. defer cleanupModel(m)
  1488. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  1489. fd, err := ffs.Create(config.DefaultMarkerName)
  1490. if err != nil {
  1491. t.Error(err)
  1492. }
  1493. fd.Close()
  1494. waitForState(t, sub, "default", "")
  1495. }
  1496. func TestGlobalDirectoryTree(t *testing.T) {
  1497. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  1498. defer wCancel()
  1499. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  1500. b := func(isfile bool, path ...string) protocol.FileInfo {
  1501. typ := protocol.FileInfoTypeDirectory
  1502. var blocks []protocol.BlockInfo
  1503. if isfile {
  1504. typ = protocol.FileInfoTypeFile
  1505. 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}}}
  1506. }
  1507. return protocol.FileInfo{
  1508. Name: filepath.Join(path...),
  1509. Type: typ,
  1510. ModifiedS: 0x666,
  1511. Blocks: blocks,
  1512. Size: 0xa,
  1513. }
  1514. }
  1515. f := func(name string) *TreeEntry {
  1516. return &TreeEntry{
  1517. Name: name,
  1518. ModTime: time.Unix(0x666, 0),
  1519. Size: 0xa,
  1520. Type: protocol.FileInfoTypeFile,
  1521. }
  1522. }
  1523. d := func(name string, entries ...*TreeEntry) *TreeEntry {
  1524. return &TreeEntry{
  1525. Name: name,
  1526. ModTime: time.Unix(0x666, 0),
  1527. Size: 128,
  1528. Type: protocol.FileInfoTypeDirectory,
  1529. Children: entries,
  1530. }
  1531. }
  1532. testdata := []protocol.FileInfo{
  1533. b(false, "another"),
  1534. b(false, "another", "directory"),
  1535. b(true, "another", "directory", "afile"),
  1536. b(false, "another", "directory", "with"),
  1537. b(false, "another", "directory", "with", "a"),
  1538. b(true, "another", "directory", "with", "a", "file"),
  1539. b(true, "another", "directory", "with", "file"),
  1540. b(true, "another", "file"),
  1541. b(false, "other"),
  1542. b(false, "other", "rand"),
  1543. b(false, "other", "random"),
  1544. b(false, "other", "random", "dir"),
  1545. b(false, "other", "random", "dirx"),
  1546. b(false, "other", "randomx"),
  1547. b(false, "some"),
  1548. b(false, "some", "directory"),
  1549. b(false, "some", "directory", "with"),
  1550. b(false, "some", "directory", "with", "a"),
  1551. b(true, "some", "directory", "with", "a", "file"),
  1552. b(true, "zzrootfile"),
  1553. }
  1554. expectedResult := []*TreeEntry{
  1555. d("another",
  1556. d("directory",
  1557. f("afile"),
  1558. d("with",
  1559. d("a",
  1560. f("file"),
  1561. ),
  1562. f("file"),
  1563. ),
  1564. ),
  1565. f("file"),
  1566. ),
  1567. d("other",
  1568. d("rand"),
  1569. d("random",
  1570. d("dir"),
  1571. d("dirx"),
  1572. ),
  1573. d("randomx"),
  1574. ),
  1575. d("some",
  1576. d("directory",
  1577. d("with",
  1578. d("a",
  1579. f("file"),
  1580. ),
  1581. ),
  1582. ),
  1583. ),
  1584. f("zzrootfile"),
  1585. }
  1586. mm := func(data interface{}) string {
  1587. bytes, err := json.MarshalIndent(data, "", " ")
  1588. if err != nil {
  1589. panic(err)
  1590. }
  1591. return string(bytes)
  1592. }
  1593. must(t, m.Index(conn, "default", testdata))
  1594. result, _ := m.GlobalDirectoryTree("default", "", -1, false)
  1595. if mm(result) != mm(expectedResult) {
  1596. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(expectedResult))
  1597. }
  1598. result, _ = m.GlobalDirectoryTree("default", "another", -1, false)
  1599. if mm(result) != mm(findByName(expectedResult, "another").Children) {
  1600. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(findByName(expectedResult, "another").Children))
  1601. }
  1602. result, _ = m.GlobalDirectoryTree("default", "", 0, false)
  1603. currentResult := []*TreeEntry{
  1604. d("another"),
  1605. d("other"),
  1606. d("some"),
  1607. f("zzrootfile"),
  1608. }
  1609. if mm(result) != mm(currentResult) {
  1610. t.Errorf("Does not match:\n%s\n============\n%s", mm(result), mm(currentResult))
  1611. }
  1612. result, _ = m.GlobalDirectoryTree("default", "", 1, false)
  1613. currentResult = []*TreeEntry{
  1614. d("another",
  1615. d("directory"),
  1616. f("file"),
  1617. ),
  1618. d("other",
  1619. d("rand"),
  1620. d("random"),
  1621. d("randomx"),
  1622. ),
  1623. d("some",
  1624. d("directory"),
  1625. ),
  1626. f("zzrootfile"),
  1627. }
  1628. if mm(result) != mm(currentResult) {
  1629. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1630. }
  1631. result, _ = m.GlobalDirectoryTree("default", "", -1, true)
  1632. currentResult = []*TreeEntry{
  1633. d("another",
  1634. d("directory",
  1635. d("with",
  1636. d("a"),
  1637. ),
  1638. ),
  1639. ),
  1640. d("other",
  1641. d("rand"),
  1642. d("random",
  1643. d("dir"),
  1644. d("dirx"),
  1645. ),
  1646. d("randomx"),
  1647. ),
  1648. d("some",
  1649. d("directory",
  1650. d("with",
  1651. d("a"),
  1652. ),
  1653. ),
  1654. ),
  1655. }
  1656. if mm(result) != mm(currentResult) {
  1657. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1658. }
  1659. result, _ = m.GlobalDirectoryTree("default", "", 1, true)
  1660. currentResult = []*TreeEntry{
  1661. d("another",
  1662. d("directory"),
  1663. ),
  1664. d("other",
  1665. d("rand"),
  1666. d("random"),
  1667. d("randomx"),
  1668. ),
  1669. d("some",
  1670. d("directory"),
  1671. ),
  1672. }
  1673. if mm(result) != mm(currentResult) {
  1674. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1675. }
  1676. result, _ = m.GlobalDirectoryTree("default", "another", 0, false)
  1677. currentResult = []*TreeEntry{
  1678. d("directory"),
  1679. f("file"),
  1680. }
  1681. if mm(result) != mm(currentResult) {
  1682. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1683. }
  1684. result, _ = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1685. currentResult = []*TreeEntry{
  1686. d("with"),
  1687. }
  1688. if mm(result) != mm(currentResult) {
  1689. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1690. }
  1691. result, _ = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1692. currentResult = []*TreeEntry{
  1693. d("with",
  1694. d("a"),
  1695. ),
  1696. }
  1697. if mm(result) != mm(currentResult) {
  1698. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1699. }
  1700. result, _ = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1701. currentResult = []*TreeEntry{
  1702. d("with",
  1703. d("a",
  1704. f("file"),
  1705. ),
  1706. ),
  1707. }
  1708. if mm(result) != mm(currentResult) {
  1709. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1710. }
  1711. result, _ = m.GlobalDirectoryTree("default", "another", -1, true)
  1712. currentResult = []*TreeEntry{
  1713. d("directory",
  1714. d("with",
  1715. d("a"),
  1716. ),
  1717. ),
  1718. }
  1719. if mm(result) != mm(currentResult) {
  1720. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1721. }
  1722. // No prefix matching!
  1723. result, _ = m.GlobalDirectoryTree("default", "som", -1, false)
  1724. currentResult = []*TreeEntry{}
  1725. if mm(result) != mm(currentResult) {
  1726. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1727. }
  1728. }
  1729. func genDeepFiles(n, d int) []protocol.FileInfo {
  1730. mrand.Seed(int64(n))
  1731. files := make([]protocol.FileInfo, n)
  1732. t := time.Now().Unix()
  1733. for i := 0; i < n; i++ {
  1734. path := ""
  1735. for i := 0; i <= d; i++ {
  1736. path = filepath.Join(path, strconv.Itoa(mrand.Int()))
  1737. }
  1738. sofar := ""
  1739. for _, path := range filepath.SplitList(path) {
  1740. sofar = filepath.Join(sofar, path)
  1741. files[i] = protocol.FileInfo{
  1742. Name: sofar,
  1743. }
  1744. i++
  1745. }
  1746. files[i].ModifiedS = t
  1747. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1748. }
  1749. return files
  1750. }
  1751. func BenchmarkTree_10000_50(b *testing.B) {
  1752. benchmarkTree(b, 10000, 50)
  1753. }
  1754. func BenchmarkTree_100_50(b *testing.B) {
  1755. benchmarkTree(b, 100, 50)
  1756. }
  1757. func BenchmarkTree_100_10(b *testing.B) {
  1758. benchmarkTree(b, 100, 10)
  1759. }
  1760. func benchmarkTree(b *testing.B, n1, n2 int) {
  1761. m, _, fcfg, wcfgCancel := setupModelWithConnection(b)
  1762. defer wcfgCancel()
  1763. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  1764. m.ScanFolder(fcfg.ID)
  1765. files := genDeepFiles(n1, n2)
  1766. must(b, m.Index(device1Conn, fcfg.ID, files))
  1767. b.ResetTimer()
  1768. for i := 0; i < b.N; i++ {
  1769. m.GlobalDirectoryTree(fcfg.ID, "", -1, false)
  1770. }
  1771. b.ReportAllocs()
  1772. }
  1773. func TestIssue3028(t *testing.T) {
  1774. w, cancel := newConfigWrapper(defaultCfg)
  1775. defer cancel()
  1776. ffs := w.FolderList()[0].Filesystem(nil)
  1777. m := setupModel(t, w)
  1778. defer cleanupModel(m)
  1779. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1780. writeFile(t, ffs, "testrm", []byte("Hello"))
  1781. writeFile(t, ffs, "testrm2", []byte("Hello"))
  1782. // Scan, and get a count of how many files are there now
  1783. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1784. locorigfiles := localSize(t, m, "default").Files
  1785. globorigfiles := globalSize(t, m, "default").Files
  1786. // Delete
  1787. must(t, ffs.Remove("testrm"))
  1788. must(t, ffs.Remove("testrm2"))
  1789. // Verify that the number of files decreased by two and the number of
  1790. // deleted files increases by two
  1791. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1792. loc := localSize(t, m, "default")
  1793. glob := globalSize(t, m, "default")
  1794. if loc.Files != locorigfiles-2 {
  1795. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1796. }
  1797. if glob.Files != globorigfiles-2 {
  1798. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1799. }
  1800. if loc.Deleted != 2 {
  1801. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1802. }
  1803. if glob.Deleted != 2 {
  1804. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1805. }
  1806. }
  1807. func TestIssue4357(t *testing.T) {
  1808. cfg := defaultCfgWrapper.RawCopy()
  1809. // Create a separate wrapper not to pollute other tests.
  1810. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  1811. defer cancel()
  1812. m := newModel(t, wrapper, myID, "syncthing", "dev", nil)
  1813. m.ServeBackground()
  1814. defer cleanupModel(m)
  1815. // Force the model to wire itself and add the folders
  1816. replace(t, wrapper, cfg)
  1817. if _, ok := m.folderCfgs["default"]; !ok {
  1818. t.Error("Folder should be running")
  1819. }
  1820. newCfg := wrapper.RawCopy()
  1821. newCfg.Folders[0].Paused = true
  1822. replace(t, wrapper, newCfg)
  1823. if _, ok := m.folderCfgs["default"]; ok {
  1824. t.Error("Folder should not be running")
  1825. }
  1826. if _, ok := m.cfg.Folder("default"); !ok {
  1827. t.Error("should still have folder in config")
  1828. }
  1829. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1830. if _, ok := m.cfg.Folder("default"); ok {
  1831. t.Error("should not have folder in config")
  1832. }
  1833. // Add the folder back, should be running
  1834. replace(t, wrapper, cfg)
  1835. if _, ok := m.folderCfgs["default"]; !ok {
  1836. t.Error("Folder should be running")
  1837. }
  1838. if _, ok := m.cfg.Folder("default"); !ok {
  1839. t.Error("should still have folder in config")
  1840. }
  1841. // Should not panic when removing a running folder.
  1842. replace(t, wrapper, config.Configuration{Version: config.CurrentVersion})
  1843. if _, ok := m.folderCfgs["default"]; ok {
  1844. t.Error("Folder should not be running")
  1845. }
  1846. if _, ok := m.cfg.Folder("default"); ok {
  1847. t.Error("should not have folder in config")
  1848. }
  1849. }
  1850. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1851. m := newModel(t, defaultCfgWrapper, myID, "syncthing", "dev", nil)
  1852. files := newFileSet(t, "default", m.db)
  1853. files.Drop(device1)
  1854. files.Update(device1, genFiles(1))
  1855. files.Drop(device2)
  1856. files.Update(device2, genFiles(1))
  1857. if len(files.ListDevices()) != 2 {
  1858. t.Error("expected two devices")
  1859. }
  1860. m.newFolder(defaultFolderConfig, false)
  1861. defer cleanupModel(m)
  1862. // Remote sequence is cached, hence need to recreated.
  1863. files = newFileSet(t, "default", m.db)
  1864. if l := len(files.ListDevices()); l != 1 {
  1865. t.Errorf("Expected one device got %v", l)
  1866. }
  1867. }
  1868. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1869. wcfg, cancel := newConfigWrapper(defaultCfg)
  1870. defer cancel()
  1871. addDevice2(t, wcfg, wcfg.FolderList()[0])
  1872. m := setupModel(t, wcfg)
  1873. defer cleanupModel(m)
  1874. conn1 := newFakeConnection(device1, m)
  1875. m.AddConnection(conn1, protocol.Hello{})
  1876. conn2 := newFakeConnection(device2, m)
  1877. m.AddConnection(conn2, protocol.Hello{})
  1878. m.ClusterConfig(conn1, protocol.ClusterConfig{
  1879. Folders: []protocol.Folder{
  1880. {
  1881. ID: "default",
  1882. Devices: []protocol.Device{
  1883. {ID: myID},
  1884. {ID: device1},
  1885. {ID: device2},
  1886. },
  1887. },
  1888. },
  1889. })
  1890. m.ClusterConfig(conn2, protocol.ClusterConfig{
  1891. Folders: []protocol.Folder{
  1892. {
  1893. ID: "default",
  1894. Devices: []protocol.Device{
  1895. {ID: myID},
  1896. {ID: device1},
  1897. {ID: device2},
  1898. },
  1899. },
  1900. },
  1901. })
  1902. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  1903. t.Error("not shared with device1")
  1904. }
  1905. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
  1906. t.Error("not shared with device2")
  1907. }
  1908. select {
  1909. case <-conn2.Closed():
  1910. t.Error("conn already closed")
  1911. default:
  1912. }
  1913. if _, err := wcfg.RemoveDevice(device2); err != nil {
  1914. t.Error(err)
  1915. }
  1916. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1917. fcfg, ok := m.cfg.Folder("default")
  1918. if !ok {
  1919. t.Fatal("default folder missing")
  1920. }
  1921. if !fcfg.SharedWith(device1) {
  1922. t.Error("not shared with device1")
  1923. }
  1924. if fcfg.SharedWith(device2) {
  1925. t.Error("shared with device2")
  1926. }
  1927. for _, dev := range fcfg.Devices {
  1928. if dev.DeviceID == device2 {
  1929. t.Error("still there")
  1930. }
  1931. }
  1932. select {
  1933. case <-conn2.Closed():
  1934. default:
  1935. t.Error("connection not closed")
  1936. }
  1937. if _, ok := wcfg.Devices()[device2]; ok {
  1938. t.Error("device still in config")
  1939. }
  1940. if _, ok := m.conn[device2]; ok {
  1941. t.Error("conn not missing")
  1942. }
  1943. if _, ok := m.helloMessages[device2]; ok {
  1944. t.Error("hello not missing")
  1945. }
  1946. if _, ok := m.deviceDownloads[device2]; ok {
  1947. t.Error("downloads not missing")
  1948. }
  1949. }
  1950. func TestIssue3804(t *testing.T) {
  1951. m := setupModel(t, defaultCfgWrapper)
  1952. defer cleanupModel(m)
  1953. // Subdirs ending in slash should be accepted
  1954. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1955. t.Error("Unexpected error:", err)
  1956. }
  1957. }
  1958. func TestIssue3829(t *testing.T) {
  1959. m := setupModel(t, defaultCfgWrapper)
  1960. defer cleanupModel(m)
  1961. // Empty subdirs should be accepted
  1962. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1963. t.Error("Unexpected error:", err)
  1964. }
  1965. }
  1966. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  1967. func TestIssue4573(t *testing.T) {
  1968. w, fcfg, wCancel := newDefaultCfgWrapper()
  1969. defer wCancel()
  1970. testFs := fcfg.Filesystem(nil)
  1971. defer os.RemoveAll(testFs.URI())
  1972. must(t, testFs.MkdirAll("inaccessible", 0o755))
  1973. defer testFs.Chmod("inaccessible", 0o777)
  1974. file := filepath.Join("inaccessible", "a")
  1975. fd, err := testFs.Create(file)
  1976. must(t, err)
  1977. fd.Close()
  1978. m := setupModel(t, w)
  1979. defer cleanupModel(m)
  1980. must(t, testFs.Chmod("inaccessible", 0o000))
  1981. m.ScanFolder("default")
  1982. if file, ok := m.testCurrentFolderFile("default", file); !ok {
  1983. t.Fatalf("File missing in db")
  1984. } else if file.Deleted {
  1985. t.Errorf("Inaccessible file has been marked as deleted.")
  1986. }
  1987. }
  1988. // TestInternalScan checks whether various fs operations are correctly represented
  1989. // in the db after scanning.
  1990. func TestInternalScan(t *testing.T) {
  1991. w, fcfg, wCancel := newDefaultCfgWrapper()
  1992. defer wCancel()
  1993. testFs := fcfg.Filesystem(nil)
  1994. defer os.RemoveAll(testFs.URI())
  1995. testCases := map[string]func(protocol.FileInfo) bool{
  1996. "removeDir": func(f protocol.FileInfo) bool {
  1997. return !f.Deleted
  1998. },
  1999. "dirToFile": func(f protocol.FileInfo) bool {
  2000. return f.Deleted || f.IsDirectory()
  2001. },
  2002. }
  2003. baseDirs := []string{"dirToFile", "removeDir"}
  2004. for _, dir := range baseDirs {
  2005. sub := filepath.Join(dir, "subDir")
  2006. for _, dir := range []string{dir, sub} {
  2007. if err := testFs.MkdirAll(dir, 0o775); err != nil {
  2008. t.Fatalf("%v: %v", dir, err)
  2009. }
  2010. }
  2011. testCases[sub] = func(f protocol.FileInfo) bool {
  2012. return !f.Deleted
  2013. }
  2014. for _, dir := range []string{dir, sub} {
  2015. file := filepath.Join(dir, "a")
  2016. fd, err := testFs.Create(file)
  2017. must(t, err)
  2018. fd.Close()
  2019. testCases[file] = func(f protocol.FileInfo) bool {
  2020. return !f.Deleted
  2021. }
  2022. }
  2023. }
  2024. m := setupModel(t, w)
  2025. defer cleanupModel(m)
  2026. for _, dir := range baseDirs {
  2027. must(t, testFs.RemoveAll(dir))
  2028. }
  2029. fd, err := testFs.Create("dirToFile")
  2030. must(t, err)
  2031. fd.Close()
  2032. m.ScanFolder("default")
  2033. for path, cond := range testCases {
  2034. if f, ok := m.testCurrentFolderFile("default", path); !ok {
  2035. t.Fatalf("%v missing in db", path)
  2036. } else if cond(f) {
  2037. t.Errorf("Incorrect db entry for %v", path)
  2038. }
  2039. }
  2040. }
  2041. func TestCustomMarkerName(t *testing.T) {
  2042. fcfg := newFolderConfig()
  2043. fcfg.ID = "default"
  2044. fcfg.RescanIntervalS = 1
  2045. fcfg.MarkerName = "myfile"
  2046. cfg, cancel := newConfigWrapper(config.Configuration{
  2047. Version: config.CurrentVersion,
  2048. Folders: []config.FolderConfiguration{fcfg},
  2049. Devices: []config.DeviceConfiguration{
  2050. {
  2051. DeviceID: device1,
  2052. },
  2053. },
  2054. })
  2055. defer cancel()
  2056. ffs := fcfg.Filesystem(nil)
  2057. m := newModel(t, cfg, myID, "syncthing", "dev", nil)
  2058. set := newFileSet(t, "default", m.db)
  2059. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2060. {Name: "dummyfile"},
  2061. })
  2062. if err := ffs.Remove(config.DefaultMarkerName); err != nil {
  2063. t.Fatal(err)
  2064. }
  2065. sub := m.evLogger.Subscribe(events.StateChanged)
  2066. defer sub.Unsubscribe()
  2067. m.ServeBackground()
  2068. defer cleanupModel(m)
  2069. waitForState(t, sub, "default", config.ErrMarkerMissing.Error())
  2070. fd, _ := ffs.Create("myfile")
  2071. fd.Close()
  2072. waitForState(t, sub, "default", "")
  2073. }
  2074. func TestRemoveDirWithContent(t *testing.T) {
  2075. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2076. defer wcfgCancel()
  2077. tfs := fcfg.Filesystem(nil)
  2078. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2079. tfs.MkdirAll("dirwith", 0o755)
  2080. content := filepath.Join("dirwith", "content")
  2081. fd, err := tfs.Create(content)
  2082. must(t, err)
  2083. fd.Close()
  2084. must(t, m.ScanFolder(fcfg.ID))
  2085. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2086. if !ok {
  2087. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2088. }
  2089. dir.Deleted = true
  2090. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2091. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2092. if !ok {
  2093. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2094. }
  2095. file.Deleted = true
  2096. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2097. must(t, m.IndexUpdate(conn, fcfg.ID, []protocol.FileInfo{dir, file}))
  2098. // Is there something we could trigger on instead of just waiting?
  2099. timeout := time.NewTimer(5 * time.Second)
  2100. for {
  2101. dir, ok := m.testCurrentFolderFile(fcfg.ID, "dirwith")
  2102. if !ok {
  2103. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2104. }
  2105. file, ok := m.testCurrentFolderFile(fcfg.ID, content)
  2106. if !ok {
  2107. t.Fatalf("Can't get file \"%v\" after index update", content)
  2108. }
  2109. if dir.Deleted && file.Deleted {
  2110. return
  2111. }
  2112. select {
  2113. case <-timeout.C:
  2114. if !dir.Deleted && !file.Deleted {
  2115. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2116. } else if !dir.Deleted {
  2117. t.Errorf("The dir was not deleted before timing out.")
  2118. } else {
  2119. t.Errorf("The content of the dir was not deleted before timing out.")
  2120. }
  2121. return
  2122. default:
  2123. time.Sleep(100 * time.Millisecond)
  2124. }
  2125. }
  2126. }
  2127. func TestIssue4475(t *testing.T) {
  2128. m, conn, fcfg, wcfgCancel := setupModelWithConnection(t)
  2129. defer wcfgCancel()
  2130. defer cleanupModel(m)
  2131. testFs := fcfg.Filesystem(nil)
  2132. // Scenario: Dir is deleted locally and before syncing/index exchange
  2133. // happens, a file is create in that dir on the remote.
  2134. // This should result in the directory being recreated and added to the
  2135. // db locally.
  2136. must(t, testFs.MkdirAll("delDir", 0o755))
  2137. m.ScanFolder("default")
  2138. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2139. t.Fatal("not shared with device1")
  2140. }
  2141. fileName := filepath.Join("delDir", "file")
  2142. conn.addFile(fileName, 0o644, protocol.FileInfoTypeFile, nil)
  2143. conn.sendIndexUpdate()
  2144. // Is there something we could trigger on instead of just waiting?
  2145. timeout := time.NewTimer(5 * time.Second)
  2146. created := false
  2147. for {
  2148. if !created {
  2149. if _, ok := m.testCurrentFolderFile("default", fileName); ok {
  2150. created = true
  2151. }
  2152. } else {
  2153. dir, ok := m.testCurrentFolderFile("default", "delDir")
  2154. if !ok {
  2155. t.Fatalf("can't get dir from db")
  2156. }
  2157. if !dir.Deleted {
  2158. return
  2159. }
  2160. }
  2161. select {
  2162. case <-timeout.C:
  2163. if created {
  2164. t.Errorf("Timed out before file from remote was created")
  2165. } else {
  2166. t.Errorf("Timed out before directory was resurrected in db")
  2167. }
  2168. return
  2169. default:
  2170. time.Sleep(100 * time.Millisecond)
  2171. }
  2172. }
  2173. }
  2174. func TestVersionRestore(t *testing.T) {
  2175. t.Skip("incompatible with fakefs")
  2176. // We create a bunch of files which we restore
  2177. // In each file, we write the filename as the content
  2178. // We verify that the content matches at the expected filenames
  2179. // after the restore operation.
  2180. fcfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", fs.FilesystemTypeFake, srand.String(32))
  2181. fcfg.Versioning.Type = "simple"
  2182. fcfg.FSWatcherEnabled = false
  2183. filesystem := fcfg.Filesystem(nil)
  2184. rawConfig := config.Configuration{
  2185. Version: config.CurrentVersion,
  2186. Folders: []config.FolderConfiguration{fcfg},
  2187. }
  2188. cfg, cancel := newConfigWrapper(rawConfig)
  2189. defer cancel()
  2190. m := setupModel(t, cfg)
  2191. defer cleanupModel(m)
  2192. m.ScanFolder("default")
  2193. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20180101-010101", time.Local)
  2194. if err != nil {
  2195. t.Fatal(err)
  2196. }
  2197. for _, file := range []string{
  2198. // Versions directory
  2199. ".stversions/file~20171210-040404.txt", // will be restored
  2200. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2201. ".stversions/something~20171210-040404", // will become directory, hence error
  2202. ".stversions/dir/file~20171210-040404.txt",
  2203. ".stversions/dir/file~20171210-040405.txt",
  2204. ".stversions/dir/file~20171210-040406.txt",
  2205. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2206. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2207. ".stversions/dir/cat", // untagged which was used by trashcan, supported
  2208. // "file.txt" will be restored
  2209. "existing",
  2210. "something/file", // Becomes directory
  2211. "dir/file.txt",
  2212. "dir/existing.txt",
  2213. } {
  2214. if build.IsWindows {
  2215. file = filepath.FromSlash(file)
  2216. }
  2217. dir := filepath.Dir(file)
  2218. must(t, filesystem.MkdirAll(dir, 0o755))
  2219. if fd, err := filesystem.Create(file); err != nil {
  2220. t.Fatal(err)
  2221. } else if _, err := fd.Write([]byte(file)); err != nil {
  2222. t.Fatal(err)
  2223. } else if err := fd.Close(); err != nil {
  2224. t.Fatal(err)
  2225. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2226. t.Fatal(err)
  2227. }
  2228. }
  2229. versions, err := m.GetFolderVersions("default")
  2230. must(t, err)
  2231. expectedVersions := map[string]int{
  2232. "file.txt": 1,
  2233. "existing": 1,
  2234. "something": 1,
  2235. "dir/file.txt": 3,
  2236. "dir/existing.txt": 1,
  2237. "very/very/deep/one.txt": 1,
  2238. "dir/cat": 1,
  2239. }
  2240. for name, vers := range versions {
  2241. cnt, ok := expectedVersions[name]
  2242. if !ok {
  2243. t.Errorf("unexpected %s", name)
  2244. }
  2245. if len(vers) != cnt {
  2246. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2247. }
  2248. // Delete, so we can check if we didn't hit something we expect afterwards.
  2249. delete(expectedVersions, name)
  2250. }
  2251. for name := range expectedVersions {
  2252. t.Errorf("not found expected %s", name)
  2253. }
  2254. // Restoring non existing folder fails.
  2255. _, err = m.RestoreFolderVersions("does not exist", nil)
  2256. if err == nil {
  2257. t.Errorf("expected an error")
  2258. }
  2259. makeTime := func(s string) time.Time {
  2260. tm, err := time.ParseInLocation(versioner.TimeFormat, s, time.Local)
  2261. if err != nil {
  2262. t.Error(err)
  2263. }
  2264. return tm.Truncate(time.Second)
  2265. }
  2266. restore := map[string]time.Time{
  2267. "file.txt": makeTime("20171210-040404"),
  2268. "existing": makeTime("20171210-040404"),
  2269. "something": makeTime("20171210-040404"),
  2270. "dir/file.txt": makeTime("20171210-040406"),
  2271. "dir/existing.txt": makeTime("20171210-040406"),
  2272. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2273. }
  2274. beforeRestore := time.Now().Truncate(time.Second)
  2275. ferr, err := m.RestoreFolderVersions("default", restore)
  2276. must(t, err)
  2277. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || !errors.Is(err, versioner.ErrDirectory) {
  2278. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2279. }
  2280. // Failed items are not expected to be restored.
  2281. // Remove them from expectations
  2282. for name := range ferr {
  2283. delete(restore, name)
  2284. }
  2285. // Check that content of files matches to the version they've been restored.
  2286. for file, version := range restore {
  2287. if build.IsWindows {
  2288. file = filepath.FromSlash(file)
  2289. }
  2290. tag := version.In(time.Local).Truncate(time.Second).Format(versioner.TimeFormat)
  2291. taggedName := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2292. fd, err := filesystem.Open(file)
  2293. if err != nil {
  2294. t.Error(err)
  2295. }
  2296. defer fd.Close()
  2297. content, err := io.ReadAll(fd)
  2298. if err != nil {
  2299. t.Error(err)
  2300. }
  2301. if !bytes.Equal(content, []byte(taggedName)) {
  2302. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2303. }
  2304. }
  2305. // Simple versioner uses now for timestamp generation, so we can check
  2306. // if existing stuff was correctly archived as we restored (oppose to deleteD), and version time as after beforeRestore
  2307. expectArchived := map[string]struct{}{
  2308. "existing": {},
  2309. "dir/file.txt": {},
  2310. "dir/existing.txt": {},
  2311. }
  2312. allFileVersions, err := m.GetFolderVersions("default")
  2313. must(t, err)
  2314. for file, versions := range allFileVersions {
  2315. key := file
  2316. if build.IsWindows {
  2317. file = filepath.FromSlash(file)
  2318. }
  2319. for _, version := range versions {
  2320. if version.VersionTime.Equal(beforeRestore) || version.VersionTime.After(beforeRestore) {
  2321. fd, err := filesystem.Open(".stversions/" + versioner.TagFilename(file, version.VersionTime.Format(versioner.TimeFormat)))
  2322. must(t, err)
  2323. defer fd.Close()
  2324. content, err := io.ReadAll(fd)
  2325. if err != nil {
  2326. t.Error(err)
  2327. }
  2328. // Even if they are at the archived path, content should have the non
  2329. // archived name.
  2330. if !bytes.Equal(content, []byte(file)) {
  2331. t.Errorf("%s (%s): %s != %s", file, fd.Name(), string(content), file)
  2332. }
  2333. _, ok := expectArchived[key]
  2334. if !ok {
  2335. t.Error("unexpected archived file with future timestamp", file, version.VersionTime)
  2336. }
  2337. delete(expectArchived, key)
  2338. }
  2339. }
  2340. }
  2341. if len(expectArchived) != 0 {
  2342. t.Fatal("missed some archived files", expectArchived)
  2343. }
  2344. }
  2345. func TestPausedFolders(t *testing.T) {
  2346. // Create a separate wrapper not to pollute other tests.
  2347. wrapper, cancel := newConfigWrapper(defaultCfgWrapper.RawCopy())
  2348. defer cancel()
  2349. m := setupModel(t, wrapper)
  2350. defer cleanupModel(m)
  2351. if err := m.ScanFolder("default"); err != nil {
  2352. t.Error(err)
  2353. }
  2354. pausedConfig := wrapper.RawCopy()
  2355. pausedConfig.Folders[0].Paused = true
  2356. replace(t, wrapper, pausedConfig)
  2357. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2358. t.Errorf("Expected folder paused error, received: %v", err)
  2359. }
  2360. if err := m.ScanFolder("nonexistent"); err != ErrFolderMissing {
  2361. t.Errorf("Expected missing folder error, received: %v", err)
  2362. }
  2363. }
  2364. func TestIssue4094(t *testing.T) {
  2365. // Create a separate wrapper not to pollute other tests.
  2366. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2367. defer cancel()
  2368. m := newModel(t, wrapper, myID, "syncthing", "dev", nil)
  2369. m.ServeBackground()
  2370. defer cleanupModel(m)
  2371. // Force the model to wire itself and add the folders
  2372. folderPath := "nonexistent"
  2373. cfg := defaultCfgWrapper.RawCopy()
  2374. fcfg := config.FolderConfiguration{
  2375. FilesystemType: fs.FilesystemTypeFake,
  2376. ID: "folder1",
  2377. Path: folderPath,
  2378. Paused: true,
  2379. Devices: []config.FolderDeviceConfiguration{
  2380. {DeviceID: device1},
  2381. },
  2382. }
  2383. cfg.Folders = []config.FolderConfiguration{fcfg}
  2384. replace(t, wrapper, cfg)
  2385. if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
  2386. t.Fatalf("failed setting ignores: %v", err)
  2387. }
  2388. if _, err := fcfg.Filesystem(nil).Lstat(".stignore"); err != nil {
  2389. t.Fatalf("failed stating .stignore: %v", err)
  2390. }
  2391. }
  2392. func TestIssue4903(t *testing.T) {
  2393. wrapper, cancel := newConfigWrapper(config.Configuration{Version: config.CurrentVersion})
  2394. defer cancel()
  2395. m := setupModel(t, wrapper)
  2396. defer cleanupModel(m)
  2397. // Force the model to wire itself and add the folders
  2398. folderPath := "nonexistent"
  2399. cfg := defaultCfgWrapper.RawCopy()
  2400. fcfg := config.FolderConfiguration{
  2401. ID: "folder1",
  2402. Path: folderPath,
  2403. Paused: true,
  2404. Devices: []config.FolderDeviceConfiguration{
  2405. {DeviceID: device1},
  2406. },
  2407. }
  2408. cfg.Folders = []config.FolderConfiguration{fcfg}
  2409. replace(t, wrapper, cfg)
  2410. if err := fcfg.CheckPath(); err != config.ErrPathMissing {
  2411. t.Fatalf("expected path missing error, got: %v, debug: %s", err, fcfg.CheckPath())
  2412. }
  2413. if _, err := fcfg.Filesystem(nil).Lstat("."); !fs.IsNotExist(err) {
  2414. t.Fatalf("Expected missing path error, got: %v", err)
  2415. }
  2416. }
  2417. func TestIssue5002(t *testing.T) {
  2418. // recheckFile should not panic when given an index equal to the number of blocks
  2419. w, fcfg, wCancel := newDefaultCfgWrapper()
  2420. defer wCancel()
  2421. ffs := fcfg.Filesystem(nil)
  2422. fd, err := ffs.Create("foo")
  2423. must(t, err)
  2424. _, err = fd.Write([]byte("foobar"))
  2425. must(t, err)
  2426. fd.Close()
  2427. m := setupModel(t, w)
  2428. defer cleanupModel(m)
  2429. if err := m.ScanFolder("default"); err != nil {
  2430. t.Error(err)
  2431. }
  2432. file, ok := m.testCurrentFolderFile("default", "foo")
  2433. if !ok {
  2434. t.Fatal("test file should exist")
  2435. }
  2436. blockSize := int32(file.BlockSize())
  2437. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size-int64(blockSize), []byte{1, 2, 3, 4}, 0)
  2438. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size, []byte{1, 2, 3, 4}, 0) // panic
  2439. m.recheckFile(protocol.LocalDeviceID, "default", "foo", file.Size+int64(blockSize), []byte{1, 2, 3, 4}, 0)
  2440. }
  2441. func TestParentOfUnignored(t *testing.T) {
  2442. w, fcfg, wCancel := newDefaultCfgWrapper()
  2443. defer wCancel()
  2444. ffs := fcfg.Filesystem(nil)
  2445. must(t, ffs.Mkdir("bar", 0o755))
  2446. must(t, ffs.Mkdir("baz", 0o755))
  2447. must(t, ffs.Mkdir("baz/quux", 0o755))
  2448. m := setupModel(t, w)
  2449. defer cleanupModel(m)
  2450. m.SetIgnores("default", []string{"!quux", "*"})
  2451. m.ScanFolder("default")
  2452. if bar, ok := m.testCurrentFolderFile("default", "bar"); !ok {
  2453. t.Error(`Directory "bar" missing in db`)
  2454. } else if !bar.IsIgnored() {
  2455. t.Error(`Directory "bar" is not ignored`)
  2456. }
  2457. if baz, ok := m.testCurrentFolderFile("default", "baz"); !ok {
  2458. t.Error(`Directory "baz" missing in db`)
  2459. } else if baz.IsIgnored() {
  2460. t.Error(`Directory "baz" is ignored`)
  2461. }
  2462. }
  2463. // TestFolderRestartZombies reproduces issue 5233, where multiple concurrent folder
  2464. // restarts would leave more than one folder runner alive.
  2465. func TestFolderRestartZombies(t *testing.T) {
  2466. wrapper, cancel := newConfigWrapper(defaultCfg.Copy())
  2467. defer cancel()
  2468. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2469. cfg.Options.RawMaxFolderConcurrency = -1
  2470. _, i, _ := cfg.Folder("default")
  2471. cfg.Folders[i].FilesystemType = fs.FilesystemTypeFake
  2472. })
  2473. must(t, err)
  2474. waiter.Wait()
  2475. folderCfg, _ := wrapper.Folder("default")
  2476. m := setupModel(t, wrapper)
  2477. defer cleanupModel(m)
  2478. // Make sure the folder is up and running, because we want to count it.
  2479. m.ScanFolder("default")
  2480. // Check how many running folders we have running before the test.
  2481. if r := m.foldersRunning.Load(); r != 1 {
  2482. t.Error("Expected one running folder, not", r)
  2483. }
  2484. // Run a few parallel configuration changers for one second. Each waits
  2485. // for the commit to complete, but there are many of them.
  2486. var wg sync.WaitGroup
  2487. for i := 0; i < 25; i++ {
  2488. wg.Add(1)
  2489. go func() {
  2490. defer wg.Done()
  2491. t0 := time.Now()
  2492. for time.Since(t0) < time.Second {
  2493. fcfg := folderCfg.Copy()
  2494. fcfg.MaxConflicts = mrand.Int() // safe change that should cause a folder restart
  2495. setFolder(t, wrapper, fcfg)
  2496. }
  2497. }()
  2498. }
  2499. // Wait for the above to complete and check how many folders we have
  2500. // running now. It should not have increased.
  2501. wg.Wait()
  2502. // Make sure the folder is up and running, because we want to count it.
  2503. m.ScanFolder("default")
  2504. if r := m.foldersRunning.Load(); r != 1 {
  2505. t.Error("Expected one running folder, not", r)
  2506. }
  2507. }
  2508. func TestRequestLimit(t *testing.T) {
  2509. wrapper, fcfg, cancel := newDefaultCfgWrapper()
  2510. ffs := fcfg.Filesystem(nil)
  2511. file := "tmpfile"
  2512. fd, err := ffs.Create(file)
  2513. must(t, err)
  2514. fd.Close()
  2515. defer cancel()
  2516. waiter, err := wrapper.Modify(func(cfg *config.Configuration) {
  2517. _, i, _ := cfg.Device(device1)
  2518. cfg.Devices[i].MaxRequestKiB = 1
  2519. })
  2520. must(t, err)
  2521. waiter.Wait()
  2522. m, conn := setupModelWithConnectionFromWrapper(t, wrapper)
  2523. defer cleanupModel(m)
  2524. m.ScanFolder("default")
  2525. befReq := time.Now()
  2526. first, err := m.Request(conn, "default", file, 0, 2000, 0, nil, 0, false)
  2527. if err != nil {
  2528. t.Fatalf("First request failed: %v", err)
  2529. }
  2530. reqDur := time.Since(befReq)
  2531. returned := make(chan struct{})
  2532. go func() {
  2533. second, err := m.Request(conn, "default", file, 0, 2000, 0, nil, 0, false)
  2534. if err != nil {
  2535. t.Errorf("Second request failed: %v", err)
  2536. }
  2537. close(returned)
  2538. second.Close()
  2539. }()
  2540. time.Sleep(10 * reqDur)
  2541. select {
  2542. case <-returned:
  2543. t.Fatalf("Second request returned before first was done")
  2544. default:
  2545. }
  2546. first.Close()
  2547. select {
  2548. case <-returned:
  2549. case <-time.After(time.Second):
  2550. t.Fatalf("Second request did not return after first was done")
  2551. }
  2552. }
  2553. // TestConnCloseOnRestart checks that there is no deadlock when calling Close
  2554. // on a protocol connection that has a blocking reader (blocking writer can't
  2555. // be done as the test requires clusterconfigs to go through).
  2556. func TestConnCloseOnRestart(t *testing.T) {
  2557. oldCloseTimeout := protocol.CloseTimeout
  2558. protocol.CloseTimeout = 100 * time.Millisecond
  2559. defer func() {
  2560. protocol.CloseTimeout = oldCloseTimeout
  2561. }()
  2562. w, fcfg, wCancel := newDefaultCfgWrapper()
  2563. defer wCancel()
  2564. m := setupModel(t, w)
  2565. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2566. br := &testutils.BlockingRW{}
  2567. nw := &testutils.NoopRW{}
  2568. ci := &protocolmocks.ConnectionInfo{}
  2569. m.AddConnection(protocol.NewConnection(device1, br, nw, testutils.NoopCloser{}, m, ci, protocol.CompressionNever, nil, m.keyGen), protocol.Hello{})
  2570. m.pmut.RLock()
  2571. if len(m.closed) != 1 {
  2572. t.Fatalf("Expected just one conn (len(m.closed) == %v)", len(m.closed))
  2573. }
  2574. var closed chan struct{}
  2575. for _, c := range m.closed {
  2576. closed = c
  2577. }
  2578. m.pmut.RUnlock()
  2579. waiter, err := w.RemoveDevice(device1)
  2580. if err != nil {
  2581. t.Fatal(err)
  2582. }
  2583. done := make(chan struct{})
  2584. go func() {
  2585. waiter.Wait()
  2586. close(done)
  2587. }()
  2588. select {
  2589. case <-done:
  2590. case <-time.After(5 * time.Second):
  2591. t.Fatal("Timed out before config took effect")
  2592. }
  2593. select {
  2594. case <-closed:
  2595. case <-time.After(5 * time.Second):
  2596. t.Fatal("Timed out before connection was closed")
  2597. }
  2598. }
  2599. func TestModTimeWindow(t *testing.T) {
  2600. w, fcfg, wCancel := newDefaultCfgWrapper()
  2601. defer wCancel()
  2602. tfs := modtimeTruncatingFS{
  2603. trunc: 0,
  2604. Filesystem: fcfg.Filesystem(nil),
  2605. }
  2606. // fcfg.RawModTimeWindowS = 2
  2607. setFolder(t, w, fcfg)
  2608. m := setupModel(t, w)
  2609. defer cleanupModelAndRemoveDir(m, tfs.URI())
  2610. name := "foo"
  2611. fd, err := tfs.Create(name)
  2612. must(t, err)
  2613. stat, err := fd.Stat()
  2614. must(t, err)
  2615. modTime := stat.ModTime()
  2616. fd.Close()
  2617. m.ScanFolders()
  2618. // Get current version
  2619. fi, ok := m.testCurrentFolderFile("default", name)
  2620. if !ok {
  2621. t.Fatal("File missing")
  2622. }
  2623. v := fi.Version
  2624. // Change the filesystem to only return modtimes to the closest two
  2625. // seconds, like FAT.
  2626. tfs.trunc = 2 * time.Second
  2627. // Scan again
  2628. m.ScanFolders()
  2629. // No change due to within window
  2630. fi, _ = m.testCurrentFolderFile("default", name)
  2631. if !fi.Version.Equal(v) {
  2632. t.Fatalf("Got version %v, expected %v", fi.Version, v)
  2633. }
  2634. // Update to be outside window
  2635. err = tfs.Chtimes(name, time.Now(), modTime.Add(2*time.Second))
  2636. must(t, err)
  2637. m.ScanFolders()
  2638. // Version should have updated
  2639. fi, _ = m.testCurrentFolderFile("default", name)
  2640. if fi.Version.Compare(v) != protocol.Greater {
  2641. t.Fatalf("Got result %v, expected %v", fi.Version.Compare(v), protocol.Greater)
  2642. }
  2643. }
  2644. func TestDevicePause(t *testing.T) {
  2645. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2646. defer wcfgCancel()
  2647. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2648. sub := m.evLogger.Subscribe(events.DevicePaused)
  2649. defer sub.Unsubscribe()
  2650. m.pmut.RLock()
  2651. var closed chan struct{}
  2652. for _, c := range m.closed {
  2653. closed = c
  2654. }
  2655. m.pmut.RUnlock()
  2656. pauseDevice(t, m.cfg, device1, true)
  2657. timeout := time.NewTimer(5 * time.Second)
  2658. select {
  2659. case <-sub.C():
  2660. select {
  2661. case <-closed:
  2662. case <-timeout.C:
  2663. t.Fatal("Timed out before connection was closed")
  2664. }
  2665. case <-timeout.C:
  2666. t.Fatal("Timed out before device was paused")
  2667. }
  2668. }
  2669. func TestDeviceWasSeen(t *testing.T) {
  2670. m, _, fcfg, wcfgCancel := setupModelWithConnection(t)
  2671. defer wcfgCancel()
  2672. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  2673. m.deviceWasSeen(device1)
  2674. stats, err := m.DeviceStatistics()
  2675. if err != nil {
  2676. t.Error("Unexpected error:", err)
  2677. }
  2678. entry := stats[device1]
  2679. if time.Since(entry.LastSeen) > time.Second {
  2680. t.Error("device should have been seen now")
  2681. }
  2682. }
  2683. func TestNewLimitedRequestResponse(t *testing.T) {
  2684. l0 := util.NewSemaphore(0)
  2685. l1 := util.NewSemaphore(1024)
  2686. l2 := (*util.Semaphore)(nil)
  2687. // Should take 500 bytes from any non-unlimited non-nil limiters.
  2688. res := newLimitedRequestResponse(500, l0, l1, l2)
  2689. if l1.Available() != 1024-500 {
  2690. t.Error("should have taken bytes from limited limiter")
  2691. }
  2692. // Closing the result should return the bytes.
  2693. res.Close()
  2694. // Try to take 1024 bytes to make sure the bytes were returned.
  2695. done := make(chan struct{})
  2696. go func() {
  2697. l1.Take(1024)
  2698. close(done)
  2699. }()
  2700. select {
  2701. case <-done:
  2702. case <-time.After(time.Second):
  2703. t.Error("Bytes weren't returned in a timely fashion")
  2704. }
  2705. }
  2706. func TestSummaryPausedNoError(t *testing.T) {
  2707. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2708. defer wcfgCancel()
  2709. pauseFolder(t, wcfg, fcfg.ID, true)
  2710. m := setupModel(t, wcfg)
  2711. defer cleanupModel(m)
  2712. fss := NewFolderSummaryService(wcfg, m, myID, events.NoopLogger)
  2713. if _, err := fss.Summary(fcfg.ID); err != nil {
  2714. t.Error("Expected no error getting a summary for a paused folder:", err)
  2715. }
  2716. }
  2717. func TestFolderAPIErrors(t *testing.T) {
  2718. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2719. defer wcfgCancel()
  2720. pauseFolder(t, wcfg, fcfg.ID, true)
  2721. m := setupModel(t, wcfg)
  2722. defer cleanupModel(m)
  2723. methods := []func(folder string) error{
  2724. m.ScanFolder,
  2725. func(folder string) error {
  2726. return m.ScanFolderSubdirs(folder, nil)
  2727. },
  2728. func(folder string) error {
  2729. _, err := m.GetFolderVersions(folder)
  2730. return err
  2731. },
  2732. func(folder string) error {
  2733. _, err := m.RestoreFolderVersions(folder, nil)
  2734. return err
  2735. },
  2736. }
  2737. for i, method := range methods {
  2738. if err := method(fcfg.ID); err != ErrFolderPaused {
  2739. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderPaused, err, i)
  2740. }
  2741. if err := method("notexisting"); err != ErrFolderMissing {
  2742. t.Errorf(`Expected "%v", got "%v" (method no %v)`, ErrFolderMissing, err, i)
  2743. }
  2744. }
  2745. }
  2746. func TestRenameSequenceOrder(t *testing.T) {
  2747. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2748. defer wcfgCancel()
  2749. m := setupModel(t, wcfg)
  2750. defer cleanupModel(m)
  2751. numFiles := 20
  2752. ffs := fcfg.Filesystem(nil)
  2753. for i := 0; i < numFiles; i++ {
  2754. v := fmt.Sprintf("%d", i)
  2755. writeFile(t, ffs, v, []byte(v))
  2756. }
  2757. m.ScanFolders()
  2758. count := 0
  2759. snap := dbSnapshot(t, m, "default")
  2760. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  2761. count++
  2762. return true
  2763. })
  2764. snap.Release()
  2765. if count != numFiles {
  2766. t.Errorf("Unexpected count: %d != %d", count, numFiles)
  2767. }
  2768. // Modify all the files, other than the ones we expect to rename
  2769. for i := 0; i < numFiles; i++ {
  2770. if i == 3 || i == 17 || i == 16 || i == 4 {
  2771. continue
  2772. }
  2773. v := fmt.Sprintf("%d", i)
  2774. writeFile(t, ffs, v, []byte(v+"-new"))
  2775. }
  2776. // Rename
  2777. must(t, ffs.Rename("3", "17"))
  2778. must(t, ffs.Rename("16", "4"))
  2779. // Scan
  2780. m.ScanFolders()
  2781. // Verify sequence of a appearing is followed by c disappearing.
  2782. snap = dbSnapshot(t, m, "default")
  2783. defer snap.Release()
  2784. var firstExpectedSequence int64
  2785. var secondExpectedSequence int64
  2786. failed := false
  2787. snap.WithHaveSequence(0, func(i protocol.FileIntf) bool {
  2788. t.Log(i)
  2789. if i.FileName() == "17" {
  2790. firstExpectedSequence = i.SequenceNo() + 1
  2791. }
  2792. if i.FileName() == "4" {
  2793. secondExpectedSequence = i.SequenceNo() + 1
  2794. }
  2795. if i.FileName() == "3" {
  2796. failed = i.SequenceNo() != firstExpectedSequence || failed
  2797. }
  2798. if i.FileName() == "16" {
  2799. failed = i.SequenceNo() != secondExpectedSequence || failed
  2800. }
  2801. return true
  2802. })
  2803. if failed {
  2804. t.Fail()
  2805. }
  2806. }
  2807. func TestRenameSameFile(t *testing.T) {
  2808. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2809. defer wcfgCancel()
  2810. m := setupModel(t, wcfg)
  2811. defer cleanupModel(m)
  2812. ffs := fcfg.Filesystem(nil)
  2813. writeFile(t, ffs, "file", []byte("file"))
  2814. m.ScanFolders()
  2815. count := 0
  2816. snap := dbSnapshot(t, m, "default")
  2817. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  2818. count++
  2819. return true
  2820. })
  2821. snap.Release()
  2822. if count != 1 {
  2823. t.Errorf("Unexpected count: %d != %d", count, 1)
  2824. }
  2825. must(t, ffs.Rename("file", "file1"))
  2826. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file0"))
  2827. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file2"))
  2828. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file3"))
  2829. must(t, osutil.Copy(fs.CopyRangeMethodStandard, ffs, ffs, "file1", "file4"))
  2830. m.ScanFolders()
  2831. snap = dbSnapshot(t, m, "default")
  2832. defer snap.Release()
  2833. prevSeq := int64(0)
  2834. seen := false
  2835. snap.WithHaveSequence(0, func(i protocol.FileIntf) bool {
  2836. if i.SequenceNo() <= prevSeq {
  2837. t.Fatalf("non-increasing sequences: %d <= %d", i.SequenceNo(), prevSeq)
  2838. }
  2839. if i.FileName() == "file" {
  2840. if seen {
  2841. t.Fatal("already seen file")
  2842. }
  2843. seen = true
  2844. }
  2845. prevSeq = i.SequenceNo()
  2846. return true
  2847. })
  2848. }
  2849. func TestRenameEmptyFile(t *testing.T) {
  2850. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2851. defer wcfgCancel()
  2852. m := setupModel(t, wcfg)
  2853. defer cleanupModel(m)
  2854. ffs := fcfg.Filesystem(nil)
  2855. writeFile(t, ffs, "file", []byte("data"))
  2856. writeFile(t, ffs, "empty", nil)
  2857. m.ScanFolders()
  2858. snap := dbSnapshot(t, m, "default")
  2859. defer snap.Release()
  2860. empty, eok := snap.Get(protocol.LocalDeviceID, "empty")
  2861. if !eok {
  2862. t.Fatal("failed to find empty file")
  2863. }
  2864. file, fok := snap.Get(protocol.LocalDeviceID, "file")
  2865. if !fok {
  2866. t.Fatal("failed to find non-empty file")
  2867. }
  2868. count := 0
  2869. snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileIntf) bool {
  2870. count++
  2871. return true
  2872. })
  2873. if count != 0 {
  2874. t.Fatalf("Found %d entries for empty file, expected 0", count)
  2875. }
  2876. count = 0
  2877. snap.WithBlocksHash(file.BlocksHash, func(_ protocol.FileIntf) bool {
  2878. count++
  2879. return true
  2880. })
  2881. if count != 1 {
  2882. t.Fatalf("Found %d entries for non-empty file, expected 1", count)
  2883. }
  2884. must(t, ffs.Rename("file", "new-file"))
  2885. must(t, ffs.Rename("empty", "new-empty"))
  2886. // Scan
  2887. m.ScanFolders()
  2888. snap = dbSnapshot(t, m, "default")
  2889. defer snap.Release()
  2890. count = 0
  2891. snap.WithBlocksHash(empty.BlocksHash, func(_ protocol.FileIntf) bool {
  2892. count++
  2893. return true
  2894. })
  2895. if count != 0 {
  2896. t.Fatalf("Found %d entries for empty file, expected 0", count)
  2897. }
  2898. count = 0
  2899. snap.WithBlocksHash(file.BlocksHash, func(i protocol.FileIntf) bool {
  2900. count++
  2901. if i.FileName() != "new-file" {
  2902. t.Fatalf("unexpected file name %s, expected new-file", i.FileName())
  2903. }
  2904. return true
  2905. })
  2906. if count != 1 {
  2907. t.Fatalf("Found %d entries for non-empty file, expected 1", count)
  2908. }
  2909. }
  2910. func TestBlockListMap(t *testing.T) {
  2911. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2912. defer wcfgCancel()
  2913. m := setupModel(t, wcfg)
  2914. defer cleanupModel(m)
  2915. ffs := fcfg.Filesystem(nil)
  2916. writeFile(t, ffs, "one", []byte("content"))
  2917. writeFile(t, ffs, "two", []byte("content"))
  2918. writeFile(t, ffs, "three", []byte("content"))
  2919. writeFile(t, ffs, "four", []byte("content"))
  2920. writeFile(t, ffs, "five", []byte("content"))
  2921. m.ScanFolders()
  2922. snap := dbSnapshot(t, m, "default")
  2923. defer snap.Release()
  2924. fi, ok := snap.Get(protocol.LocalDeviceID, "one")
  2925. if !ok {
  2926. t.Error("failed to find existing file")
  2927. }
  2928. var paths []string
  2929. snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileIntf) bool {
  2930. paths = append(paths, fi.FileName())
  2931. return true
  2932. })
  2933. snap.Release()
  2934. expected := []string{"one", "two", "three", "four", "five"}
  2935. if !equalStringsInAnyOrder(paths, expected) {
  2936. t.Errorf("expected %q got %q", expected, paths)
  2937. }
  2938. // Fudge the files around
  2939. // Remove
  2940. must(t, ffs.Remove("one"))
  2941. // Modify
  2942. must(t, ffs.Remove("two"))
  2943. writeFile(t, ffs, "two", []byte("mew-content"))
  2944. // Rename
  2945. must(t, ffs.Rename("three", "new-three"))
  2946. // Change type
  2947. must(t, ffs.Remove("four"))
  2948. must(t, ffs.Mkdir("four", 0o644))
  2949. m.ScanFolders()
  2950. // Check we're left with 2 of the 5
  2951. snap = dbSnapshot(t, m, "default")
  2952. defer snap.Release()
  2953. paths = paths[:0]
  2954. snap.WithBlocksHash(fi.BlocksHash, func(fi protocol.FileIntf) bool {
  2955. paths = append(paths, fi.FileName())
  2956. return true
  2957. })
  2958. snap.Release()
  2959. expected = []string{"new-three", "five"}
  2960. if !equalStringsInAnyOrder(paths, expected) {
  2961. t.Errorf("expected %q got %q", expected, paths)
  2962. }
  2963. }
  2964. func TestScanRenameCaseOnly(t *testing.T) {
  2965. wcfg, fcfg, wcfgCancel := newDefaultCfgWrapper()
  2966. defer wcfgCancel()
  2967. m := setupModel(t, wcfg)
  2968. defer cleanupModel(m)
  2969. ffs := fcfg.Filesystem(nil)
  2970. name := "foo"
  2971. writeFile(t, ffs, name, []byte("contents"))
  2972. m.ScanFolders()
  2973. snap := dbSnapshot(t, m, fcfg.ID)
  2974. defer snap.Release()
  2975. found := false
  2976. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  2977. if found {
  2978. t.Fatal("got more than one file")
  2979. }
  2980. if i.FileName() != name {
  2981. t.Fatalf("got file %v, expected %v", i.FileName(), name)
  2982. }
  2983. found = true
  2984. return true
  2985. })
  2986. snap.Release()
  2987. upper := strings.ToUpper(name)
  2988. must(t, ffs.Rename(name, upper))
  2989. m.ScanFolders()
  2990. snap = dbSnapshot(t, m, fcfg.ID)
  2991. defer snap.Release()
  2992. found = false
  2993. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  2994. if i.FileName() == name {
  2995. if i.IsDeleted() {
  2996. return true
  2997. }
  2998. t.Fatal("renamed file not deleted")
  2999. }
  3000. if i.FileName() != upper {
  3001. t.Fatalf("got file %v, expected %v", i.FileName(), upper)
  3002. }
  3003. if found {
  3004. t.Fatal("got more than the expected files")
  3005. }
  3006. found = true
  3007. return true
  3008. })
  3009. }
  3010. func TestClusterConfigOnFolderAdd(t *testing.T) {
  3011. testConfigChangeTriggersClusterConfigs(t, false, true, nil, func(wrapper config.Wrapper) {
  3012. fcfg := newFolderConfig()
  3013. fcfg.ID = "second"
  3014. fcfg.Label = "second"
  3015. fcfg.Devices = []config.FolderDeviceConfiguration{{
  3016. DeviceID: device2,
  3017. IntroducedBy: protocol.EmptyDeviceID,
  3018. }}
  3019. setFolder(t, wrapper, fcfg)
  3020. })
  3021. }
  3022. func TestClusterConfigOnFolderShare(t *testing.T) {
  3023. testConfigChangeTriggersClusterConfigs(t, true, true, nil, func(cfg config.Wrapper) {
  3024. fcfg := cfg.FolderList()[0]
  3025. fcfg.Devices = []config.FolderDeviceConfiguration{{
  3026. DeviceID: device2,
  3027. IntroducedBy: protocol.EmptyDeviceID,
  3028. }}
  3029. setFolder(t, cfg, fcfg)
  3030. })
  3031. }
  3032. func TestClusterConfigOnFolderUnshare(t *testing.T) {
  3033. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3034. fcfg := cfg.FolderList()[0]
  3035. fcfg.Devices = nil
  3036. setFolder(t, cfg, fcfg)
  3037. })
  3038. }
  3039. func TestClusterConfigOnFolderRemove(t *testing.T) {
  3040. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3041. rcfg := cfg.RawCopy()
  3042. rcfg.Folders = nil
  3043. replace(t, cfg, rcfg)
  3044. })
  3045. }
  3046. func TestClusterConfigOnFolderPause(t *testing.T) {
  3047. testConfigChangeTriggersClusterConfigs(t, true, false, nil, func(cfg config.Wrapper) {
  3048. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  3049. })
  3050. }
  3051. func TestClusterConfigOnFolderUnpause(t *testing.T) {
  3052. testConfigChangeTriggersClusterConfigs(t, true, false, func(cfg config.Wrapper) {
  3053. pauseFolder(t, cfg, cfg.FolderList()[0].ID, true)
  3054. }, func(cfg config.Wrapper) {
  3055. pauseFolder(t, cfg, cfg.FolderList()[0].ID, false)
  3056. })
  3057. }
  3058. func TestAddFolderCompletion(t *testing.T) {
  3059. // Empty folders are always 100% complete.
  3060. comp := newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderValid)
  3061. comp.add(newFolderCompletion(db.Counts{}, db.Counts{}, 0, remoteFolderPaused))
  3062. if comp.CompletionPct != 100 {
  3063. t.Error(comp.CompletionPct)
  3064. }
  3065. // Completion is of the whole
  3066. comp = newFolderCompletion(db.Counts{Bytes: 100}, db.Counts{}, 0, remoteFolderValid) // 100% complete
  3067. comp.add(newFolderCompletion(db.Counts{Bytes: 400}, db.Counts{Bytes: 50}, 0, remoteFolderValid)) // 82.5% complete
  3068. if comp.CompletionPct != 90 { // 100 * (1 - 50/500)
  3069. t.Error(comp.CompletionPct)
  3070. }
  3071. }
  3072. func TestScanDeletedROChangedOnSR(t *testing.T) {
  3073. m, conn, fcfg, wCancel := setupModelWithConnection(t)
  3074. ffs := fcfg.Filesystem(nil)
  3075. defer wCancel()
  3076. defer cleanupModelAndRemoveDir(m, ffs.URI())
  3077. fcfg.Type = config.FolderTypeReceiveOnly
  3078. setFolder(t, m.cfg, fcfg)
  3079. name := "foo"
  3080. writeFile(t, ffs, name, []byte(name))
  3081. m.ScanFolders()
  3082. file, ok := m.testCurrentFolderFile(fcfg.ID, name)
  3083. if !ok {
  3084. t.Fatal("file missing in db")
  3085. }
  3086. // A remote must have the file, otherwise the deletion below is
  3087. // automatically resolved as not a ro-changed item.
  3088. must(t, m.IndexUpdate(conn, fcfg.ID, []protocol.FileInfo{file}))
  3089. must(t, ffs.Remove(name))
  3090. m.ScanFolders()
  3091. if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 1 {
  3092. t.Fatal("expected one receive only changed deleted item")
  3093. }
  3094. fcfg.Type = config.FolderTypeSendReceive
  3095. setFolder(t, m.cfg, fcfg)
  3096. m.ScanFolders()
  3097. if receiveOnlyChangedSize(t, m, fcfg.ID).Deleted != 0 {
  3098. t.Fatal("expected no receive only changed deleted item")
  3099. }
  3100. if localSize(t, m, fcfg.ID).Deleted != 1 {
  3101. t.Fatal("expected one local deleted item")
  3102. }
  3103. }
  3104. func testConfigChangeTriggersClusterConfigs(t *testing.T, expectFirst, expectSecond bool, pre func(config.Wrapper), fn func(config.Wrapper)) {
  3105. t.Helper()
  3106. wcfg, _, wcfgCancel := newDefaultCfgWrapper()
  3107. defer wcfgCancel()
  3108. m := setupModel(t, wcfg)
  3109. defer cleanupModel(m)
  3110. setDevice(t, wcfg, newDeviceConfiguration(wcfg.DefaultDevice(), device2, "device2"))
  3111. if pre != nil {
  3112. pre(wcfg)
  3113. }
  3114. cc1 := make(chan struct{}, 1)
  3115. cc2 := make(chan struct{}, 1)
  3116. fc1 := newFakeConnection(device1, m)
  3117. fc1.ClusterConfigCalls(func(_ protocol.ClusterConfig) {
  3118. cc1 <- struct{}{}
  3119. })
  3120. fc2 := newFakeConnection(device2, m)
  3121. fc2.ClusterConfigCalls(func(_ protocol.ClusterConfig) {
  3122. cc2 <- struct{}{}
  3123. })
  3124. m.AddConnection(fc1, protocol.Hello{})
  3125. m.AddConnection(fc2, protocol.Hello{})
  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, "syncthing", "dev", 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, fcfg.ID, []protocol.FileInfo{{Name: name, Version: version, Sequence: 1}}))
  3187. // Remote, invalid (receive-only) and existing file
  3188. must(t, m.Index(conn2, fcfg.ID, []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, fcfg.ID, []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.fmut.Lock()
  3227. m.folderFiles[fcfg.ID].Update(protocol.LocalDeviceID, files)
  3228. m.fmut.Unlock()
  3229. files[0].Deleted = true
  3230. files[0].Version = files[0].Version.Update(device1.Short())
  3231. must(t, m.IndexUpdate(conn, fcfg.ID, 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, fcfg.ID, files))
  3250. must(t, m.Index(conn2, fcfg.ID, files))
  3251. seq++
  3252. files[0].SetDeleted(device2.Short())
  3253. files[0].Sequence = seq
  3254. must(t, m.IndexUpdate(conn1, fcfg.ID, files))
  3255. must(t, m.IndexUpdate(conn2, fcfg.ID, 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, fcfg.ID, 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, fcfg.ID, 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, "syncthing", "dev", 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. sort.Strings(a)
  3538. sort.Strings(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. }