model_test.go 106 KB

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