api.go 59 KB

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