api.go 54 KB

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