model_test.go 91 KB

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