model_test.go 85 KB

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