model_test.go 113 KB

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