api.go 61 KB

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