api.go 49 KB

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