model_test.go 111 KB

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