model_test.go 106 KB

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