model_test.go 85 KB

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