api.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  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. "previousBlocksHash": f.PreviousBlocksHash,
  1539. }
  1540. if f.HasPermissionBits() {
  1541. out["permissions"] = fmt.Sprintf("%#o", f.FilePermissions())
  1542. }
  1543. return out
  1544. }
  1545. type jsonVersionVector protocol.Vector
  1546. func (v jsonVersionVector) MarshalJSON() ([]byte, error) {
  1547. res := make([]string, len(v.Counters))
  1548. for i, c := range v.Counters {
  1549. res[i] = fmt.Sprintf("%v:%d", c.ID, c.Value)
  1550. }
  1551. return json.Marshal(res)
  1552. }
  1553. func dirNames(dir string) []string {
  1554. fis, err := os.ReadDir(dir)
  1555. if err != nil {
  1556. return nil
  1557. }
  1558. var dirs []string
  1559. for _, fi := range fis {
  1560. if fi.IsDir() {
  1561. dirs = append(dirs, filepath.Base(fi.Name()))
  1562. }
  1563. }
  1564. slices.Sort(dirs)
  1565. return dirs
  1566. }
  1567. func addressIsLocalhost(addr string) bool {
  1568. host, _, err := net.SplitHostPort(addr)
  1569. if err != nil {
  1570. // There was no port, so we assume the address was just a hostname
  1571. host = addr
  1572. }
  1573. host = strings.ToLower(host)
  1574. switch {
  1575. case host == "localhost":
  1576. return true
  1577. case host == "localhost.":
  1578. return true
  1579. case strings.HasSuffix(host, ".localhost"):
  1580. return true
  1581. default:
  1582. ip := net.ParseIP(host)
  1583. if ip == nil {
  1584. // not an IP address
  1585. return false
  1586. }
  1587. return ip.IsLoopback()
  1588. }
  1589. }
  1590. // shouldRegenerateCertificate checks for certificate expiry or other known
  1591. // issues with our API/GUI certificate and returns either nil (leave the
  1592. // certificate alone) or an error describing the reason the certificate
  1593. // should be regenerated.
  1594. func shouldRegenerateCertificate(cert tls.Certificate) error {
  1595. leaf := cert.Leaf
  1596. if leaf == nil {
  1597. // Leaf can be nil or not, depending on how parsed the certificate
  1598. // was when we got it.
  1599. if len(cert.Certificate) < 1 {
  1600. // can't happen
  1601. return errors.New("no certificate in certificate")
  1602. }
  1603. var err error
  1604. leaf, err = x509.ParseCertificate(cert.Certificate[0])
  1605. if err != nil {
  1606. return err
  1607. }
  1608. }
  1609. if leaf.Subject.String() != leaf.Issuer.String() || len(leaf.IPAddresses) != 0 {
  1610. // The certificate is not self signed, or has IP attributes we don't
  1611. // add, so we leave it alone.
  1612. return nil
  1613. }
  1614. if len(leaf.DNSNames) > 1 {
  1615. // The certificate has more DNS SANs attributes than we ever add, so
  1616. // we leave it alone.
  1617. return nil
  1618. }
  1619. if len(leaf.DNSNames) == 1 && leaf.DNSNames[0] != leaf.Issuer.CommonName {
  1620. // The one SAN is different from the issuer, so it's not one of our
  1621. // newer self signed certificates.
  1622. return nil
  1623. }
  1624. if leaf.NotAfter.Before(time.Now()) {
  1625. return errors.New("certificate has expired")
  1626. }
  1627. if leaf.NotAfter.Before(time.Now().Add(30 * 24 * time.Hour)) {
  1628. return errors.New("certificate will soon expire")
  1629. }
  1630. // On macOS, check for certificates issued on or after July 1st, 2019,
  1631. // with a longer validity time than 825 days.
  1632. cutoff := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
  1633. if build.IsDarwin &&
  1634. leaf.NotBefore.After(cutoff) &&
  1635. leaf.NotAfter.Sub(leaf.NotBefore) > 825*24*time.Hour {
  1636. return errors.New("certificate incompatible with macOS 10.15 (Catalina)")
  1637. }
  1638. return nil
  1639. }
  1640. func errorStringMap(errs map[string]error) map[string]*string {
  1641. out := make(map[string]*string, len(errs))
  1642. for s, e := range errs {
  1643. out[s] = errorString(e)
  1644. }
  1645. return out
  1646. }
  1647. func errorString(err error) *string {
  1648. if err != nil {
  1649. msg := err.Error()
  1650. return &msg
  1651. }
  1652. return nil
  1653. }
  1654. type discoveryStatusEntry struct {
  1655. Error *string `json:"error"`
  1656. }
  1657. func discoveryStatusMap(errs map[string]error) map[string]discoveryStatusEntry {
  1658. out := make(map[string]discoveryStatusEntry, len(errs))
  1659. for s, e := range errs {
  1660. out[s] = discoveryStatusEntry{
  1661. Error: errorString(e),
  1662. }
  1663. }
  1664. return out
  1665. }
  1666. // sanitizedHostname returns the given name in a suitable form for use as
  1667. // the common name in a certificate, or an error.
  1668. func sanitizedHostname(name string) (string, error) {
  1669. // Remove diacritics and non-alphanumerics. This works by first
  1670. // transforming into normalization form D (things with diacriticals are
  1671. // split into the base character and the mark) and then removing
  1672. // undesired characters.
  1673. t := transform.Chain(
  1674. // Split runes with diacritics into base character and mark.
  1675. norm.NFD,
  1676. // Leave only [A-Za-z0-9-.].
  1677. runes.Remove(runes.Predicate(func(r rune) bool {
  1678. return r > unicode.MaxASCII ||
  1679. !unicode.IsLetter(r) && !unicode.IsNumber(r) &&
  1680. r != '.' && r != '-'
  1681. })))
  1682. name, _, err := transform.String(t, name)
  1683. if err != nil {
  1684. return "", err
  1685. }
  1686. // Name should not start or end with a dash or dot.
  1687. name = strings.Trim(name, "-.")
  1688. // Name should not be empty.
  1689. if name == "" {
  1690. return "", errors.New("no suitable name")
  1691. }
  1692. return strings.ToLower(name), nil
  1693. }
  1694. func isFolderNotFound(err error) bool {
  1695. for _, target := range []error{
  1696. model.ErrFolderMissing,
  1697. model.ErrFolderPaused,
  1698. model.ErrFolderNotRunning,
  1699. } {
  1700. if errors.Is(err, target) {
  1701. return true
  1702. }
  1703. }
  1704. return false
  1705. }
  1706. func httpError(w http.ResponseWriter, err error) {
  1707. if errors.Is(err, upgrade.ErrUpgradeUnsupported) {
  1708. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
  1709. } else {
  1710. http.Error(w, err.Error(), http.StatusInternalServerError)
  1711. }
  1712. }
  1713. type bufferedResponseWriter struct {
  1714. io.Writer
  1715. }
  1716. func (w bufferedResponseWriter) WriteHeader(int) {}
  1717. func (w bufferedResponseWriter) Header() http.Header {
  1718. return http.Header{}
  1719. }