api.go 63 KB

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