api.go 61 KB

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