model_test.go 110 KB

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