api.go 60 KB

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