api.go 62 KB

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