model_test.go 109 KB

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