api.go 51 KB

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