model_test.go 109 KB

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