api.go 59 KB

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