api.go 57 KB

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