api.go 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  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 api
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "runtime"
  24. "runtime/pprof"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "unicode"
  30. "github.com/calmh/incontainer"
  31. "github.com/julienschmidt/httprouter"
  32. "github.com/prometheus/client_golang/prometheus/promhttp"
  33. "github.com/rcrowley/go-metrics"
  34. "github.com/thejerf/suture/v4"
  35. "github.com/vitrun/qart/qr"
  36. "golang.org/x/text/runes"
  37. "golang.org/x/text/transform"
  38. "golang.org/x/text/unicode/norm"
  39. "github.com/syncthing/syncthing/lib/build"
  40. "github.com/syncthing/syncthing/lib/config"
  41. "github.com/syncthing/syncthing/lib/connections"
  42. "github.com/syncthing/syncthing/lib/db"
  43. "github.com/syncthing/syncthing/lib/discover"
  44. "github.com/syncthing/syncthing/lib/events"
  45. "github.com/syncthing/syncthing/lib/fs"
  46. "github.com/syncthing/syncthing/lib/locations"
  47. "github.com/syncthing/syncthing/lib/logger"
  48. "github.com/syncthing/syncthing/lib/model"
  49. "github.com/syncthing/syncthing/lib/protocol"
  50. "github.com/syncthing/syncthing/lib/rand"
  51. "github.com/syncthing/syncthing/lib/svcutil"
  52. "github.com/syncthing/syncthing/lib/sync"
  53. "github.com/syncthing/syncthing/lib/tlsutil"
  54. "github.com/syncthing/syncthing/lib/upgrade"
  55. "github.com/syncthing/syncthing/lib/ur"
  56. )
  57. const (
  58. // Default mask excludes these very noisy event types to avoid filling the pipe.
  59. // FIXME: ItemStarted and ItemFinished should be excluded for the same reason.
  60. DefaultEventMask = events.AllEvents &^ events.LocalChangeDetected &^ events.RemoteChangeDetected
  61. DiskEventMask = events.LocalChangeDetected | events.RemoteChangeDetected
  62. EventSubBufferSize = 1000
  63. defaultEventTimeout = time.Minute
  64. httpsCertLifetimeDays = 820
  65. )
  66. type service struct {
  67. suture.Service
  68. id protocol.DeviceID
  69. cfg config.Wrapper
  70. statics *staticsServer
  71. model model.Model
  72. eventSubs map[events.EventType]events.BufferedSubscription
  73. eventSubsMut sync.Mutex
  74. evLogger events.Logger
  75. discoverer discover.Manager
  76. connectionsService connections.Service
  77. fss model.FolderSummaryService
  78. urService *ur.Service
  79. noUpgrade bool
  80. tlsDefaultCommonName string
  81. configChanged chan struct{} // signals intentional listener close due to config change
  82. started chan string // signals startup complete by sending the listener address, for testing only
  83. startedOnce chan struct{} // the service has started successfully at least once
  84. startupErr error
  85. listenerAddr net.Addr
  86. exitChan chan *svcutil.FatalErr
  87. miscDB *db.NamespacedKV
  88. shutdownTimeout time.Duration
  89. guiErrors logger.Recorder
  90. systemLog logger.Recorder
  91. }
  92. var _ config.Verifier = &service{}
  93. type Service interface {
  94. suture.Service
  95. config.Committer
  96. WaitForStart() error
  97. }
  98. func New(id protocol.DeviceID, cfg config.Wrapper, assetDir, tlsDefaultCommonName string, m model.Model, defaultSub, diskSub events.BufferedSubscription, evLogger events.Logger, discoverer discover.Manager, connectionsService connections.Service, urService *ur.Service, fss model.FolderSummaryService, errors, systemLog logger.Recorder, noUpgrade bool, miscDB *db.NamespacedKV) Service {
  99. return &service{
  100. id: id,
  101. cfg: cfg,
  102. statics: newStaticsServer(cfg.GUI().Theme, assetDir),
  103. model: m,
  104. eventSubs: map[events.EventType]events.BufferedSubscription{
  105. DefaultEventMask: defaultSub,
  106. DiskEventMask: diskSub,
  107. },
  108. eventSubsMut: sync.NewMutex(),
  109. evLogger: evLogger,
  110. discoverer: discoverer,
  111. connectionsService: connectionsService,
  112. fss: fss,
  113. urService: urService,
  114. guiErrors: errors,
  115. systemLog: systemLog,
  116. noUpgrade: noUpgrade,
  117. tlsDefaultCommonName: tlsDefaultCommonName,
  118. configChanged: make(chan struct{}),
  119. startedOnce: make(chan struct{}),
  120. exitChan: make(chan *svcutil.FatalErr, 1),
  121. miscDB: miscDB,
  122. shutdownTimeout: 100 * time.Millisecond,
  123. }
  124. }
  125. func (s *service) WaitForStart() error {
  126. <-s.startedOnce
  127. return s.startupErr
  128. }
  129. func (s *service) getListener(guiCfg config.GUIConfiguration) (net.Listener, error) {
  130. httpsCertFile := locations.Get(locations.HTTPSCertFile)
  131. httpsKeyFile := locations.Get(locations.HTTPSKeyFile)
  132. cert, err := tls.LoadX509KeyPair(httpsCertFile, httpsKeyFile)
  133. // If the certificate has expired or will expire in the next month, fail
  134. // it and generate a new one.
  135. if err == nil {
  136. err = shouldRegenerateCertificate(cert)
  137. }
  138. if err != nil {
  139. l.Infoln("Loading HTTPS certificate:", err)
  140. l.Infoln("Creating new HTTPS certificate")
  141. // When generating the HTTPS certificate, use the system host name per
  142. // default. If that isn't available, use the "syncthing" default.
  143. var name string
  144. name, err = os.Hostname()
  145. if err != nil {
  146. name = s.tlsDefaultCommonName
  147. }
  148. name, err = sanitizedHostname(name)
  149. if err != nil {
  150. name = s.tlsDefaultCommonName
  151. }
  152. cert, err = tlsutil.NewCertificate(httpsCertFile, httpsKeyFile, name, httpsCertLifetimeDays)
  153. }
  154. if err != nil {
  155. return nil, err
  156. }
  157. tlsCfg := tlsutil.SecureDefaultWithTLS12()
  158. tlsCfg.Certificates = []tls.Certificate{cert}
  159. if guiCfg.Network() == "unix" {
  160. // When listening on a UNIX socket we should unlink before bind,
  161. // lest we get a "bind: address already in use". We don't
  162. // particularly care if this succeeds or not.
  163. os.Remove(guiCfg.Address())
  164. }
  165. rawListener, err := net.Listen(guiCfg.Network(), guiCfg.Address())
  166. if err != nil {
  167. return nil, err
  168. }
  169. if guiCfg.Network() == "unix" && guiCfg.UnixSocketPermissions() != 0 {
  170. // We should error if this fails under the assumption that these permissions are
  171. // required for operation.
  172. err = os.Chmod(guiCfg.Address(), guiCfg.UnixSocketPermissions())
  173. if err != nil {
  174. return nil, err
  175. }
  176. }
  177. listener := &tlsutil.DowngradingListener{
  178. Listener: rawListener,
  179. TLSConfig: tlsCfg,
  180. }
  181. return listener, nil
  182. }
  183. func sendJSON(w http.ResponseWriter, jsonObject interface{}) {
  184. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  185. // Marshalling might fail, in which case we should return a 500 with the
  186. // actual error.
  187. bs, err := json.MarshalIndent(jsonObject, "", " ")
  188. if err != nil {
  189. // This Marshal() can't fail though.
  190. bs, _ = json.Marshal(map[string]string{"error": err.Error()})
  191. http.Error(w, string(bs), http.StatusInternalServerError)
  192. return
  193. }
  194. fmt.Fprintf(w, "%s\n", bs)
  195. }
  196. func (s *service) Serve(ctx context.Context) error {
  197. listener, err := s.getListener(s.cfg.GUI())
  198. if err != nil {
  199. select {
  200. case <-s.startedOnce:
  201. // We let this be a loud user-visible warning as it may be the only
  202. // indication they get that the GUI won't be available.
  203. l.Warnln("Starting API/GUI:", err)
  204. default:
  205. // This is during initialization. A failure here should be fatal
  206. // as there will be no way for the user to communicate with us
  207. // otherwise anyway.
  208. s.startupErr = err
  209. close(s.startedOnce)
  210. }
  211. return err
  212. }
  213. if listener == nil {
  214. // Not much we can do here other than exit quickly. The supervisor
  215. // will log an error at some point.
  216. return nil
  217. }
  218. s.listenerAddr = listener.Addr()
  219. defer listener.Close()
  220. s.cfg.Subscribe(s)
  221. defer s.cfg.Unsubscribe(s)
  222. restMux := httprouter.New()
  223. // The GET handlers
  224. restMux.HandlerFunc(http.MethodGet, "/rest/cluster/pending/devices", s.getPendingDevices) // -
  225. restMux.HandlerFunc(http.MethodGet, "/rest/cluster/pending/folders", s.getPendingFolders) // [device]
  226. restMux.HandlerFunc(http.MethodGet, "/rest/db/completion", s.getDBCompletion) // [device] [folder]
  227. restMux.HandlerFunc(http.MethodGet, "/rest/db/file", s.getDBFile) // folder file
  228. restMux.HandlerFunc(http.MethodGet, "/rest/db/ignores", s.getDBIgnores) // folder
  229. restMux.HandlerFunc(http.MethodGet, "/rest/db/need", s.getDBNeed) // folder [perpage] [page]
  230. restMux.HandlerFunc(http.MethodGet, "/rest/db/remoteneed", s.getDBRemoteNeed) // device folder [perpage] [page]
  231. restMux.HandlerFunc(http.MethodGet, "/rest/db/localchanged", s.getDBLocalChanged) // folder [perpage] [page]
  232. restMux.HandlerFunc(http.MethodGet, "/rest/db/status", s.getDBStatus) // folder
  233. restMux.HandlerFunc(http.MethodGet, "/rest/db/browse", s.getDBBrowse) // folder [prefix] [dirsonly] [levels]
  234. restMux.HandlerFunc(http.MethodGet, "/rest/folder/versions", s.getFolderVersions) // folder
  235. restMux.HandlerFunc(http.MethodGet, "/rest/folder/errors", s.getFolderErrors) // folder [perpage] [page]
  236. restMux.HandlerFunc(http.MethodGet, "/rest/folder/pullerrors", s.getFolderErrors) // folder (deprecated)
  237. restMux.HandlerFunc(http.MethodGet, "/rest/events", s.getIndexEvents) // [since] [limit] [timeout] [events]
  238. restMux.HandlerFunc(http.MethodGet, "/rest/events/disk", s.getDiskEvents) // [since] [limit] [timeout]
  239. restMux.HandlerFunc(http.MethodGet, "/rest/noauth/health", s.getHealth) // -
  240. restMux.HandlerFunc(http.MethodGet, "/rest/stats/device", s.getDeviceStats) // -
  241. restMux.HandlerFunc(http.MethodGet, "/rest/stats/folder", s.getFolderStats) // -
  242. restMux.HandlerFunc(http.MethodGet, "/rest/svc/deviceid", s.getDeviceID) // id
  243. restMux.HandlerFunc(http.MethodGet, "/rest/svc/lang", s.getLang) // -
  244. restMux.HandlerFunc(http.MethodGet, "/rest/svc/report", s.getReport) // -
  245. restMux.HandlerFunc(http.MethodGet, "/rest/svc/random/string", s.getRandomString) // [length]
  246. restMux.HandlerFunc(http.MethodGet, "/rest/system/browse", s.getSystemBrowse) // current
  247. restMux.HandlerFunc(http.MethodGet, "/rest/system/connections", s.getSystemConnections) // -
  248. restMux.HandlerFunc(http.MethodGet, "/rest/system/discovery", s.getSystemDiscovery) // -
  249. restMux.HandlerFunc(http.MethodGet, "/rest/system/error", s.getSystemError) // -
  250. restMux.HandlerFunc(http.MethodGet, "/rest/system/paths", s.getSystemPaths) // -
  251. restMux.HandlerFunc(http.MethodGet, "/rest/system/ping", s.restPing) // -
  252. restMux.HandlerFunc(http.MethodGet, "/rest/system/status", s.getSystemStatus) // -
  253. restMux.HandlerFunc(http.MethodGet, "/rest/system/upgrade", s.getSystemUpgrade) // -
  254. restMux.HandlerFunc(http.MethodGet, "/rest/system/version", s.getSystemVersion) // -
  255. restMux.HandlerFunc(http.MethodGet, "/rest/system/debug", s.getSystemDebug) // -
  256. restMux.HandlerFunc(http.MethodGet, "/rest/system/log", s.getSystemLog) // [since]
  257. restMux.HandlerFunc(http.MethodGet, "/rest/system/log.txt", s.getSystemLogTxt) // [since]
  258. // The POST handlers
  259. restMux.HandlerFunc(http.MethodPost, "/rest/db/prio", s.postDBPrio) // folder file
  260. restMux.HandlerFunc(http.MethodPost, "/rest/db/ignores", s.postDBIgnores) // folder
  261. restMux.HandlerFunc(http.MethodPost, "/rest/db/override", s.postDBOverride) // folder
  262. restMux.HandlerFunc(http.MethodPost, "/rest/db/revert", s.postDBRevert) // folder
  263. restMux.HandlerFunc(http.MethodPost, "/rest/db/scan", s.postDBScan) // folder [sub...] [delay]
  264. restMux.HandlerFunc(http.MethodPost, "/rest/folder/versions", s.postFolderVersionsRestore) // folder <body>
  265. restMux.HandlerFunc(http.MethodPost, "/rest/system/error", s.postSystemError) // <body>
  266. restMux.HandlerFunc(http.MethodPost, "/rest/system/error/clear", s.postSystemErrorClear) // -
  267. restMux.HandlerFunc(http.MethodPost, "/rest/system/ping", s.restPing) // -
  268. restMux.HandlerFunc(http.MethodPost, "/rest/system/reset", s.postSystemReset) // [folder]
  269. restMux.HandlerFunc(http.MethodPost, "/rest/system/restart", s.postSystemRestart) // -
  270. restMux.HandlerFunc(http.MethodPost, "/rest/system/shutdown", s.postSystemShutdown) // -
  271. restMux.HandlerFunc(http.MethodPost, "/rest/system/upgrade", s.postSystemUpgrade) // -
  272. restMux.HandlerFunc(http.MethodPost, "/rest/system/pause", s.makeDevicePauseHandler(true)) // [device]
  273. restMux.HandlerFunc(http.MethodPost, "/rest/system/resume", s.makeDevicePauseHandler(false)) // [device]
  274. restMux.HandlerFunc(http.MethodPost, "/rest/system/debug", s.postSystemDebug) // [enable] [disable]
  275. // The DELETE handlers
  276. restMux.HandlerFunc(http.MethodDelete, "/rest/cluster/pending/devices", s.deletePendingDevices) // device
  277. restMux.HandlerFunc(http.MethodDelete, "/rest/cluster/pending/folders", s.deletePendingFolders) // folder [device]
  278. // Config endpoints
  279. configBuilder := &configMuxBuilder{
  280. Router: restMux,
  281. id: s.id,
  282. cfg: s.cfg,
  283. }
  284. configBuilder.registerConfig("/rest/config")
  285. configBuilder.registerConfigInsync("/rest/config/insync") // deprecated
  286. configBuilder.registerConfigRequiresRestart("/rest/config/restart-required")
  287. configBuilder.registerFolders("/rest/config/folders")
  288. configBuilder.registerDevices("/rest/config/devices")
  289. configBuilder.registerFolder("/rest/config/folders/:id")
  290. configBuilder.registerDevice("/rest/config/devices/:id")
  291. configBuilder.registerDefaultFolder("/rest/config/defaults/folder")
  292. configBuilder.registerDefaultDevice("/rest/config/defaults/device")
  293. configBuilder.registerDefaultIgnores("/rest/config/defaults/ignores")
  294. configBuilder.registerOptions("/rest/config/options")
  295. configBuilder.registerLDAP("/rest/config/ldap")
  296. configBuilder.registerGUI("/rest/config/gui")
  297. // Deprecated config endpoints
  298. configBuilder.registerConfigDeprecated("/rest/system/config") // POST instead of PUT
  299. configBuilder.registerConfigInsync("/rest/system/config/insync")
  300. // Debug endpoints, not for general use
  301. debugMux := http.NewServeMux()
  302. debugMux.HandleFunc("/rest/debug/peerCompletion", s.getPeerCompletion)
  303. debugMux.HandleFunc("/rest/debug/httpmetrics", s.getSystemHTTPMetrics)
  304. debugMux.HandleFunc("/rest/debug/cpuprof", s.getCPUProf) // duration
  305. debugMux.HandleFunc("/rest/debug/heapprof", s.getHeapProf)
  306. debugMux.HandleFunc("/rest/debug/support", s.getSupportBundle)
  307. debugMux.HandleFunc("/rest/debug/file", s.getDebugFile)
  308. restMux.Handler(http.MethodGet, "/rest/debug/*method", s.whenDebugging(debugMux))
  309. // A handler that disables caching
  310. noCacheRestMux := noCacheMiddleware(metricsMiddleware(restMux))
  311. // The main routing handler
  312. mux := http.NewServeMux()
  313. mux.Handle("/rest/", noCacheRestMux)
  314. mux.HandleFunc("/qr/", s.getQR)
  315. // Serve compiled in assets unless an asset directory was set (for development)
  316. mux.Handle("/", s.statics)
  317. // Handle the special meta.js path
  318. mux.Handle("/meta.js", noCacheMiddleware(http.HandlerFunc(s.getJSMetadata)))
  319. // Handle Prometheus metrics
  320. promHttpHandler := promhttp.Handler()
  321. mux.Handle("/metrics", promHttpHandler)
  322. guiCfg := s.cfg.GUI()
  323. // Wrap everything in CSRF protection. The /rest prefix should be
  324. // protected, other requests will grant cookies.
  325. var handler http.Handler = newCsrfManager(s.id.Short().String(), "/rest", guiCfg, mux, s.miscDB)
  326. // Add our version and ID as a header to responses
  327. handler = withDetailsMiddleware(s.id, handler)
  328. // Wrap everything in basic auth, if user/password is set.
  329. if guiCfg.IsAuthEnabled() {
  330. tokenCookieManager := newTokenCookieManager(s.id.Short().String(), guiCfg, s.evLogger, s.miscDB)
  331. authMW := newBasicAuthAndSessionMiddleware(tokenCookieManager, guiCfg, s.cfg.LDAP(), handler, s.evLogger)
  332. handler = authMW
  333. restMux.Handler(http.MethodPost, "/rest/noauth/auth/password", http.HandlerFunc(authMW.passwordAuthHandler))
  334. // Logout is a no-op without a valid session cookie, so /noauth/ is fine here
  335. restMux.Handler(http.MethodPost, "/rest/noauth/auth/logout", http.HandlerFunc(authMW.handleLogout))
  336. }
  337. // Redirect to HTTPS if we are supposed to
  338. if guiCfg.UseTLS() {
  339. handler = redirectToHTTPSMiddleware(handler)
  340. }
  341. // Add the CORS handling
  342. handler = corsMiddleware(handler, guiCfg.InsecureAllowFrameLoading)
  343. if addressIsLocalhost(guiCfg.Address()) && !guiCfg.InsecureSkipHostCheck {
  344. // Verify source host
  345. handler = localhostMiddleware(handler)
  346. }
  347. handler = debugMiddleware(handler)
  348. srv := http.Server{
  349. Handler: handler,
  350. // ReadTimeout must be longer than SyncthingController $scope.refresh
  351. // interval to avoid HTTP keepalive/GUI refresh race.
  352. ReadTimeout: 15 * time.Second,
  353. // Prevent the HTTP server from logging stuff on its own. The things we
  354. // care about we log ourselves from the handlers.
  355. ErrorLog: log.New(io.Discard, "", 0),
  356. }
  357. if shouldDebugHTTP() {
  358. srv.ErrorLog = log.Default()
  359. }
  360. l.Infoln("GUI and API listening on", listener.Addr())
  361. l.Infoln("Access the GUI via the following URL:", guiCfg.URL())
  362. if s.started != nil {
  363. // only set when run by the tests
  364. select {
  365. case <-ctx.Done(): // Shouldn't return directly due to cleanup below
  366. case s.started <- listener.Addr().String():
  367. }
  368. }
  369. // Indicate successful initial startup, to ourselves and to interested
  370. // listeners (i.e. the thing that starts the browser).
  371. select {
  372. case <-s.startedOnce:
  373. default:
  374. close(s.startedOnce)
  375. }
  376. // Serve in the background
  377. serveError := make(chan error, 1)
  378. go func() {
  379. select {
  380. case serveError <- srv.Serve(listener):
  381. case <-ctx.Done():
  382. }
  383. }()
  384. // Wait for stop, restart or error signals
  385. err = nil
  386. select {
  387. case <-ctx.Done():
  388. // Shutting down permanently
  389. l.Debugln("shutting down (stop)")
  390. case <-s.configChanged:
  391. // Soft restart due to configuration change
  392. l.Debugln("restarting (config changed)")
  393. case err = <-s.exitChan:
  394. case err = <-serveError:
  395. // Restart due to listen/serve failure
  396. l.Warnln("GUI/API:", err, "(restarting)")
  397. }
  398. // Give it a moment to shut down gracefully, e.g. if we are restarting
  399. // due to a config change through the API, let that finish successfully.
  400. timeout, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
  401. defer cancel()
  402. if err := srv.Shutdown(timeout); err == timeout.Err() {
  403. srv.Close()
  404. }
  405. return err
  406. }
  407. // Complete implements suture.IsCompletable, which signifies to the supervisor
  408. // whether to stop restarting the service.
  409. func (s *service) Complete() bool {
  410. select {
  411. case <-s.startedOnce:
  412. return s.startupErr != nil
  413. default:
  414. }
  415. return false
  416. }
  417. func (s *service) String() string {
  418. return fmt.Sprintf("api.service@%p", s)
  419. }
  420. func (*service) VerifyConfiguration(_, to config.Configuration) error {
  421. if to.GUI.Network() != "tcp" {
  422. return nil
  423. }
  424. _, err := net.ResolveTCPAddr("tcp", to.GUI.Address())
  425. return err
  426. }
  427. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  428. // No action required when this changes, so mask the fact that it changed at all.
  429. from.GUI.Debugging = to.GUI.Debugging
  430. if to.GUI == from.GUI {
  431. // No GUI changes, we're done here.
  432. return true
  433. }
  434. if to.GUI.Theme != from.GUI.Theme {
  435. s.statics.setTheme(to.GUI.Theme)
  436. }
  437. // Tell the serve loop to restart
  438. s.configChanged <- struct{}{}
  439. return true
  440. }
  441. func (s *service) fatal(err *svcutil.FatalErr) {
  442. // s.exitChan is 1-buffered and whoever is first gets handled.
  443. select {
  444. case s.exitChan <- err:
  445. default:
  446. }
  447. }
  448. func debugMiddleware(h http.Handler) http.Handler {
  449. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  450. t0 := time.Now()
  451. h.ServeHTTP(w, r)
  452. if shouldDebugHTTP() {
  453. ms := 1000 * time.Since(t0).Seconds()
  454. // The variable `w` is most likely a *http.response, which we can't do
  455. // much with since it's a non exported type. We can however peek into
  456. // it with reflection to get at the status code and number of bytes
  457. // written.
  458. var status, written int64
  459. if rw := reflect.Indirect(reflect.ValueOf(w)); rw.IsValid() && rw.Kind() == reflect.Struct {
  460. if rf := rw.FieldByName("status"); rf.IsValid() && rf.Kind() == reflect.Int {
  461. status = rf.Int()
  462. }
  463. if rf := rw.FieldByName("written"); rf.IsValid() && rf.Kind() == reflect.Int64 {
  464. written = rf.Int()
  465. }
  466. }
  467. l.Debugf("http: %s %q: status %d, %d bytes in %.02f ms", r.Method, r.URL.String(), status, written, ms)
  468. }
  469. })
  470. }
  471. func corsMiddleware(next http.Handler, allowFrameLoading bool) http.Handler {
  472. // Handle CORS headers and CORS OPTIONS request.
  473. // CORS OPTIONS request are typically sent by browser during AJAX preflight
  474. // when the browser initiate a POST request.
  475. //
  476. // As the OPTIONS request is unauthorized, this handler must be the first
  477. // of the chain (hence added at the end).
  478. //
  479. // See https://www.w3.org/TR/cors/ for details.
  480. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  481. // Process OPTIONS requests
  482. if r.Method == "OPTIONS" {
  483. // Add a generous access-control-allow-origin header for CORS requests
  484. w.Header().Add("Access-Control-Allow-Origin", "*")
  485. // Only GET/POST/OPTIONS Methods are supported
  486. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
  487. // Only these headers can be set
  488. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
  489. // The request is meant to be cached 10 minutes
  490. w.Header().Set("Access-Control-Max-Age", "600")
  491. // Indicate that no content will be returned
  492. w.WriteHeader(204)
  493. return
  494. }
  495. // Other security related headers that should be present.
  496. // https://www.owasp.org/index.php/Security_Headers
  497. if !allowFrameLoading {
  498. // We don't want to be rendered in an <iframe>,
  499. // <frame> or <object>. (Unless we do it ourselves.
  500. // This is also an escape hatch for people who serve
  501. // Syncthing GUI as part of their own website
  502. // through a proxy, so they don't need to set the
  503. // allowFrameLoading bool.)
  504. w.Header().Set("X-Frame-Options", "SAMEORIGIN")
  505. }
  506. // If the browser senses an XSS attack it's allowed to take
  507. // action. (How this would not always be the default I
  508. // don't fully understand.)
  509. w.Header().Set("X-XSS-Protection", "1; mode=block")
  510. // Our content type headers are correct. Don't guess.
  511. w.Header().Set("X-Content-Type-Options", "nosniff")
  512. // For everything else, pass to the next handler
  513. next.ServeHTTP(w, r)
  514. })
  515. }
  516. func metricsMiddleware(h http.Handler) http.Handler {
  517. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  518. t := metrics.GetOrRegisterTimer(r.URL.Path, nil)
  519. t0 := time.Now()
  520. h.ServeHTTP(w, r)
  521. t.UpdateSince(t0)
  522. })
  523. }
  524. func redirectToHTTPSMiddleware(h http.Handler) http.Handler {
  525. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  526. if r.TLS == nil {
  527. // Redirect HTTP requests to HTTPS
  528. r.URL.Host = r.Host
  529. r.URL.Scheme = "https"
  530. http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
  531. } else {
  532. h.ServeHTTP(w, r)
  533. }
  534. })
  535. }
  536. func noCacheMiddleware(h http.Handler) http.Handler {
  537. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  538. w.Header().Set("Cache-Control", "max-age=0, no-cache, no-store")
  539. w.Header().Set("Expires", time.Now().UTC().Format(http.TimeFormat))
  540. w.Header().Set("Pragma", "no-cache")
  541. h.ServeHTTP(w, r)
  542. })
  543. }
  544. func withDetailsMiddleware(id protocol.DeviceID, h http.Handler) http.Handler {
  545. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  546. w.Header().Set("X-Syncthing-Version", build.Version)
  547. w.Header().Set("X-Syncthing-ID", id.String())
  548. h.ServeHTTP(w, r)
  549. })
  550. }
  551. func localhostMiddleware(h http.Handler) http.Handler {
  552. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  553. if addressIsLocalhost(r.Host) {
  554. h.ServeHTTP(w, r)
  555. return
  556. }
  557. http.Error(w, "Host check error", http.StatusForbidden)
  558. })
  559. }
  560. func (s *service) whenDebugging(h http.Handler) http.Handler {
  561. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  562. if s.cfg.GUI().Debugging {
  563. h.ServeHTTP(w, r)
  564. return
  565. }
  566. http.Error(w, "Debugging disabled", http.StatusForbidden)
  567. })
  568. }
  569. func (s *service) getPendingDevices(w http.ResponseWriter, _ *http.Request) {
  570. devices, err := s.model.PendingDevices()
  571. if err != nil {
  572. http.Error(w, err.Error(), http.StatusInternalServerError)
  573. return
  574. }
  575. sendJSON(w, devices)
  576. }
  577. func (s *service) deletePendingDevices(w http.ResponseWriter, r *http.Request) {
  578. qs := r.URL.Query()
  579. device := qs.Get("device")
  580. deviceID, err := protocol.DeviceIDFromString(device)
  581. if err != nil {
  582. http.Error(w, err.Error(), http.StatusBadRequest)
  583. return
  584. }
  585. if err := s.model.DismissPendingDevice(deviceID); err != nil {
  586. http.Error(w, err.Error(), http.StatusInternalServerError)
  587. }
  588. }
  589. func (s *service) getPendingFolders(w http.ResponseWriter, r *http.Request) {
  590. qs := r.URL.Query()
  591. device := qs.Get("device")
  592. deviceID, err := protocol.DeviceIDFromString(device)
  593. if err != nil {
  594. http.Error(w, err.Error(), http.StatusBadRequest)
  595. return
  596. }
  597. folders, err := s.model.PendingFolders(deviceID)
  598. if err != nil {
  599. http.Error(w, err.Error(), http.StatusInternalServerError)
  600. return
  601. }
  602. sendJSON(w, folders)
  603. }
  604. func (s *service) deletePendingFolders(w http.ResponseWriter, r *http.Request) {
  605. qs := r.URL.Query()
  606. device := qs.Get("device")
  607. deviceID, err := protocol.DeviceIDFromString(device)
  608. if err != nil {
  609. http.Error(w, err.Error(), http.StatusBadRequest)
  610. return
  611. }
  612. folderID := qs.Get("folder")
  613. if err := s.model.DismissPendingFolder(deviceID, folderID); err != nil {
  614. http.Error(w, err.Error(), http.StatusInternalServerError)
  615. }
  616. }
  617. func (*service) restPing(w http.ResponseWriter, _ *http.Request) {
  618. sendJSON(w, map[string]string{"ping": "pong"})
  619. }
  620. func (*service) getSystemPaths(w http.ResponseWriter, _ *http.Request) {
  621. sendJSON(w, locations.ListExpandedPaths())
  622. }
  623. func (s *service) getJSMetadata(w http.ResponseWriter, _ *http.Request) {
  624. meta, _ := json.Marshal(map[string]interface{}{
  625. "deviceID": s.id.String(),
  626. "deviceIDShort": s.id.Short().String(),
  627. "authenticated": true,
  628. })
  629. w.Header().Set("Content-Type", "application/javascript")
  630. fmt.Fprintf(w, "var metadata = %s;\n", meta)
  631. }
  632. func (*service) getSystemVersion(w http.ResponseWriter, _ *http.Request) {
  633. sendJSON(w, map[string]interface{}{
  634. "version": build.Version,
  635. "codename": build.Codename,
  636. "longVersion": build.LongVersion,
  637. "extra": build.Extra,
  638. "os": runtime.GOOS,
  639. "arch": runtime.GOARCH,
  640. "isBeta": build.IsBeta,
  641. "isCandidate": build.IsCandidate,
  642. "isRelease": build.IsRelease,
  643. "date": build.Date,
  644. "tags": build.TagsList(),
  645. "stamp": build.Stamp,
  646. "user": build.User,
  647. "container": incontainer.Detect(),
  648. })
  649. }
  650. func (*service) getSystemDebug(w http.ResponseWriter, _ *http.Request) {
  651. names := l.Facilities()
  652. enabled := l.FacilityDebugging()
  653. sort.Strings(enabled)
  654. sendJSON(w, map[string]interface{}{
  655. "facilities": names,
  656. "enabled": enabled,
  657. })
  658. }
  659. func (*service) postSystemDebug(w http.ResponseWriter, r *http.Request) {
  660. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  661. q := r.URL.Query()
  662. for _, f := range strings.Split(q.Get("enable"), ",") {
  663. if f == "" || l.ShouldDebug(f) {
  664. continue
  665. }
  666. l.SetDebug(f, true)
  667. l.Infof("Enabled debug data for %q", f)
  668. }
  669. for _, f := range strings.Split(q.Get("disable"), ",") {
  670. if f == "" || !l.ShouldDebug(f) {
  671. continue
  672. }
  673. l.SetDebug(f, false)
  674. l.Infof("Disabled debug data for %q", f)
  675. }
  676. }
  677. func (s *service) getDBBrowse(w http.ResponseWriter, r *http.Request) {
  678. qs := r.URL.Query()
  679. folder := qs.Get("folder")
  680. prefix := qs.Get("prefix")
  681. dirsOnly := qs.Get("dirsonly") != ""
  682. levels, err := strconv.Atoi(qs.Get("levels"))
  683. if err != nil {
  684. levels = -1
  685. }
  686. result, err := s.model.GlobalDirectoryTree(folder, prefix, levels, dirsOnly)
  687. if err != nil {
  688. http.Error(w, err.Error(), http.StatusInternalServerError)
  689. return
  690. }
  691. sendJSON(w, result)
  692. }
  693. func (s *service) getDBCompletion(w http.ResponseWriter, r *http.Request) {
  694. qs := r.URL.Query()
  695. folder := qs.Get("folder") // empty means all folders
  696. deviceStr := qs.Get("device") // empty means local device ID
  697. // We will check completion status for either the local device, or a
  698. // specific given device ID.
  699. device := protocol.LocalDeviceID
  700. if deviceStr != "" {
  701. var err error
  702. device, err = protocol.DeviceIDFromString(deviceStr)
  703. if err != nil {
  704. http.Error(w, err.Error(), http.StatusBadRequest)
  705. return
  706. }
  707. }
  708. if comp, err := s.model.Completion(device, folder); err != nil {
  709. status := http.StatusInternalServerError
  710. if isFolderNotFound(err) {
  711. status = http.StatusNotFound
  712. }
  713. http.Error(w, err.Error(), status)
  714. } else {
  715. sendJSON(w, comp.Map())
  716. }
  717. }
  718. func (s *service) getDBStatus(w http.ResponseWriter, r *http.Request) {
  719. qs := r.URL.Query()
  720. folder := qs.Get("folder")
  721. if sum, err := s.fss.Summary(folder); err != nil {
  722. http.Error(w, err.Error(), http.StatusNotFound)
  723. } else {
  724. sendJSON(w, sum)
  725. }
  726. }
  727. func (s *service) postDBOverride(_ http.ResponseWriter, r *http.Request) {
  728. qs := r.URL.Query()
  729. folder := qs.Get("folder")
  730. go s.model.Override(folder)
  731. }
  732. func (s *service) postDBRevert(_ http.ResponseWriter, r *http.Request) {
  733. qs := r.URL.Query()
  734. folder := qs.Get("folder")
  735. go s.model.Revert(folder)
  736. }
  737. func getPagingParams(qs url.Values) (int, int) {
  738. page, err := strconv.Atoi(qs.Get("page"))
  739. if err != nil || page < 1 {
  740. page = 1
  741. }
  742. perpage, err := strconv.Atoi(qs.Get("perpage"))
  743. if err != nil || perpage < 1 {
  744. perpage = 1 << 16
  745. }
  746. return page, perpage
  747. }
  748. func (s *service) getDBNeed(w http.ResponseWriter, r *http.Request) {
  749. qs := r.URL.Query()
  750. folder := qs.Get("folder")
  751. page, perpage := getPagingParams(qs)
  752. progress, queued, rest, err := s.model.NeedFolderFiles(folder, page, perpage)
  753. if err != nil {
  754. http.Error(w, err.Error(), http.StatusNotFound)
  755. return
  756. }
  757. // Convert the struct to a more loose structure, and inject the size.
  758. sendJSON(w, map[string]interface{}{
  759. "progress": toJsonFileInfoSlice(progress),
  760. "queued": toJsonFileInfoSlice(queued),
  761. "rest": toJsonFileInfoSlice(rest),
  762. "page": page,
  763. "perpage": perpage,
  764. })
  765. }
  766. func (s *service) getDBRemoteNeed(w http.ResponseWriter, r *http.Request) {
  767. qs := r.URL.Query()
  768. folder := qs.Get("folder")
  769. device := qs.Get("device")
  770. deviceID, err := protocol.DeviceIDFromString(device)
  771. if err != nil {
  772. http.Error(w, err.Error(), http.StatusInternalServerError)
  773. return
  774. }
  775. page, perpage := getPagingParams(qs)
  776. files, err := s.model.RemoteNeedFolderFiles(folder, deviceID, page, perpage)
  777. if err != nil {
  778. http.Error(w, err.Error(), http.StatusNotFound)
  779. return
  780. }
  781. sendJSON(w, map[string]interface{}{
  782. "files": toJsonFileInfoSlice(files),
  783. "page": page,
  784. "perpage": perpage,
  785. })
  786. }
  787. func (s *service) getDBLocalChanged(w http.ResponseWriter, r *http.Request) {
  788. qs := r.URL.Query()
  789. folder := qs.Get("folder")
  790. page, perpage := getPagingParams(qs)
  791. files, err := s.model.LocalChangedFolderFiles(folder, page, perpage)
  792. if err != nil {
  793. http.Error(w, err.Error(), http.StatusNotFound)
  794. return
  795. }
  796. sendJSON(w, map[string]interface{}{
  797. "files": toJsonFileInfoSlice(files),
  798. "page": page,
  799. "perpage": perpage,
  800. })
  801. }
  802. func (s *service) getSystemConnections(w http.ResponseWriter, _ *http.Request) {
  803. sendJSON(w, s.model.ConnectionStats())
  804. }
  805. func (s *service) getDeviceStats(w http.ResponseWriter, _ *http.Request) {
  806. stats, err := s.model.DeviceStatistics()
  807. if err != nil {
  808. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  809. return
  810. }
  811. sendJSON(w, stats)
  812. }
  813. func (s *service) getFolderStats(w http.ResponseWriter, _ *http.Request) {
  814. stats, err := s.model.FolderStatistics()
  815. if err != nil {
  816. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  817. return
  818. }
  819. sendJSON(w, stats)
  820. }
  821. func (s *service) getDBFile(w http.ResponseWriter, r *http.Request) {
  822. qs := r.URL.Query()
  823. folder := qs.Get("folder")
  824. file := qs.Get("file")
  825. errStatus := http.StatusInternalServerError
  826. gf, gfOk, err := s.model.CurrentGlobalFile(folder, file)
  827. if err != nil {
  828. if isFolderNotFound(err) {
  829. errStatus = http.StatusNotFound
  830. }
  831. http.Error(w, err.Error(), errStatus)
  832. return
  833. }
  834. lf, lfOk, err := s.model.CurrentFolderFile(folder, file)
  835. if err != nil {
  836. if isFolderNotFound(err) {
  837. errStatus = http.StatusNotFound
  838. }
  839. http.Error(w, err.Error(), errStatus)
  840. return
  841. }
  842. if !(gfOk || lfOk) {
  843. // This file for sure does not exist.
  844. http.Error(w, "No such object in the index", http.StatusNotFound)
  845. return
  846. }
  847. av, err := s.model.Availability(folder, gf, protocol.BlockInfo{})
  848. if err != nil {
  849. http.Error(w, err.Error(), http.StatusInternalServerError)
  850. return
  851. }
  852. mtimeMapping, mtimeErr := s.model.GetMtimeMapping(folder, file)
  853. sendJSON(w, map[string]interface{}{
  854. "global": jsonFileInfo(gf),
  855. "local": jsonFileInfo(lf),
  856. "availability": av,
  857. "mtime": map[string]interface{}{
  858. "err": mtimeErr,
  859. "value": mtimeMapping,
  860. },
  861. })
  862. }
  863. func (s *service) getDebugFile(w http.ResponseWriter, r *http.Request) {
  864. qs := r.URL.Query()
  865. folder := qs.Get("folder")
  866. file := qs.Get("file")
  867. snap, err := s.model.DBSnapshot(folder)
  868. if err != nil {
  869. http.Error(w, err.Error(), http.StatusNotFound)
  870. return
  871. }
  872. mtimeMapping, mtimeErr := s.model.GetMtimeMapping(folder, file)
  873. lf, _ := snap.Get(protocol.LocalDeviceID, file)
  874. gf, _ := snap.GetGlobal(file)
  875. av := snap.Availability(file)
  876. vl := snap.DebugGlobalVersions(file)
  877. sendJSON(w, map[string]interface{}{
  878. "global": jsonFileInfo(gf),
  879. "local": jsonFileInfo(lf),
  880. "availability": av,
  881. "globalVersions": vl.String(),
  882. "mtime": map[string]interface{}{
  883. "err": mtimeErr,
  884. "value": mtimeMapping,
  885. },
  886. })
  887. }
  888. func (s *service) postSystemRestart(w http.ResponseWriter, _ *http.Request) {
  889. s.flushResponse(`{"ok": "restarting"}`, w)
  890. s.fatal(&svcutil.FatalErr{
  891. Err: errors.New("restart initiated by rest API"),
  892. Status: svcutil.ExitRestart,
  893. })
  894. }
  895. func (s *service) postSystemReset(w http.ResponseWriter, r *http.Request) {
  896. qs := r.URL.Query()
  897. folder := qs.Get("folder")
  898. if len(folder) > 0 {
  899. if _, ok := s.cfg.Folders()[folder]; !ok {
  900. http.Error(w, "Invalid folder ID", http.StatusInternalServerError)
  901. return
  902. }
  903. }
  904. if folder == "" {
  905. // Reset all folders.
  906. for folder := range s.cfg.Folders() {
  907. if err := s.model.ResetFolder(folder); err != nil {
  908. http.Error(w, err.Error(), http.StatusInternalServerError)
  909. return
  910. }
  911. }
  912. s.flushResponse(`{"ok": "resetting database"}`, w)
  913. } else {
  914. // Reset a specific folder, assuming it's supposed to exist.
  915. if err := s.model.ResetFolder(folder); err != nil {
  916. http.Error(w, err.Error(), http.StatusInternalServerError)
  917. return
  918. }
  919. s.flushResponse(`{"ok": "resetting folder `+folder+`"}`, w)
  920. }
  921. s.fatal(&svcutil.FatalErr{
  922. Err: errors.New("restart after db reset initiated by rest API"),
  923. Status: svcutil.ExitRestart,
  924. })
  925. }
  926. func (s *service) postSystemShutdown(w http.ResponseWriter, _ *http.Request) {
  927. s.flushResponse(`{"ok": "shutting down"}`, w)
  928. s.fatal(&svcutil.FatalErr{
  929. Err: errors.New("shutdown initiated by rest API"),
  930. Status: svcutil.ExitSuccess,
  931. })
  932. }
  933. func (*service) flushResponse(resp string, w http.ResponseWriter) {
  934. w.Write([]byte(resp + "\n"))
  935. f := w.(http.Flusher)
  936. f.Flush()
  937. }
  938. func (s *service) getSystemStatus(w http.ResponseWriter, _ *http.Request) {
  939. var m runtime.MemStats
  940. runtime.ReadMemStats(&m)
  941. tilde, _ := fs.ExpandTilde("~")
  942. res := make(map[string]interface{})
  943. res["myID"] = s.id.String()
  944. res["goroutines"] = runtime.NumGoroutine()
  945. res["alloc"] = m.Alloc
  946. res["sys"] = m.Sys - m.HeapReleased
  947. res["tilde"] = tilde
  948. if s.cfg.Options().LocalAnnEnabled || s.cfg.Options().GlobalAnnEnabled {
  949. res["discoveryEnabled"] = true
  950. discoStatus := s.discoverer.ChildErrors()
  951. res["discoveryStatus"] = discoveryStatusMap(discoStatus)
  952. res["discoveryMethods"] = len(discoStatus) // DEPRECATED: Redundant, only for backwards compatibility, should be removed.
  953. discoErrors := make(map[string]*string, len(discoStatus))
  954. for s, e := range discoStatus {
  955. if e != nil {
  956. discoErrors[s] = errorString(e)
  957. }
  958. }
  959. res["discoveryErrors"] = discoErrors // DEPRECATED: Redundant, only for backwards compatibility, should be removed.
  960. }
  961. res["connectionServiceStatus"] = s.connectionsService.ListenerStatus()
  962. res["lastDialStatus"] = s.connectionsService.ConnectionStatus()
  963. res["cpuPercent"] = 0 // deprecated from API
  964. res["pathSeparator"] = string(filepath.Separator)
  965. res["urVersionMax"] = ur.Version
  966. res["uptime"] = s.urService.UptimeS()
  967. res["startTime"] = ur.StartTime
  968. res["guiAddressOverridden"] = s.cfg.GUI().IsOverridden()
  969. res["guiAddressUsed"] = s.listenerAddr.String()
  970. sendJSON(w, res)
  971. }
  972. func (s *service) getSystemError(w http.ResponseWriter, _ *http.Request) {
  973. sendJSON(w, map[string][]logger.Line{
  974. "errors": s.guiErrors.Since(time.Time{}),
  975. })
  976. }
  977. func (*service) postSystemError(_ http.ResponseWriter, r *http.Request) {
  978. bs, _ := io.ReadAll(r.Body)
  979. r.Body.Close()
  980. l.Warnln(string(bs))
  981. }
  982. func (s *service) postSystemErrorClear(_ http.ResponseWriter, _ *http.Request) {
  983. s.guiErrors.Clear()
  984. }
  985. func (s *service) getSystemLog(w http.ResponseWriter, r *http.Request) {
  986. q := r.URL.Query()
  987. since, err := time.Parse(time.RFC3339, q.Get("since"))
  988. if err != nil {
  989. l.Debugln(err)
  990. }
  991. sendJSON(w, map[string][]logger.Line{
  992. "messages": s.systemLog.Since(since),
  993. })
  994. }
  995. func (s *service) getSystemLogTxt(w http.ResponseWriter, r *http.Request) {
  996. q := r.URL.Query()
  997. since, err := time.Parse(time.RFC3339, q.Get("since"))
  998. if err != nil {
  999. l.Debugln(err)
  1000. }
  1001. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  1002. for _, line := range s.systemLog.Since(since) {
  1003. fmt.Fprintf(w, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  1004. }
  1005. }
  1006. type fileEntry struct {
  1007. name string
  1008. data []byte
  1009. }
  1010. func (s *service) getSupportBundle(w http.ResponseWriter, r *http.Request) {
  1011. var files []fileEntry
  1012. const profilingDuration = 4 * time.Second
  1013. // Redacted configuration as a JSON
  1014. if jsonConfig, err := json.MarshalIndent(getRedactedConfig(s), "", " "); err != nil {
  1015. l.Warnln("Support bundle: failed to create config.json:", err)
  1016. } else {
  1017. files = append(files, fileEntry{name: "config.json.txt", data: jsonConfig})
  1018. }
  1019. // Log as a text
  1020. var buflog bytes.Buffer
  1021. for _, line := range s.systemLog.Since(time.Time{}) {
  1022. fmt.Fprintf(&buflog, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  1023. }
  1024. files = append(files, fileEntry{name: "log-inmemory.txt", data: buflog.Bytes()})
  1025. // Errors as a JSON
  1026. if errs := s.guiErrors.Since(time.Time{}); len(errs) > 0 {
  1027. if jsonError, err := json.MarshalIndent(errs, "", " "); err != nil {
  1028. l.Warnln("Support bundle: failed to create errors.json:", err)
  1029. } else {
  1030. files = append(files, fileEntry{name: "errors.json.txt", data: jsonError})
  1031. }
  1032. }
  1033. // Panic files
  1034. if panicFiles, err := filepath.Glob(filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), "panic*")); err == nil {
  1035. for _, f := range panicFiles {
  1036. if panicFile, err := os.ReadFile(f); err != nil {
  1037. l.Warnf("Support bundle: failed to load %s: %s", filepath.Base(f), err)
  1038. } else {
  1039. files = append(files, fileEntry{name: filepath.Base(f), data: panicFile})
  1040. }
  1041. }
  1042. }
  1043. // Archived log (default on Windows)
  1044. if logFile, err := os.ReadFile(locations.Get(locations.LogFile)); err == nil {
  1045. files = append(files, fileEntry{name: "log-ondisk.txt", data: logFile})
  1046. }
  1047. // Version and platform information as a JSON
  1048. if versionPlatform, err := json.MarshalIndent(map[string]string{
  1049. "now": time.Now().Format(time.RFC3339),
  1050. "version": build.Version,
  1051. "codename": build.Codename,
  1052. "longVersion": build.LongVersion,
  1053. "os": runtime.GOOS,
  1054. "arch": runtime.GOARCH,
  1055. }, "", " "); err == nil {
  1056. files = append(files, fileEntry{name: "version-platform.json.txt", data: versionPlatform})
  1057. } else {
  1058. l.Warnln("Failed to create versionPlatform.json: ", err)
  1059. }
  1060. // Report Data as a JSON
  1061. if r, err := s.urService.ReportDataPreview(r.Context(), ur.Version); err != nil {
  1062. l.Warnln("Support bundle: failed to create usage-reporting.json.txt:", err)
  1063. } else {
  1064. if usageReportingData, err := json.MarshalIndent(r, "", " "); err != nil {
  1065. l.Warnln("Support bundle: failed to serialize usage-reporting.json.txt", err)
  1066. } else {
  1067. files = append(files, fileEntry{name: "usage-reporting.json.txt", data: usageReportingData})
  1068. }
  1069. }
  1070. // Metrics data as text
  1071. var metricsBuf bytes.Buffer
  1072. wr := bufferedResponseWriter{Writer: &metricsBuf}
  1073. promhttp.Handler().ServeHTTP(wr, &http.Request{Method: http.MethodGet})
  1074. files = append(files, fileEntry{name: "metrics.txt", data: metricsBuf.Bytes()})
  1075. // Connection data as JSON
  1076. connStats := s.model.ConnectionStats()
  1077. if connStatsJSON, err := json.MarshalIndent(connStats, "", " "); err != nil {
  1078. l.Warnln("Support bundle: failed to serialize connection-stats.json.txt", err)
  1079. } else {
  1080. files = append(files, fileEntry{name: "connection-stats.json.txt", data: connStatsJSON})
  1081. }
  1082. // Write a goroutine profile
  1083. if p := pprof.Lookup("goroutine"); p != nil {
  1084. var goroutineBuf bytes.Buffer
  1085. _ = p.WriteTo(&goroutineBuf, 0)
  1086. filename := fmt.Sprintf("syncthing-goroutines-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1087. files = append(files, fileEntry{name: filename, data: goroutineBuf.Bytes()})
  1088. }
  1089. // Take a heap profile
  1090. var heapBuf bytes.Buffer
  1091. runtime.GC()
  1092. if err := pprof.WriteHeapProfile(&heapBuf); err == nil {
  1093. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1094. files = append(files, fileEntry{name: filename, data: heapBuf.Bytes()})
  1095. }
  1096. // Enable block profiling
  1097. runtime.SetBlockProfileRate(1)
  1098. defer runtime.SetBlockProfileRate(0)
  1099. // Take a CPU profile, waiting for the profiling duration. This also
  1100. // gives time for the block profile.
  1101. var cpuBuf bytes.Buffer
  1102. if err := pprof.StartCPUProfile(&cpuBuf); err == nil {
  1103. time.Sleep(profilingDuration)
  1104. pprof.StopCPUProfile()
  1105. filename := fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1106. files = append(files, fileEntry{name: filename, data: cpuBuf.Bytes()})
  1107. }
  1108. // Write the block profile
  1109. if p := pprof.Lookup("block"); p != nil {
  1110. var blockBuf bytes.Buffer
  1111. _ = p.WriteTo(&blockBuf, 0)
  1112. filename := fmt.Sprintf("syncthing-block-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1113. files = append(files, fileEntry{name: filename, data: blockBuf.Bytes()})
  1114. }
  1115. // Add buffer files to buffer zip
  1116. var zipFilesBuffer bytes.Buffer
  1117. if err := writeZip(&zipFilesBuffer, files); err != nil {
  1118. l.Warnln("Support bundle: failed to create support bundle zip:", err)
  1119. http.Error(w, err.Error(), http.StatusInternalServerError)
  1120. return
  1121. }
  1122. // Set zip file name and path
  1123. zipFileName := fmt.Sprintf("support-bundle-%s-%s.zip", s.id.Short().String(), time.Now().Format("2006-01-02T150405"))
  1124. zipFilePath := filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), zipFileName)
  1125. // Write buffer zip to local zip file (back up)
  1126. if err := os.WriteFile(zipFilePath, zipFilesBuffer.Bytes(), 0o600); err != nil {
  1127. l.Warnln("Support bundle: support bundle zip could not be created:", err)
  1128. }
  1129. // Serve the buffer zip to client for download
  1130. w.Header().Set("Content-Type", "application/zip")
  1131. w.Header().Set("Content-Disposition", "attachment; filename="+zipFileName)
  1132. io.Copy(w, &zipFilesBuffer)
  1133. }
  1134. func (*service) getSystemHTTPMetrics(w http.ResponseWriter, _ *http.Request) {
  1135. stats := make(map[string]interface{})
  1136. metrics.Each(func(name string, intf interface{}) {
  1137. if m, ok := intf.(*metrics.StandardTimer); ok {
  1138. pct := m.Percentiles([]float64{0.50, 0.95, 0.99})
  1139. for i := range pct {
  1140. pct[i] /= 1e6 // ns to ms
  1141. }
  1142. stats[name] = map[string]interface{}{
  1143. "count": m.Count(),
  1144. "sumMs": m.Sum() / 1e6, // ns to ms
  1145. "ratesPerS": []float64{m.Rate1(), m.Rate5(), m.Rate15()},
  1146. "percentilesMs": pct,
  1147. }
  1148. }
  1149. })
  1150. bs, _ := json.MarshalIndent(stats, "", " ")
  1151. w.Write(bs)
  1152. }
  1153. func (s *service) getSystemDiscovery(w http.ResponseWriter, _ *http.Request) {
  1154. devices := make(map[string]discover.CacheEntry)
  1155. if s.discoverer != nil {
  1156. // Device ids can't be marshalled as keys so we need to manually
  1157. // rebuild this map using strings. Discoverer may be nil if discovery
  1158. // has not started yet.
  1159. for device, entry := range s.discoverer.Cache() {
  1160. devices[device.String()] = entry
  1161. }
  1162. }
  1163. sendJSON(w, devices)
  1164. }
  1165. func (s *service) getReport(w http.ResponseWriter, r *http.Request) {
  1166. version := ur.Version
  1167. if val, _ := strconv.Atoi(r.URL.Query().Get("version")); val > 0 {
  1168. version = val
  1169. }
  1170. if r, err := s.urService.ReportDataPreview(context.TODO(), version); err != nil {
  1171. http.Error(w, err.Error(), http.StatusInternalServerError)
  1172. return
  1173. } else {
  1174. sendJSON(w, r)
  1175. }
  1176. }
  1177. func (*service) getRandomString(w http.ResponseWriter, r *http.Request) {
  1178. length := 32
  1179. if val, _ := strconv.Atoi(r.URL.Query().Get("length")); val > 0 {
  1180. length = val
  1181. }
  1182. str := rand.String(length)
  1183. sendJSON(w, map[string]string{"random": str})
  1184. }
  1185. func (s *service) getDBIgnores(w http.ResponseWriter, r *http.Request) {
  1186. qs := r.URL.Query()
  1187. folder := qs.Get("folder")
  1188. lines, patterns, err := s.model.LoadIgnores(folder)
  1189. sendJSON(w, map[string]interface{}{
  1190. "ignore": lines,
  1191. "expanded": patterns,
  1192. "error": errorString(err),
  1193. })
  1194. }
  1195. func (s *service) postDBIgnores(w http.ResponseWriter, r *http.Request) {
  1196. qs := r.URL.Query()
  1197. bs, err := io.ReadAll(r.Body)
  1198. r.Body.Close()
  1199. if err != nil {
  1200. http.Error(w, err.Error(), http.StatusInternalServerError)
  1201. return
  1202. }
  1203. var data map[string][]string
  1204. err = json.Unmarshal(bs, &data)
  1205. if err != nil {
  1206. http.Error(w, err.Error(), http.StatusInternalServerError)
  1207. return
  1208. }
  1209. err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
  1210. if err != nil {
  1211. http.Error(w, err.Error(), http.StatusInternalServerError)
  1212. return
  1213. }
  1214. s.getDBIgnores(w, r)
  1215. }
  1216. func (s *service) getIndexEvents(w http.ResponseWriter, r *http.Request) {
  1217. mask := s.getEventMask(r.URL.Query().Get("events"))
  1218. sub := s.getEventSub(mask)
  1219. s.getEvents(w, r, sub)
  1220. }
  1221. func (s *service) getDiskEvents(w http.ResponseWriter, r *http.Request) {
  1222. sub := s.getEventSub(DiskEventMask)
  1223. s.getEvents(w, r, sub)
  1224. }
  1225. func (*service) getEvents(w http.ResponseWriter, r *http.Request, eventSub events.BufferedSubscription) {
  1226. qs := r.URL.Query()
  1227. sinceStr := qs.Get("since")
  1228. limitStr := qs.Get("limit")
  1229. timeoutStr := qs.Get("timeout")
  1230. since, _ := strconv.Atoi(sinceStr)
  1231. limit, _ := strconv.Atoi(limitStr)
  1232. timeout := defaultEventTimeout
  1233. if timeoutSec, timeoutErr := strconv.Atoi(timeoutStr); timeoutErr == nil && timeoutSec >= 0 { // 0 is a valid timeout
  1234. timeout = time.Duration(timeoutSec) * time.Second
  1235. }
  1236. // Flush before blocking, to indicate that we've received the request and
  1237. // that it should not be retried. Must set Content-Type header before
  1238. // flushing.
  1239. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  1240. f := w.(http.Flusher)
  1241. f.Flush()
  1242. // If there are no events available return an empty slice, as this gets serialized as `[]`
  1243. evs := eventSub.Since(since, []events.Event{}, timeout)
  1244. if 0 < limit && limit < len(evs) {
  1245. evs = evs[len(evs)-limit:]
  1246. }
  1247. sendJSON(w, evs)
  1248. }
  1249. func (*service) getEventMask(evs string) events.EventType {
  1250. eventMask := DefaultEventMask
  1251. if evs != "" {
  1252. eventList := strings.Split(evs, ",")
  1253. eventMask = 0
  1254. for _, ev := range eventList {
  1255. eventMask |= events.UnmarshalEventType(strings.TrimSpace(ev))
  1256. }
  1257. }
  1258. return eventMask
  1259. }
  1260. func (s *service) getEventSub(mask events.EventType) events.BufferedSubscription {
  1261. s.eventSubsMut.Lock()
  1262. bufsub, ok := s.eventSubs[mask]
  1263. if !ok {
  1264. evsub := s.evLogger.Subscribe(mask)
  1265. bufsub = events.NewBufferedSubscription(evsub, EventSubBufferSize)
  1266. s.eventSubs[mask] = bufsub
  1267. }
  1268. s.eventSubsMut.Unlock()
  1269. return bufsub
  1270. }
  1271. func (s *service) getSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
  1272. if s.noUpgrade {
  1273. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
  1274. return
  1275. }
  1276. opts := s.cfg.Options()
  1277. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1278. if err != nil {
  1279. httpError(w, err)
  1280. return
  1281. }
  1282. res := make(map[string]interface{})
  1283. res["running"] = build.Version
  1284. res["latest"] = rel.Tag
  1285. res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer
  1286. res["majorNewer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.MajorNewer
  1287. sendJSON(w, res)
  1288. }
  1289. func (*service) getDeviceID(w http.ResponseWriter, r *http.Request) {
  1290. qs := r.URL.Query()
  1291. idStr := qs.Get("id")
  1292. id, err := protocol.DeviceIDFromString(idStr)
  1293. if err == nil {
  1294. sendJSON(w, map[string]string{
  1295. "id": id.String(),
  1296. })
  1297. } else {
  1298. sendJSON(w, map[string]string{
  1299. "error": err.Error(),
  1300. })
  1301. }
  1302. }
  1303. func (*service) getLang(w http.ResponseWriter, r *http.Request) {
  1304. lang := r.Header.Get("Accept-Language")
  1305. weights := make(map[string]float64)
  1306. for _, l := range strings.Split(lang, ",") {
  1307. parts := strings.SplitN(l, ";", 2)
  1308. code := strings.ToLower(strings.TrimSpace(parts[0]))
  1309. weights[code] = 1.0
  1310. if len(parts) < 2 {
  1311. continue
  1312. }
  1313. weight := strings.ToLower(strings.TrimSpace(parts[1]))
  1314. if !strings.HasPrefix(weight, "q=") {
  1315. continue
  1316. }
  1317. if q, err := strconv.ParseFloat(weight[2:], 32); err != nil {
  1318. // Completely dismiss entries with invalid weight
  1319. delete(weights, code)
  1320. } else {
  1321. weights[code] = q
  1322. }
  1323. }
  1324. langs := make([]string, 0, len(weights))
  1325. for code := range weights {
  1326. langs = append(langs, code)
  1327. }
  1328. // Reorder by descending q value
  1329. sort.SliceStable(langs, func(i, j int) bool {
  1330. return weights[langs[i]] > weights[langs[j]]
  1331. })
  1332. sendJSON(w, langs)
  1333. }
  1334. func (s *service) postSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
  1335. opts := s.cfg.Options()
  1336. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1337. if err != nil {
  1338. httpError(w, err)
  1339. return
  1340. }
  1341. if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
  1342. err = upgrade.To(rel)
  1343. if err != nil {
  1344. l.Warnln("upgrading:", err)
  1345. http.Error(w, err.Error(), http.StatusInternalServerError)
  1346. return
  1347. }
  1348. s.flushResponse(`{"ok": "restarting"}`, w)
  1349. s.fatal(&svcutil.FatalErr{
  1350. Err: errors.New("exit after upgrade initiated by rest API"),
  1351. Status: svcutil.ExitUpgrade,
  1352. })
  1353. }
  1354. }
  1355. func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
  1356. return func(w http.ResponseWriter, r *http.Request) {
  1357. qs := r.URL.Query()
  1358. deviceStr := qs.Get("device")
  1359. var msg string
  1360. var status int
  1361. _, err := s.cfg.Modify(func(cfg *config.Configuration) {
  1362. if deviceStr == "" {
  1363. for i := range cfg.Devices {
  1364. cfg.Devices[i].Paused = paused
  1365. }
  1366. return
  1367. }
  1368. device, err := protocol.DeviceIDFromString(deviceStr)
  1369. if err != nil {
  1370. msg = err.Error()
  1371. status = 500
  1372. return
  1373. }
  1374. _, i, ok := cfg.Device(device)
  1375. if !ok {
  1376. msg = "not found"
  1377. status = http.StatusNotFound
  1378. return
  1379. }
  1380. cfg.Devices[i].Paused = paused
  1381. })
  1382. if msg != "" {
  1383. http.Error(w, msg, status)
  1384. } else if err != nil {
  1385. http.Error(w, err.Error(), http.StatusInternalServerError)
  1386. }
  1387. }
  1388. }
  1389. func (s *service) postDBScan(w http.ResponseWriter, r *http.Request) {
  1390. qs := r.URL.Query()
  1391. folder := qs.Get("folder")
  1392. if folder != "" {
  1393. subs := qs["sub"]
  1394. err := s.model.ScanFolderSubdirs(folder, subs)
  1395. if err != nil {
  1396. http.Error(w, err.Error(), http.StatusInternalServerError)
  1397. return
  1398. }
  1399. nextStr := qs.Get("next")
  1400. next, err := strconv.Atoi(nextStr)
  1401. if err == nil {
  1402. s.model.DelayScan(folder, time.Duration(next)*time.Second)
  1403. }
  1404. } else {
  1405. errors := s.model.ScanFolders()
  1406. if len(errors) > 0 {
  1407. http.Error(w, "Error scanning folders", http.StatusInternalServerError)
  1408. sendJSON(w, errors)
  1409. return
  1410. }
  1411. }
  1412. }
  1413. func (s *service) postDBPrio(w http.ResponseWriter, r *http.Request) {
  1414. qs := r.URL.Query()
  1415. folder := qs.Get("folder")
  1416. file := qs.Get("file")
  1417. s.model.BringToFront(folder, file)
  1418. s.getDBNeed(w, r)
  1419. }
  1420. func (*service) getHealth(w http.ResponseWriter, _ *http.Request) {
  1421. sendJSON(w, map[string]string{"status": "OK"})
  1422. }
  1423. func (*service) getQR(w http.ResponseWriter, r *http.Request) {
  1424. qs := r.URL.Query()
  1425. text := qs.Get("text")
  1426. code, err := qr.Encode(text, qr.M)
  1427. if err != nil {
  1428. http.Error(w, "Invalid", http.StatusInternalServerError)
  1429. return
  1430. }
  1431. w.Header().Set("Content-Type", "image/png")
  1432. w.Write(code.PNG())
  1433. }
  1434. func (s *service) getPeerCompletion(w http.ResponseWriter, _ *http.Request) {
  1435. tot := map[string]float64{}
  1436. count := map[string]float64{}
  1437. for _, folder := range s.cfg.Folders() {
  1438. for _, device := range folder.DeviceIDs() {
  1439. deviceStr := device.String()
  1440. if s.model.ConnectedTo(device) {
  1441. comp, err := s.model.Completion(device, folder.ID)
  1442. if err != nil {
  1443. http.Error(w, err.Error(), http.StatusInternalServerError)
  1444. return
  1445. }
  1446. tot[deviceStr] += comp.CompletionPct
  1447. } else {
  1448. tot[deviceStr] = 0
  1449. }
  1450. count[deviceStr]++
  1451. }
  1452. }
  1453. comp := map[string]int{}
  1454. for device := range tot {
  1455. comp[device] = int(tot[device] / count[device])
  1456. }
  1457. sendJSON(w, comp)
  1458. }
  1459. func (s *service) getFolderVersions(w http.ResponseWriter, r *http.Request) {
  1460. qs := r.URL.Query()
  1461. versions, err := s.model.GetFolderVersions(qs.Get("folder"))
  1462. if err != nil {
  1463. http.Error(w, err.Error(), http.StatusInternalServerError)
  1464. return
  1465. }
  1466. sendJSON(w, versions)
  1467. }
  1468. func (s *service) postFolderVersionsRestore(w http.ResponseWriter, r *http.Request) {
  1469. qs := r.URL.Query()
  1470. bs, err := io.ReadAll(r.Body)
  1471. r.Body.Close()
  1472. if err != nil {
  1473. http.Error(w, err.Error(), http.StatusInternalServerError)
  1474. return
  1475. }
  1476. var versions map[string]time.Time
  1477. err = json.Unmarshal(bs, &versions)
  1478. if err != nil {
  1479. http.Error(w, err.Error(), http.StatusInternalServerError)
  1480. return
  1481. }
  1482. ferr, err := s.model.RestoreFolderVersions(qs.Get("folder"), versions)
  1483. if err != nil {
  1484. http.Error(w, err.Error(), http.StatusInternalServerError)
  1485. return
  1486. }
  1487. sendJSON(w, errorStringMap(ferr))
  1488. }
  1489. func (s *service) getFolderErrors(w http.ResponseWriter, r *http.Request) {
  1490. qs := r.URL.Query()
  1491. folder := qs.Get("folder")
  1492. page, perpage := getPagingParams(qs)
  1493. errors, err := s.model.FolderErrors(folder)
  1494. if err != nil {
  1495. http.Error(w, err.Error(), http.StatusNotFound)
  1496. return
  1497. }
  1498. start := (page - 1) * perpage
  1499. if start >= len(errors) {
  1500. errors = nil
  1501. } else {
  1502. errors = errors[start:]
  1503. if perpage < len(errors) {
  1504. errors = errors[:perpage]
  1505. }
  1506. }
  1507. sendJSON(w, map[string]interface{}{
  1508. "folder": folder,
  1509. "errors": errors,
  1510. "page": page,
  1511. "perpage": perpage,
  1512. })
  1513. }
  1514. func (*service) getSystemBrowse(w http.ResponseWriter, r *http.Request) {
  1515. qs := r.URL.Query()
  1516. current := qs.Get("current")
  1517. // Default value or in case of error unmarshalling ends up being basic fs.
  1518. var fsType config.FilesystemType
  1519. fsType.UnmarshalText([]byte(qs.Get("filesystem")))
  1520. sendJSON(w, browse(fsType.ToFS(), current))
  1521. }
  1522. func browse(fsType fs.FilesystemType, current string) []string {
  1523. if current == "" {
  1524. return browseRoots(fsType)
  1525. }
  1526. parent, base := parentAndBase(current)
  1527. ffs := fs.NewFilesystem(fsType, parent)
  1528. files := browseFiles(ffs, base)
  1529. for i := range files {
  1530. files[i] = filepath.Join(parent, files[i])
  1531. }
  1532. return files
  1533. }
  1534. const (
  1535. matchExact int = iota
  1536. matchCaseIns
  1537. noMatch
  1538. )
  1539. func checkPrefixMatch(s, prefix string) int {
  1540. if strings.HasPrefix(s, prefix) {
  1541. return matchExact
  1542. }
  1543. if strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
  1544. return matchCaseIns
  1545. }
  1546. return noMatch
  1547. }
  1548. func browseRoots(fsType fs.FilesystemType) []string {
  1549. filesystem := fs.NewFilesystem(fsType, "")
  1550. if roots, err := filesystem.Roots(); err == nil {
  1551. return roots
  1552. }
  1553. return nil
  1554. }
  1555. // parentAndBase returns the parent directory and the remaining base of the
  1556. // path. The base may be empty if the path ends with a path separator.
  1557. func parentAndBase(current string) (string, string) {
  1558. search, _ := fs.ExpandTilde(current)
  1559. pathSeparator := string(fs.PathSeparator)
  1560. if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) {
  1561. search = search + pathSeparator
  1562. }
  1563. searchDir := filepath.Dir(search)
  1564. // The searchFile should be the last component of search, or empty if it
  1565. // ends with a path separator
  1566. var searchFile string
  1567. if !strings.HasSuffix(search, pathSeparator) {
  1568. searchFile = filepath.Base(search)
  1569. }
  1570. return searchDir, searchFile
  1571. }
  1572. func browseFiles(ffs fs.Filesystem, search string) []string {
  1573. subdirectories, _ := ffs.DirNames(".")
  1574. pathSeparator := string(fs.PathSeparator)
  1575. exactMatches := make([]string, 0, len(subdirectories))
  1576. caseInsMatches := make([]string, 0, len(subdirectories))
  1577. for _, subdirectory := range subdirectories {
  1578. info, err := ffs.Stat(subdirectory)
  1579. if err != nil || !info.IsDir() {
  1580. continue
  1581. }
  1582. switch checkPrefixMatch(subdirectory, search) {
  1583. case matchExact:
  1584. exactMatches = append(exactMatches, subdirectory+pathSeparator)
  1585. case matchCaseIns:
  1586. caseInsMatches = append(caseInsMatches, subdirectory+pathSeparator)
  1587. }
  1588. }
  1589. // sort to return matches in deterministic order (don't depend on file system order)
  1590. sort.Strings(exactMatches)
  1591. sort.Strings(caseInsMatches)
  1592. return append(exactMatches, caseInsMatches...)
  1593. }
  1594. func (*service) getCPUProf(w http.ResponseWriter, r *http.Request) {
  1595. duration, err := time.ParseDuration(r.FormValue("duration"))
  1596. if err != nil {
  1597. duration = 30 * time.Second
  1598. }
  1599. filename := fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1600. w.Header().Set("Content-Type", "application/octet-stream")
  1601. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1602. if err := pprof.StartCPUProfile(w); err == nil {
  1603. time.Sleep(duration)
  1604. pprof.StopCPUProfile()
  1605. }
  1606. }
  1607. func (*service) getHeapProf(w http.ResponseWriter, _ *http.Request) {
  1608. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1609. w.Header().Set("Content-Type", "application/octet-stream")
  1610. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1611. runtime.GC()
  1612. pprof.WriteHeapProfile(w)
  1613. }
  1614. func toJsonFileInfoSlice(fs []protocol.FileInfo) []jsonFileInfo {
  1615. res := make([]jsonFileInfo, len(fs))
  1616. for i, f := range fs {
  1617. res[i] = jsonFileInfo(f)
  1618. }
  1619. return res
  1620. }
  1621. // Type wrappers for nice JSON serialization
  1622. type jsonFileInfo protocol.FileInfo
  1623. func (f jsonFileInfo) MarshalJSON() ([]byte, error) {
  1624. m := fileIntfJSONMap(protocol.FileInfo(f))
  1625. m["numBlocks"] = len(f.Blocks)
  1626. return json.Marshal(m)
  1627. }
  1628. func fileIntfJSONMap(f protocol.FileInfo) map[string]interface{} {
  1629. out := map[string]interface{}{
  1630. "name": f.FileName(),
  1631. "type": f.FileType().String(),
  1632. "size": f.FileSize(),
  1633. "deleted": f.IsDeleted(),
  1634. "invalid": f.IsInvalid(),
  1635. "ignored": f.IsIgnored(),
  1636. "mustRescan": f.MustRescan(),
  1637. "noPermissions": !f.HasPermissionBits(),
  1638. "modified": f.ModTime(),
  1639. "modifiedBy": f.FileModifiedBy().String(),
  1640. "sequence": f.SequenceNo(),
  1641. "version": jsonVersionVector(f.FileVersion()),
  1642. "localFlags": f.FileLocalFlags(),
  1643. "platform": f.PlatformData(),
  1644. "inodeChange": f.InodeChangeTime(),
  1645. "blocksHash": f.FileBlocksHash(),
  1646. }
  1647. if f.HasPermissionBits() {
  1648. out["permissions"] = fmt.Sprintf("%#o", f.FilePermissions())
  1649. }
  1650. return out
  1651. }
  1652. type jsonVersionVector protocol.Vector
  1653. func (v jsonVersionVector) MarshalJSON() ([]byte, error) {
  1654. res := make([]string, len(v.Counters))
  1655. for i, c := range v.Counters {
  1656. res[i] = fmt.Sprintf("%v:%d", c.ID, c.Value)
  1657. }
  1658. return json.Marshal(res)
  1659. }
  1660. func dirNames(dir string) []string {
  1661. fis, err := os.ReadDir(dir)
  1662. if err != nil {
  1663. return nil
  1664. }
  1665. var dirs []string
  1666. for _, fi := range fis {
  1667. if fi.IsDir() {
  1668. dirs = append(dirs, filepath.Base(fi.Name()))
  1669. }
  1670. }
  1671. sort.Strings(dirs)
  1672. return dirs
  1673. }
  1674. func addressIsLocalhost(addr string) bool {
  1675. host, _, err := net.SplitHostPort(addr)
  1676. if err != nil {
  1677. // There was no port, so we assume the address was just a hostname
  1678. host = addr
  1679. }
  1680. host = strings.ToLower(host)
  1681. switch {
  1682. case host == "localhost":
  1683. return true
  1684. case host == "localhost.":
  1685. return true
  1686. case strings.HasSuffix(host, ".localhost"):
  1687. return true
  1688. default:
  1689. ip := net.ParseIP(host)
  1690. if ip == nil {
  1691. // not an IP address
  1692. return false
  1693. }
  1694. return ip.IsLoopback()
  1695. }
  1696. }
  1697. // shouldRegenerateCertificate checks for certificate expiry or other known
  1698. // issues with our API/GUI certificate and returns either nil (leave the
  1699. // certificate alone) or an error describing the reason the certificate
  1700. // should be regenerated.
  1701. func shouldRegenerateCertificate(cert tls.Certificate) error {
  1702. leaf := cert.Leaf
  1703. if leaf == nil {
  1704. // Leaf can be nil or not, depending on how parsed the certificate
  1705. // was when we got it.
  1706. if len(cert.Certificate) < 1 {
  1707. // can't happen
  1708. return errors.New("no certificate in certificate")
  1709. }
  1710. var err error
  1711. leaf, err = x509.ParseCertificate(cert.Certificate[0])
  1712. if err != nil {
  1713. return err
  1714. }
  1715. }
  1716. if leaf.Subject.String() != leaf.Issuer.String() || len(leaf.IPAddresses) != 0 {
  1717. // The certificate is not self signed, or has IP attributes we don't
  1718. // add, so we leave it alone.
  1719. return nil
  1720. }
  1721. if len(leaf.DNSNames) > 1 {
  1722. // The certificate has more DNS SANs attributes than we ever add, so
  1723. // we leave it alone.
  1724. return nil
  1725. }
  1726. if len(leaf.DNSNames) == 1 && leaf.DNSNames[0] != leaf.Issuer.CommonName {
  1727. // The one SAN is different from the issuer, so it's not one of our
  1728. // newer self signed certificates.
  1729. return nil
  1730. }
  1731. if leaf.NotAfter.Before(time.Now()) {
  1732. return errors.New("certificate has expired")
  1733. }
  1734. if leaf.NotAfter.Before(time.Now().Add(30 * 24 * time.Hour)) {
  1735. return errors.New("certificate will soon expire")
  1736. }
  1737. // On macOS, check for certificates issued on or after July 1st, 2019,
  1738. // with a longer validity time than 825 days.
  1739. cutoff := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
  1740. if build.IsDarwin &&
  1741. leaf.NotBefore.After(cutoff) &&
  1742. leaf.NotAfter.Sub(leaf.NotBefore) > 825*24*time.Hour {
  1743. return errors.New("certificate incompatible with macOS 10.15 (Catalina)")
  1744. }
  1745. return nil
  1746. }
  1747. func errorStringMap(errs map[string]error) map[string]*string {
  1748. out := make(map[string]*string, len(errs))
  1749. for s, e := range errs {
  1750. out[s] = errorString(e)
  1751. }
  1752. return out
  1753. }
  1754. func errorString(err error) *string {
  1755. if err != nil {
  1756. msg := err.Error()
  1757. return &msg
  1758. }
  1759. return nil
  1760. }
  1761. type discoveryStatusEntry struct {
  1762. Error *string `json:"error"`
  1763. }
  1764. func discoveryStatusMap(errs map[string]error) map[string]discoveryStatusEntry {
  1765. out := make(map[string]discoveryStatusEntry, len(errs))
  1766. for s, e := range errs {
  1767. out[s] = discoveryStatusEntry{
  1768. Error: errorString(e),
  1769. }
  1770. }
  1771. return out
  1772. }
  1773. // sanitizedHostname returns the given name in a suitable form for use as
  1774. // the common name in a certificate, or an error.
  1775. func sanitizedHostname(name string) (string, error) {
  1776. // Remove diacritics and non-alphanumerics. This works by first
  1777. // transforming into normalization form D (things with diacriticals are
  1778. // split into the base character and the mark) and then removing
  1779. // undesired characters.
  1780. t := transform.Chain(
  1781. // Split runes with diacritics into base character and mark.
  1782. norm.NFD,
  1783. // Leave only [A-Za-z0-9-.].
  1784. runes.Remove(runes.Predicate(func(r rune) bool {
  1785. return r > unicode.MaxASCII ||
  1786. !unicode.IsLetter(r) && !unicode.IsNumber(r) &&
  1787. r != '.' && r != '-'
  1788. })))
  1789. name, _, err := transform.String(t, name)
  1790. if err != nil {
  1791. return "", err
  1792. }
  1793. // Name should not start or end with a dash or dot.
  1794. name = strings.Trim(name, "-.")
  1795. // Name should not be empty.
  1796. if name == "" {
  1797. return "", errors.New("no suitable name")
  1798. }
  1799. return strings.ToLower(name), nil
  1800. }
  1801. func isFolderNotFound(err error) bool {
  1802. for _, target := range []error{
  1803. model.ErrFolderMissing,
  1804. model.ErrFolderPaused,
  1805. model.ErrFolderNotRunning,
  1806. } {
  1807. if errors.Is(err, target) {
  1808. return true
  1809. }
  1810. }
  1811. return false
  1812. }
  1813. func httpError(w http.ResponseWriter, err error) {
  1814. if errors.Is(err, upgrade.ErrUpgradeUnsupported) {
  1815. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
  1816. } else {
  1817. http.Error(w, err.Error(), http.StatusInternalServerError)
  1818. }
  1819. }
  1820. type bufferedResponseWriter struct {
  1821. io.Writer
  1822. }
  1823. func (w bufferedResponseWriter) WriteHeader(int) {}
  1824. func (w bufferedResponseWriter) Header() http.Header {
  1825. return http.Header{}
  1826. }