model_test.go 106 KB

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