model_test.go 113 KB

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