model_test.go 99 KB

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