model_test.go 113 KB

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