model_test.go 99 KB

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