model_test.go 96 KB

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