model_test.go 89 KB

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