api.go 57 KB

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