api.go 58 KB

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