model_test.go 108 KB

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