api.go 64 KB

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