api.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package api
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "runtime"
  24. "runtime/pprof"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "unicode"
  30. "github.com/julienschmidt/httprouter"
  31. "github.com/rcrowley/go-metrics"
  32. "github.com/thejerf/suture/v4"
  33. "github.com/vitrun/qart/qr"
  34. "golang.org/x/text/runes"
  35. "golang.org/x/text/transform"
  36. "golang.org/x/text/unicode/norm"
  37. "github.com/syncthing/syncthing/lib/build"
  38. "github.com/syncthing/syncthing/lib/config"
  39. "github.com/syncthing/syncthing/lib/connections"
  40. "github.com/syncthing/syncthing/lib/db"
  41. "github.com/syncthing/syncthing/lib/discover"
  42. "github.com/syncthing/syncthing/lib/events"
  43. "github.com/syncthing/syncthing/lib/fs"
  44. "github.com/syncthing/syncthing/lib/ignore"
  45. "github.com/syncthing/syncthing/lib/locations"
  46. "github.com/syncthing/syncthing/lib/logger"
  47. "github.com/syncthing/syncthing/lib/model"
  48. "github.com/syncthing/syncthing/lib/protocol"
  49. "github.com/syncthing/syncthing/lib/rand"
  50. "github.com/syncthing/syncthing/lib/svcutil"
  51. "github.com/syncthing/syncthing/lib/sync"
  52. "github.com/syncthing/syncthing/lib/tlsutil"
  53. "github.com/syncthing/syncthing/lib/upgrade"
  54. "github.com/syncthing/syncthing/lib/ur"
  55. )
  56. const (
  57. DefaultEventMask = events.AllEvents &^ events.LocalChangeDetected &^ events.RemoteChangeDetected
  58. DiskEventMask = events.LocalChangeDetected | events.RemoteChangeDetected
  59. EventSubBufferSize = 1000
  60. defaultEventTimeout = time.Minute
  61. httpsCertLifetimeDays = 820
  62. )
  63. type service struct {
  64. suture.Service
  65. id protocol.DeviceID
  66. cfg config.Wrapper
  67. statics *staticsServer
  68. model model.Model
  69. eventSubs map[events.EventType]events.BufferedSubscription
  70. eventSubsMut sync.Mutex
  71. evLogger events.Logger
  72. discoverer discover.Manager
  73. connectionsService connections.Service
  74. fss model.FolderSummaryService
  75. urService *ur.Service
  76. noUpgrade bool
  77. tlsDefaultCommonName string
  78. configChanged chan struct{} // signals intentional listener close due to config change
  79. started chan string // signals startup complete by sending the listener address, for testing only
  80. startedOnce chan struct{} // the service has started successfully at least once
  81. startupErr error
  82. listenerAddr net.Addr
  83. exitChan chan *svcutil.FatalErr
  84. guiErrors logger.Recorder
  85. systemLog logger.Recorder
  86. }
  87. var _ config.Verifier = &service{}
  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(io.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, _ := io.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 := os.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 := os.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 := os.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 := io.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 := io.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. }