model_test.go 83 KB

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