model_test.go 111 KB

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