api.go 63 KB

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