api.go 59 KB

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