api.go 55 KB

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