api.go 52 KB

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