model_test.go 101 KB

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