api.go 62 KB

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