api.go 51 KB

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