1
0

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