model_test.go 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305
  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. m.pmut.Lock()
  758. for _, c := range m.conn {
  759. conn := c.(*fakeConnection)
  760. conn.mut.Lock()
  761. conn.closeFn = func(_ error) {}
  762. conn.mut.Unlock()
  763. defer m.Closed(c, errStopped) // to unblock deferred m.Stop()
  764. }
  765. m.pmut.Unlock()
  766. wg := sync.WaitGroup{}
  767. addAndVerify := func(id string) {
  768. m.ClusterConfig(device1, protocol.ClusterConfig{
  769. Folders: []protocol.Folder{
  770. {
  771. ID: id,
  772. Label: id,
  773. },
  774. },
  775. })
  776. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  777. t.Error("expected shared", id)
  778. }
  779. wg.Done()
  780. }
  781. reps := 10
  782. ids := make([]string, reps)
  783. for i := 0; i < reps; i++ {
  784. wg.Add(1)
  785. ids[i] = srand.String(8)
  786. go addAndVerify(ids[i])
  787. }
  788. defer func() {
  789. for _, id := range ids {
  790. os.RemoveAll(id)
  791. }
  792. }()
  793. finished := make(chan struct{})
  794. go func() {
  795. wg.Wait()
  796. close(finished)
  797. }()
  798. select {
  799. case <-finished:
  800. case <-time.After(10 * time.Second):
  801. pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
  802. t.Fatal("Timed out before all devices were added")
  803. }
  804. }
  805. func TestAutoAcceptRejected(t *testing.T) {
  806. // Nothing happens if AutoAcceptFolders not set
  807. tcfg := defaultAutoAcceptCfg.Copy()
  808. for i := range tcfg.Devices {
  809. tcfg.Devices[i].AutoAcceptFolders = false
  810. }
  811. m := newState(tcfg)
  812. defer cleanupModel(m)
  813. id := srand.String(8)
  814. defer os.RemoveAll(id)
  815. m.ClusterConfig(device1, protocol.ClusterConfig{
  816. Folders: []protocol.Folder{
  817. {
  818. ID: id,
  819. Label: id,
  820. },
  821. },
  822. })
  823. if cfg, ok := m.cfg.Folder(id); ok && cfg.SharedWith(device1) {
  824. t.Error("unexpected shared", id)
  825. }
  826. }
  827. func TestAutoAcceptNewFolder(t *testing.T) {
  828. // New folder
  829. m := newState(defaultAutoAcceptCfg)
  830. defer cleanupModel(m)
  831. id := srand.String(8)
  832. defer os.RemoveAll(id)
  833. m.ClusterConfig(device1, protocol.ClusterConfig{
  834. Folders: []protocol.Folder{
  835. {
  836. ID: id,
  837. Label: id,
  838. },
  839. },
  840. })
  841. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  842. t.Error("expected shared", id)
  843. }
  844. }
  845. func TestAutoAcceptNewFolderFromTwoDevices(t *testing.T) {
  846. m := newState(defaultAutoAcceptCfg)
  847. defer cleanupModel(m)
  848. id := srand.String(8)
  849. defer os.RemoveAll(id)
  850. m.ClusterConfig(device1, protocol.ClusterConfig{
  851. Folders: []protocol.Folder{
  852. {
  853. ID: id,
  854. Label: id,
  855. },
  856. },
  857. })
  858. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  859. t.Error("expected shared", id)
  860. }
  861. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  862. t.Error("unexpected expected shared", id)
  863. }
  864. m.ClusterConfig(device2, protocol.ClusterConfig{
  865. Folders: []protocol.Folder{
  866. {
  867. ID: id,
  868. Label: id,
  869. },
  870. },
  871. })
  872. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device2) {
  873. t.Error("expected shared", id)
  874. }
  875. }
  876. func TestAutoAcceptNewFolderFromOnlyOneDevice(t *testing.T) {
  877. modifiedCfg := defaultAutoAcceptCfg.Copy()
  878. modifiedCfg.Devices[2].AutoAcceptFolders = false
  879. m := newState(modifiedCfg)
  880. id := srand.String(8)
  881. defer os.RemoveAll(id)
  882. defer cleanupModel(m)
  883. m.ClusterConfig(device1, protocol.ClusterConfig{
  884. Folders: []protocol.Folder{
  885. {
  886. ID: id,
  887. Label: id,
  888. },
  889. },
  890. })
  891. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  892. t.Error("expected shared", id)
  893. }
  894. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  895. t.Error("unexpected expected shared", id)
  896. }
  897. m.ClusterConfig(device2, protocol.ClusterConfig{
  898. Folders: []protocol.Folder{
  899. {
  900. ID: id,
  901. Label: id,
  902. },
  903. },
  904. })
  905. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  906. t.Error("unexpected shared", id)
  907. }
  908. }
  909. func TestAutoAcceptNewFolderPremutationsNoPanic(t *testing.T) {
  910. if testing.Short() {
  911. t.Skip("short tests only")
  912. }
  913. testOs := &fatalOs{t}
  914. id := srand.String(8)
  915. label := srand.String(8)
  916. premutations := []protocol.Folder{
  917. {ID: id, Label: id},
  918. {ID: id, Label: label},
  919. {ID: label, Label: id},
  920. {ID: label, Label: label},
  921. }
  922. localFolders := append(premutations, protocol.Folder{})
  923. for _, localFolder := range localFolders {
  924. for _, localFolderPaused := range []bool{false, true} {
  925. for _, dev1folder := range premutations {
  926. for _, dev2folder := range premutations {
  927. cfg := defaultAutoAcceptCfg.Copy()
  928. if localFolder.Label != "" {
  929. fcfg := config.NewFolderConfiguration(myID, localFolder.ID, localFolder.Label, fs.FilesystemTypeBasic, localFolder.ID)
  930. fcfg.Paused = localFolderPaused
  931. cfg.Folders = append(cfg.Folders, fcfg)
  932. }
  933. m := newState(cfg)
  934. m.ClusterConfig(device1, protocol.ClusterConfig{
  935. Folders: []protocol.Folder{dev1folder},
  936. })
  937. m.ClusterConfig(device2, protocol.ClusterConfig{
  938. Folders: []protocol.Folder{dev2folder},
  939. })
  940. cleanupModel(m)
  941. testOs.RemoveAll(id)
  942. testOs.RemoveAll(label)
  943. }
  944. }
  945. }
  946. }
  947. }
  948. func TestAutoAcceptMultipleFolders(t *testing.T) {
  949. // Multiple new folders
  950. id1 := srand.String(8)
  951. defer os.RemoveAll(id1)
  952. id2 := srand.String(8)
  953. defer os.RemoveAll(id2)
  954. m := newState(defaultAutoAcceptCfg)
  955. defer cleanupModel(m)
  956. m.ClusterConfig(device1, protocol.ClusterConfig{
  957. Folders: []protocol.Folder{
  958. {
  959. ID: id1,
  960. Label: id1,
  961. },
  962. {
  963. ID: id2,
  964. Label: id2,
  965. },
  966. },
  967. })
  968. if fcfg, ok := m.cfg.Folder(id1); !ok || !fcfg.SharedWith(device1) {
  969. t.Error("expected shared", id1)
  970. }
  971. if fcfg, ok := m.cfg.Folder(id2); !ok || !fcfg.SharedWith(device1) {
  972. t.Error("expected shared", id2)
  973. }
  974. }
  975. func TestAutoAcceptExistingFolder(t *testing.T) {
  976. // Existing folder
  977. id := srand.String(8)
  978. idOther := srand.String(8) // To check that path does not get changed.
  979. defer os.RemoveAll(id)
  980. defer os.RemoveAll(idOther)
  981. tcfg := defaultAutoAcceptCfg.Copy()
  982. tcfg.Folders = []config.FolderConfiguration{
  983. {
  984. ID: id,
  985. Path: idOther, // To check that path does not get changed.
  986. },
  987. }
  988. m := newState(tcfg)
  989. defer cleanupModel(m)
  990. if fcfg, ok := m.cfg.Folder(id); !ok || fcfg.SharedWith(device1) {
  991. t.Error("missing folder, or shared", id)
  992. }
  993. m.ClusterConfig(device1, protocol.ClusterConfig{
  994. Folders: []protocol.Folder{
  995. {
  996. ID: id,
  997. Label: id,
  998. },
  999. },
  1000. })
  1001. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || fcfg.Path != idOther {
  1002. t.Error("missing folder, or unshared, or path changed", id)
  1003. }
  1004. }
  1005. func TestAutoAcceptNewAndExistingFolder(t *testing.T) {
  1006. // New and existing folder
  1007. id1 := srand.String(8)
  1008. defer os.RemoveAll(id1)
  1009. id2 := srand.String(8)
  1010. defer os.RemoveAll(id2)
  1011. tcfg := defaultAutoAcceptCfg.Copy()
  1012. tcfg.Folders = []config.FolderConfiguration{
  1013. {
  1014. ID: id1,
  1015. Path: id1, // from previous test case, to verify that path doesn't get changed.
  1016. },
  1017. }
  1018. m := newState(tcfg)
  1019. defer cleanupModel(m)
  1020. if fcfg, ok := m.cfg.Folder(id1); !ok || fcfg.SharedWith(device1) {
  1021. t.Error("missing folder, or shared", id1)
  1022. }
  1023. m.ClusterConfig(device1, protocol.ClusterConfig{
  1024. Folders: []protocol.Folder{
  1025. {
  1026. ID: id1,
  1027. Label: id1,
  1028. },
  1029. {
  1030. ID: id2,
  1031. Label: id2,
  1032. },
  1033. },
  1034. })
  1035. for i, id := range []string{id1, id2} {
  1036. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1037. t.Error("missing folder, or unshared", i, id)
  1038. }
  1039. }
  1040. }
  1041. func TestAutoAcceptAlreadyShared(t *testing.T) {
  1042. // Already shared
  1043. id := srand.String(8)
  1044. defer os.RemoveAll(id)
  1045. tcfg := defaultAutoAcceptCfg.Copy()
  1046. tcfg.Folders = []config.FolderConfiguration{
  1047. {
  1048. ID: id,
  1049. Path: id,
  1050. Devices: []config.FolderDeviceConfiguration{
  1051. {
  1052. DeviceID: device1,
  1053. },
  1054. },
  1055. },
  1056. }
  1057. m := newState(tcfg)
  1058. defer cleanupModel(m)
  1059. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1060. t.Error("missing folder, or not shared", id)
  1061. }
  1062. m.ClusterConfig(device1, protocol.ClusterConfig{
  1063. Folders: []protocol.Folder{
  1064. {
  1065. ID: id,
  1066. Label: id,
  1067. },
  1068. },
  1069. })
  1070. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1071. t.Error("missing folder, or not shared", id)
  1072. }
  1073. }
  1074. func TestAutoAcceptNameConflict(t *testing.T) {
  1075. testOs := &fatalOs{t}
  1076. id := srand.String(8)
  1077. label := srand.String(8)
  1078. testOs.MkdirAll(id, 0777)
  1079. testOs.MkdirAll(label, 0777)
  1080. defer os.RemoveAll(id)
  1081. defer os.RemoveAll(label)
  1082. m := newState(defaultAutoAcceptCfg)
  1083. defer cleanupModel(m)
  1084. m.ClusterConfig(device1, protocol.ClusterConfig{
  1085. Folders: []protocol.Folder{
  1086. {
  1087. ID: id,
  1088. Label: label,
  1089. },
  1090. },
  1091. })
  1092. if fcfg, ok := m.cfg.Folder(id); ok && fcfg.SharedWith(device1) {
  1093. t.Error("unexpected folder", id)
  1094. }
  1095. }
  1096. func TestAutoAcceptPrefersLabel(t *testing.T) {
  1097. // Prefers label, falls back to ID.
  1098. m := newState(defaultAutoAcceptCfg)
  1099. id := srand.String(8)
  1100. label := srand.String(8)
  1101. defer os.RemoveAll(id)
  1102. defer os.RemoveAll(label)
  1103. defer cleanupModel(m)
  1104. m.ClusterConfig(device1, protocol.ClusterConfig{
  1105. Folders: []protocol.Folder{
  1106. {
  1107. ID: id,
  1108. Label: label,
  1109. },
  1110. },
  1111. })
  1112. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, label) {
  1113. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1114. }
  1115. }
  1116. func TestAutoAcceptFallsBackToID(t *testing.T) {
  1117. testOs := &fatalOs{t}
  1118. // Prefers label, falls back to ID.
  1119. m := newState(defaultAutoAcceptCfg)
  1120. id := srand.String(8)
  1121. label := srand.String(8)
  1122. t.Log(id, label)
  1123. testOs.MkdirAll(label, 0777)
  1124. defer os.RemoveAll(label)
  1125. defer os.RemoveAll(id)
  1126. defer cleanupModel(m)
  1127. m.ClusterConfig(device1, protocol.ClusterConfig{
  1128. Folders: []protocol.Folder{
  1129. {
  1130. ID: id,
  1131. Label: label,
  1132. },
  1133. },
  1134. })
  1135. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, id) {
  1136. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1137. }
  1138. }
  1139. func TestAutoAcceptPausedWhenFolderConfigChanged(t *testing.T) {
  1140. // Existing folder
  1141. id := srand.String(8)
  1142. idOther := srand.String(8) // To check that path does not get changed.
  1143. defer os.RemoveAll(id)
  1144. defer os.RemoveAll(idOther)
  1145. tcfg := defaultAutoAcceptCfg.Copy()
  1146. fcfg := config.NewFolderConfiguration(myID, id, "", fs.FilesystemTypeBasic, idOther)
  1147. fcfg.Paused = true
  1148. // The order of devices here is wrong (cfg.clean() sorts them), which will cause the folder to restart.
  1149. // Because of the restart, folder gets removed from m.deviceFolder, which means that generateClusterConfig will not panic.
  1150. // This wasn't an issue before, yet keeping the test case to prove that it still isn't.
  1151. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1152. DeviceID: device1,
  1153. })
  1154. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1155. m := newState(tcfg)
  1156. defer cleanupModel(m)
  1157. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1158. t.Error("missing folder, or not shared", id)
  1159. }
  1160. if _, ok := m.folderRunners[id]; ok {
  1161. t.Fatal("folder running?")
  1162. }
  1163. m.ClusterConfig(device1, protocol.ClusterConfig{
  1164. Folders: []protocol.Folder{
  1165. {
  1166. ID: id,
  1167. Label: id,
  1168. },
  1169. },
  1170. })
  1171. m.generateClusterConfig(device1)
  1172. if fcfg, ok := m.cfg.Folder(id); !ok {
  1173. t.Error("missing folder")
  1174. } else if fcfg.Path != idOther {
  1175. t.Error("folder path changed")
  1176. } else {
  1177. for _, dev := range fcfg.DeviceIDs() {
  1178. if dev == device1 {
  1179. return
  1180. }
  1181. }
  1182. t.Error("device missing")
  1183. }
  1184. if _, ok := m.folderRunners[id]; ok {
  1185. t.Error("folder started")
  1186. }
  1187. }
  1188. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1189. // Existing folder
  1190. id := srand.String(8)
  1191. idOther := srand.String(8) // To check that path does not get changed.
  1192. defer os.RemoveAll(id)
  1193. defer os.RemoveAll(idOther)
  1194. tcfg := defaultAutoAcceptCfg.Copy()
  1195. fcfg := config.NewFolderConfiguration(myID, id, "", fs.FilesystemTypeBasic, idOther)
  1196. fcfg.Paused = true
  1197. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1198. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1199. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1200. // did not have a file set.
  1201. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1202. {
  1203. DeviceID: device1,
  1204. },
  1205. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1206. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1207. m := newState(tcfg)
  1208. defer cleanupModel(m)
  1209. if fcfg, ok := m.cfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1210. t.Error("missing folder, or not shared", id)
  1211. }
  1212. if _, ok := m.folderRunners[id]; ok {
  1213. t.Fatal("folder running?")
  1214. }
  1215. m.ClusterConfig(device1, protocol.ClusterConfig{
  1216. Folders: []protocol.Folder{
  1217. {
  1218. ID: id,
  1219. Label: id,
  1220. },
  1221. },
  1222. })
  1223. m.generateClusterConfig(device1)
  1224. if fcfg, ok := m.cfg.Folder(id); !ok {
  1225. t.Error("missing folder")
  1226. } else if fcfg.Path != idOther {
  1227. t.Error("folder path changed")
  1228. } else {
  1229. for _, dev := range fcfg.DeviceIDs() {
  1230. if dev == device1 {
  1231. return
  1232. }
  1233. }
  1234. t.Error("device missing")
  1235. }
  1236. if _, ok := m.folderRunners[id]; ok {
  1237. t.Error("folder started")
  1238. }
  1239. }
  1240. func changeIgnores(t *testing.T, m *model, expected []string) {
  1241. arrEqual := func(a, b []string) bool {
  1242. if len(a) != len(b) {
  1243. return false
  1244. }
  1245. for i := range a {
  1246. if a[i] != b[i] {
  1247. return false
  1248. }
  1249. }
  1250. return true
  1251. }
  1252. ignores, _, err := m.GetIgnores("default")
  1253. if err != nil {
  1254. t.Error(err)
  1255. }
  1256. if !arrEqual(ignores, expected) {
  1257. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1258. }
  1259. ignores = append(ignores, "pox")
  1260. err = m.SetIgnores("default", ignores)
  1261. if err != nil {
  1262. t.Error(err)
  1263. }
  1264. ignores2, _, err := m.GetIgnores("default")
  1265. if err != nil {
  1266. t.Error(err)
  1267. }
  1268. if !arrEqual(ignores, ignores2) {
  1269. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1270. }
  1271. if runtime.GOOS == "darwin" {
  1272. // see above
  1273. time.Sleep(time.Second)
  1274. } else {
  1275. time.Sleep(time.Millisecond)
  1276. }
  1277. err = m.SetIgnores("default", expected)
  1278. if err != nil {
  1279. t.Error(err)
  1280. }
  1281. ignores, _, err = m.GetIgnores("default")
  1282. if err != nil {
  1283. t.Error(err)
  1284. }
  1285. if !arrEqual(ignores, expected) {
  1286. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1287. }
  1288. }
  1289. func TestIgnores(t *testing.T) {
  1290. testOs := &fatalOs{t}
  1291. // Assure a clean start state
  1292. testOs.RemoveAll(filepath.Join("testdata", config.DefaultMarkerName))
  1293. testOs.MkdirAll(filepath.Join("testdata", config.DefaultMarkerName), 0644)
  1294. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  1295. m := setupModel(defaultCfgWrapper)
  1296. defer cleanupModel(m)
  1297. m.RemoveFolder(defaultFolderConfig)
  1298. m.AddFolder(defaultFolderConfig)
  1299. // Reach in and update the ignore matcher to one that always does
  1300. // reloads when asked to, instead of checking file mtimes. This is
  1301. // because we will be changing the files on disk often enough that the
  1302. // mtimes will be unreliable to determine change status.
  1303. m.fmut.Lock()
  1304. m.folderIgnores["default"] = ignore.New(defaultFs, ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  1305. m.fmut.Unlock()
  1306. m.StartFolder("default")
  1307. // Make sure the initial scan has finished (ScanFolders is blocking)
  1308. m.ScanFolders()
  1309. expected := []string{
  1310. ".*",
  1311. "quux",
  1312. }
  1313. changeIgnores(t, m, expected)
  1314. _, _, err := m.GetIgnores("doesnotexist")
  1315. if err == nil {
  1316. t.Error("No error")
  1317. }
  1318. err = m.SetIgnores("doesnotexist", expected)
  1319. if err == nil {
  1320. t.Error("No error")
  1321. }
  1322. // Invalid path, marker should be missing, hence returns an error.
  1323. m.AddFolder(config.FolderConfiguration{ID: "fresh", Path: "XXX"})
  1324. _, _, err = m.GetIgnores("fresh")
  1325. if err == nil {
  1326. t.Error("No error")
  1327. }
  1328. // Repeat tests with paused folder
  1329. pausedDefaultFolderConfig := defaultFolderConfig
  1330. pausedDefaultFolderConfig.Paused = true
  1331. m.RestartFolder(defaultFolderConfig, pausedDefaultFolderConfig)
  1332. // Here folder initialization is not an issue as a paused folder isn't
  1333. // added to the model and thus there is no initial scan happening.
  1334. changeIgnores(t, m, expected)
  1335. // Make sure no .stignore file is considered valid
  1336. defer func() {
  1337. testOs.Rename("testdata/.stignore.bak", "testdata/.stignore")
  1338. }()
  1339. testOs.Rename("testdata/.stignore", "testdata/.stignore.bak")
  1340. changeIgnores(t, m, []string{})
  1341. }
  1342. func waitForState(t *testing.T, m *model, folder, status string) {
  1343. t.Helper()
  1344. timeout := time.Now().Add(2 * time.Second)
  1345. var err error
  1346. for !time.Now().After(timeout) {
  1347. _, _, err = m.State(folder)
  1348. if err == nil && status == "" {
  1349. return
  1350. }
  1351. if err != nil && err.Error() == status {
  1352. return
  1353. }
  1354. time.Sleep(10 * time.Millisecond)
  1355. }
  1356. t.Fatalf("Timed out waiting for status: %s, current status: %v", status, err)
  1357. }
  1358. func TestROScanRecovery(t *testing.T) {
  1359. testOs := &fatalOs{t}
  1360. ldb := db.OpenMemory()
  1361. set := db.NewFileSet("default", defaultFs, ldb)
  1362. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1363. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1364. })
  1365. fcfg := config.FolderConfiguration{
  1366. ID: "default",
  1367. Path: "rotestfolder",
  1368. Type: config.FolderTypeSendOnly,
  1369. RescanIntervalS: 1,
  1370. MarkerName: config.DefaultMarkerName,
  1371. }
  1372. cfg := createTmpWrapper(config.Configuration{
  1373. Folders: []config.FolderConfiguration{fcfg},
  1374. Devices: []config.DeviceConfiguration{
  1375. {
  1376. DeviceID: device1,
  1377. },
  1378. },
  1379. })
  1380. testOs.RemoveAll(fcfg.Path)
  1381. m := newModel(cfg, myID, "syncthing", "dev", ldb, nil)
  1382. m.AddFolder(fcfg)
  1383. m.StartFolder("default")
  1384. m.ServeBackground()
  1385. defer cleanupModel(m)
  1386. waitForState(t, m, "default", "folder path missing")
  1387. testOs.Mkdir(fcfg.Path, 0700)
  1388. waitForState(t, m, "default", "folder marker missing")
  1389. fd := testOs.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1390. fd.Close()
  1391. waitForState(t, m, "default", "")
  1392. testOs.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1393. waitForState(t, m, "default", "folder marker missing")
  1394. testOs.Remove(fcfg.Path)
  1395. waitForState(t, m, "default", "folder path missing")
  1396. }
  1397. func TestRWScanRecovery(t *testing.T) {
  1398. testOs := &fatalOs{t}
  1399. ldb := db.OpenMemory()
  1400. set := db.NewFileSet("default", defaultFs, ldb)
  1401. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1402. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1403. })
  1404. fcfg := config.FolderConfiguration{
  1405. ID: "default",
  1406. Path: "rwtestfolder",
  1407. Type: config.FolderTypeSendReceive,
  1408. RescanIntervalS: 1,
  1409. MarkerName: config.DefaultMarkerName,
  1410. }
  1411. cfg := createTmpWrapper(config.Configuration{
  1412. Folders: []config.FolderConfiguration{fcfg},
  1413. Devices: []config.DeviceConfiguration{
  1414. {
  1415. DeviceID: device1,
  1416. },
  1417. },
  1418. })
  1419. testOs.RemoveAll(fcfg.Path)
  1420. m := newModel(cfg, myID, "syncthing", "dev", ldb, nil)
  1421. m.AddFolder(fcfg)
  1422. m.StartFolder("default")
  1423. m.ServeBackground()
  1424. defer cleanupModel(m)
  1425. waitForState(t, m, "default", "folder path missing")
  1426. testOs.Mkdir(fcfg.Path, 0700)
  1427. waitForState(t, m, "default", "folder marker missing")
  1428. fd := testOs.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1429. fd.Close()
  1430. waitForState(t, m, "default", "")
  1431. testOs.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1432. waitForState(t, m, "default", "folder marker missing")
  1433. testOs.Remove(fcfg.Path)
  1434. waitForState(t, m, "default", "folder path missing")
  1435. }
  1436. func TestGlobalDirectoryTree(t *testing.T) {
  1437. db := db.OpenMemory()
  1438. m := newModel(defaultCfgWrapper, myID, "syncthing", "dev", db, nil)
  1439. m.AddFolder(defaultFolderConfig)
  1440. m.ServeBackground()
  1441. defer cleanupModel(m)
  1442. b := func(isfile bool, path ...string) protocol.FileInfo {
  1443. typ := protocol.FileInfoTypeDirectory
  1444. blocks := []protocol.BlockInfo{}
  1445. if isfile {
  1446. typ = protocol.FileInfoTypeFile
  1447. 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}}}
  1448. }
  1449. return protocol.FileInfo{
  1450. Name: filepath.Join(path...),
  1451. Type: typ,
  1452. ModifiedS: 0x666,
  1453. Blocks: blocks,
  1454. Size: 0xa,
  1455. }
  1456. }
  1457. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1458. testdata := []protocol.FileInfo{
  1459. b(false, "another"),
  1460. b(false, "another", "directory"),
  1461. b(true, "another", "directory", "afile"),
  1462. b(false, "another", "directory", "with"),
  1463. b(false, "another", "directory", "with", "a"),
  1464. b(true, "another", "directory", "with", "a", "file"),
  1465. b(true, "another", "directory", "with", "file"),
  1466. b(true, "another", "file"),
  1467. b(false, "other"),
  1468. b(false, "other", "rand"),
  1469. b(false, "other", "random"),
  1470. b(false, "other", "random", "dir"),
  1471. b(false, "other", "random", "dirx"),
  1472. b(false, "other", "randomx"),
  1473. b(false, "some"),
  1474. b(false, "some", "directory"),
  1475. b(false, "some", "directory", "with"),
  1476. b(false, "some", "directory", "with", "a"),
  1477. b(true, "some", "directory", "with", "a", "file"),
  1478. b(true, "rootfile"),
  1479. }
  1480. expectedResult := map[string]interface{}{
  1481. "another": map[string]interface{}{
  1482. "directory": map[string]interface{}{
  1483. "afile": filedata,
  1484. "with": map[string]interface{}{
  1485. "a": map[string]interface{}{
  1486. "file": filedata,
  1487. },
  1488. "file": filedata,
  1489. },
  1490. },
  1491. "file": filedata,
  1492. },
  1493. "other": map[string]interface{}{
  1494. "rand": map[string]interface{}{},
  1495. "random": map[string]interface{}{
  1496. "dir": map[string]interface{}{},
  1497. "dirx": map[string]interface{}{},
  1498. },
  1499. "randomx": map[string]interface{}{},
  1500. },
  1501. "some": map[string]interface{}{
  1502. "directory": map[string]interface{}{
  1503. "with": map[string]interface{}{
  1504. "a": map[string]interface{}{
  1505. "file": filedata,
  1506. },
  1507. },
  1508. },
  1509. },
  1510. "rootfile": filedata,
  1511. }
  1512. mm := func(data interface{}) string {
  1513. bytes, err := json.Marshal(data)
  1514. if err != nil {
  1515. panic(err)
  1516. }
  1517. return string(bytes)
  1518. }
  1519. m.Index(device1, "default", testdata)
  1520. result := m.GlobalDirectoryTree("default", "", -1, false)
  1521. if mm(result) != mm(expectedResult) {
  1522. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1523. }
  1524. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1525. if mm(result) != mm(expectedResult["another"]) {
  1526. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1527. }
  1528. result = m.GlobalDirectoryTree("default", "", 0, false)
  1529. currentResult := map[string]interface{}{
  1530. "another": map[string]interface{}{},
  1531. "other": map[string]interface{}{},
  1532. "some": map[string]interface{}{},
  1533. "rootfile": filedata,
  1534. }
  1535. if mm(result) != mm(currentResult) {
  1536. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1537. }
  1538. result = m.GlobalDirectoryTree("default", "", 1, false)
  1539. currentResult = map[string]interface{}{
  1540. "another": map[string]interface{}{
  1541. "directory": map[string]interface{}{},
  1542. "file": filedata,
  1543. },
  1544. "other": map[string]interface{}{
  1545. "rand": map[string]interface{}{},
  1546. "random": map[string]interface{}{},
  1547. "randomx": map[string]interface{}{},
  1548. },
  1549. "some": map[string]interface{}{
  1550. "directory": map[string]interface{}{},
  1551. },
  1552. "rootfile": filedata,
  1553. }
  1554. if mm(result) != mm(currentResult) {
  1555. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1556. }
  1557. result = m.GlobalDirectoryTree("default", "", -1, true)
  1558. currentResult = map[string]interface{}{
  1559. "another": map[string]interface{}{
  1560. "directory": map[string]interface{}{
  1561. "with": map[string]interface{}{
  1562. "a": map[string]interface{}{},
  1563. },
  1564. },
  1565. },
  1566. "other": map[string]interface{}{
  1567. "rand": map[string]interface{}{},
  1568. "random": map[string]interface{}{
  1569. "dir": map[string]interface{}{},
  1570. "dirx": map[string]interface{}{},
  1571. },
  1572. "randomx": map[string]interface{}{},
  1573. },
  1574. "some": map[string]interface{}{
  1575. "directory": map[string]interface{}{
  1576. "with": map[string]interface{}{
  1577. "a": map[string]interface{}{},
  1578. },
  1579. },
  1580. },
  1581. }
  1582. if mm(result) != mm(currentResult) {
  1583. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1584. }
  1585. result = m.GlobalDirectoryTree("default", "", 1, true)
  1586. currentResult = map[string]interface{}{
  1587. "another": map[string]interface{}{
  1588. "directory": map[string]interface{}{},
  1589. },
  1590. "other": map[string]interface{}{
  1591. "rand": map[string]interface{}{},
  1592. "random": map[string]interface{}{},
  1593. "randomx": map[string]interface{}{},
  1594. },
  1595. "some": map[string]interface{}{
  1596. "directory": map[string]interface{}{},
  1597. },
  1598. }
  1599. if mm(result) != mm(currentResult) {
  1600. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1601. }
  1602. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1603. currentResult = map[string]interface{}{
  1604. "directory": map[string]interface{}{},
  1605. "file": filedata,
  1606. }
  1607. if mm(result) != mm(currentResult) {
  1608. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1609. }
  1610. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1611. currentResult = map[string]interface{}{
  1612. "with": map[string]interface{}{},
  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", 1, false)
  1618. currentResult = map[string]interface{}{
  1619. "with": map[string]interface{}{
  1620. "a": map[string]interface{}{},
  1621. },
  1622. }
  1623. if mm(result) != mm(currentResult) {
  1624. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1625. }
  1626. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1627. currentResult = map[string]interface{}{
  1628. "with": map[string]interface{}{
  1629. "a": map[string]interface{}{
  1630. "file": filedata,
  1631. },
  1632. },
  1633. }
  1634. if mm(result) != mm(currentResult) {
  1635. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1636. }
  1637. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1638. currentResult = map[string]interface{}{
  1639. "directory": map[string]interface{}{
  1640. "with": map[string]interface{}{
  1641. "a": map[string]interface{}{},
  1642. },
  1643. },
  1644. }
  1645. if mm(result) != mm(currentResult) {
  1646. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1647. }
  1648. // No prefix matching!
  1649. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1650. currentResult = map[string]interface{}{}
  1651. if mm(result) != mm(currentResult) {
  1652. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1653. }
  1654. }
  1655. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1656. db := db.OpenMemory()
  1657. m := newModel(defaultCfgWrapper, myID, "syncthing", "dev", db, nil)
  1658. m.AddFolder(defaultFolderConfig)
  1659. m.ServeBackground()
  1660. defer cleanupModel(m)
  1661. b := func(isfile bool, path ...string) protocol.FileInfo {
  1662. typ := protocol.FileInfoTypeDirectory
  1663. blocks := []protocol.BlockInfo{}
  1664. if isfile {
  1665. typ = protocol.FileInfoTypeFile
  1666. 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}}}
  1667. }
  1668. return protocol.FileInfo{
  1669. Name: filepath.Join(path...),
  1670. Type: typ,
  1671. ModifiedS: 0x666,
  1672. Blocks: blocks,
  1673. Size: 0xa,
  1674. }
  1675. }
  1676. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1677. testdata := []protocol.FileInfo{
  1678. b(true, "another", "directory", "afile"),
  1679. b(true, "another", "directory", "with", "a", "file"),
  1680. b(true, "another", "directory", "with", "file"),
  1681. b(false, "other", "random", "dirx"),
  1682. b(false, "other", "randomx"),
  1683. b(false, "some", "directory", "with", "x"),
  1684. b(true, "some", "directory", "with", "a", "file"),
  1685. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1686. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1687. }
  1688. expectedResult := map[string]interface{}{
  1689. "another": map[string]interface{}{
  1690. "directory": map[string]interface{}{
  1691. "afile": filedata,
  1692. "with": map[string]interface{}{
  1693. "a": map[string]interface{}{
  1694. "file": filedata,
  1695. },
  1696. "file": filedata,
  1697. },
  1698. },
  1699. },
  1700. "other": map[string]interface{}{
  1701. "random": map[string]interface{}{
  1702. "dirx": map[string]interface{}{},
  1703. },
  1704. "randomx": map[string]interface{}{},
  1705. },
  1706. "some": map[string]interface{}{
  1707. "directory": map[string]interface{}{
  1708. "with": map[string]interface{}{
  1709. "a": map[string]interface{}{
  1710. "file": filedata,
  1711. },
  1712. "x": map[string]interface{}{},
  1713. },
  1714. },
  1715. },
  1716. "this": map[string]interface{}{
  1717. "is": map[string]interface{}{
  1718. "a": map[string]interface{}{
  1719. "deep": map[string]interface{}{
  1720. "invalid": map[string]interface{}{
  1721. "directory": map[string]interface{}{},
  1722. },
  1723. },
  1724. },
  1725. },
  1726. },
  1727. "xthis": map[string]interface{}{
  1728. "is": map[string]interface{}{
  1729. "a": map[string]interface{}{
  1730. "deep": map[string]interface{}{
  1731. "invalid": map[string]interface{}{
  1732. "file": filedata,
  1733. },
  1734. },
  1735. },
  1736. },
  1737. },
  1738. }
  1739. mm := func(data interface{}) string {
  1740. bytes, err := json.Marshal(data)
  1741. if err != nil {
  1742. panic(err)
  1743. }
  1744. return string(bytes)
  1745. }
  1746. m.Index(device1, "default", testdata)
  1747. result := m.GlobalDirectoryTree("default", "", -1, false)
  1748. if mm(result) != mm(expectedResult) {
  1749. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1750. }
  1751. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1752. currentResult := map[string]interface{}{
  1753. "invalid": map[string]interface{}{
  1754. "file": filedata,
  1755. },
  1756. }
  1757. if mm(result) != mm(currentResult) {
  1758. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1759. }
  1760. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1761. currentResult = map[string]interface{}{
  1762. "invalid": map[string]interface{}{},
  1763. }
  1764. if mm(result) != mm(currentResult) {
  1765. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1766. }
  1767. // !!! This is actually BAD, because we don't have enough level allowance
  1768. // to accept this file, hence the tree is left unbuilt !!!
  1769. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1770. currentResult = map[string]interface{}{}
  1771. if mm(result) != mm(currentResult) {
  1772. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1773. }
  1774. }
  1775. func genDeepFiles(n, d int) []protocol.FileInfo {
  1776. rand.Seed(int64(n))
  1777. files := make([]protocol.FileInfo, n)
  1778. t := time.Now().Unix()
  1779. for i := 0; i < n; i++ {
  1780. path := ""
  1781. for i := 0; i <= d; i++ {
  1782. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1783. }
  1784. sofar := ""
  1785. for _, path := range filepath.SplitList(path) {
  1786. sofar = filepath.Join(sofar, path)
  1787. files[i] = protocol.FileInfo{
  1788. Name: sofar,
  1789. }
  1790. i++
  1791. }
  1792. files[i].ModifiedS = t
  1793. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1794. }
  1795. return files
  1796. }
  1797. func BenchmarkTree_10000_50(b *testing.B) {
  1798. benchmarkTree(b, 10000, 50)
  1799. }
  1800. func BenchmarkTree_100_50(b *testing.B) {
  1801. benchmarkTree(b, 100, 50)
  1802. }
  1803. func BenchmarkTree_100_10(b *testing.B) {
  1804. benchmarkTree(b, 100, 10)
  1805. }
  1806. func benchmarkTree(b *testing.B, n1, n2 int) {
  1807. db := db.OpenMemory()
  1808. m := newModel(defaultCfgWrapper, myID, "syncthing", "dev", db, nil)
  1809. m.AddFolder(defaultFolderConfig)
  1810. m.ServeBackground()
  1811. defer cleanupModel(m)
  1812. m.ScanFolder("default")
  1813. files := genDeepFiles(n1, n2)
  1814. m.Index(device1, "default", files)
  1815. b.ResetTimer()
  1816. for i := 0; i < b.N; i++ {
  1817. m.GlobalDirectoryTree("default", "", -1, false)
  1818. }
  1819. b.ReportAllocs()
  1820. }
  1821. func TestIssue3028(t *testing.T) {
  1822. testOs := &fatalOs{t}
  1823. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1824. must(t, ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644))
  1825. defer testOs.Remove("testdata/testrm")
  1826. must(t, ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644))
  1827. defer testOs.Remove("testdata/testrm2")
  1828. // Create a model and default folder
  1829. m := setupModel(defaultCfgWrapper)
  1830. defer cleanupModel(m)
  1831. // Get a count of how many files are there now
  1832. locorigfiles := m.LocalSize("default").Files
  1833. globorigfiles := m.GlobalSize("default").Files
  1834. // Delete and rescan specifically these two
  1835. testOs.Remove("testdata/testrm")
  1836. testOs.Remove("testdata/testrm2")
  1837. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1838. // Verify that the number of files decreased by two and the number of
  1839. // deleted files increases by two
  1840. loc := m.LocalSize("default")
  1841. glob := m.GlobalSize("default")
  1842. if loc.Files != locorigfiles-2 {
  1843. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1844. }
  1845. if glob.Files != globorigfiles-2 {
  1846. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1847. }
  1848. if loc.Deleted != 2 {
  1849. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1850. }
  1851. if glob.Deleted != 2 {
  1852. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1853. }
  1854. }
  1855. func TestIssue4357(t *testing.T) {
  1856. db := db.OpenMemory()
  1857. cfg := defaultCfgWrapper.RawCopy()
  1858. // Create a separate wrapper not to pollute other tests.
  1859. wrapper := createTmpWrapper(config.Configuration{})
  1860. m := newModel(wrapper, myID, "syncthing", "dev", db, nil)
  1861. m.ServeBackground()
  1862. defer cleanupModel(m)
  1863. // Force the model to wire itself and add the folders
  1864. p, err := wrapper.Replace(cfg)
  1865. p.Wait()
  1866. if err != nil {
  1867. t.Error(err)
  1868. }
  1869. if _, ok := m.folderCfgs["default"]; !ok {
  1870. t.Error("Folder should be running")
  1871. }
  1872. newCfg := wrapper.RawCopy()
  1873. newCfg.Folders[0].Paused = true
  1874. p, err = wrapper.Replace(newCfg)
  1875. p.Wait()
  1876. if err != nil {
  1877. t.Error(err)
  1878. }
  1879. if _, ok := m.folderCfgs["default"]; ok {
  1880. t.Error("Folder should not be running")
  1881. }
  1882. if _, ok := m.cfg.Folder("default"); !ok {
  1883. t.Error("should still have folder in config")
  1884. }
  1885. p, err = wrapper.Replace(config.Configuration{})
  1886. p.Wait()
  1887. if err != nil {
  1888. t.Error(err)
  1889. }
  1890. if _, ok := m.cfg.Folder("default"); ok {
  1891. t.Error("should not have folder in config")
  1892. }
  1893. // Add the folder back, should be running
  1894. p, err = wrapper.Replace(cfg)
  1895. p.Wait()
  1896. if err != nil {
  1897. t.Error(err)
  1898. }
  1899. if _, ok := m.folderCfgs["default"]; !ok {
  1900. t.Error("Folder should be running")
  1901. }
  1902. if _, ok := m.cfg.Folder("default"); !ok {
  1903. t.Error("should still have folder in config")
  1904. }
  1905. // Should not panic when removing a running folder.
  1906. p, err = wrapper.Replace(config.Configuration{})
  1907. p.Wait()
  1908. if err != nil {
  1909. t.Error(err)
  1910. }
  1911. if _, ok := m.folderCfgs["default"]; ok {
  1912. t.Error("Folder should not be running")
  1913. }
  1914. if _, ok := m.cfg.Folder("default"); ok {
  1915. t.Error("should not have folder in config")
  1916. }
  1917. }
  1918. func TestIssue2782(t *testing.T) {
  1919. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  1920. if runtime.GOOS == "windows" {
  1921. t.Skip("not reliable on Windows")
  1922. return
  1923. }
  1924. home := os.Getenv("HOME")
  1925. if home == "" {
  1926. t.Skip("no home")
  1927. }
  1928. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1929. // part of the issue. Skip the test if any of this fails, as we are a
  1930. // bit outside of our stated domain here...
  1931. testName := ".syncthing-test." + srand.String(16)
  1932. testDir := filepath.Join(home, testName)
  1933. if err := os.RemoveAll(testDir); err != nil {
  1934. t.Skip(err)
  1935. }
  1936. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1937. t.Skip(err)
  1938. }
  1939. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1940. t.Skip(err)
  1941. }
  1942. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1943. t.Skip(err)
  1944. }
  1945. defer os.RemoveAll(testDir)
  1946. m := setupModel(defaultCfgWrapper)
  1947. defer cleanupModel(m)
  1948. if err := m.ScanFolder("default"); err != nil {
  1949. t.Error("scan error:", err)
  1950. }
  1951. m.fmut.Lock()
  1952. runner := m.folderRunners["default"]
  1953. m.fmut.Unlock()
  1954. if err := runner.CheckHealth(); err != nil {
  1955. t.Error("health check error:", err)
  1956. }
  1957. }
  1958. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1959. dbi := db.OpenMemory()
  1960. files := db.NewFileSet("default", defaultFs, dbi)
  1961. files.Drop(device1)
  1962. files.Update(device1, genFiles(1))
  1963. files.Drop(device2)
  1964. files.Update(device2, genFiles(1))
  1965. if len(files.ListDevices()) != 2 {
  1966. t.Error("expected two devices")
  1967. }
  1968. m := newModel(defaultCfgWrapper, myID, "syncthing", "dev", dbi, nil)
  1969. m.AddFolder(defaultFolderConfig)
  1970. m.StartFolder("default")
  1971. defer cleanupModel(m)
  1972. // Remote sequence is cached, hence need to recreated.
  1973. files = db.NewFileSet("default", defaultFs, dbi)
  1974. if len(files.ListDevices()) != 1 {
  1975. t.Error("Expected one device")
  1976. }
  1977. }
  1978. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1979. wcfg := createTmpWrapper(defaultCfg)
  1980. wcfg.SetDevice(config.NewDeviceConfiguration(device2, "device2"))
  1981. fcfg := wcfg.FolderList()[0]
  1982. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  1983. wcfg.SetFolder(fcfg)
  1984. defer os.Remove(wcfg.ConfigPath())
  1985. m := setupModel(wcfg)
  1986. defer cleanupModel(m)
  1987. conn1 := &fakeConnection{id: device1, model: m}
  1988. m.AddConnection(conn1, protocol.HelloResult{})
  1989. conn2 := &fakeConnection{id: device2, model: m}
  1990. m.AddConnection(conn2, protocol.HelloResult{})
  1991. m.ClusterConfig(device1, protocol.ClusterConfig{
  1992. Folders: []protocol.Folder{
  1993. {
  1994. ID: "default",
  1995. Devices: []protocol.Device{
  1996. {ID: myID},
  1997. {ID: device1},
  1998. {ID: device2},
  1999. },
  2000. },
  2001. },
  2002. })
  2003. m.ClusterConfig(device2, protocol.ClusterConfig{
  2004. Folders: []protocol.Folder{
  2005. {
  2006. ID: "default",
  2007. Devices: []protocol.Device{
  2008. {ID: myID},
  2009. {ID: device1},
  2010. {ID: device2},
  2011. },
  2012. },
  2013. },
  2014. })
  2015. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2016. t.Error("not shared with device1")
  2017. }
  2018. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
  2019. t.Error("not shared with device2")
  2020. }
  2021. if conn2.Closed() {
  2022. t.Error("conn already closed")
  2023. }
  2024. if _, err := wcfg.RemoveDevice(device2); err != nil {
  2025. t.Error(err)
  2026. }
  2027. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  2028. fcfg, ok := m.cfg.Folder("default")
  2029. if !ok {
  2030. t.Fatal("default folder missing")
  2031. }
  2032. if !fcfg.SharedWith(device1) {
  2033. t.Error("not shared with device1")
  2034. }
  2035. if fcfg.SharedWith(device2) {
  2036. t.Error("shared with device2")
  2037. }
  2038. for _, dev := range fcfg.Devices {
  2039. if dev.DeviceID == device2 {
  2040. t.Error("still there")
  2041. }
  2042. }
  2043. if !conn2.Closed() {
  2044. t.Error("connection not closed")
  2045. }
  2046. if _, ok := wcfg.Devices()[device2]; ok {
  2047. t.Error("device still in config")
  2048. }
  2049. if _, ok := m.conn[device2]; ok {
  2050. t.Error("conn not missing")
  2051. }
  2052. if _, ok := m.helloMessages[device2]; ok {
  2053. t.Error("hello not missing")
  2054. }
  2055. if _, ok := m.deviceDownloads[device2]; ok {
  2056. t.Error("downloads not missing")
  2057. }
  2058. }
  2059. func TestIssue3496(t *testing.T) {
  2060. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  2061. // It seems like lots of deleted files can cause negative completion
  2062. // percentages. Lets make sure that doesn't happen. Also do some general
  2063. // checks on the completion calculation stuff.
  2064. m := setupModel(defaultCfgWrapper)
  2065. defer cleanupModel(m)
  2066. m.ScanFolder("default")
  2067. addFakeConn(m, device1)
  2068. addFakeConn(m, device2)
  2069. // Reach into the model and grab the current file list...
  2070. m.fmut.RLock()
  2071. fs := m.folderFiles["default"]
  2072. m.fmut.RUnlock()
  2073. var localFiles []protocol.FileInfo
  2074. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  2075. localFiles = append(localFiles, i.(protocol.FileInfo))
  2076. return true
  2077. })
  2078. // Mark all files as deleted and fake it as update from device1
  2079. for i := range localFiles {
  2080. localFiles[i].Deleted = true
  2081. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  2082. localFiles[i].Blocks = nil
  2083. }
  2084. // Also add a small file that we're supposed to need, or the global size
  2085. // stuff will bail out early due to the entire folder being zero size.
  2086. localFiles = append(localFiles, protocol.FileInfo{
  2087. Name: "fake",
  2088. Size: 1234,
  2089. Type: protocol.FileInfoTypeFile,
  2090. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  2091. })
  2092. m.IndexUpdate(device1, "default", localFiles)
  2093. // Check that the completion percentage for us makes sense
  2094. comp := m.Completion(protocol.LocalDeviceID, "default")
  2095. if comp.NeedBytes > comp.GlobalBytes {
  2096. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  2097. }
  2098. if comp.CompletionPct < 0 {
  2099. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  2100. }
  2101. if comp.NeedBytes == 0 {
  2102. t.Error("Need no bytes even though some files are deleted")
  2103. }
  2104. if comp.CompletionPct == 100 {
  2105. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  2106. }
  2107. t.Log(comp)
  2108. // Check that NeedSize does the correct thing
  2109. need := m.NeedSize("default")
  2110. if need.Files != 1 || need.Bytes != 1234 {
  2111. // The one we added synthetically above
  2112. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  2113. }
  2114. if int(need.Deleted) != len(localFiles)-1 {
  2115. // The rest
  2116. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  2117. }
  2118. }
  2119. func TestIssue3804(t *testing.T) {
  2120. m := setupModel(defaultCfgWrapper)
  2121. defer cleanupModel(m)
  2122. // Subdirs ending in slash should be accepted
  2123. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  2124. t.Error("Unexpected error:", err)
  2125. }
  2126. }
  2127. func TestIssue3829(t *testing.T) {
  2128. m := setupModel(defaultCfgWrapper)
  2129. defer cleanupModel(m)
  2130. // Empty subdirs should be accepted
  2131. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  2132. t.Error("Unexpected error:", err)
  2133. }
  2134. }
  2135. func TestNoRequestsFromPausedDevices(t *testing.T) {
  2136. t.Skip("broken, fails randomly, #3843")
  2137. wcfg := createTmpWrapper(defaultCfg)
  2138. wcfg.SetDevice(config.NewDeviceConfiguration(device2, "device2"))
  2139. fcfg := wcfg.FolderList()[0]
  2140. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  2141. wcfg.SetFolder(fcfg)
  2142. m := setupModel(wcfg)
  2143. defer cleanupModel(m)
  2144. file := testDataExpected["foo"]
  2145. files := m.folderFiles["default"]
  2146. files.Update(device1, []protocol.FileInfo{file})
  2147. files.Update(device2, []protocol.FileInfo{file})
  2148. avail := m.Availability("default", file, file.Blocks[0])
  2149. if len(avail) != 0 {
  2150. t.Errorf("should not be available, no connections")
  2151. }
  2152. addFakeConn(m, device1)
  2153. addFakeConn(m, device2)
  2154. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2155. avail = m.Availability("default", file, file.Blocks[0])
  2156. if len(avail) != 2 {
  2157. t.Errorf("should have two available")
  2158. }
  2159. cc := protocol.ClusterConfig{
  2160. Folders: []protocol.Folder{
  2161. {
  2162. ID: "default",
  2163. Devices: []protocol.Device{
  2164. {ID: device1},
  2165. {ID: device2},
  2166. },
  2167. },
  2168. },
  2169. }
  2170. m.ClusterConfig(device1, cc)
  2171. m.ClusterConfig(device2, cc)
  2172. avail = m.Availability("default", file, file.Blocks[0])
  2173. if len(avail) != 2 {
  2174. t.Errorf("should have two available")
  2175. }
  2176. m.Closed(&fakeConnection{id: device1, model: m}, errDeviceUnknown)
  2177. m.Closed(&fakeConnection{id: device2, model: m}, errDeviceUnknown)
  2178. avail = m.Availability("default", file, file.Blocks[0])
  2179. if len(avail) != 0 {
  2180. t.Errorf("should have no available")
  2181. }
  2182. // Test that remote paused folders are not used.
  2183. addFakeConn(m, device1)
  2184. addFakeConn(m, device2)
  2185. m.ClusterConfig(device1, cc)
  2186. ccp := cc
  2187. ccp.Folders[0].Paused = true
  2188. m.ClusterConfig(device1, ccp)
  2189. avail = m.Availability("default", file, file.Blocks[0])
  2190. if len(avail) != 1 {
  2191. t.Errorf("should have one available")
  2192. }
  2193. }
  2194. // TestIssue2571 tests replacing a directory with content with a symlink
  2195. func TestIssue2571(t *testing.T) {
  2196. if runtime.GOOS == "windows" {
  2197. t.Skip("Scanning symlinks isn't supported on windows")
  2198. }
  2199. w, fcfg := tmpDefaultWrapper()
  2200. testFs := fcfg.Filesystem()
  2201. defer os.RemoveAll(testFs.URI())
  2202. for _, dir := range []string{"toLink", "linkTarget"} {
  2203. must(t, testFs.MkdirAll(dir, 0775))
  2204. fd, err := testFs.Create(filepath.Join(dir, "a"))
  2205. must(t, err)
  2206. fd.Close()
  2207. }
  2208. m := setupModel(w)
  2209. defer cleanupModel(m)
  2210. must(t, testFs.RemoveAll("toLink"))
  2211. must(t, osutil.DebugSymlinkForTestsOnly(filepath.Join(testFs.URI(), "linkTarget"), filepath.Join(testFs.URI(), "toLink")))
  2212. m.ScanFolder("default")
  2213. if dir, ok := m.CurrentFolderFile("default", "toLink"); !ok {
  2214. t.Fatalf("Dir missing in db")
  2215. } else if !dir.IsSymlink() {
  2216. t.Errorf("Dir wasn't changed to symlink")
  2217. }
  2218. if file, ok := m.CurrentFolderFile("default", filepath.Join("toLink", "a")); !ok {
  2219. t.Fatalf("File missing in db")
  2220. } else if !file.Deleted {
  2221. t.Errorf("File below symlink has not been marked as deleted")
  2222. }
  2223. }
  2224. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  2225. func TestIssue4573(t *testing.T) {
  2226. if runtime.GOOS == "windows" {
  2227. t.Skip("Can't make the dir inaccessible on windows")
  2228. }
  2229. w, fcfg := tmpDefaultWrapper()
  2230. testFs := fcfg.Filesystem()
  2231. defer os.RemoveAll(testFs.URI())
  2232. must(t, testFs.MkdirAll("inaccessible", 0755))
  2233. defer testFs.Chmod("inaccessible", 0777)
  2234. file := filepath.Join("inaccessible", "a")
  2235. fd, err := testFs.Create(file)
  2236. must(t, err)
  2237. fd.Close()
  2238. m := setupModel(w)
  2239. defer cleanupModel(m)
  2240. must(t, testFs.Chmod("inaccessible", 0000))
  2241. m.ScanFolder("default")
  2242. if file, ok := m.CurrentFolderFile("default", file); !ok {
  2243. t.Fatalf("File missing in db")
  2244. } else if file.Deleted {
  2245. t.Errorf("Inaccessible file has been marked as deleted.")
  2246. }
  2247. }
  2248. // TestInternalScan checks whether various fs operations are correctly represented
  2249. // in the db after scanning.
  2250. func TestInternalScan(t *testing.T) {
  2251. w, fcfg := tmpDefaultWrapper()
  2252. testFs := fcfg.Filesystem()
  2253. defer os.RemoveAll(testFs.URI())
  2254. testCases := map[string]func(protocol.FileInfo) bool{
  2255. "removeDir": func(f protocol.FileInfo) bool {
  2256. return !f.Deleted
  2257. },
  2258. "dirToFile": func(f protocol.FileInfo) bool {
  2259. return f.Deleted || f.IsDirectory()
  2260. },
  2261. }
  2262. baseDirs := []string{"dirToFile", "removeDir"}
  2263. for _, dir := range baseDirs {
  2264. sub := filepath.Join(dir, "subDir")
  2265. for _, dir := range []string{dir, sub} {
  2266. if err := testFs.MkdirAll(dir, 0775); err != nil {
  2267. t.Fatalf("%v: %v", dir, err)
  2268. }
  2269. }
  2270. testCases[sub] = func(f protocol.FileInfo) bool {
  2271. return !f.Deleted
  2272. }
  2273. for _, dir := range []string{dir, sub} {
  2274. file := filepath.Join(dir, "a")
  2275. fd, err := testFs.Create(file)
  2276. must(t, err)
  2277. fd.Close()
  2278. testCases[file] = func(f protocol.FileInfo) bool {
  2279. return !f.Deleted
  2280. }
  2281. }
  2282. }
  2283. m := setupModel(w)
  2284. defer cleanupModel(m)
  2285. for _, dir := range baseDirs {
  2286. must(t, testFs.RemoveAll(dir))
  2287. }
  2288. fd, err := testFs.Create("dirToFile")
  2289. must(t, err)
  2290. fd.Close()
  2291. m.ScanFolder("default")
  2292. for path, cond := range testCases {
  2293. if f, ok := m.CurrentFolderFile("default", path); !ok {
  2294. t.Fatalf("%v missing in db", path)
  2295. } else if cond(f) {
  2296. t.Errorf("Incorrect db entry for %v", path)
  2297. }
  2298. }
  2299. }
  2300. func TestCustomMarkerName(t *testing.T) {
  2301. testOs := &fatalOs{t}
  2302. ldb := db.OpenMemory()
  2303. set := db.NewFileSet("default", defaultFs, ldb)
  2304. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2305. {Name: "dummyfile"},
  2306. })
  2307. fcfg := config.FolderConfiguration{
  2308. ID: "default",
  2309. Path: "rwtestfolder",
  2310. Type: config.FolderTypeSendReceive,
  2311. RescanIntervalS: 1,
  2312. MarkerName: "myfile",
  2313. }
  2314. cfg := createTmpWrapper(config.Configuration{
  2315. Folders: []config.FolderConfiguration{fcfg},
  2316. Devices: []config.DeviceConfiguration{
  2317. {
  2318. DeviceID: device1,
  2319. },
  2320. },
  2321. })
  2322. testOs.RemoveAll(fcfg.Path)
  2323. defer testOs.RemoveAll(fcfg.Path)
  2324. m := newModel(cfg, myID, "syncthing", "dev", ldb, nil)
  2325. m.AddFolder(fcfg)
  2326. m.StartFolder("default")
  2327. m.ServeBackground()
  2328. defer cleanupModel(m)
  2329. waitForState(t, m, "default", "folder path missing")
  2330. testOs.Mkdir(fcfg.Path, 0700)
  2331. fd := testOs.Create(filepath.Join(fcfg.Path, "myfile"))
  2332. fd.Close()
  2333. waitForState(t, m, "default", "")
  2334. }
  2335. func TestRemoveDirWithContent(t *testing.T) {
  2336. defer func() {
  2337. defaultFs.RemoveAll("dirwith")
  2338. }()
  2339. defaultFs.MkdirAll("dirwith", 0755)
  2340. content := filepath.Join("dirwith", "content")
  2341. fd, err := defaultFs.Create(content)
  2342. must(t, err)
  2343. fd.Close()
  2344. m := setupModel(defaultCfgWrapper)
  2345. defer cleanupModel(m)
  2346. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2347. if !ok {
  2348. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2349. }
  2350. dir.Deleted = true
  2351. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2352. file, ok := m.CurrentFolderFile("default", content)
  2353. if !ok {
  2354. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2355. }
  2356. file.Deleted = true
  2357. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2358. m.IndexUpdate(device1, "default", []protocol.FileInfo{dir, file})
  2359. // Is there something we could trigger on instead of just waiting?
  2360. timeout := time.NewTimer(5 * time.Second)
  2361. for {
  2362. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2363. if !ok {
  2364. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2365. }
  2366. file, ok := m.CurrentFolderFile("default", content)
  2367. if !ok {
  2368. t.Fatalf("Can't get file \"%v\" after index update", content)
  2369. }
  2370. if dir.Deleted && file.Deleted {
  2371. return
  2372. }
  2373. select {
  2374. case <-timeout.C:
  2375. if !dir.Deleted && !file.Deleted {
  2376. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2377. } else if !dir.Deleted {
  2378. t.Errorf("The dir was not deleted before timing out.")
  2379. } else {
  2380. t.Errorf("The content of the dir was not deleted before timing out.")
  2381. }
  2382. return
  2383. default:
  2384. time.Sleep(100 * time.Millisecond)
  2385. }
  2386. }
  2387. }
  2388. func TestIssue4475(t *testing.T) {
  2389. m, conn, fcfg := setupModelWithConnection()
  2390. defer cleanupModel(m)
  2391. testFs := fcfg.Filesystem()
  2392. // Scenario: Dir is deleted locally and before syncing/index exchange
  2393. // happens, a file is create in that dir on the remote.
  2394. // This should result in the directory being recreated and added to the
  2395. // db locally.
  2396. must(t, testFs.MkdirAll("delDir", 0755))
  2397. m.ScanFolder("default")
  2398. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2399. t.Fatal("not shared with device1")
  2400. }
  2401. fileName := filepath.Join("delDir", "file")
  2402. conn.addFile(fileName, 0644, protocol.FileInfoTypeFile, nil)
  2403. conn.sendIndexUpdate()
  2404. // Is there something we could trigger on instead of just waiting?
  2405. timeout := time.NewTimer(5 * time.Second)
  2406. created := false
  2407. for {
  2408. if !created {
  2409. if _, ok := m.CurrentFolderFile("default", fileName); ok {
  2410. created = true
  2411. }
  2412. } else {
  2413. dir, ok := m.CurrentFolderFile("default", "delDir")
  2414. if !ok {
  2415. t.Fatalf("can't get dir from db")
  2416. }
  2417. if !dir.Deleted {
  2418. return
  2419. }
  2420. }
  2421. select {
  2422. case <-timeout.C:
  2423. if created {
  2424. t.Errorf("Timed out before file from remote was created")
  2425. } else {
  2426. t.Errorf("Timed out before directory was resurrected in db")
  2427. }
  2428. return
  2429. default:
  2430. time.Sleep(100 * time.Millisecond)
  2431. }
  2432. }
  2433. }
  2434. func TestVersionRestore(t *testing.T) {
  2435. // We create a bunch of files which we restore
  2436. // In each file, we write the filename as the content
  2437. // We verify that the content matches at the expected filenames
  2438. // after the restore operation.
  2439. dir, err := ioutil.TempDir("", "")
  2440. must(t, err)
  2441. defer os.RemoveAll(dir)
  2442. fcfg := config.NewFolderConfiguration(myID, "default", "default", fs.FilesystemTypeBasic, dir)
  2443. fcfg.Versioning.Type = "simple"
  2444. fcfg.FSWatcherEnabled = false
  2445. filesystem := fcfg.Filesystem()
  2446. rawConfig := config.Configuration{
  2447. Folders: []config.FolderConfiguration{fcfg},
  2448. }
  2449. cfg := createTmpWrapper(rawConfig)
  2450. m := setupModel(cfg)
  2451. defer cleanupModel(m)
  2452. m.ScanFolder("default")
  2453. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20180101-010101", time.Local)
  2454. if err != nil {
  2455. t.Fatal(err)
  2456. }
  2457. for _, file := range []string{
  2458. // Versions directory
  2459. ".stversions/file~20171210-040404.txt", // will be restored
  2460. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2461. ".stversions/something~20171210-040404", // will become directory, hence error
  2462. ".stversions/dir/file~20171210-040404.txt",
  2463. ".stversions/dir/file~20171210-040405.txt",
  2464. ".stversions/dir/file~20171210-040406.txt",
  2465. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2466. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2467. ".stversions/dir/cat", // untagged which was used by trashcan, supported
  2468. // "file.txt" will be restored
  2469. "existing",
  2470. "something/file", // Becomes directory
  2471. "dir/file.txt",
  2472. "dir/existing.txt",
  2473. } {
  2474. if runtime.GOOS == "windows" {
  2475. file = filepath.FromSlash(file)
  2476. }
  2477. dir := filepath.Dir(file)
  2478. must(t, filesystem.MkdirAll(dir, 0755))
  2479. if fd, err := filesystem.Create(file); err != nil {
  2480. t.Fatal(err)
  2481. } else if _, err := fd.Write([]byte(file)); err != nil {
  2482. t.Fatal(err)
  2483. } else if err := fd.Close(); err != nil {
  2484. t.Fatal(err)
  2485. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2486. t.Fatal(err)
  2487. }
  2488. }
  2489. versions, err := m.GetFolderVersions("default")
  2490. must(t, err)
  2491. expectedVersions := map[string]int{
  2492. "file.txt": 1,
  2493. "existing": 1,
  2494. "something": 1,
  2495. "dir/file.txt": 3,
  2496. "dir/existing.txt": 1,
  2497. "very/very/deep/one.txt": 1,
  2498. "dir/cat": 1,
  2499. }
  2500. for name, vers := range versions {
  2501. cnt, ok := expectedVersions[name]
  2502. if !ok {
  2503. t.Errorf("unexpected %s", name)
  2504. }
  2505. if len(vers) != cnt {
  2506. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2507. }
  2508. // Delete, so we can check if we didn't hit something we expect afterwards.
  2509. delete(expectedVersions, name)
  2510. }
  2511. for name := range expectedVersions {
  2512. t.Errorf("not found expected %s", name)
  2513. }
  2514. // Restoring non existing folder fails.
  2515. _, err = m.RestoreFolderVersions("does not exist", nil)
  2516. if err == nil {
  2517. t.Errorf("expected an error")
  2518. }
  2519. makeTime := func(s string) time.Time {
  2520. tm, err := time.ParseInLocation(versioner.TimeFormat, s, time.Local)
  2521. if err != nil {
  2522. t.Error(err)
  2523. }
  2524. return tm.Truncate(time.Second)
  2525. }
  2526. restore := map[string]time.Time{
  2527. "file.txt": makeTime("20171210-040404"),
  2528. "existing": makeTime("20171210-040404"),
  2529. "something": makeTime("20171210-040404"),
  2530. "dir/file.txt": makeTime("20171210-040406"),
  2531. "dir/existing.txt": makeTime("20171210-040406"),
  2532. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2533. }
  2534. beforeRestore := time.Now().Truncate(time.Second)
  2535. ferr, err := m.RestoreFolderVersions("default", restore)
  2536. must(t, err)
  2537. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || err != "cannot restore on top of a directory" {
  2538. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2539. }
  2540. // Failed items are not expected to be restored.
  2541. // Remove them from expectations
  2542. for name := range ferr {
  2543. delete(restore, name)
  2544. }
  2545. // Check that content of files matches to the version they've been restored.
  2546. for file, version := range restore {
  2547. if runtime.GOOS == "windows" {
  2548. file = filepath.FromSlash(file)
  2549. }
  2550. tag := version.In(time.Local).Truncate(time.Second).Format(versioner.TimeFormat)
  2551. taggedName := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2552. fd, err := filesystem.Open(file)
  2553. if err != nil {
  2554. t.Error(err)
  2555. }
  2556. defer fd.Close()
  2557. content, err := ioutil.ReadAll(fd)
  2558. if err != nil {
  2559. t.Error(err)
  2560. }
  2561. if !bytes.Equal(content, []byte(taggedName)) {
  2562. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2563. }
  2564. }
  2565. // Simple versioner uses now for timestamp generation, so we can check
  2566. // if existing stuff was correctly archived as we restored (oppose to deleteD), and version time as after beforeRestore
  2567. expectArchived := map[string]struct{}{
  2568. "existing": {},
  2569. "dir/file.txt": {},
  2570. "dir/existing.txt": {},
  2571. }
  2572. allFileVersions, err := m.GetFolderVersions("default")
  2573. must(t, err)
  2574. for file, versions := range allFileVersions {
  2575. key := file
  2576. if runtime.GOOS == "windows" {
  2577. file = filepath.FromSlash(file)
  2578. }
  2579. for _, version := range versions {
  2580. if version.VersionTime.Equal(beforeRestore) || version.VersionTime.After(beforeRestore) {
  2581. fd, err := filesystem.Open(".stversions/" + versioner.TagFilename(file, version.VersionTime.Format(versioner.TimeFormat)))
  2582. must(t, err)
  2583. defer fd.Close()
  2584. content, err := ioutil.ReadAll(fd)
  2585. if err != nil {
  2586. t.Error(err)
  2587. }
  2588. // Even if they are at the archived path, content should have the non
  2589. // archived name.
  2590. if !bytes.Equal(content, []byte(file)) {
  2591. t.Errorf("%s (%s): %s != %s", file, fd.Name(), string(content), file)
  2592. }
  2593. _, ok := expectArchived[key]
  2594. if !ok {
  2595. t.Error("unexpected archived file with future timestamp", file, version.VersionTime)
  2596. }
  2597. delete(expectArchived, key)
  2598. }
  2599. }
  2600. }
  2601. if len(expectArchived) != 0 {
  2602. t.Fatal("missed some archived files", expectArchived)
  2603. }
  2604. }
  2605. func TestPausedFolders(t *testing.T) {
  2606. // Create a separate wrapper not to pollute other tests.
  2607. wrapper := createTmpWrapper(defaultCfgWrapper.RawCopy())
  2608. m := setupModel(wrapper)
  2609. defer cleanupModel(m)
  2610. if err := m.ScanFolder("default"); err != nil {
  2611. t.Error(err)
  2612. }
  2613. pausedConfig := wrapper.RawCopy()
  2614. pausedConfig.Folders[0].Paused = true
  2615. w, err := m.cfg.Replace(pausedConfig)
  2616. must(t, err)
  2617. w.Wait()
  2618. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  2619. t.Errorf("Expected folder paused error, received: %v", err)
  2620. }
  2621. if err := m.ScanFolder("nonexistent"); err != errFolderMissing {
  2622. t.Errorf("Expected missing folder error, received: %v", err)
  2623. }
  2624. }
  2625. func TestIssue4094(t *testing.T) {
  2626. testOs := &fatalOs{t}
  2627. db := db.OpenMemory()
  2628. // Create a separate wrapper not to pollute other tests.
  2629. wrapper := createTmpWrapper(config.Configuration{})
  2630. m := newModel(wrapper, myID, "syncthing", "dev", db, nil)
  2631. m.ServeBackground()
  2632. defer cleanupModel(m)
  2633. // Force the model to wire itself and add the folders
  2634. folderPath := "nonexistent"
  2635. defer testOs.RemoveAll(folderPath)
  2636. cfg := defaultCfgWrapper.RawCopy()
  2637. fcfg := config.FolderConfiguration{
  2638. ID: "folder1",
  2639. Path: folderPath,
  2640. Paused: true,
  2641. Devices: []config.FolderDeviceConfiguration{
  2642. {DeviceID: device1},
  2643. },
  2644. }
  2645. cfg.Folders = []config.FolderConfiguration{fcfg}
  2646. p, err := wrapper.Replace(cfg)
  2647. must(t, err)
  2648. p.Wait()
  2649. if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
  2650. t.Fatalf("failed setting ignores: %v", err)
  2651. }
  2652. if _, err := fcfg.Filesystem().Lstat(".stignore"); err != nil {
  2653. t.Fatalf("failed stating .stignore: %v", err)
  2654. }
  2655. }
  2656. func TestIssue4903(t *testing.T) {
  2657. testOs := &fatalOs{t}
  2658. db := db.OpenMemory()
  2659. // Create a separate wrapper not to pollute other tests.
  2660. wrapper := createTmpWrapper(config.Configuration{})
  2661. m := newModel(wrapper, myID, "syncthing", "dev", db, nil)
  2662. m.ServeBackground()
  2663. defer cleanupModel(m)
  2664. // Force the model to wire itself and add the folders
  2665. folderPath := "nonexistent"
  2666. defer testOs.RemoveAll(folderPath)
  2667. cfg := defaultCfgWrapper.RawCopy()
  2668. fcfg := config.FolderConfiguration{
  2669. ID: "folder1",
  2670. Path: folderPath,
  2671. Paused: true,
  2672. Devices: []config.FolderDeviceConfiguration{
  2673. {DeviceID: device1},
  2674. },
  2675. }
  2676. cfg.Folders = []config.FolderConfiguration{fcfg}
  2677. p, err := wrapper.Replace(cfg)
  2678. must(t, err)
  2679. p.Wait()
  2680. if err := fcfg.CheckPath(); err != config.ErrPathMissing {
  2681. t.Fatalf("expected path missing error, got: %v", err)
  2682. }
  2683. if _, err := fcfg.Filesystem().Lstat("."); !fs.IsNotExist(err) {
  2684. t.Fatalf("Expected missing path error, got: %v", err)
  2685. }
  2686. }
  2687. func TestIssue5002(t *testing.T) {
  2688. // recheckFile should not panic when given an index equal to the number of blocks
  2689. m := setupModel(defaultCfgWrapper)
  2690. defer cleanupModel(m)
  2691. if err := m.ScanFolder("default"); err != nil {
  2692. t.Error(err)
  2693. }
  2694. file, ok := m.CurrentFolderFile("default", "foo")
  2695. if !ok {
  2696. t.Fatal("test file should exist")
  2697. }
  2698. blockSize := int32(file.BlockSize())
  2699. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", blockSize, file.Size-int64(blockSize), []byte{1, 2, 3, 4})
  2700. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", blockSize, file.Size, []byte{1, 2, 3, 4}) // panic
  2701. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", blockSize, file.Size+int64(blockSize), []byte{1, 2, 3, 4})
  2702. }
  2703. func TestParentOfUnignored(t *testing.T) {
  2704. m := newState(defaultCfg)
  2705. defer cleanupModel(m)
  2706. defer defaultFolderConfig.Filesystem().Remove(".stignore")
  2707. m.SetIgnores("default", []string{"!quux", "*"})
  2708. if parent, ok := m.CurrentFolderFile("default", "baz"); !ok {
  2709. t.Errorf(`Directory "baz" missing in db`)
  2710. } else if parent.IsIgnored() {
  2711. t.Errorf(`Directory "baz" is ignored`)
  2712. }
  2713. }
  2714. // TestFolderRestartZombies reproduces issue 5233, where multiple concurrent folder
  2715. // restarts would leave more than one folder runner alive.
  2716. func TestFolderRestartZombies(t *testing.T) {
  2717. wrapper := createTmpWrapper(defaultCfg.Copy())
  2718. folderCfg, _ := wrapper.Folder("default")
  2719. folderCfg.FilesystemType = fs.FilesystemTypeFake
  2720. wrapper.SetFolder(folderCfg)
  2721. m := setupModel(wrapper)
  2722. defer cleanupModel(m)
  2723. // Make sure the folder is up and running, because we want to count it.
  2724. m.ScanFolder("default")
  2725. // Check how many running folders we have running before the test.
  2726. if r := atomic.LoadInt32(&m.foldersRunning); r != 1 {
  2727. t.Error("Expected one running folder, not", r)
  2728. }
  2729. // Run a few parallel configuration changers for one second. Each waits
  2730. // for the commit to complete, but there are many of them.
  2731. var wg sync.WaitGroup
  2732. for i := 0; i < 25; i++ {
  2733. wg.Add(1)
  2734. go func() {
  2735. defer wg.Done()
  2736. t0 := time.Now()
  2737. for time.Since(t0) < time.Second {
  2738. cfg := folderCfg.Copy()
  2739. cfg.MaxConflicts = rand.Int() // safe change that should cause a folder restart
  2740. w, err := wrapper.SetFolder(cfg)
  2741. if err != nil {
  2742. panic(err)
  2743. }
  2744. w.Wait()
  2745. }
  2746. }()
  2747. }
  2748. // Wait for the above to complete and check how many folders we have
  2749. // running now. It should not have increased.
  2750. wg.Wait()
  2751. // Make sure the folder is up and running, because we want to count it.
  2752. m.ScanFolder("default")
  2753. if r := atomic.LoadInt32(&m.foldersRunning); r != 1 {
  2754. t.Error("Expected one running folder, not", r)
  2755. }
  2756. }
  2757. func TestRequestLimit(t *testing.T) {
  2758. wrapper := createTmpWrapper(defaultCfg.Copy())
  2759. dev, _ := wrapper.Device(device1)
  2760. dev.MaxRequestKiB = 1
  2761. wrapper.SetDevice(dev)
  2762. m, _ := setupModelWithConnectionFromWrapper(wrapper)
  2763. defer cleanupModel(m)
  2764. file := "tmpfile"
  2765. befReq := time.Now()
  2766. first, err := m.Request(device1, "default", file, 2000, 0, nil, 0, false)
  2767. if err != nil {
  2768. t.Fatalf("First request failed: %v", err)
  2769. }
  2770. reqDur := time.Since(befReq)
  2771. returned := make(chan struct{})
  2772. go func() {
  2773. second, err := m.Request(device1, "default", file, 2000, 0, nil, 0, false)
  2774. if err != nil {
  2775. t.Fatalf("Second request failed: %v", err)
  2776. }
  2777. close(returned)
  2778. second.Close()
  2779. }()
  2780. time.Sleep(10 * reqDur)
  2781. select {
  2782. case <-returned:
  2783. t.Fatalf("Second request returned before first was done")
  2784. default:
  2785. }
  2786. first.Close()
  2787. select {
  2788. case <-returned:
  2789. case <-time.After(time.Second):
  2790. t.Fatalf("Second request did not return after first was done")
  2791. }
  2792. }
  2793. func TestSanitizePath(t *testing.T) {
  2794. cases := [][2]string{
  2795. {"", ""},
  2796. {"foo", "foo"},
  2797. {`\*/foo\?/bar[{!@$%^&*#()}]`, "foo bar ()"},
  2798. {"Räksmörgås", "Räksmörgås"},
  2799. {`Räk \/ smörgås`, "Räk smörgås"},
  2800. {"هذا هو *\x07?اسم الملف", "هذا هو اسم الملف"},
  2801. {`../foo.txt`, `.. foo.txt`},
  2802. }
  2803. for _, tc := range cases {
  2804. res := sanitizePath(tc[0])
  2805. if res != tc[1] {
  2806. t.Errorf("sanitizePath(%q) => %q, expected %q", tc[0], res, tc[1])
  2807. }
  2808. }
  2809. }
  2810. // TestConnCloseOnRestart checks that there is no deadlock when calling Close
  2811. // on a protocol connection that has a blocking reader (blocking writer can't
  2812. // be done as the test requires clusterconfigs to go through).
  2813. func TestConnCloseOnRestart(t *testing.T) {
  2814. oldCloseTimeout := protocol.CloseTimeout
  2815. protocol.CloseTimeout = 100 * time.Millisecond
  2816. defer func() {
  2817. protocol.CloseTimeout = oldCloseTimeout
  2818. }()
  2819. w, fcfg := tmpDefaultWrapper()
  2820. m := setupModel(w)
  2821. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  2822. br := &testutils.BlockingRW{}
  2823. nw := &testutils.NoopRW{}
  2824. m.AddConnection(newFakeProtoConn(protocol.NewConnection(device1, br, nw, m, "testConn", protocol.CompressNever)), protocol.HelloResult{})
  2825. m.pmut.RLock()
  2826. if len(m.closed) != 1 {
  2827. t.Fatalf("Expected just one conn (len(m.conn) == %v)", len(m.conn))
  2828. }
  2829. closed := m.closed[device1]
  2830. m.pmut.RUnlock()
  2831. newFcfg := fcfg.Copy()
  2832. newFcfg.Paused = true
  2833. done := make(chan struct{})
  2834. go func() {
  2835. m.RestartFolder(fcfg, newFcfg)
  2836. close(done)
  2837. }()
  2838. select {
  2839. case <-done:
  2840. case <-time.After(5 * time.Second):
  2841. t.Fatal("Timed out before folder restart returned")
  2842. }
  2843. select {
  2844. case <-closed:
  2845. case <-time.After(5 * time.Second):
  2846. t.Fatal("Timed out before connection was closed")
  2847. }
  2848. }