model_test.go 98 KB

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