api.go 63 KB

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