model_test.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565
  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. "sync"
  20. "testing"
  21. "time"
  22. "github.com/d4l3k/messagediff"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/db"
  25. "github.com/syncthing/syncthing/lib/fs"
  26. "github.com/syncthing/syncthing/lib/ignore"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. srand "github.com/syncthing/syncthing/lib/rand"
  29. "github.com/syncthing/syncthing/lib/scanner"
  30. )
  31. var device1, device2 protocol.DeviceID
  32. var defaultConfig *config.Wrapper
  33. var defaultFolderConfig config.FolderConfiguration
  34. var defaultFs fs.Filesystem
  35. func init() {
  36. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  37. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  38. defaultFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  39. defaultFolderConfig = config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  40. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  41. _defaultConfig := config.Configuration{
  42. Folders: []config.FolderConfiguration{defaultFolderConfig},
  43. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  44. Options: config.OptionsConfiguration{
  45. // Don't remove temporaries directly on startup
  46. KeepTemporariesH: 1,
  47. },
  48. }
  49. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  50. }
  51. var testDataExpected = map[string]protocol.FileInfo{
  52. "foo": {
  53. Name: "foo",
  54. Type: protocol.FileInfoTypeFile,
  55. ModifiedS: 0,
  56. 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}}},
  57. },
  58. "empty": {
  59. Name: "empty",
  60. Type: protocol.FileInfoTypeFile,
  61. ModifiedS: 0,
  62. 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}}},
  63. },
  64. "bar": {
  65. Name: "bar",
  66. Type: protocol.FileInfoTypeFile,
  67. ModifiedS: 0,
  68. 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}}},
  69. },
  70. }
  71. func init() {
  72. // Fix expected test data to match reality
  73. for n, f := range testDataExpected {
  74. fi, _ := os.Stat("testdata/" + n)
  75. f.Permissions = uint32(fi.Mode())
  76. f.ModifiedS = fi.ModTime().Unix()
  77. f.Size = fi.Size()
  78. testDataExpected[n] = f
  79. }
  80. }
  81. func TestRequest(t *testing.T) {
  82. db := db.OpenMemory()
  83. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  84. // device1 shares default, but device2 doesn't
  85. m.AddFolder(defaultFolderConfig)
  86. m.StartFolder("default")
  87. m.ServeBackground()
  88. defer m.Stop()
  89. m.ScanFolder("default")
  90. bs := make([]byte, protocol.BlockSize)
  91. // Existing, shared file
  92. bs = bs[:6]
  93. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  94. if err != nil {
  95. t.Error(err)
  96. }
  97. if !bytes.Equal(bs, []byte("foobar")) {
  98. t.Errorf("Incorrect data from request: %q", string(bs))
  99. }
  100. // Existing, nonshared file
  101. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  102. if err == nil {
  103. t.Error("Unexpected nil error on insecure file read")
  104. }
  105. // Nonexistent file
  106. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  107. if err == nil {
  108. t.Error("Unexpected nil error on insecure file read")
  109. }
  110. // Shared folder, but disallowed file name
  111. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  112. if err == nil {
  113. t.Error("Unexpected nil error on insecure file read")
  114. }
  115. // Negative offset
  116. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  117. if err == nil {
  118. t.Error("Unexpected nil error on insecure file read")
  119. }
  120. // Larger block than available
  121. bs = bs[:42]
  122. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  123. if err == nil {
  124. t.Error("Unexpected nil error on insecure file read")
  125. }
  126. }
  127. func genFiles(n int) []protocol.FileInfo {
  128. files := make([]protocol.FileInfo, n)
  129. t := time.Now().Unix()
  130. for i := 0; i < n; i++ {
  131. files[i] = protocol.FileInfo{
  132. Name: fmt.Sprintf("file%d", i),
  133. ModifiedS: t,
  134. Sequence: int64(i + 1),
  135. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  136. }
  137. }
  138. return files
  139. }
  140. func BenchmarkIndex_10000(b *testing.B) {
  141. benchmarkIndex(b, 10000)
  142. }
  143. func BenchmarkIndex_100(b *testing.B) {
  144. benchmarkIndex(b, 100)
  145. }
  146. func benchmarkIndex(b *testing.B, nfiles int) {
  147. db := db.OpenMemory()
  148. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  149. m.AddFolder(defaultFolderConfig)
  150. m.StartFolder("default")
  151. m.ServeBackground()
  152. defer m.Stop()
  153. files := genFiles(nfiles)
  154. m.Index(device1, "default", files)
  155. b.ResetTimer()
  156. for i := 0; i < b.N; i++ {
  157. m.Index(device1, "default", files)
  158. }
  159. b.ReportAllocs()
  160. }
  161. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  162. benchmarkIndexUpdate(b, 10000, 10000)
  163. }
  164. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  165. benchmarkIndexUpdate(b, 10000, 100)
  166. }
  167. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  168. benchmarkIndexUpdate(b, 10000, 1)
  169. }
  170. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  171. db := db.OpenMemory()
  172. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  173. m.AddFolder(defaultFolderConfig)
  174. m.StartFolder("default")
  175. m.ServeBackground()
  176. defer m.Stop()
  177. files := genFiles(nfiles)
  178. ufiles := genFiles(nufiles)
  179. m.Index(device1, "default", files)
  180. b.ResetTimer()
  181. for i := 0; i < b.N; i++ {
  182. m.IndexUpdate(device1, "default", ufiles)
  183. }
  184. b.ReportAllocs()
  185. }
  186. type downloadProgressMessage struct {
  187. folder string
  188. updates []protocol.FileDownloadProgressUpdate
  189. }
  190. type fakeConnection struct {
  191. id protocol.DeviceID
  192. downloadProgressMessages []downloadProgressMessage
  193. closed bool
  194. files []protocol.FileInfo
  195. fileData map[string][]byte
  196. folder string
  197. model *Model
  198. indexFn func(string, []protocol.FileInfo)
  199. requestFn func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error)
  200. mut sync.Mutex
  201. }
  202. func (f *fakeConnection) Close() error {
  203. f.mut.Lock()
  204. defer f.mut.Unlock()
  205. f.closed = true
  206. return nil
  207. }
  208. func (f *fakeConnection) Start() {
  209. }
  210. func (f *fakeConnection) ID() protocol.DeviceID {
  211. return f.id
  212. }
  213. func (f *fakeConnection) Name() string {
  214. return ""
  215. }
  216. func (f *fakeConnection) Option(string) string {
  217. return ""
  218. }
  219. func (f *fakeConnection) Index(folder string, fs []protocol.FileInfo) error {
  220. f.mut.Lock()
  221. defer f.mut.Unlock()
  222. if f.indexFn != nil {
  223. f.indexFn(folder, fs)
  224. }
  225. return nil
  226. }
  227. func (f *fakeConnection) IndexUpdate(folder string, fs []protocol.FileInfo) error {
  228. f.mut.Lock()
  229. defer f.mut.Unlock()
  230. if f.indexFn != nil {
  231. f.indexFn(folder, fs)
  232. }
  233. return nil
  234. }
  235. func (f *fakeConnection) Request(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  236. f.mut.Lock()
  237. defer f.mut.Unlock()
  238. if f.requestFn != nil {
  239. return f.requestFn(folder, name, offset, size, hash, fromTemporary)
  240. }
  241. return f.fileData[name], nil
  242. }
  243. func (f *fakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  244. func (f *fakeConnection) Ping() bool {
  245. f.mut.Lock()
  246. defer f.mut.Unlock()
  247. return f.closed
  248. }
  249. func (f *fakeConnection) Closed() bool {
  250. f.mut.Lock()
  251. defer f.mut.Unlock()
  252. return f.closed
  253. }
  254. func (f *fakeConnection) Statistics() protocol.Statistics {
  255. return protocol.Statistics{}
  256. }
  257. func (f *fakeConnection) RemoteAddr() net.Addr {
  258. return &fakeAddr{}
  259. }
  260. func (f *fakeConnection) Type() string {
  261. return "fake"
  262. }
  263. func (f *fakeConnection) Transport() string {
  264. return "fake"
  265. }
  266. func (f *fakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  267. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  268. folder: folder,
  269. updates: updates,
  270. })
  271. }
  272. func (f *fakeConnection) addFile(name string, flags uint32, ftype protocol.FileInfoType, data []byte) {
  273. f.mut.Lock()
  274. defer f.mut.Unlock()
  275. blocks, _ := scanner.Blocks(context.TODO(), bytes.NewReader(data), protocol.BlockSize, int64(len(data)), nil, true)
  276. var version protocol.Vector
  277. version = version.Update(f.id.Short())
  278. if ftype == protocol.FileInfoTypeFile || ftype == protocol.FileInfoTypeDirectory {
  279. f.files = append(f.files, protocol.FileInfo{
  280. Name: name,
  281. Type: ftype,
  282. Size: int64(len(data)),
  283. ModifiedS: time.Now().Unix(),
  284. Permissions: flags,
  285. Version: version,
  286. Sequence: time.Now().UnixNano(),
  287. Blocks: blocks,
  288. })
  289. } else {
  290. // Symlink
  291. f.files = append(f.files, protocol.FileInfo{
  292. Name: name,
  293. Type: ftype,
  294. Version: version,
  295. Sequence: time.Now().UnixNano(),
  296. SymlinkTarget: string(data),
  297. })
  298. }
  299. if f.fileData == nil {
  300. f.fileData = make(map[string][]byte)
  301. }
  302. f.fileData[name] = data
  303. }
  304. func (f *fakeConnection) deleteFile(name string) {
  305. f.mut.Lock()
  306. defer f.mut.Unlock()
  307. for i, fi := range f.files {
  308. if fi.Name == name {
  309. fi.Deleted = true
  310. fi.ModifiedS = time.Now().Unix()
  311. fi.Version = fi.Version.Update(f.id.Short())
  312. fi.Sequence = time.Now().UnixNano()
  313. fi.Blocks = nil
  314. f.files = append(append(f.files[:i], f.files[i+1:]...), fi)
  315. return
  316. }
  317. }
  318. }
  319. func (f *fakeConnection) sendIndexUpdate() {
  320. f.model.IndexUpdate(f.id, f.folder, f.files)
  321. }
  322. func BenchmarkRequestOut(b *testing.B) {
  323. db := db.OpenMemory()
  324. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  325. m.AddFolder(defaultFolderConfig)
  326. m.ServeBackground()
  327. defer m.Stop()
  328. m.ScanFolder("default")
  329. const n = 1000
  330. files := genFiles(n)
  331. fc := &fakeConnection{id: device1}
  332. for _, f := range files {
  333. fc.addFile(f.Name, 0644, protocol.FileInfoTypeFile, []byte("some data to return"))
  334. }
  335. m.AddConnection(fc, protocol.HelloResult{})
  336. m.Index(device1, "default", files)
  337. b.ResetTimer()
  338. for i := 0; i < b.N; i++ {
  339. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, false)
  340. if err != nil {
  341. b.Error(err)
  342. }
  343. if data == nil {
  344. b.Error("nil data")
  345. }
  346. }
  347. }
  348. func BenchmarkRequestInSingleFile(b *testing.B) {
  349. db := db.OpenMemory()
  350. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  351. m.AddFolder(defaultFolderConfig)
  352. m.ServeBackground()
  353. defer m.Stop()
  354. m.ScanFolder("default")
  355. buf := make([]byte, 128<<10)
  356. rand.Read(buf)
  357. os.RemoveAll("testdata/request")
  358. defer os.RemoveAll("testdata/request")
  359. os.MkdirAll("testdata/request/for/a/file/in/a/couple/of/dirs", 0755)
  360. ioutil.WriteFile("testdata/request/for/a/file/in/a/couple/of/dirs/128k", buf, 0644)
  361. b.ResetTimer()
  362. for i := 0; i < b.N; i++ {
  363. if err := m.Request(device1, "default", "request/for/a/file/in/a/couple/of/dirs/128k", 0, nil, false, buf); err != nil {
  364. b.Error(err)
  365. }
  366. }
  367. b.SetBytes(128 << 10)
  368. }
  369. func TestDeviceRename(t *testing.T) {
  370. hello := protocol.HelloResult{
  371. ClientName: "syncthing",
  372. ClientVersion: "v0.9.4",
  373. }
  374. defer os.Remove("tmpconfig.xml")
  375. rawCfg := config.New(device1)
  376. rawCfg.Devices = []config.DeviceConfiguration{
  377. {
  378. DeviceID: device1,
  379. },
  380. }
  381. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  382. db := db.OpenMemory()
  383. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  384. if cfg.Devices()[device1].Name != "" {
  385. t.Errorf("Device already has a name")
  386. }
  387. conn := &fakeConnection{id: device1}
  388. m.AddConnection(conn, hello)
  389. m.ServeBackground()
  390. defer m.Stop()
  391. if cfg.Devices()[device1].Name != "" {
  392. t.Errorf("Device already has a name")
  393. }
  394. m.Closed(conn, protocol.ErrTimeout)
  395. hello.DeviceName = "tester"
  396. m.AddConnection(conn, hello)
  397. if cfg.Devices()[device1].Name != "tester" {
  398. t.Errorf("Device did not get a name")
  399. }
  400. m.Closed(conn, protocol.ErrTimeout)
  401. hello.DeviceName = "tester2"
  402. m.AddConnection(conn, hello)
  403. if cfg.Devices()[device1].Name != "tester" {
  404. t.Errorf("Device name got overwritten")
  405. }
  406. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  407. if err != nil {
  408. t.Error(err)
  409. return
  410. }
  411. if cfgw.Devices()[device1].Name != "tester" {
  412. t.Errorf("Device name not saved in config")
  413. }
  414. m.Closed(conn, protocol.ErrTimeout)
  415. opts := cfg.Options()
  416. opts.OverwriteRemoteDevNames = true
  417. cfg.SetOptions(opts)
  418. hello.DeviceName = "tester2"
  419. m.AddConnection(conn, hello)
  420. if cfg.Devices()[device1].Name != "tester2" {
  421. t.Errorf("Device name not overwritten")
  422. }
  423. }
  424. func TestClusterConfig(t *testing.T) {
  425. cfg := config.New(device1)
  426. cfg.Devices = []config.DeviceConfiguration{
  427. {
  428. DeviceID: device1,
  429. Introducer: true,
  430. },
  431. {
  432. DeviceID: device2,
  433. },
  434. }
  435. cfg.Folders = []config.FolderConfiguration{
  436. {
  437. ID: "folder1",
  438. Path: "testdata",
  439. Devices: []config.FolderDeviceConfiguration{
  440. {DeviceID: device1},
  441. {DeviceID: device2},
  442. },
  443. },
  444. {
  445. ID: "folder2",
  446. Path: "testdata",
  447. Devices: []config.FolderDeviceConfiguration{
  448. {DeviceID: device1},
  449. {DeviceID: device2},
  450. },
  451. },
  452. }
  453. db := db.OpenMemory()
  454. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  455. m.AddFolder(cfg.Folders[0])
  456. m.AddFolder(cfg.Folders[1])
  457. m.ServeBackground()
  458. defer m.Stop()
  459. cm := m.generateClusterConfig(device2)
  460. if l := len(cm.Folders); l != 2 {
  461. t.Fatalf("Incorrect number of folders %d != 2", l)
  462. }
  463. r := cm.Folders[0]
  464. if r.ID != "folder1" {
  465. t.Errorf("Incorrect folder %q != folder1", r.ID)
  466. }
  467. if l := len(r.Devices); l != 2 {
  468. t.Errorf("Incorrect number of devices %d != 2", l)
  469. }
  470. if id := r.Devices[0].ID; id != device1 {
  471. t.Errorf("Incorrect device ID %s != %s", id, device1)
  472. }
  473. if !r.Devices[0].Introducer {
  474. t.Error("Device1 should be flagged as Introducer")
  475. }
  476. if id := r.Devices[1].ID; id != device2 {
  477. t.Errorf("Incorrect device ID %s != %s", id, device2)
  478. }
  479. if r.Devices[1].Introducer {
  480. t.Error("Device2 should not be flagged as Introducer")
  481. }
  482. r = cm.Folders[1]
  483. if r.ID != "folder2" {
  484. t.Errorf("Incorrect folder %q != folder2", r.ID)
  485. }
  486. if l := len(r.Devices); l != 2 {
  487. t.Errorf("Incorrect number of devices %d != 2", l)
  488. }
  489. if id := r.Devices[0].ID; id != device1 {
  490. t.Errorf("Incorrect device ID %s != %s", id, device1)
  491. }
  492. if !r.Devices[0].Introducer {
  493. t.Error("Device1 should be flagged as Introducer")
  494. }
  495. if id := r.Devices[1].ID; id != device2 {
  496. t.Errorf("Incorrect device ID %s != %s", id, device2)
  497. }
  498. if r.Devices[1].Introducer {
  499. t.Error("Device2 should not be flagged as Introducer")
  500. }
  501. }
  502. func TestIntroducer(t *testing.T) {
  503. var introducedByAnyone protocol.DeviceID
  504. // LocalDeviceID is a magic value meaning don't check introducer
  505. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  506. for _, dev := range cfg.Devices {
  507. if dev.DeviceID.Equals(id) {
  508. if introducedBy.Equals(introducedByAnyone) {
  509. return true
  510. }
  511. return introducedBy.Equals(introducedBy)
  512. }
  513. }
  514. return false
  515. }
  516. newState := func(cfg config.Configuration) (*config.Wrapper, *Model) {
  517. db := db.OpenMemory()
  518. wcfg := config.Wrap("/tmp/test", cfg)
  519. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  520. for _, folder := range cfg.Folders {
  521. m.AddFolder(folder)
  522. }
  523. m.ServeBackground()
  524. m.AddConnection(&fakeConnection{id: device1}, protocol.HelloResult{})
  525. return wcfg, m
  526. }
  527. wcfg, m := newState(config.Configuration{
  528. Devices: []config.DeviceConfiguration{
  529. {
  530. DeviceID: device1,
  531. Introducer: true,
  532. },
  533. },
  534. Folders: []config.FolderConfiguration{
  535. {
  536. ID: "folder1",
  537. Path: "testdata",
  538. Devices: []config.FolderDeviceConfiguration{
  539. {DeviceID: device1},
  540. },
  541. },
  542. {
  543. ID: "folder2",
  544. Path: "testdata",
  545. Devices: []config.FolderDeviceConfiguration{
  546. {DeviceID: device1},
  547. },
  548. },
  549. },
  550. })
  551. m.ClusterConfig(device1, protocol.ClusterConfig{
  552. Folders: []protocol.Folder{
  553. {
  554. ID: "folder1",
  555. Devices: []protocol.Device{
  556. {
  557. ID: device2,
  558. Introducer: true,
  559. SkipIntroductionRemovals: true,
  560. },
  561. },
  562. },
  563. },
  564. })
  565. if newDev, ok := wcfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  566. t.Error("devie 2 missing or wrong flags")
  567. }
  568. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  569. t.Error("expected folder 1 to have device2 introduced by device 1")
  570. }
  571. wcfg, m = newState(config.Configuration{
  572. Devices: []config.DeviceConfiguration{
  573. {
  574. DeviceID: device1,
  575. Introducer: true,
  576. },
  577. {
  578. DeviceID: device2,
  579. IntroducedBy: device1,
  580. },
  581. },
  582. Folders: []config.FolderConfiguration{
  583. {
  584. ID: "folder1",
  585. Path: "testdata",
  586. Devices: []config.FolderDeviceConfiguration{
  587. {DeviceID: device1},
  588. {DeviceID: device2, IntroducedBy: device1},
  589. },
  590. },
  591. {
  592. ID: "folder2",
  593. Path: "testdata",
  594. Devices: []config.FolderDeviceConfiguration{
  595. {DeviceID: device1},
  596. },
  597. },
  598. },
  599. })
  600. m.ClusterConfig(device1, protocol.ClusterConfig{
  601. Folders: []protocol.Folder{
  602. {
  603. ID: "folder2",
  604. Devices: []protocol.Device{
  605. {
  606. ID: device2,
  607. Introducer: true,
  608. SkipIntroductionRemovals: true,
  609. },
  610. },
  611. },
  612. },
  613. })
  614. // Should not get introducer, as it's already unset, and it's an existing device.
  615. if newDev, ok := wcfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  616. t.Error("device 2 missing or changed flags")
  617. }
  618. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  619. t.Error("expected device 2 to be removed from folder 1")
  620. }
  621. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  622. t.Error("expected device 2 to be added to folder 2")
  623. }
  624. wcfg, m = newState(config.Configuration{
  625. Devices: []config.DeviceConfiguration{
  626. {
  627. DeviceID: device1,
  628. Introducer: true,
  629. },
  630. {
  631. DeviceID: device2,
  632. IntroducedBy: device1,
  633. },
  634. },
  635. Folders: []config.FolderConfiguration{
  636. {
  637. ID: "folder1",
  638. Path: "testdata",
  639. Devices: []config.FolderDeviceConfiguration{
  640. {DeviceID: device1},
  641. {DeviceID: device2, IntroducedBy: device1},
  642. },
  643. },
  644. {
  645. ID: "folder2",
  646. Path: "testdata",
  647. Devices: []config.FolderDeviceConfiguration{
  648. {DeviceID: device1},
  649. {DeviceID: device2, IntroducedBy: device1},
  650. },
  651. },
  652. },
  653. })
  654. m.ClusterConfig(device1, protocol.ClusterConfig{})
  655. if _, ok := wcfg.Device(device2); ok {
  656. t.Error("device 2 should have been removed")
  657. }
  658. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  659. t.Error("expected device 2 to be removed from folder 1")
  660. }
  661. if contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  662. t.Error("expected device 2 to be removed from folder 2")
  663. }
  664. // Two cases when removals should not happen
  665. // 1. Introducer flag no longer set on device
  666. wcfg, m = newState(config.Configuration{
  667. Devices: []config.DeviceConfiguration{
  668. {
  669. DeviceID: device1,
  670. Introducer: false,
  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. {DeviceID: device2, IntroducedBy: device1},
  692. },
  693. },
  694. },
  695. })
  696. m.ClusterConfig(device1, protocol.ClusterConfig{})
  697. if _, ok := wcfg.Device(device2); !ok {
  698. t.Error("device 2 should not have been removed")
  699. }
  700. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  701. t.Error("expected device 2 not to be removed from folder 1")
  702. }
  703. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  704. t.Error("expected device 2 not to be removed from folder 2")
  705. }
  706. // 2. SkipIntroductionRemovals is set
  707. wcfg, m = newState(config.Configuration{
  708. Devices: []config.DeviceConfiguration{
  709. {
  710. DeviceID: device1,
  711. Introducer: true,
  712. SkipIntroductionRemovals: true,
  713. },
  714. {
  715. DeviceID: device2,
  716. IntroducedBy: device1,
  717. },
  718. },
  719. Folders: []config.FolderConfiguration{
  720. {
  721. ID: "folder1",
  722. Path: "testdata",
  723. Devices: []config.FolderDeviceConfiguration{
  724. {DeviceID: device1},
  725. {DeviceID: device2, IntroducedBy: device1},
  726. },
  727. },
  728. {
  729. ID: "folder2",
  730. Path: "testdata",
  731. Devices: []config.FolderDeviceConfiguration{
  732. {DeviceID: device1},
  733. },
  734. },
  735. },
  736. })
  737. m.ClusterConfig(device1, protocol.ClusterConfig{
  738. Folders: []protocol.Folder{
  739. {
  740. ID: "folder2",
  741. Devices: []protocol.Device{
  742. {
  743. ID: device2,
  744. Introducer: true,
  745. SkipIntroductionRemovals: true,
  746. },
  747. },
  748. },
  749. },
  750. })
  751. if _, ok := wcfg.Device(device2); !ok {
  752. t.Error("device 2 should not have been removed")
  753. }
  754. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  755. t.Error("expected device 2 not to be removed from folder 1")
  756. }
  757. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  758. t.Error("expected device 2 not to be added to folder 2")
  759. }
  760. // Test device not being removed as it's shared without an introducer.
  761. wcfg, m = newState(config.Configuration{
  762. Devices: []config.DeviceConfiguration{
  763. {
  764. DeviceID: device1,
  765. Introducer: true,
  766. },
  767. {
  768. DeviceID: device2,
  769. IntroducedBy: device1,
  770. },
  771. },
  772. Folders: []config.FolderConfiguration{
  773. {
  774. ID: "folder1",
  775. Path: "testdata",
  776. Devices: []config.FolderDeviceConfiguration{
  777. {DeviceID: device1},
  778. {DeviceID: device2, IntroducedBy: device1},
  779. },
  780. },
  781. {
  782. ID: "folder2",
  783. Path: "testdata",
  784. Devices: []config.FolderDeviceConfiguration{
  785. {DeviceID: device1},
  786. {DeviceID: device2},
  787. },
  788. },
  789. },
  790. })
  791. m.ClusterConfig(device1, protocol.ClusterConfig{})
  792. if _, ok := wcfg.Device(device2); !ok {
  793. t.Error("device 2 should not have been removed")
  794. }
  795. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  796. t.Error("expected device 2 to be removed from folder 1")
  797. }
  798. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  799. t.Error("expected device 2 not to be removed from folder 2")
  800. }
  801. // Test device not being removed as it's shared by a different introducer.
  802. wcfg, m = newState(config.Configuration{
  803. Devices: []config.DeviceConfiguration{
  804. {
  805. DeviceID: device1,
  806. Introducer: true,
  807. },
  808. {
  809. DeviceID: device2,
  810. IntroducedBy: device1,
  811. },
  812. },
  813. Folders: []config.FolderConfiguration{
  814. {
  815. ID: "folder1",
  816. Path: "testdata",
  817. Devices: []config.FolderDeviceConfiguration{
  818. {DeviceID: device1},
  819. {DeviceID: device2, IntroducedBy: device1},
  820. },
  821. },
  822. {
  823. ID: "folder2",
  824. Path: "testdata",
  825. Devices: []config.FolderDeviceConfiguration{
  826. {DeviceID: device1},
  827. {DeviceID: device2, IntroducedBy: protocol.LocalDeviceID},
  828. },
  829. },
  830. },
  831. })
  832. m.ClusterConfig(device1, protocol.ClusterConfig{})
  833. if _, ok := wcfg.Device(device2); !ok {
  834. t.Error("device 2 should not have been removed")
  835. }
  836. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  837. t.Error("expected device 2 to be removed from folder 1")
  838. }
  839. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  840. t.Error("expected device 2 not to be removed from folder 2")
  841. }
  842. }
  843. func changeIgnores(t *testing.T, m *Model, expected []string) {
  844. arrEqual := func(a, b []string) bool {
  845. if len(a) != len(b) {
  846. return false
  847. }
  848. for i := range a {
  849. if a[i] != b[i] {
  850. return false
  851. }
  852. }
  853. return true
  854. }
  855. ignores, _, err := m.GetIgnores("default")
  856. if err != nil {
  857. t.Error(err)
  858. }
  859. if !arrEqual(ignores, expected) {
  860. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  861. }
  862. ignores = append(ignores, "pox")
  863. err = m.SetIgnores("default", ignores)
  864. if err != nil {
  865. t.Error(err)
  866. }
  867. ignores2, _, err := m.GetIgnores("default")
  868. if err != nil {
  869. t.Error(err)
  870. }
  871. if !arrEqual(ignores, ignores2) {
  872. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  873. }
  874. if runtime.GOOS == "darwin" {
  875. // see above
  876. time.Sleep(time.Second)
  877. } else {
  878. time.Sleep(time.Millisecond)
  879. }
  880. err = m.SetIgnores("default", expected)
  881. if err != nil {
  882. t.Error(err)
  883. }
  884. ignores, _, err = m.GetIgnores("default")
  885. if err != nil {
  886. t.Error(err)
  887. }
  888. if !arrEqual(ignores, expected) {
  889. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  890. }
  891. }
  892. func TestIgnores(t *testing.T) {
  893. // Assure a clean start state
  894. os.RemoveAll(filepath.Join("testdata", config.DefaultMarkerName))
  895. os.MkdirAll(filepath.Join("testdata", config.DefaultMarkerName), 0644)
  896. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  897. db := db.OpenMemory()
  898. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  899. m.ServeBackground()
  900. defer m.Stop()
  901. // m.cfg.SetFolder is not usable as it is non-blocking, and there is no
  902. // way to know when the folder is actually added.
  903. m.AddFolder(defaultFolderConfig)
  904. m.StartFolder("default")
  905. // Reach in and update the ignore matcher to one that always does
  906. // reloads when asked to, instead of checking file mtimes. This is
  907. // because we will be changing the files on disk often enough that the
  908. // mtimes will be unreliable to determine change status.
  909. m.fmut.Lock()
  910. m.folderIgnores["default"] = ignore.New(defaultFs, ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  911. m.fmut.Unlock()
  912. // Make sure the initial scan has finished (ScanFolders is blocking)
  913. m.ScanFolders()
  914. expected := []string{
  915. ".*",
  916. "quux",
  917. }
  918. changeIgnores(t, m, expected)
  919. _, _, err := m.GetIgnores("doesnotexist")
  920. if err == nil {
  921. t.Error("No error")
  922. }
  923. err = m.SetIgnores("doesnotexist", expected)
  924. if err == nil {
  925. t.Error("No error")
  926. }
  927. // Invalid path, marker should be missing, hence returns an error.
  928. m.AddFolder(config.FolderConfiguration{ID: "fresh", Path: "XXX"})
  929. _, _, err = m.GetIgnores("fresh")
  930. if err == nil {
  931. t.Error("No error")
  932. }
  933. // Repeat tests with paused folder
  934. pausedDefaultFolderConfig := defaultFolderConfig
  935. pausedDefaultFolderConfig.Paused = true
  936. m.RestartFolder(pausedDefaultFolderConfig)
  937. // Here folder initialization is not an issue as a paused folder isn't
  938. // added to the model and thus there is no initial scan happening.
  939. changeIgnores(t, m, expected)
  940. // Make sure no .stignore file is considered valid
  941. os.Rename("testdata/.stignore", "testdata/.stignore.bak")
  942. changeIgnores(t, m, []string{})
  943. os.Rename("testdata/.stignore.bak", "testdata/.stignore")
  944. }
  945. func TestROScanRecovery(t *testing.T) {
  946. ldb := db.OpenMemory()
  947. set := db.NewFileSet("default", defaultFs, ldb)
  948. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  949. {Name: "dummyfile"},
  950. })
  951. fcfg := config.FolderConfiguration{
  952. ID: "default",
  953. Path: "testdata/rotestfolder",
  954. Type: config.FolderTypeSendOnly,
  955. RescanIntervalS: 1,
  956. MarkerName: config.DefaultMarkerName,
  957. }
  958. cfg := config.Wrap("/tmp/test", config.Configuration{
  959. Folders: []config.FolderConfiguration{fcfg},
  960. Devices: []config.DeviceConfiguration{
  961. {
  962. DeviceID: device1,
  963. },
  964. },
  965. })
  966. os.RemoveAll(fcfg.Path)
  967. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  968. m.AddFolder(fcfg)
  969. m.StartFolder("default")
  970. m.ServeBackground()
  971. defer m.Stop()
  972. waitFor := func(status string) error {
  973. timeout := time.Now().Add(2 * time.Second)
  974. for {
  975. _, _, err := m.State("default")
  976. if err == nil && status == "" {
  977. return nil
  978. }
  979. if err != nil && err.Error() == status {
  980. return nil
  981. }
  982. if time.Now().After(timeout) {
  983. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  984. }
  985. time.Sleep(10 * time.Millisecond)
  986. }
  987. }
  988. if err := waitFor("folder path missing"); err != nil {
  989. t.Error(err)
  990. return
  991. }
  992. os.Mkdir(fcfg.Path, 0700)
  993. if err := waitFor("folder marker missing"); err != nil {
  994. t.Error(err)
  995. return
  996. }
  997. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  998. if err != nil {
  999. t.Error(err)
  1000. return
  1001. }
  1002. fd.Close()
  1003. if err := waitFor(""); err != nil {
  1004. t.Error(err)
  1005. return
  1006. }
  1007. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1008. if err := waitFor("folder marker missing"); err != nil {
  1009. t.Error(err)
  1010. return
  1011. }
  1012. os.Remove(fcfg.Path)
  1013. if err := waitFor("folder path missing"); err != nil {
  1014. t.Error(err)
  1015. return
  1016. }
  1017. }
  1018. func TestRWScanRecovery(t *testing.T) {
  1019. ldb := db.OpenMemory()
  1020. set := db.NewFileSet("default", defaultFs, ldb)
  1021. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1022. {Name: "dummyfile"},
  1023. })
  1024. fcfg := config.FolderConfiguration{
  1025. ID: "default",
  1026. Path: "testdata/rwtestfolder",
  1027. Type: config.FolderTypeSendReceive,
  1028. RescanIntervalS: 1,
  1029. MarkerName: config.DefaultMarkerName,
  1030. }
  1031. cfg := config.Wrap("/tmp/test", config.Configuration{
  1032. Folders: []config.FolderConfiguration{fcfg},
  1033. Devices: []config.DeviceConfiguration{
  1034. {
  1035. DeviceID: device1,
  1036. },
  1037. },
  1038. })
  1039. os.RemoveAll(fcfg.Path)
  1040. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1041. m.AddFolder(fcfg)
  1042. m.StartFolder("default")
  1043. m.ServeBackground()
  1044. defer m.Stop()
  1045. waitFor := func(status string) error {
  1046. timeout := time.Now().Add(2 * time.Second)
  1047. for {
  1048. _, _, err := m.State("default")
  1049. if err == nil && status == "" {
  1050. return nil
  1051. }
  1052. if err != nil && err.Error() == status {
  1053. return nil
  1054. }
  1055. if time.Now().After(timeout) {
  1056. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1057. }
  1058. time.Sleep(10 * time.Millisecond)
  1059. }
  1060. }
  1061. if err := waitFor("folder path missing"); err != nil {
  1062. t.Error(err)
  1063. return
  1064. }
  1065. os.Mkdir(fcfg.Path, 0700)
  1066. if err := waitFor("folder marker missing"); err != nil {
  1067. t.Error(err)
  1068. return
  1069. }
  1070. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1071. if err != nil {
  1072. t.Error(err)
  1073. return
  1074. }
  1075. fd.Close()
  1076. if err := waitFor(""); err != nil {
  1077. t.Error(err)
  1078. return
  1079. }
  1080. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1081. if err := waitFor("folder marker missing"); err != nil {
  1082. t.Error(err)
  1083. return
  1084. }
  1085. os.Remove(fcfg.Path)
  1086. if err := waitFor("folder path missing"); err != nil {
  1087. t.Error(err)
  1088. return
  1089. }
  1090. }
  1091. func TestGlobalDirectoryTree(t *testing.T) {
  1092. db := db.OpenMemory()
  1093. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1094. m.AddFolder(defaultFolderConfig)
  1095. m.ServeBackground()
  1096. defer m.Stop()
  1097. b := func(isfile bool, path ...string) protocol.FileInfo {
  1098. typ := protocol.FileInfoTypeDirectory
  1099. blocks := []protocol.BlockInfo{}
  1100. if isfile {
  1101. typ = protocol.FileInfoTypeFile
  1102. 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}}}
  1103. }
  1104. return protocol.FileInfo{
  1105. Name: filepath.Join(path...),
  1106. Type: typ,
  1107. ModifiedS: 0x666,
  1108. Blocks: blocks,
  1109. Size: 0xa,
  1110. }
  1111. }
  1112. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1113. testdata := []protocol.FileInfo{
  1114. b(false, "another"),
  1115. b(false, "another", "directory"),
  1116. b(true, "another", "directory", "afile"),
  1117. b(false, "another", "directory", "with"),
  1118. b(false, "another", "directory", "with", "a"),
  1119. b(true, "another", "directory", "with", "a", "file"),
  1120. b(true, "another", "directory", "with", "file"),
  1121. b(true, "another", "file"),
  1122. b(false, "other"),
  1123. b(false, "other", "rand"),
  1124. b(false, "other", "random"),
  1125. b(false, "other", "random", "dir"),
  1126. b(false, "other", "random", "dirx"),
  1127. b(false, "other", "randomx"),
  1128. b(false, "some"),
  1129. b(false, "some", "directory"),
  1130. b(false, "some", "directory", "with"),
  1131. b(false, "some", "directory", "with", "a"),
  1132. b(true, "some", "directory", "with", "a", "file"),
  1133. b(true, "rootfile"),
  1134. }
  1135. expectedResult := map[string]interface{}{
  1136. "another": map[string]interface{}{
  1137. "directory": map[string]interface{}{
  1138. "afile": filedata,
  1139. "with": map[string]interface{}{
  1140. "a": map[string]interface{}{
  1141. "file": filedata,
  1142. },
  1143. "file": filedata,
  1144. },
  1145. },
  1146. "file": filedata,
  1147. },
  1148. "other": map[string]interface{}{
  1149. "rand": map[string]interface{}{},
  1150. "random": map[string]interface{}{
  1151. "dir": map[string]interface{}{},
  1152. "dirx": map[string]interface{}{},
  1153. },
  1154. "randomx": map[string]interface{}{},
  1155. },
  1156. "some": map[string]interface{}{
  1157. "directory": map[string]interface{}{
  1158. "with": map[string]interface{}{
  1159. "a": map[string]interface{}{
  1160. "file": filedata,
  1161. },
  1162. },
  1163. },
  1164. },
  1165. "rootfile": filedata,
  1166. }
  1167. mm := func(data interface{}) string {
  1168. bytes, err := json.Marshal(data)
  1169. if err != nil {
  1170. panic(err)
  1171. }
  1172. return string(bytes)
  1173. }
  1174. m.Index(device1, "default", testdata)
  1175. result := m.GlobalDirectoryTree("default", "", -1, false)
  1176. if mm(result) != mm(expectedResult) {
  1177. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1178. }
  1179. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1180. if mm(result) != mm(expectedResult["another"]) {
  1181. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1182. }
  1183. result = m.GlobalDirectoryTree("default", "", 0, false)
  1184. currentResult := map[string]interface{}{
  1185. "another": map[string]interface{}{},
  1186. "other": map[string]interface{}{},
  1187. "some": map[string]interface{}{},
  1188. "rootfile": filedata,
  1189. }
  1190. if mm(result) != mm(currentResult) {
  1191. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1192. }
  1193. result = m.GlobalDirectoryTree("default", "", 1, false)
  1194. currentResult = map[string]interface{}{
  1195. "another": map[string]interface{}{
  1196. "directory": map[string]interface{}{},
  1197. "file": filedata,
  1198. },
  1199. "other": map[string]interface{}{
  1200. "rand": map[string]interface{}{},
  1201. "random": map[string]interface{}{},
  1202. "randomx": map[string]interface{}{},
  1203. },
  1204. "some": map[string]interface{}{
  1205. "directory": map[string]interface{}{},
  1206. },
  1207. "rootfile": filedata,
  1208. }
  1209. if mm(result) != mm(currentResult) {
  1210. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1211. }
  1212. result = m.GlobalDirectoryTree("default", "", -1, true)
  1213. currentResult = map[string]interface{}{
  1214. "another": map[string]interface{}{
  1215. "directory": map[string]interface{}{
  1216. "with": map[string]interface{}{
  1217. "a": map[string]interface{}{},
  1218. },
  1219. },
  1220. },
  1221. "other": map[string]interface{}{
  1222. "rand": map[string]interface{}{},
  1223. "random": map[string]interface{}{
  1224. "dir": map[string]interface{}{},
  1225. "dirx": map[string]interface{}{},
  1226. },
  1227. "randomx": map[string]interface{}{},
  1228. },
  1229. "some": map[string]interface{}{
  1230. "directory": map[string]interface{}{
  1231. "with": map[string]interface{}{
  1232. "a": map[string]interface{}{},
  1233. },
  1234. },
  1235. },
  1236. }
  1237. if mm(result) != mm(currentResult) {
  1238. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1239. }
  1240. result = m.GlobalDirectoryTree("default", "", 1, true)
  1241. currentResult = map[string]interface{}{
  1242. "another": map[string]interface{}{
  1243. "directory": map[string]interface{}{},
  1244. },
  1245. "other": map[string]interface{}{
  1246. "rand": map[string]interface{}{},
  1247. "random": map[string]interface{}{},
  1248. "randomx": map[string]interface{}{},
  1249. },
  1250. "some": map[string]interface{}{
  1251. "directory": map[string]interface{}{},
  1252. },
  1253. }
  1254. if mm(result) != mm(currentResult) {
  1255. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1256. }
  1257. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1258. currentResult = map[string]interface{}{
  1259. "directory": map[string]interface{}{},
  1260. "file": filedata,
  1261. }
  1262. if mm(result) != mm(currentResult) {
  1263. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1264. }
  1265. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1266. currentResult = map[string]interface{}{
  1267. "with": map[string]interface{}{},
  1268. }
  1269. if mm(result) != mm(currentResult) {
  1270. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1271. }
  1272. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1273. currentResult = map[string]interface{}{
  1274. "with": map[string]interface{}{
  1275. "a": map[string]interface{}{},
  1276. },
  1277. }
  1278. if mm(result) != mm(currentResult) {
  1279. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1280. }
  1281. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1282. currentResult = map[string]interface{}{
  1283. "with": map[string]interface{}{
  1284. "a": map[string]interface{}{
  1285. "file": filedata,
  1286. },
  1287. },
  1288. }
  1289. if mm(result) != mm(currentResult) {
  1290. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1291. }
  1292. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1293. currentResult = map[string]interface{}{
  1294. "directory": map[string]interface{}{
  1295. "with": map[string]interface{}{
  1296. "a": map[string]interface{}{},
  1297. },
  1298. },
  1299. }
  1300. if mm(result) != mm(currentResult) {
  1301. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1302. }
  1303. // No prefix matching!
  1304. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1305. currentResult = map[string]interface{}{}
  1306. if mm(result) != mm(currentResult) {
  1307. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1308. }
  1309. }
  1310. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1311. db := db.OpenMemory()
  1312. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1313. m.AddFolder(defaultFolderConfig)
  1314. m.ServeBackground()
  1315. b := func(isfile bool, path ...string) protocol.FileInfo {
  1316. typ := protocol.FileInfoTypeDirectory
  1317. blocks := []protocol.BlockInfo{}
  1318. if isfile {
  1319. typ = protocol.FileInfoTypeFile
  1320. 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}}}
  1321. }
  1322. return protocol.FileInfo{
  1323. Name: filepath.Join(path...),
  1324. Type: typ,
  1325. ModifiedS: 0x666,
  1326. Blocks: blocks,
  1327. Size: 0xa,
  1328. }
  1329. }
  1330. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1331. testdata := []protocol.FileInfo{
  1332. b(true, "another", "directory", "afile"),
  1333. b(true, "another", "directory", "with", "a", "file"),
  1334. b(true, "another", "directory", "with", "file"),
  1335. b(false, "other", "random", "dirx"),
  1336. b(false, "other", "randomx"),
  1337. b(false, "some", "directory", "with", "x"),
  1338. b(true, "some", "directory", "with", "a", "file"),
  1339. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1340. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1341. }
  1342. expectedResult := map[string]interface{}{
  1343. "another": map[string]interface{}{
  1344. "directory": map[string]interface{}{
  1345. "afile": filedata,
  1346. "with": map[string]interface{}{
  1347. "a": map[string]interface{}{
  1348. "file": filedata,
  1349. },
  1350. "file": filedata,
  1351. },
  1352. },
  1353. },
  1354. "other": map[string]interface{}{
  1355. "random": map[string]interface{}{
  1356. "dirx": map[string]interface{}{},
  1357. },
  1358. "randomx": map[string]interface{}{},
  1359. },
  1360. "some": map[string]interface{}{
  1361. "directory": map[string]interface{}{
  1362. "with": map[string]interface{}{
  1363. "a": map[string]interface{}{
  1364. "file": filedata,
  1365. },
  1366. "x": map[string]interface{}{},
  1367. },
  1368. },
  1369. },
  1370. "this": map[string]interface{}{
  1371. "is": map[string]interface{}{
  1372. "a": map[string]interface{}{
  1373. "deep": map[string]interface{}{
  1374. "invalid": map[string]interface{}{
  1375. "directory": map[string]interface{}{},
  1376. },
  1377. },
  1378. },
  1379. },
  1380. },
  1381. "xthis": map[string]interface{}{
  1382. "is": map[string]interface{}{
  1383. "a": map[string]interface{}{
  1384. "deep": map[string]interface{}{
  1385. "invalid": map[string]interface{}{
  1386. "file": filedata,
  1387. },
  1388. },
  1389. },
  1390. },
  1391. },
  1392. }
  1393. mm := func(data interface{}) string {
  1394. bytes, err := json.Marshal(data)
  1395. if err != nil {
  1396. panic(err)
  1397. }
  1398. return string(bytes)
  1399. }
  1400. m.Index(device1, "default", testdata)
  1401. result := m.GlobalDirectoryTree("default", "", -1, false)
  1402. if mm(result) != mm(expectedResult) {
  1403. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1404. }
  1405. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1406. currentResult := map[string]interface{}{
  1407. "invalid": map[string]interface{}{
  1408. "file": filedata,
  1409. },
  1410. }
  1411. if mm(result) != mm(currentResult) {
  1412. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1413. }
  1414. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1415. currentResult = map[string]interface{}{
  1416. "invalid": map[string]interface{}{},
  1417. }
  1418. if mm(result) != mm(currentResult) {
  1419. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1420. }
  1421. // !!! This is actually BAD, because we don't have enough level allowance
  1422. // to accept this file, hence the tree is left unbuilt !!!
  1423. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1424. currentResult = map[string]interface{}{}
  1425. if mm(result) != mm(currentResult) {
  1426. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1427. }
  1428. }
  1429. func genDeepFiles(n, d int) []protocol.FileInfo {
  1430. rand.Seed(int64(n))
  1431. files := make([]protocol.FileInfo, n)
  1432. t := time.Now().Unix()
  1433. for i := 0; i < n; i++ {
  1434. path := ""
  1435. for i := 0; i <= d; i++ {
  1436. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1437. }
  1438. sofar := ""
  1439. for _, path := range filepath.SplitList(path) {
  1440. sofar = filepath.Join(sofar, path)
  1441. files[i] = protocol.FileInfo{
  1442. Name: sofar,
  1443. }
  1444. i++
  1445. }
  1446. files[i].ModifiedS = t
  1447. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1448. }
  1449. return files
  1450. }
  1451. func BenchmarkTree_10000_50(b *testing.B) {
  1452. benchmarkTree(b, 10000, 50)
  1453. }
  1454. func BenchmarkTree_100_50(b *testing.B) {
  1455. benchmarkTree(b, 100, 50)
  1456. }
  1457. func BenchmarkTree_100_10(b *testing.B) {
  1458. benchmarkTree(b, 100, 10)
  1459. }
  1460. func benchmarkTree(b *testing.B, n1, n2 int) {
  1461. db := db.OpenMemory()
  1462. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1463. m.AddFolder(defaultFolderConfig)
  1464. m.ServeBackground()
  1465. m.ScanFolder("default")
  1466. files := genDeepFiles(n1, n2)
  1467. m.Index(device1, "default", files)
  1468. b.ResetTimer()
  1469. for i := 0; i < b.N; i++ {
  1470. m.GlobalDirectoryTree("default", "", -1, false)
  1471. }
  1472. b.ReportAllocs()
  1473. }
  1474. func TestUnifySubs(t *testing.T) {
  1475. cases := []struct {
  1476. in []string // input to unifySubs
  1477. exists []string // paths that exist in the database
  1478. out []string // expected output
  1479. }{
  1480. {
  1481. // 0. trailing slashes are cleaned, known paths are just passed on
  1482. []string{"foo/", "bar//"},
  1483. []string{"foo", "bar"},
  1484. []string{"bar", "foo"}, // the output is sorted
  1485. },
  1486. {
  1487. // 1. "foo/bar" gets trimmed as it's covered by foo
  1488. []string{"foo", "bar/", "foo/bar/"},
  1489. []string{"foo", "bar"},
  1490. []string{"bar", "foo"},
  1491. },
  1492. {
  1493. // 2. "" gets simplified to the empty list; ie scan all
  1494. []string{"foo", ""},
  1495. []string{"foo"},
  1496. nil,
  1497. },
  1498. {
  1499. // 3. "foo/bar" is unknown, but it's kept
  1500. // because its parent is known
  1501. []string{"foo/bar"},
  1502. []string{"foo"},
  1503. []string{"foo/bar"},
  1504. },
  1505. {
  1506. // 4. two independent known paths, both are kept
  1507. // "usr/lib" is not a prefix of "usr/libexec"
  1508. []string{"usr/lib", "usr/libexec"},
  1509. []string{"usr", "usr/lib", "usr/libexec"},
  1510. []string{"usr/lib", "usr/libexec"},
  1511. },
  1512. {
  1513. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1514. []string{"usr/lib", "usr/lib/exec"},
  1515. []string{"usr", "usr/lib", "usr/libexec"},
  1516. []string{"usr/lib"},
  1517. },
  1518. {
  1519. // 6. .stignore and .stfolder are special and are passed on
  1520. // verbatim even though they are unknown
  1521. []string{config.DefaultMarkerName, ".stignore"},
  1522. []string{},
  1523. []string{config.DefaultMarkerName, ".stignore"},
  1524. },
  1525. {
  1526. // 7. but the presence of something else unknown forces an actual
  1527. // scan
  1528. []string{config.DefaultMarkerName, ".stignore", "foo/bar"},
  1529. []string{},
  1530. []string{config.DefaultMarkerName, ".stignore", "foo"},
  1531. },
  1532. {
  1533. // 8. explicit request to scan all
  1534. nil,
  1535. []string{"foo"},
  1536. nil,
  1537. },
  1538. {
  1539. // 9. empty list of subs
  1540. []string{},
  1541. []string{"foo"},
  1542. nil,
  1543. },
  1544. }
  1545. if runtime.GOOS == "windows" {
  1546. // Fixup path separators
  1547. for i := range cases {
  1548. for j, p := range cases[i].in {
  1549. cases[i].in[j] = filepath.FromSlash(p)
  1550. }
  1551. for j, p := range cases[i].exists {
  1552. cases[i].exists[j] = filepath.FromSlash(p)
  1553. }
  1554. for j, p := range cases[i].out {
  1555. cases[i].out[j] = filepath.FromSlash(p)
  1556. }
  1557. }
  1558. }
  1559. for i, tc := range cases {
  1560. exists := func(f string) bool {
  1561. for _, e := range tc.exists {
  1562. if f == e {
  1563. return true
  1564. }
  1565. }
  1566. return false
  1567. }
  1568. out := unifySubs(tc.in, exists)
  1569. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1570. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1571. }
  1572. }
  1573. }
  1574. func TestIssue3028(t *testing.T) {
  1575. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1576. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1577. t.Fatal(err)
  1578. }
  1579. defer os.Remove("testdata/testrm")
  1580. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1581. t.Fatal(err)
  1582. }
  1583. defer os.Remove("testdata/testrm2")
  1584. // Create a model and default folder
  1585. db := db.OpenMemory()
  1586. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1587. defCfg := defaultFolderConfig.Copy()
  1588. defCfg.RescanIntervalS = 86400
  1589. m.AddFolder(defCfg)
  1590. m.StartFolder("default")
  1591. m.ServeBackground()
  1592. // Make sure the initial scan has finished (ScanFolders is blocking)
  1593. m.ScanFolders()
  1594. // Get a count of how many files are there now
  1595. locorigfiles := m.LocalSize("default").Files
  1596. globorigfiles := m.GlobalSize("default").Files
  1597. // Delete and rescan specifically these two
  1598. os.Remove("testdata/testrm")
  1599. os.Remove("testdata/testrm2")
  1600. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1601. // Verify that the number of files decreased by two and the number of
  1602. // deleted files increases by two
  1603. loc := m.LocalSize("default")
  1604. glob := m.GlobalSize("default")
  1605. if loc.Files != locorigfiles-2 {
  1606. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1607. }
  1608. if glob.Files != globorigfiles-2 {
  1609. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1610. }
  1611. if loc.Deleted != 2 {
  1612. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1613. }
  1614. if glob.Deleted != 2 {
  1615. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1616. }
  1617. }
  1618. func TestIssue3164(t *testing.T) {
  1619. os.RemoveAll("testdata/issue3164")
  1620. defer os.RemoveAll("testdata/issue3164")
  1621. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1622. t.Fatal(err)
  1623. }
  1624. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1625. t.Fatal(err)
  1626. }
  1627. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1628. t.Fatal(err)
  1629. }
  1630. f := protocol.FileInfo{
  1631. Name: "issue3164",
  1632. }
  1633. m := ignore.New(defaultFs)
  1634. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1635. t.Fatal(err)
  1636. }
  1637. fl := sendReceiveFolder{
  1638. dbUpdates: make(chan dbUpdateJob, 1),
  1639. fs: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  1640. }
  1641. fl.deleteDir(f, m)
  1642. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1643. t.Fatal(err)
  1644. }
  1645. }
  1646. func TestIssue4357(t *testing.T) {
  1647. db := db.OpenMemory()
  1648. cfg := defaultConfig.RawCopy()
  1649. // Create a separate wrapper not to pollute other tests.
  1650. wrapper := config.Wrap("/tmp/test", config.Configuration{})
  1651. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1652. m.ServeBackground()
  1653. defer m.Stop()
  1654. // Force the model to wire itself and add the folders
  1655. if err := wrapper.ReplaceBlocking(cfg); err != nil {
  1656. t.Error(err)
  1657. }
  1658. if _, ok := m.folderCfgs["default"]; !ok {
  1659. t.Error("Folder should be running")
  1660. }
  1661. newCfg := wrapper.RawCopy()
  1662. newCfg.Folders[0].Paused = true
  1663. if err := wrapper.ReplaceBlocking(newCfg); err != nil {
  1664. t.Error(err)
  1665. }
  1666. if _, ok := m.folderCfgs["default"]; ok {
  1667. t.Error("Folder should not be running")
  1668. }
  1669. if _, ok := m.cfg.Folder("default"); !ok {
  1670. t.Error("should still have folder in config")
  1671. }
  1672. if err := wrapper.ReplaceBlocking(config.Configuration{}); err != nil {
  1673. t.Error(err)
  1674. }
  1675. if _, ok := m.cfg.Folder("default"); ok {
  1676. t.Error("should not have folder in config")
  1677. }
  1678. // Add the folder back, should be running
  1679. if err := wrapper.ReplaceBlocking(cfg); err != nil {
  1680. t.Error(err)
  1681. }
  1682. if _, ok := m.folderCfgs["default"]; !ok {
  1683. t.Error("Folder should be running")
  1684. }
  1685. if _, ok := m.cfg.Folder("default"); !ok {
  1686. t.Error("should still have folder in config")
  1687. }
  1688. // Should not panic when removing a running folder.
  1689. if err := wrapper.ReplaceBlocking(config.Configuration{}); err != nil {
  1690. t.Error(err)
  1691. }
  1692. if _, ok := m.folderCfgs["default"]; ok {
  1693. t.Error("Folder should not be running")
  1694. }
  1695. if _, ok := m.cfg.Folder("default"); ok {
  1696. t.Error("should not have folder in config")
  1697. }
  1698. }
  1699. func TestScanNoDatabaseWrite(t *testing.T) {
  1700. // When scanning, nothing should be committed to database unless
  1701. // something actually changed.
  1702. db := db.OpenMemory()
  1703. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1704. m.AddFolder(defaultFolderConfig)
  1705. m.StartFolder("default")
  1706. m.ServeBackground()
  1707. // Start with no ignores, and restore the previous state when the test completes
  1708. curIgn, _, err := m.GetIgnores("default")
  1709. if err != nil {
  1710. t.Fatal(err)
  1711. }
  1712. defer m.SetIgnores("default", curIgn)
  1713. m.SetIgnores("default", nil)
  1714. fakeTime := time.Now().Add(5 * time.Second)
  1715. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1716. // Scan the folder twice. The second scan should be a no-op database wise
  1717. m.ScanFolder("default")
  1718. c0 := db.Committed()
  1719. m.ScanFolder("default")
  1720. c1 := db.Committed()
  1721. if c1 != c0 {
  1722. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1723. }
  1724. // Ignore a file we know exists. It'll be updated in the database.
  1725. m.SetIgnores("default", []string{"foo"})
  1726. fakeTime = time.Now().Add(10 * time.Second)
  1727. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1728. m.ScanFolder("default")
  1729. c2 := db.Committed()
  1730. if c2 <= c1 {
  1731. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1732. }
  1733. // Scan again. Nothing should happen.
  1734. m.ScanFolder("default")
  1735. c3 := db.Committed()
  1736. if c3 != c2 {
  1737. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1738. }
  1739. }
  1740. func TestIssue2782(t *testing.T) {
  1741. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  1742. if runtime.GOOS == "windows" {
  1743. t.Skip("not reliable on Windows")
  1744. return
  1745. }
  1746. home := os.Getenv("HOME")
  1747. if home == "" {
  1748. t.Skip("no home")
  1749. }
  1750. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1751. // part of the issue. Skip the test if any of this fails, as we are a
  1752. // bit outside of our stated domain here...
  1753. testName := ".syncthing-test." + srand.String(16)
  1754. testDir := filepath.Join(home, testName)
  1755. if err := os.RemoveAll(testDir); err != nil {
  1756. t.Skip(err)
  1757. }
  1758. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1759. t.Skip(err)
  1760. }
  1761. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1762. t.Skip(err)
  1763. }
  1764. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1765. t.Skip(err)
  1766. }
  1767. defer os.RemoveAll(testDir)
  1768. db := db.OpenMemory()
  1769. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1770. m.AddFolder(config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  1771. m.StartFolder("default")
  1772. m.ServeBackground()
  1773. defer m.Stop()
  1774. if err := m.ScanFolder("default"); err != nil {
  1775. t.Error("scan error:", err)
  1776. }
  1777. m.fmut.Lock()
  1778. runner, _ := m.folderRunners["default"]
  1779. m.fmut.Unlock()
  1780. if err := runner.CheckHealth(); err != nil {
  1781. t.Error("health check error:", err)
  1782. }
  1783. }
  1784. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1785. dbi := db.OpenMemory()
  1786. files := db.NewFileSet("default", defaultFs, dbi)
  1787. files.Replace(device1, genFiles(1))
  1788. files.Replace(device2, genFiles(1))
  1789. if len(files.ListDevices()) != 2 {
  1790. t.Error("expected two devices")
  1791. }
  1792. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1793. m.AddFolder(defaultFolderConfig)
  1794. m.StartFolder("default")
  1795. // Remote sequence is cached, hence need to recreated.
  1796. files = db.NewFileSet("default", defaultFs, dbi)
  1797. if len(files.ListDevices()) != 1 {
  1798. t.Error("Expected one device")
  1799. }
  1800. }
  1801. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1802. dbi := db.OpenMemory()
  1803. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  1804. fcfg.Devices = []config.FolderDeviceConfiguration{
  1805. {DeviceID: device1},
  1806. {DeviceID: device2},
  1807. }
  1808. cfg := config.Configuration{
  1809. Folders: []config.FolderConfiguration{fcfg},
  1810. Devices: []config.DeviceConfiguration{
  1811. config.NewDeviceConfiguration(device1, "device1"),
  1812. config.NewDeviceConfiguration(device2, "device2"),
  1813. },
  1814. Options: config.OptionsConfiguration{
  1815. // Don't remove temporaries directly on startup
  1816. KeepTemporariesH: 1,
  1817. },
  1818. }
  1819. wcfg := config.Wrap("/tmp/test", cfg)
  1820. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1821. m.AddFolder(fcfg)
  1822. m.StartFolder(fcfg.ID)
  1823. m.ServeBackground()
  1824. conn1 := &fakeConnection{id: device1}
  1825. m.AddConnection(conn1, protocol.HelloResult{})
  1826. conn2 := &fakeConnection{id: device2}
  1827. m.AddConnection(conn2, protocol.HelloResult{})
  1828. m.ClusterConfig(device1, protocol.ClusterConfig{
  1829. Folders: []protocol.Folder{
  1830. {
  1831. ID: "default",
  1832. Devices: []protocol.Device{
  1833. {ID: device1},
  1834. {ID: device2},
  1835. },
  1836. },
  1837. },
  1838. })
  1839. m.ClusterConfig(device2, protocol.ClusterConfig{
  1840. Folders: []protocol.Folder{
  1841. {
  1842. ID: "default",
  1843. Devices: []protocol.Device{
  1844. {ID: device1},
  1845. {ID: device2},
  1846. },
  1847. },
  1848. },
  1849. })
  1850. if !m.folderSharedWith("default", device1) {
  1851. t.Error("not shared with device1")
  1852. }
  1853. if !m.folderSharedWith("default", device2) {
  1854. t.Error("not shared with device2")
  1855. }
  1856. if conn2.Closed() {
  1857. t.Error("conn already closed")
  1858. }
  1859. cfg = cfg.Copy()
  1860. cfg.Devices = cfg.Devices[:1]
  1861. if err := wcfg.Replace(cfg); err != nil {
  1862. t.Error(err)
  1863. }
  1864. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1865. if !m.folderSharedWith("default", device1) {
  1866. t.Error("not shared with device1")
  1867. }
  1868. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1869. t.Error("shared with device2")
  1870. }
  1871. if !conn2.Closed() {
  1872. t.Error("connection not closed")
  1873. }
  1874. if _, ok := wcfg.Devices()[device2]; ok {
  1875. t.Error("device still in config")
  1876. }
  1877. fdevs, ok := m.folderDevices["default"]
  1878. if !ok {
  1879. t.Error("folder missing?")
  1880. }
  1881. for id := range fdevs {
  1882. if id == device2 {
  1883. t.Error("still there")
  1884. }
  1885. }
  1886. if _, ok := m.conn[device2]; !ok {
  1887. t.Error("conn missing early")
  1888. }
  1889. if _, ok := m.helloMessages[device2]; !ok {
  1890. t.Error("hello missing early")
  1891. }
  1892. if _, ok := m.deviceDownloads[device2]; !ok {
  1893. t.Error("downloads missing early")
  1894. }
  1895. m.Closed(conn2, fmt.Errorf("foo"))
  1896. if _, ok := m.conn[device2]; ok {
  1897. t.Error("conn not missing")
  1898. }
  1899. if _, ok := m.helloMessages[device2]; ok {
  1900. t.Error("hello not missing")
  1901. }
  1902. if _, ok := m.deviceDownloads[device2]; ok {
  1903. t.Error("downloads not missing")
  1904. }
  1905. }
  1906. func TestIssue3496(t *testing.T) {
  1907. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  1908. // It seems like lots of deleted files can cause negative completion
  1909. // percentages. Lets make sure that doesn't happen. Also do some general
  1910. // checks on the completion calculation stuff.
  1911. dbi := db.OpenMemory()
  1912. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1913. m.AddFolder(defaultFolderConfig)
  1914. m.StartFolder("default")
  1915. m.ServeBackground()
  1916. defer m.Stop()
  1917. m.ScanFolder("default")
  1918. addFakeConn(m, device1)
  1919. addFakeConn(m, device2)
  1920. // Reach into the model and grab the current file list...
  1921. m.fmut.RLock()
  1922. fs := m.folderFiles["default"]
  1923. m.fmut.RUnlock()
  1924. var localFiles []protocol.FileInfo
  1925. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1926. localFiles = append(localFiles, i.(protocol.FileInfo))
  1927. return true
  1928. })
  1929. // Mark all files as deleted and fake it as update from device1
  1930. for i := range localFiles {
  1931. localFiles[i].Deleted = true
  1932. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1933. localFiles[i].Blocks = nil
  1934. }
  1935. // Also add a small file that we're supposed to need, or the global size
  1936. // stuff will bail out early due to the entire folder being zero size.
  1937. localFiles = append(localFiles, protocol.FileInfo{
  1938. Name: "fake",
  1939. Size: 1234,
  1940. Type: protocol.FileInfoTypeFile,
  1941. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1942. })
  1943. m.IndexUpdate(device1, "default", localFiles)
  1944. // Check that the completion percentage for us makes sense
  1945. comp := m.Completion(protocol.LocalDeviceID, "default")
  1946. if comp.NeedBytes > comp.GlobalBytes {
  1947. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1948. }
  1949. if comp.CompletionPct < 0 {
  1950. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1951. }
  1952. if comp.NeedBytes == 0 {
  1953. t.Error("Need no bytes even though some files are deleted")
  1954. }
  1955. if comp.CompletionPct == 100 {
  1956. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1957. }
  1958. t.Log(comp)
  1959. // Check that NeedSize does the correct thing
  1960. need := m.NeedSize("default")
  1961. if need.Files != 1 || need.Bytes != 1234 {
  1962. // The one we added synthetically above
  1963. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1964. }
  1965. if need.Deleted != len(localFiles)-1 {
  1966. // The rest
  1967. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1968. }
  1969. }
  1970. func TestIssue3804(t *testing.T) {
  1971. dbi := db.OpenMemory()
  1972. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1973. m.AddFolder(defaultFolderConfig)
  1974. m.StartFolder("default")
  1975. m.ServeBackground()
  1976. defer m.Stop()
  1977. // Subdirs ending in slash should be accepted
  1978. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1979. t.Error("Unexpected error:", err)
  1980. }
  1981. }
  1982. func TestIssue3829(t *testing.T) {
  1983. dbi := db.OpenMemory()
  1984. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  1985. m.AddFolder(defaultFolderConfig)
  1986. m.StartFolder("default")
  1987. m.ServeBackground()
  1988. defer m.Stop()
  1989. // Empty subdirs should be accepted
  1990. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1991. t.Error("Unexpected error:", err)
  1992. }
  1993. }
  1994. func TestNoRequestsFromPausedDevices(t *testing.T) {
  1995. t.Skip("broken, fails randomly, #3843")
  1996. dbi := db.OpenMemory()
  1997. fcfg := config.NewFolderConfiguration("default", fs.FilesystemTypeBasic, "testdata")
  1998. fcfg.Devices = []config.FolderDeviceConfiguration{
  1999. {DeviceID: device1},
  2000. {DeviceID: device2},
  2001. }
  2002. cfg := config.Configuration{
  2003. Folders: []config.FolderConfiguration{fcfg},
  2004. Devices: []config.DeviceConfiguration{
  2005. config.NewDeviceConfiguration(device1, "device1"),
  2006. config.NewDeviceConfiguration(device2, "device2"),
  2007. },
  2008. Options: config.OptionsConfiguration{
  2009. // Don't remove temporaries directly on startup
  2010. KeepTemporariesH: 1,
  2011. },
  2012. }
  2013. wcfg := config.Wrap("/tmp/test", cfg)
  2014. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2015. m.AddFolder(fcfg)
  2016. m.StartFolder(fcfg.ID)
  2017. m.ServeBackground()
  2018. file := testDataExpected["foo"]
  2019. files := m.folderFiles["default"]
  2020. files.Update(device1, []protocol.FileInfo{file})
  2021. files.Update(device2, []protocol.FileInfo{file})
  2022. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2023. if len(avail) != 0 {
  2024. t.Errorf("should not be available, no connections")
  2025. }
  2026. addFakeConn(m, device1)
  2027. addFakeConn(m, device2)
  2028. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2029. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2030. if len(avail) != 2 {
  2031. t.Errorf("should have two available")
  2032. }
  2033. cc := protocol.ClusterConfig{
  2034. Folders: []protocol.Folder{
  2035. {
  2036. ID: "default",
  2037. Devices: []protocol.Device{
  2038. {ID: device1},
  2039. {ID: device2},
  2040. },
  2041. },
  2042. },
  2043. }
  2044. m.ClusterConfig(device1, cc)
  2045. m.ClusterConfig(device2, cc)
  2046. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2047. if len(avail) != 2 {
  2048. t.Errorf("should have two available")
  2049. }
  2050. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2051. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2052. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2053. if len(avail) != 0 {
  2054. t.Errorf("should have no available")
  2055. }
  2056. // Test that remote paused folders are not used.
  2057. addFakeConn(m, device1)
  2058. addFakeConn(m, device2)
  2059. m.ClusterConfig(device1, cc)
  2060. ccp := cc
  2061. ccp.Folders[0].Paused = true
  2062. m.ClusterConfig(device1, ccp)
  2063. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  2064. if len(avail) != 1 {
  2065. t.Errorf("should have one available")
  2066. }
  2067. }
  2068. func TestCustomMarkerName(t *testing.T) {
  2069. ldb := db.OpenMemory()
  2070. set := db.NewFileSet("default", defaultFs, ldb)
  2071. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2072. {Name: "dummyfile"},
  2073. })
  2074. fcfg := config.FolderConfiguration{
  2075. ID: "default",
  2076. Path: "testdata/rwtestfolder",
  2077. Type: config.FolderTypeSendReceive,
  2078. RescanIntervalS: 1,
  2079. MarkerName: "myfile",
  2080. }
  2081. cfg := config.Wrap("/tmp/test", config.Configuration{
  2082. Folders: []config.FolderConfiguration{fcfg},
  2083. Devices: []config.DeviceConfiguration{
  2084. {
  2085. DeviceID: device1,
  2086. },
  2087. },
  2088. })
  2089. os.RemoveAll(fcfg.Path)
  2090. defer os.RemoveAll(fcfg.Path)
  2091. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  2092. m.AddFolder(fcfg)
  2093. m.StartFolder("default")
  2094. m.ServeBackground()
  2095. defer m.Stop()
  2096. waitFor := func(status string) error {
  2097. timeout := time.Now().Add(2 * time.Second)
  2098. for {
  2099. _, _, err := m.State("default")
  2100. if err == nil && status == "" {
  2101. return nil
  2102. }
  2103. if err != nil && err.Error() == status {
  2104. return nil
  2105. }
  2106. if time.Now().After(timeout) {
  2107. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  2108. }
  2109. time.Sleep(10 * time.Millisecond)
  2110. }
  2111. }
  2112. if err := waitFor("folder path missing"); err != nil {
  2113. t.Error(err)
  2114. return
  2115. }
  2116. os.Mkdir(fcfg.Path, 0700)
  2117. fd, err := os.Create(filepath.Join(fcfg.Path, "myfile"))
  2118. if err != nil {
  2119. t.Error(err)
  2120. return
  2121. }
  2122. fd.Close()
  2123. if err := waitFor(""); err != nil {
  2124. t.Error(err)
  2125. return
  2126. }
  2127. }
  2128. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2129. fc := &fakeConnection{id: dev, model: m}
  2130. m.AddConnection(fc, protocol.HelloResult{})
  2131. m.ClusterConfig(dev, protocol.ClusterConfig{
  2132. Folders: []protocol.Folder{
  2133. {
  2134. ID: "default",
  2135. Devices: []protocol.Device{
  2136. {ID: device1},
  2137. {ID: device2},
  2138. },
  2139. },
  2140. },
  2141. })
  2142. return fc
  2143. }
  2144. type fakeAddr struct{}
  2145. func (fakeAddr) Network() string {
  2146. return "network"
  2147. }
  2148. func (fakeAddr) String() string {
  2149. return "address"
  2150. }
  2151. type alwaysChangedKey struct {
  2152. fs fs.Filesystem
  2153. name string
  2154. }
  2155. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  2156. type alwaysChanged struct {
  2157. seen map[alwaysChangedKey]struct{}
  2158. }
  2159. func newAlwaysChanged() *alwaysChanged {
  2160. return &alwaysChanged{
  2161. seen: make(map[alwaysChangedKey]struct{}),
  2162. }
  2163. }
  2164. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  2165. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  2166. }
  2167. func (c *alwaysChanged) Reset() {
  2168. c.seen = make(map[alwaysChangedKey]struct{})
  2169. }
  2170. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  2171. _, ok := c.seen[alwaysChangedKey{fs, name}]
  2172. return ok
  2173. }
  2174. func (c *alwaysChanged) Changed() bool {
  2175. return true
  2176. }