1
0

api.go 55 KB

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