model_test.go 98 KB

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