model_test.go 107 KB

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