1
0

api.go 62 KB

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