1
0

model_test.go 82 KB

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