model_test.go 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466
  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 http://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)
  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 TestIgnores(t *testing.T) {
  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. // Assure a clean start state
  819. ioutil.WriteFile("testdata/.stfolder", nil, 0644)
  820. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  821. db := db.OpenMemory()
  822. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  823. m.AddFolder(defaultFolderConfig)
  824. m.StartFolder("default")
  825. m.ServeBackground()
  826. defer m.Stop()
  827. expected := []string{
  828. ".*",
  829. "quux",
  830. }
  831. ignores, _, err := m.GetIgnores("default")
  832. if err != nil {
  833. t.Error(err)
  834. }
  835. if !arrEqual(ignores, expected) {
  836. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  837. }
  838. ignores = append(ignores, "pox")
  839. err = m.SetIgnores("default", ignores)
  840. if err != nil {
  841. t.Error(err)
  842. }
  843. ignores2, _, err := m.GetIgnores("default")
  844. if err != nil {
  845. t.Error(err)
  846. }
  847. if arrEqual(expected, ignores2) {
  848. t.Errorf("Incorrect ignores: %v == %v", ignores2, expected)
  849. }
  850. if !arrEqual(ignores, ignores2) {
  851. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  852. }
  853. err = m.SetIgnores("default", expected)
  854. if err != nil {
  855. t.Error(err)
  856. }
  857. ignores, _, err = m.GetIgnores("default")
  858. if err != nil {
  859. t.Error(err)
  860. }
  861. if !arrEqual(ignores, expected) {
  862. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  863. }
  864. _, _, err = m.GetIgnores("doesnotexist")
  865. if err == nil {
  866. t.Error("No error")
  867. }
  868. err = m.SetIgnores("doesnotexist", expected)
  869. if err == nil {
  870. t.Error("No error")
  871. }
  872. // Invalid path, marker should be missing, hence returns an error.
  873. m.AddFolder(config.FolderConfiguration{ID: "fresh", RawPath: "XXX"})
  874. _, _, err = m.GetIgnores("fresh")
  875. if err == nil {
  876. t.Error("No error")
  877. }
  878. }
  879. func TestROScanRecovery(t *testing.T) {
  880. ldb := db.OpenMemory()
  881. set := db.NewFileSet("default", ldb)
  882. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  883. {Name: "dummyfile"},
  884. })
  885. fcfg := config.FolderConfiguration{
  886. ID: "default",
  887. RawPath: "testdata/rotestfolder",
  888. Type: config.FolderTypeSendOnly,
  889. RescanIntervalS: 1,
  890. }
  891. cfg := config.Wrap("/tmp/test", config.Configuration{
  892. Folders: []config.FolderConfiguration{fcfg},
  893. Devices: []config.DeviceConfiguration{
  894. {
  895. DeviceID: device1,
  896. },
  897. },
  898. })
  899. os.RemoveAll(fcfg.RawPath)
  900. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  901. m.AddFolder(fcfg)
  902. m.StartFolder("default")
  903. m.ServeBackground()
  904. defer m.Stop()
  905. waitFor := func(status string) error {
  906. timeout := time.Now().Add(2 * time.Second)
  907. for {
  908. _, _, err := m.State("default")
  909. if err == nil && status == "" {
  910. return nil
  911. }
  912. if err != nil && err.Error() == status {
  913. return nil
  914. }
  915. if time.Now().After(timeout) {
  916. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  917. }
  918. time.Sleep(10 * time.Millisecond)
  919. }
  920. }
  921. if err := waitFor("folder path missing"); err != nil {
  922. t.Error(err)
  923. return
  924. }
  925. os.Mkdir(fcfg.RawPath, 0700)
  926. if err := waitFor("folder marker missing"); err != nil {
  927. t.Error(err)
  928. return
  929. }
  930. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  931. if err != nil {
  932. t.Error(err)
  933. return
  934. }
  935. fd.Close()
  936. if err := waitFor(""); err != nil {
  937. t.Error(err)
  938. return
  939. }
  940. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  941. if err := waitFor("folder marker missing"); err != nil {
  942. t.Error(err)
  943. return
  944. }
  945. os.Remove(fcfg.RawPath)
  946. if err := waitFor("folder path missing"); err != nil {
  947. t.Error(err)
  948. return
  949. }
  950. }
  951. func TestRWScanRecovery(t *testing.T) {
  952. ldb := db.OpenMemory()
  953. set := db.NewFileSet("default", ldb)
  954. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  955. {Name: "dummyfile"},
  956. })
  957. fcfg := config.FolderConfiguration{
  958. ID: "default",
  959. RawPath: "testdata/rwtestfolder",
  960. Type: config.FolderTypeSendReceive,
  961. RescanIntervalS: 1,
  962. }
  963. cfg := config.Wrap("/tmp/test", config.Configuration{
  964. Folders: []config.FolderConfiguration{fcfg},
  965. Devices: []config.DeviceConfiguration{
  966. {
  967. DeviceID: device1,
  968. },
  969. },
  970. })
  971. os.RemoveAll(fcfg.RawPath)
  972. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  973. m.AddFolder(fcfg)
  974. m.StartFolder("default")
  975. m.ServeBackground()
  976. defer m.Stop()
  977. waitFor := func(status string) error {
  978. timeout := time.Now().Add(2 * time.Second)
  979. for {
  980. _, _, err := m.State("default")
  981. if err == nil && status == "" {
  982. return nil
  983. }
  984. if err != nil && err.Error() == status {
  985. return nil
  986. }
  987. if time.Now().After(timeout) {
  988. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  989. }
  990. time.Sleep(10 * time.Millisecond)
  991. }
  992. }
  993. if err := waitFor("folder path missing"); err != nil {
  994. t.Error(err)
  995. return
  996. }
  997. os.Mkdir(fcfg.RawPath, 0700)
  998. if err := waitFor("folder marker missing"); err != nil {
  999. t.Error(err)
  1000. return
  1001. }
  1002. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  1003. if err != nil {
  1004. t.Error(err)
  1005. return
  1006. }
  1007. fd.Close()
  1008. if err := waitFor(""); err != nil {
  1009. t.Error(err)
  1010. return
  1011. }
  1012. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  1013. if err := waitFor("folder marker missing"); err != nil {
  1014. t.Error(err)
  1015. return
  1016. }
  1017. os.Remove(fcfg.RawPath)
  1018. if err := waitFor("folder path missing"); err != nil {
  1019. t.Error(err)
  1020. return
  1021. }
  1022. }
  1023. func TestGlobalDirectoryTree(t *testing.T) {
  1024. db := db.OpenMemory()
  1025. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1026. m.AddFolder(defaultFolderConfig)
  1027. m.ServeBackground()
  1028. defer m.Stop()
  1029. b := func(isfile bool, path ...string) protocol.FileInfo {
  1030. typ := protocol.FileInfoTypeDirectory
  1031. blocks := []protocol.BlockInfo{}
  1032. if isfile {
  1033. typ = protocol.FileInfoTypeFile
  1034. 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}}}
  1035. }
  1036. return protocol.FileInfo{
  1037. Name: filepath.Join(path...),
  1038. Type: typ,
  1039. ModifiedS: 0x666,
  1040. Blocks: blocks,
  1041. Size: 0xa,
  1042. }
  1043. }
  1044. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1045. testdata := []protocol.FileInfo{
  1046. b(false, "another"),
  1047. b(false, "another", "directory"),
  1048. b(true, "another", "directory", "afile"),
  1049. b(false, "another", "directory", "with"),
  1050. b(false, "another", "directory", "with", "a"),
  1051. b(true, "another", "directory", "with", "a", "file"),
  1052. b(true, "another", "directory", "with", "file"),
  1053. b(true, "another", "file"),
  1054. b(false, "other"),
  1055. b(false, "other", "rand"),
  1056. b(false, "other", "random"),
  1057. b(false, "other", "random", "dir"),
  1058. b(false, "other", "random", "dirx"),
  1059. b(false, "other", "randomx"),
  1060. b(false, "some"),
  1061. b(false, "some", "directory"),
  1062. b(false, "some", "directory", "with"),
  1063. b(false, "some", "directory", "with", "a"),
  1064. b(true, "some", "directory", "with", "a", "file"),
  1065. b(true, "rootfile"),
  1066. }
  1067. expectedResult := map[string]interface{}{
  1068. "another": map[string]interface{}{
  1069. "directory": map[string]interface{}{
  1070. "afile": filedata,
  1071. "with": map[string]interface{}{
  1072. "a": map[string]interface{}{
  1073. "file": filedata,
  1074. },
  1075. "file": filedata,
  1076. },
  1077. },
  1078. "file": filedata,
  1079. },
  1080. "other": map[string]interface{}{
  1081. "rand": map[string]interface{}{},
  1082. "random": map[string]interface{}{
  1083. "dir": map[string]interface{}{},
  1084. "dirx": map[string]interface{}{},
  1085. },
  1086. "randomx": map[string]interface{}{},
  1087. },
  1088. "some": map[string]interface{}{
  1089. "directory": map[string]interface{}{
  1090. "with": map[string]interface{}{
  1091. "a": map[string]interface{}{
  1092. "file": filedata,
  1093. },
  1094. },
  1095. },
  1096. },
  1097. "rootfile": filedata,
  1098. }
  1099. mm := func(data interface{}) string {
  1100. bytes, err := json.Marshal(data)
  1101. if err != nil {
  1102. panic(err)
  1103. }
  1104. return string(bytes)
  1105. }
  1106. m.Index(device1, "default", testdata)
  1107. result := m.GlobalDirectoryTree("default", "", -1, false)
  1108. if mm(result) != mm(expectedResult) {
  1109. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1110. }
  1111. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1112. if mm(result) != mm(expectedResult["another"]) {
  1113. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1114. }
  1115. result = m.GlobalDirectoryTree("default", "", 0, false)
  1116. currentResult := map[string]interface{}{
  1117. "another": map[string]interface{}{},
  1118. "other": map[string]interface{}{},
  1119. "some": map[string]interface{}{},
  1120. "rootfile": filedata,
  1121. }
  1122. if mm(result) != mm(currentResult) {
  1123. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1124. }
  1125. result = m.GlobalDirectoryTree("default", "", 1, false)
  1126. currentResult = map[string]interface{}{
  1127. "another": map[string]interface{}{
  1128. "directory": map[string]interface{}{},
  1129. "file": filedata,
  1130. },
  1131. "other": map[string]interface{}{
  1132. "rand": map[string]interface{}{},
  1133. "random": map[string]interface{}{},
  1134. "randomx": map[string]interface{}{},
  1135. },
  1136. "some": map[string]interface{}{
  1137. "directory": map[string]interface{}{},
  1138. },
  1139. "rootfile": filedata,
  1140. }
  1141. if mm(result) != mm(currentResult) {
  1142. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1143. }
  1144. result = m.GlobalDirectoryTree("default", "", -1, true)
  1145. currentResult = map[string]interface{}{
  1146. "another": map[string]interface{}{
  1147. "directory": map[string]interface{}{
  1148. "with": map[string]interface{}{
  1149. "a": map[string]interface{}{},
  1150. },
  1151. },
  1152. },
  1153. "other": map[string]interface{}{
  1154. "rand": map[string]interface{}{},
  1155. "random": map[string]interface{}{
  1156. "dir": map[string]interface{}{},
  1157. "dirx": map[string]interface{}{},
  1158. },
  1159. "randomx": map[string]interface{}{},
  1160. },
  1161. "some": map[string]interface{}{
  1162. "directory": map[string]interface{}{
  1163. "with": map[string]interface{}{
  1164. "a": map[string]interface{}{},
  1165. },
  1166. },
  1167. },
  1168. }
  1169. if mm(result) != mm(currentResult) {
  1170. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1171. }
  1172. result = m.GlobalDirectoryTree("default", "", 1, true)
  1173. currentResult = map[string]interface{}{
  1174. "another": map[string]interface{}{
  1175. "directory": map[string]interface{}{},
  1176. },
  1177. "other": map[string]interface{}{
  1178. "rand": map[string]interface{}{},
  1179. "random": map[string]interface{}{},
  1180. "randomx": map[string]interface{}{},
  1181. },
  1182. "some": map[string]interface{}{
  1183. "directory": map[string]interface{}{},
  1184. },
  1185. }
  1186. if mm(result) != mm(currentResult) {
  1187. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1188. }
  1189. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1190. currentResult = map[string]interface{}{
  1191. "directory": map[string]interface{}{},
  1192. "file": filedata,
  1193. }
  1194. if mm(result) != mm(currentResult) {
  1195. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1196. }
  1197. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1198. currentResult = map[string]interface{}{
  1199. "with": map[string]interface{}{},
  1200. }
  1201. if mm(result) != mm(currentResult) {
  1202. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1203. }
  1204. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1205. currentResult = map[string]interface{}{
  1206. "with": map[string]interface{}{
  1207. "a": map[string]interface{}{},
  1208. },
  1209. }
  1210. if mm(result) != mm(currentResult) {
  1211. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1212. }
  1213. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1214. currentResult = map[string]interface{}{
  1215. "with": map[string]interface{}{
  1216. "a": map[string]interface{}{
  1217. "file": filedata,
  1218. },
  1219. },
  1220. }
  1221. if mm(result) != mm(currentResult) {
  1222. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1223. }
  1224. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1225. currentResult = map[string]interface{}{
  1226. "directory": map[string]interface{}{
  1227. "with": map[string]interface{}{
  1228. "a": map[string]interface{}{},
  1229. },
  1230. },
  1231. }
  1232. if mm(result) != mm(currentResult) {
  1233. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1234. }
  1235. // No prefix matching!
  1236. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1237. currentResult = map[string]interface{}{}
  1238. if mm(result) != mm(currentResult) {
  1239. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1240. }
  1241. }
  1242. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1243. db := db.OpenMemory()
  1244. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1245. m.AddFolder(defaultFolderConfig)
  1246. m.ServeBackground()
  1247. b := func(isfile bool, path ...string) protocol.FileInfo {
  1248. typ := protocol.FileInfoTypeDirectory
  1249. blocks := []protocol.BlockInfo{}
  1250. if isfile {
  1251. typ = protocol.FileInfoTypeFile
  1252. 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}}}
  1253. }
  1254. return protocol.FileInfo{
  1255. Name: filepath.Join(path...),
  1256. Type: typ,
  1257. ModifiedS: 0x666,
  1258. Blocks: blocks,
  1259. Size: 0xa,
  1260. }
  1261. }
  1262. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1263. testdata := []protocol.FileInfo{
  1264. b(true, "another", "directory", "afile"),
  1265. b(true, "another", "directory", "with", "a", "file"),
  1266. b(true, "another", "directory", "with", "file"),
  1267. b(false, "other", "random", "dirx"),
  1268. b(false, "other", "randomx"),
  1269. b(false, "some", "directory", "with", "x"),
  1270. b(true, "some", "directory", "with", "a", "file"),
  1271. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1272. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1273. }
  1274. expectedResult := map[string]interface{}{
  1275. "another": map[string]interface{}{
  1276. "directory": map[string]interface{}{
  1277. "afile": filedata,
  1278. "with": map[string]interface{}{
  1279. "a": map[string]interface{}{
  1280. "file": filedata,
  1281. },
  1282. "file": filedata,
  1283. },
  1284. },
  1285. },
  1286. "other": map[string]interface{}{
  1287. "random": map[string]interface{}{
  1288. "dirx": map[string]interface{}{},
  1289. },
  1290. "randomx": map[string]interface{}{},
  1291. },
  1292. "some": map[string]interface{}{
  1293. "directory": map[string]interface{}{
  1294. "with": map[string]interface{}{
  1295. "a": map[string]interface{}{
  1296. "file": filedata,
  1297. },
  1298. "x": map[string]interface{}{},
  1299. },
  1300. },
  1301. },
  1302. "this": map[string]interface{}{
  1303. "is": map[string]interface{}{
  1304. "a": map[string]interface{}{
  1305. "deep": map[string]interface{}{
  1306. "invalid": map[string]interface{}{
  1307. "directory": map[string]interface{}{},
  1308. },
  1309. },
  1310. },
  1311. },
  1312. },
  1313. "xthis": map[string]interface{}{
  1314. "is": map[string]interface{}{
  1315. "a": map[string]interface{}{
  1316. "deep": map[string]interface{}{
  1317. "invalid": map[string]interface{}{
  1318. "file": filedata,
  1319. },
  1320. },
  1321. },
  1322. },
  1323. },
  1324. }
  1325. mm := func(data interface{}) string {
  1326. bytes, err := json.Marshal(data)
  1327. if err != nil {
  1328. panic(err)
  1329. }
  1330. return string(bytes)
  1331. }
  1332. m.Index(device1, "default", testdata)
  1333. result := m.GlobalDirectoryTree("default", "", -1, false)
  1334. if mm(result) != mm(expectedResult) {
  1335. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1336. }
  1337. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1338. currentResult := map[string]interface{}{
  1339. "invalid": map[string]interface{}{
  1340. "file": filedata,
  1341. },
  1342. }
  1343. if mm(result) != mm(currentResult) {
  1344. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1345. }
  1346. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1347. currentResult = map[string]interface{}{
  1348. "invalid": map[string]interface{}{},
  1349. }
  1350. if mm(result) != mm(currentResult) {
  1351. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1352. }
  1353. // !!! This is actually BAD, because we don't have enough level allowance
  1354. // to accept this file, hence the tree is left unbuilt !!!
  1355. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1356. currentResult = map[string]interface{}{}
  1357. if mm(result) != mm(currentResult) {
  1358. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1359. }
  1360. }
  1361. func genDeepFiles(n, d int) []protocol.FileInfo {
  1362. rand.Seed(int64(n))
  1363. files := make([]protocol.FileInfo, n)
  1364. t := time.Now().Unix()
  1365. for i := 0; i < n; i++ {
  1366. path := ""
  1367. for i := 0; i <= d; i++ {
  1368. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1369. }
  1370. sofar := ""
  1371. for _, path := range filepath.SplitList(path) {
  1372. sofar = filepath.Join(sofar, path)
  1373. files[i] = protocol.FileInfo{
  1374. Name: sofar,
  1375. }
  1376. i++
  1377. }
  1378. files[i].ModifiedS = t
  1379. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1380. }
  1381. return files
  1382. }
  1383. func BenchmarkTree_10000_50(b *testing.B) {
  1384. benchmarkTree(b, 10000, 50)
  1385. }
  1386. func BenchmarkTree_100_50(b *testing.B) {
  1387. benchmarkTree(b, 100, 50)
  1388. }
  1389. func BenchmarkTree_100_10(b *testing.B) {
  1390. benchmarkTree(b, 100, 10)
  1391. }
  1392. func benchmarkTree(b *testing.B, n1, n2 int) {
  1393. db := db.OpenMemory()
  1394. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1395. m.AddFolder(defaultFolderConfig)
  1396. m.ServeBackground()
  1397. m.ScanFolder("default")
  1398. files := genDeepFiles(n1, n2)
  1399. m.Index(device1, "default", files)
  1400. b.ResetTimer()
  1401. for i := 0; i < b.N; i++ {
  1402. m.GlobalDirectoryTree("default", "", -1, false)
  1403. }
  1404. b.ReportAllocs()
  1405. }
  1406. func TestUnifySubs(t *testing.T) {
  1407. cases := []struct {
  1408. in []string // input to unifySubs
  1409. exists []string // paths that exist in the database
  1410. out []string // expected output
  1411. }{
  1412. {
  1413. // 0. trailing slashes are cleaned, known paths are just passed on
  1414. []string{"foo/", "bar//"},
  1415. []string{"foo", "bar"},
  1416. []string{"bar", "foo"}, // the output is sorted
  1417. },
  1418. {
  1419. // 1. "foo/bar" gets trimmed as it's covered by foo
  1420. []string{"foo", "bar/", "foo/bar/"},
  1421. []string{"foo", "bar"},
  1422. []string{"bar", "foo"},
  1423. },
  1424. {
  1425. // 2. "" gets simplified to the empty list; ie scan all
  1426. []string{"foo", ""},
  1427. []string{"foo"},
  1428. nil,
  1429. },
  1430. {
  1431. // 3. "foo/bar" is unknown, but it's kept
  1432. // because its parent is known
  1433. []string{"foo/bar"},
  1434. []string{"foo"},
  1435. []string{"foo/bar"},
  1436. },
  1437. {
  1438. // 4. two independent known paths, both are kept
  1439. // "usr/lib" is not a prefix of "usr/libexec"
  1440. []string{"usr/lib", "usr/libexec"},
  1441. []string{"usr", "usr/lib", "usr/libexec"},
  1442. []string{"usr/lib", "usr/libexec"},
  1443. },
  1444. {
  1445. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1446. []string{"usr/lib", "usr/lib/exec"},
  1447. []string{"usr", "usr/lib", "usr/libexec"},
  1448. []string{"usr/lib"},
  1449. },
  1450. {
  1451. // 6. .stignore and .stfolder are special and are passed on
  1452. // verbatim even though they are unknown
  1453. []string{".stfolder", ".stignore"},
  1454. []string{},
  1455. []string{".stfolder", ".stignore"},
  1456. },
  1457. {
  1458. // 7. but the presence of something else unknown forces an actual
  1459. // scan
  1460. []string{".stfolder", ".stignore", "foo/bar"},
  1461. []string{},
  1462. []string{".stfolder", ".stignore", "foo"},
  1463. },
  1464. {
  1465. // 8. explicit request to scan all
  1466. nil,
  1467. []string{"foo"},
  1468. nil,
  1469. },
  1470. {
  1471. // 9. empty list of subs
  1472. []string{},
  1473. []string{"foo"},
  1474. nil,
  1475. },
  1476. }
  1477. if runtime.GOOS == "windows" {
  1478. // Fixup path separators
  1479. for i := range cases {
  1480. for j, p := range cases[i].in {
  1481. cases[i].in[j] = filepath.FromSlash(p)
  1482. }
  1483. for j, p := range cases[i].exists {
  1484. cases[i].exists[j] = filepath.FromSlash(p)
  1485. }
  1486. for j, p := range cases[i].out {
  1487. cases[i].out[j] = filepath.FromSlash(p)
  1488. }
  1489. }
  1490. }
  1491. for i, tc := range cases {
  1492. exists := func(f string) bool {
  1493. for _, e := range tc.exists {
  1494. if f == e {
  1495. return true
  1496. }
  1497. }
  1498. return false
  1499. }
  1500. out := unifySubs(tc.in, exists)
  1501. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1502. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1503. }
  1504. }
  1505. }
  1506. func TestIssue3028(t *testing.T) {
  1507. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1508. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1509. t.Fatal(err)
  1510. }
  1511. defer os.Remove("testdata/testrm")
  1512. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1513. t.Fatal(err)
  1514. }
  1515. defer os.Remove("testdata/testrm2")
  1516. // Create a model and default folder
  1517. db := db.OpenMemory()
  1518. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1519. defCfg := defaultFolderConfig.Copy()
  1520. defCfg.RescanIntervalS = 86400
  1521. m.AddFolder(defCfg)
  1522. m.StartFolder("default")
  1523. m.ServeBackground()
  1524. // Ugly hack for testing: reach into the model for the SendReceiveFolder and wait
  1525. // for it to complete the initial scan. The risk is that it otherwise
  1526. // runs during our modifications and screws up the test.
  1527. m.fmut.RLock()
  1528. folder := m.folderRunners["default"].(*sendReceiveFolder)
  1529. m.fmut.RUnlock()
  1530. <-folder.initialScanCompleted
  1531. // Get a count of how many files are there now
  1532. locorigfiles := m.LocalSize("default").Files
  1533. globorigfiles := m.GlobalSize("default").Files
  1534. // Delete and rescan specifically these two
  1535. os.Remove("testdata/testrm")
  1536. os.Remove("testdata/testrm2")
  1537. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1538. // Verify that the number of files decreased by two and the number of
  1539. // deleted files increases by two
  1540. loc := m.LocalSize("default")
  1541. glob := m.GlobalSize("default")
  1542. if loc.Files != locorigfiles-2 {
  1543. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1544. }
  1545. if glob.Files != globorigfiles-2 {
  1546. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1547. }
  1548. if loc.Deleted != 2 {
  1549. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1550. }
  1551. if glob.Deleted != 2 {
  1552. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1553. }
  1554. }
  1555. func TestIssue3164(t *testing.T) {
  1556. os.RemoveAll("testdata/issue3164")
  1557. defer os.RemoveAll("testdata/issue3164")
  1558. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1559. t.Fatal(err)
  1560. }
  1561. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1562. t.Fatal(err)
  1563. }
  1564. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1565. t.Fatal(err)
  1566. }
  1567. f := protocol.FileInfo{
  1568. Name: "issue3164",
  1569. }
  1570. m := ignore.New(false)
  1571. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1572. t.Fatal(err)
  1573. }
  1574. fl := sendReceiveFolder{
  1575. dbUpdates: make(chan dbUpdateJob, 1),
  1576. dir: "testdata",
  1577. }
  1578. fl.deleteDir(f, m)
  1579. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1580. t.Fatal(err)
  1581. }
  1582. }
  1583. func TestScanNoDatabaseWrite(t *testing.T) {
  1584. // When scanning, nothing should be committed to database unless
  1585. // something actually changed.
  1586. db := db.OpenMemory()
  1587. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1588. m.AddFolder(defaultFolderConfig)
  1589. m.StartFolder("default")
  1590. m.ServeBackground()
  1591. // Start with no ignores, and restore the previous state when the test completes
  1592. curIgn, _, err := m.GetIgnores("default")
  1593. if err != nil {
  1594. t.Fatal(err)
  1595. }
  1596. defer m.SetIgnores("default", curIgn)
  1597. m.SetIgnores("default", nil)
  1598. fakeTime := time.Now().Add(5 * time.Second)
  1599. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1600. // Scan the folder twice. The second scan should be a no-op database wise
  1601. m.ScanFolder("default")
  1602. c0 := db.Committed()
  1603. m.ScanFolder("default")
  1604. c1 := db.Committed()
  1605. if c1 != c0 {
  1606. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1607. }
  1608. // Ignore a file we know exists. It'll be updated in the database.
  1609. m.SetIgnores("default", []string{"foo"})
  1610. fakeTime = time.Now().Add(10 * time.Second)
  1611. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1612. m.ScanFolder("default")
  1613. c2 := db.Committed()
  1614. if c2 <= c1 {
  1615. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1616. }
  1617. // Scan again. Nothing should happen.
  1618. m.ScanFolder("default")
  1619. c3 := db.Committed()
  1620. if c3 != c2 {
  1621. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1622. }
  1623. }
  1624. func TestIssue2782(t *testing.T) {
  1625. // CheckFolderHealth should accept a symlinked folder, when using tilde-expanded path.
  1626. if runtime.GOOS == "windows" {
  1627. t.Skip("not reliable on Windows")
  1628. return
  1629. }
  1630. home := os.Getenv("HOME")
  1631. if home == "" {
  1632. t.Skip("no home")
  1633. }
  1634. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1635. // part of the issue. Skip the test if any of this fails, as we are a
  1636. // bit outside of our stated domain here...
  1637. testName := ".syncthing-test." + srand.String(16)
  1638. testDir := filepath.Join(home, testName)
  1639. if err := os.RemoveAll(testDir); err != nil {
  1640. t.Skip(err)
  1641. }
  1642. if err := osutil.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1643. t.Skip(err)
  1644. }
  1645. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1646. t.Skip(err)
  1647. }
  1648. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1649. t.Skip(err)
  1650. }
  1651. defer os.RemoveAll(testDir)
  1652. db := db.OpenMemory()
  1653. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1654. m.AddFolder(config.NewFolderConfiguration("default", "~/"+testName+"/synclink/"))
  1655. m.StartFolder("default")
  1656. m.ServeBackground()
  1657. defer m.Stop()
  1658. if err := m.ScanFolder("default"); err != nil {
  1659. t.Error("scan error:", err)
  1660. }
  1661. if err := m.CheckFolderHealth("default"); err != nil {
  1662. t.Error("health check error:", err)
  1663. }
  1664. }
  1665. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1666. dbi := db.OpenMemory()
  1667. files := db.NewFileSet("default", dbi)
  1668. files.Replace(device1, genFiles(1))
  1669. files.Replace(device2, genFiles(1))
  1670. if len(files.ListDevices()) != 2 {
  1671. t.Error("expected two devices")
  1672. }
  1673. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1674. m.AddFolder(defaultFolderConfig)
  1675. m.StartFolder("default")
  1676. // Remote sequence is cached, hence need to recreated.
  1677. files = db.NewFileSet("default", dbi)
  1678. if len(files.ListDevices()) != 1 {
  1679. t.Error("Expected one device")
  1680. }
  1681. }
  1682. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1683. dbi := db.OpenMemory()
  1684. fcfg := config.NewFolderConfiguration("default", "testdata")
  1685. fcfg.Devices = []config.FolderDeviceConfiguration{
  1686. {DeviceID: device1},
  1687. {DeviceID: device2},
  1688. }
  1689. cfg := config.Configuration{
  1690. Folders: []config.FolderConfiguration{fcfg},
  1691. Devices: []config.DeviceConfiguration{
  1692. config.NewDeviceConfiguration(device1, "device1"),
  1693. config.NewDeviceConfiguration(device2, "device2"),
  1694. },
  1695. Options: config.OptionsConfiguration{
  1696. // Don't remove temporaries directly on startup
  1697. KeepTemporariesH: 1,
  1698. },
  1699. }
  1700. wcfg := config.Wrap("/tmp/test", cfg)
  1701. m := NewModel(wcfg, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1702. m.AddFolder(fcfg)
  1703. m.StartFolder(fcfg.ID)
  1704. m.ServeBackground()
  1705. conn1 := &fakeConnection{id: device1}
  1706. m.AddConnection(conn1, protocol.HelloResult{})
  1707. conn2 := &fakeConnection{id: device2}
  1708. m.AddConnection(conn2, protocol.HelloResult{})
  1709. m.ClusterConfig(device1, protocol.ClusterConfig{
  1710. Folders: []protocol.Folder{
  1711. {
  1712. ID: "default",
  1713. Devices: []protocol.Device{
  1714. {ID: device1},
  1715. {ID: device2},
  1716. },
  1717. },
  1718. },
  1719. })
  1720. m.ClusterConfig(device2, protocol.ClusterConfig{
  1721. Folders: []protocol.Folder{
  1722. {
  1723. ID: "default",
  1724. Devices: []protocol.Device{
  1725. {ID: device1},
  1726. {ID: device2},
  1727. },
  1728. },
  1729. },
  1730. })
  1731. if !m.folderSharedWith("default", device1) {
  1732. t.Error("not shared with device1")
  1733. }
  1734. if !m.folderSharedWith("default", device2) {
  1735. t.Error("not shared with device2")
  1736. }
  1737. if conn2.Closed() {
  1738. t.Error("conn already closed")
  1739. }
  1740. cfg = cfg.Copy()
  1741. cfg.Devices = cfg.Devices[:1]
  1742. if err := wcfg.Replace(cfg); err != nil {
  1743. t.Error(err)
  1744. }
  1745. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1746. if !m.folderSharedWith("default", device1) {
  1747. t.Error("not shared with device1")
  1748. }
  1749. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1750. t.Error("shared with device2")
  1751. }
  1752. if !conn2.Closed() {
  1753. t.Error("connection not closed")
  1754. }
  1755. if _, ok := wcfg.Devices()[device2]; ok {
  1756. t.Error("device still in config")
  1757. }
  1758. fdevs, ok := m.folderDevices["default"]
  1759. if !ok {
  1760. t.Error("folder missing?")
  1761. }
  1762. for id := range fdevs {
  1763. if id == device2 {
  1764. t.Error("still there")
  1765. }
  1766. }
  1767. if _, ok := m.conn[device2]; !ok {
  1768. t.Error("conn missing early")
  1769. }
  1770. if _, ok := m.helloMessages[device2]; !ok {
  1771. t.Error("hello missing early")
  1772. }
  1773. if _, ok := m.deviceDownloads[device2]; !ok {
  1774. t.Error("downloads missing early")
  1775. }
  1776. m.Closed(conn2, fmt.Errorf("foo"))
  1777. if _, ok := m.conn[device2]; ok {
  1778. t.Error("conn not missing")
  1779. }
  1780. if _, ok := m.helloMessages[device2]; ok {
  1781. t.Error("hello not missing")
  1782. }
  1783. if _, ok := m.deviceDownloads[device2]; ok {
  1784. t.Error("downloads not missing")
  1785. }
  1786. }
  1787. func TestIssue3496(t *testing.T) {
  1788. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  1789. // It seems like lots of deleted files can cause negative completion
  1790. // percentages. Lets make sure that doesn't happen. Also do some general
  1791. // checks on the completion calculation stuff.
  1792. dbi := db.OpenMemory()
  1793. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1794. m.AddFolder(defaultFolderConfig)
  1795. m.StartFolder("default")
  1796. m.ServeBackground()
  1797. defer m.Stop()
  1798. m.ScanFolder("default")
  1799. addFakeConn(m, device1)
  1800. addFakeConn(m, device2)
  1801. // Reach into the model and grab the current file list...
  1802. m.fmut.RLock()
  1803. fs := m.folderFiles["default"]
  1804. m.fmut.RUnlock()
  1805. var localFiles []protocol.FileInfo
  1806. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1807. localFiles = append(localFiles, i.(protocol.FileInfo))
  1808. return true
  1809. })
  1810. // Mark all files as deleted and fake it as update from device1
  1811. for i := range localFiles {
  1812. localFiles[i].Deleted = true
  1813. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1814. localFiles[i].Blocks = nil
  1815. }
  1816. // Also add a small file that we're supposed to need, or the global size
  1817. // stuff will bail out early due to the entire folder being zero size.
  1818. localFiles = append(localFiles, protocol.FileInfo{
  1819. Name: "fake",
  1820. Size: 1234,
  1821. Type: protocol.FileInfoTypeFile,
  1822. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1823. })
  1824. m.IndexUpdate(device1, "default", localFiles)
  1825. // Check that the completion percentage for us makes sense
  1826. comp := m.Completion(protocol.LocalDeviceID, "default")
  1827. if comp.NeedBytes > comp.GlobalBytes {
  1828. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1829. }
  1830. if comp.CompletionPct < 0 {
  1831. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1832. }
  1833. if comp.NeedBytes == 0 {
  1834. t.Error("Need no bytes even though some files are deleted")
  1835. }
  1836. if comp.CompletionPct == 100 {
  1837. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1838. }
  1839. t.Log(comp)
  1840. // Check that NeedSize does the correct thing
  1841. need := m.NeedSize("default")
  1842. if need.Files != 1 || need.Bytes != 1234 {
  1843. // The one we added synthetically above
  1844. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1845. }
  1846. if need.Deleted != len(localFiles)-1 {
  1847. // The rest
  1848. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1849. }
  1850. }
  1851. func TestIssue3804(t *testing.T) {
  1852. dbi := db.OpenMemory()
  1853. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1854. m.AddFolder(defaultFolderConfig)
  1855. m.StartFolder("default")
  1856. m.ServeBackground()
  1857. defer m.Stop()
  1858. // Subdirs ending in slash should be accepted
  1859. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  1860. t.Error("Unexpected error:", err)
  1861. }
  1862. }
  1863. func TestIssue3829(t *testing.T) {
  1864. dbi := db.OpenMemory()
  1865. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1866. m.AddFolder(defaultFolderConfig)
  1867. m.StartFolder("default")
  1868. m.ServeBackground()
  1869. defer m.Stop()
  1870. // Empty subdirs should be accepted
  1871. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  1872. t.Error("Unexpected error:", err)
  1873. }
  1874. }
  1875. func TestNoRequestsFromPausedDevices(t *testing.T) {
  1876. t.Skip("broken, fails randomly, #3843")
  1877. dbi := db.OpenMemory()
  1878. fcfg := config.NewFolderConfiguration("default", "testdata")
  1879. fcfg.Devices = []config.FolderDeviceConfiguration{
  1880. {DeviceID: device1},
  1881. {DeviceID: device2},
  1882. }
  1883. cfg := config.Configuration{
  1884. Folders: []config.FolderConfiguration{fcfg},
  1885. Devices: []config.DeviceConfiguration{
  1886. config.NewDeviceConfiguration(device1, "device1"),
  1887. config.NewDeviceConfiguration(device2, "device2"),
  1888. },
  1889. Options: config.OptionsConfiguration{
  1890. // Don't remove temporaries directly on startup
  1891. KeepTemporariesH: 1,
  1892. },
  1893. }
  1894. wcfg := config.Wrap("/tmp/test", cfg)
  1895. m := NewModel(wcfg, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1896. m.AddFolder(fcfg)
  1897. m.StartFolder(fcfg.ID)
  1898. m.ServeBackground()
  1899. file := testDataExpected["foo"]
  1900. files := m.folderFiles["default"]
  1901. files.Update(device1, []protocol.FileInfo{file})
  1902. files.Update(device2, []protocol.FileInfo{file})
  1903. avail := m.Availability("default", file.Name, file.Version, file.Blocks[0])
  1904. if len(avail) != 0 {
  1905. t.Errorf("should not be available, no connections")
  1906. }
  1907. addFakeConn(m, device1)
  1908. addFakeConn(m, device2)
  1909. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  1910. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  1911. if len(avail) != 2 {
  1912. t.Errorf("should have two available")
  1913. }
  1914. cc := protocol.ClusterConfig{
  1915. Folders: []protocol.Folder{
  1916. {
  1917. ID: "default",
  1918. Devices: []protocol.Device{
  1919. {ID: device1},
  1920. {ID: device2},
  1921. },
  1922. },
  1923. },
  1924. }
  1925. m.ClusterConfig(device1, cc)
  1926. m.ClusterConfig(device2, cc)
  1927. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  1928. if len(avail) != 2 {
  1929. t.Errorf("should have two available")
  1930. }
  1931. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  1932. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  1933. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  1934. if len(avail) != 0 {
  1935. t.Errorf("should have no available")
  1936. }
  1937. // Test that remote paused folders are not used.
  1938. addFakeConn(m, device1)
  1939. addFakeConn(m, device2)
  1940. m.ClusterConfig(device1, cc)
  1941. ccp := cc
  1942. ccp.Folders[0].Paused = true
  1943. m.ClusterConfig(device1, ccp)
  1944. avail = m.Availability("default", file.Name, file.Version, file.Blocks[0])
  1945. if len(avail) != 1 {
  1946. t.Errorf("should have one available")
  1947. }
  1948. }
  1949. func TestRootedJoinedPath(t *testing.T) {
  1950. type testcase struct {
  1951. root string
  1952. rel string
  1953. joined string
  1954. ok bool
  1955. }
  1956. cases := []testcase{
  1957. // Valid cases
  1958. {"foo", "bar", "foo/bar", true},
  1959. {"foo", "/bar", "foo/bar", true},
  1960. {"foo/", "bar", "foo/bar", true},
  1961. {"foo/", "/bar", "foo/bar", true},
  1962. {"baz/foo", "bar", "baz/foo/bar", true},
  1963. {"baz/foo", "/bar", "baz/foo/bar", true},
  1964. {"baz/foo/", "bar", "baz/foo/bar", true},
  1965. {"baz/foo/", "/bar", "baz/foo/bar", true},
  1966. {"foo", "bar/baz", "foo/bar/baz", true},
  1967. {"foo", "/bar/baz", "foo/bar/baz", true},
  1968. {"foo/", "bar/baz", "foo/bar/baz", true},
  1969. {"foo/", "/bar/baz", "foo/bar/baz", true},
  1970. {"baz/foo", "bar/baz", "baz/foo/bar/baz", true},
  1971. {"baz/foo", "/bar/baz", "baz/foo/bar/baz", true},
  1972. {"baz/foo/", "bar/baz", "baz/foo/bar/baz", true},
  1973. {"baz/foo/", "/bar/baz", "baz/foo/bar/baz", true},
  1974. // Not escape attempts, but oddly formatted relative paths. Disallowed.
  1975. {"foo", "./bar", "", false},
  1976. {"baz/foo", "./bar", "", false},
  1977. {"foo", "./bar/baz", "", false},
  1978. {"baz/foo", "./bar/baz", "", false},
  1979. {"baz/foo", "bar/../baz", "", false},
  1980. {"baz/foo", "/bar/../baz", "", false},
  1981. {"baz/foo", "./bar/../baz", "", false},
  1982. {"baz/foo", "bar/../baz", "", false},
  1983. {"baz/foo", "/bar/../baz", "", false},
  1984. {"baz/foo", "./bar/../baz", "", false},
  1985. // Results in an allowed path, but does it by probing. Disallowed.
  1986. {"foo", "../foo", "", false},
  1987. {"foo", "../foo/bar", "", false},
  1988. {"baz/foo", "../foo/bar", "", false},
  1989. {"baz/foo", "../../baz/foo/bar", "", false},
  1990. {"baz/foo", "bar/../../foo/bar", "", false},
  1991. {"baz/foo", "bar/../../../baz/foo/bar", "", false},
  1992. // Escape attempts.
  1993. {"foo", "", "", false},
  1994. {"foo", "/", "", false},
  1995. {"foo", "..", "", false},
  1996. {"foo", "/..", "", false},
  1997. {"foo", "../", "", false},
  1998. {"foo", "../bar", "", false},
  1999. {"foo", "../foobar", "", false},
  2000. {"foo/", "../bar", "", false},
  2001. {"foo/", "../foobar", "", false},
  2002. {"baz/foo", "../bar", "", false},
  2003. {"baz/foo", "../foobar", "", false},
  2004. {"baz/foo/", "../bar", "", false},
  2005. {"baz/foo/", "../foobar", "", false},
  2006. {"baz/foo/", "bar/../../quux/baz", "", false},
  2007. // Empty root is a misconfiguration.
  2008. {"", "/foo", "", false},
  2009. {"", "foo", "", false},
  2010. {"", ".", "", false},
  2011. {"", "..", "", false},
  2012. {"", "/", "", false},
  2013. {"", "", "", false},
  2014. // Root=/ is valid, and things should be verified as usual.
  2015. {"/", "foo", "/foo", true},
  2016. {"/", "/foo", "/foo", true},
  2017. {"/", "../foo", "", false},
  2018. {"/", ".", "", false},
  2019. {"/", "..", "", false},
  2020. {"/", "/", "", false},
  2021. {"/", "", "", false},
  2022. }
  2023. if runtime.GOOS == "windows" {
  2024. extraCases := []testcase{
  2025. {`c:\`, `foo`, `c:\foo`, true},
  2026. {`\\?\c:\`, `foo`, `\\?\c:\foo`, true},
  2027. {`c:\`, `\foo`, `c:\foo`, true},
  2028. {`\\?\c:\`, `\foo`, `\\?\c:\foo`, true},
  2029. {`c:\`, `\\foo`, ``, false},
  2030. {`c:\`, ``, ``, false},
  2031. {`c:\`, `.`, ``, false},
  2032. {`c:\`, `\`, ``, false},
  2033. {`\\?\c:\`, `\\foo`, ``, false},
  2034. {`\\?\c:\`, ``, ``, false},
  2035. {`\\?\c:\`, `.`, ``, false},
  2036. {`\\?\c:\`, `\`, ``, false},
  2037. // makes no sense, but will be treated simply as a bad filename
  2038. {`c:\foo`, `d:\bar`, `c:\foo\d:\bar`, true},
  2039. }
  2040. for _, tc := range cases {
  2041. // Add case where root is backslashed, rel is forward slashed
  2042. extraCases = append(extraCases, testcase{
  2043. root: filepath.FromSlash(tc.root),
  2044. rel: tc.rel,
  2045. joined: tc.joined,
  2046. ok: tc.ok,
  2047. })
  2048. // and the opposite
  2049. extraCases = append(extraCases, testcase{
  2050. root: tc.root,
  2051. rel: filepath.FromSlash(tc.rel),
  2052. joined: tc.joined,
  2053. ok: tc.ok,
  2054. })
  2055. // and both backslashed
  2056. extraCases = append(extraCases, testcase{
  2057. root: filepath.FromSlash(tc.root),
  2058. rel: filepath.FromSlash(tc.rel),
  2059. joined: tc.joined,
  2060. ok: tc.ok,
  2061. })
  2062. }
  2063. cases = append(cases, extraCases...)
  2064. }
  2065. for _, tc := range cases {
  2066. res, err := rootedJoinedPath(tc.root, tc.rel)
  2067. if tc.ok {
  2068. if err != nil {
  2069. t.Errorf("Unexpected error for rootedJoinedPath(%q, %q): %v", tc.root, tc.rel, err)
  2070. continue
  2071. }
  2072. exp := filepath.FromSlash(tc.joined)
  2073. if res != exp {
  2074. t.Errorf("Unexpected result for rootedJoinedPath(%q, %q): %q != expected %q", tc.root, tc.rel, res, exp)
  2075. }
  2076. } else if err == nil {
  2077. t.Errorf("Unexpected pass for rootedJoinedPath(%q, %q) => %q", tc.root, tc.rel, res)
  2078. continue
  2079. }
  2080. }
  2081. }
  2082. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  2083. fc := &fakeConnection{id: dev, model: m}
  2084. m.AddConnection(fc, protocol.HelloResult{})
  2085. m.ClusterConfig(dev, protocol.ClusterConfig{
  2086. Folders: []protocol.Folder{
  2087. {
  2088. ID: "default",
  2089. Devices: []protocol.Device{
  2090. {ID: device1},
  2091. {ID: device2},
  2092. },
  2093. },
  2094. },
  2095. })
  2096. return fc
  2097. }
  2098. type fakeAddr struct{}
  2099. func (fakeAddr) Network() string {
  2100. return "network"
  2101. }
  2102. func (fakeAddr) String() string {
  2103. return "address"
  2104. }