api.go 57 KB

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