api.go 53 KB

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