model_test.go 70 KB

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