model_test.go 114 KB

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