api.go 61 KB

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