model_test.go 63 KB

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