api.go 63 KB

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