model_test.go 99 KB

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