model_test.go 62 KB

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