gui.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "encoding/base64"
  9. "encoding/json"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "math/rand"
  14. "mime"
  15. "net"
  16. "net/http"
  17. "os"
  18. "path/filepath"
  19. "reflect"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "code.google.com/p/go.crypto/bcrypt"
  26. "github.com/syncthing/syncthing/auto"
  27. "github.com/syncthing/syncthing/config"
  28. "github.com/syncthing/syncthing/events"
  29. "github.com/syncthing/syncthing/logger"
  30. "github.com/syncthing/syncthing/model"
  31. "github.com/syncthing/syncthing/protocol"
  32. "github.com/syncthing/syncthing/upgrade"
  33. "github.com/vitrun/qart/qr"
  34. )
  35. type guiError struct {
  36. Time time.Time
  37. Error string
  38. }
  39. var (
  40. configInSync = true
  41. guiErrors = []guiError{}
  42. guiErrorsMut sync.Mutex
  43. static func(http.ResponseWriter, *http.Request, *log.Logger)
  44. apiKey string
  45. modt = time.Now().UTC().Format(http.TimeFormat)
  46. eventSub *events.BufferedSubscription
  47. )
  48. const (
  49. unchangedPassword = "--password-unchanged--"
  50. )
  51. func init() {
  52. l.AddHandler(logger.LevelWarn, showGuiError)
  53. sub := events.Default.Subscribe(events.AllEvents)
  54. eventSub = events.NewBufferedSubscription(sub, 1000)
  55. }
  56. func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) error {
  57. var listener net.Listener
  58. var err error
  59. if cfg.UseTLS {
  60. cert, err := loadCert(confDir, "https-")
  61. if err != nil {
  62. l.Infoln("Loading HTTPS certificate:", err)
  63. l.Infoln("Creating new HTTPS certificate")
  64. newCertificate(confDir, "https-")
  65. cert, err = loadCert(confDir, "https-")
  66. }
  67. if err != nil {
  68. return err
  69. }
  70. tlsCfg := &tls.Config{
  71. Certificates: []tls.Certificate{cert},
  72. ServerName: "syncthing",
  73. }
  74. listener, err = tls.Listen("tcp", cfg.Address, tlsCfg)
  75. if err != nil {
  76. return err
  77. }
  78. } else {
  79. listener, err = net.Listen("tcp", cfg.Address)
  80. if err != nil {
  81. return err
  82. }
  83. }
  84. apiKey = cfg.APIKey
  85. loadCsrfTokens()
  86. // The GET handlers
  87. getRestMux := http.NewServeMux()
  88. getRestMux.HandleFunc("/rest/completion", withModel(m, restGetCompletion))
  89. getRestMux.HandleFunc("/rest/config", restGetConfig)
  90. getRestMux.HandleFunc("/rest/config/sync", restGetConfigInSync)
  91. getRestMux.HandleFunc("/rest/connections", withModel(m, restGetConnections))
  92. getRestMux.HandleFunc("/rest/discovery", restGetDiscovery)
  93. getRestMux.HandleFunc("/rest/errors", restGetErrors)
  94. getRestMux.HandleFunc("/rest/events", restGetEvents)
  95. getRestMux.HandleFunc("/rest/lang", restGetLang)
  96. getRestMux.HandleFunc("/rest/model", withModel(m, restGetModel))
  97. getRestMux.HandleFunc("/rest/model/version", withModel(m, restGetModelVersion))
  98. getRestMux.HandleFunc("/rest/need", withModel(m, restGetNeed))
  99. getRestMux.HandleFunc("/rest/nodeid", restGetNodeID)
  100. getRestMux.HandleFunc("/rest/report", withModel(m, restGetReport))
  101. getRestMux.HandleFunc("/rest/system", restGetSystem)
  102. getRestMux.HandleFunc("/rest/upgrade", restGetUpgrade)
  103. getRestMux.HandleFunc("/rest/version", restGetVersion)
  104. getRestMux.HandleFunc("/rest/stats/node", withModel(m, restGetNodeStats))
  105. // Debug endpoints, not for general use
  106. getRestMux.HandleFunc("/rest/debug/peerCompletion", withModel(m, restGetPeerCompletion))
  107. // The POST handlers
  108. postRestMux := http.NewServeMux()
  109. postRestMux.HandleFunc("/rest/config", withModel(m, restPostConfig))
  110. postRestMux.HandleFunc("/rest/discovery/hint", restPostDiscoveryHint)
  111. postRestMux.HandleFunc("/rest/error", restPostError)
  112. postRestMux.HandleFunc("/rest/error/clear", restClearErrors)
  113. postRestMux.HandleFunc("/rest/model/override", withModel(m, restPostOverride))
  114. postRestMux.HandleFunc("/rest/reset", restPostReset)
  115. postRestMux.HandleFunc("/rest/restart", restPostRestart)
  116. postRestMux.HandleFunc("/rest/shutdown", restPostShutdown)
  117. postRestMux.HandleFunc("/rest/upgrade", restPostUpgrade)
  118. postRestMux.HandleFunc("/rest/scan", withModel(m, restPostScan))
  119. // A handler that splits requests between the two above and disables
  120. // caching
  121. restMux := noCacheMiddleware(getPostHandler(getRestMux, postRestMux))
  122. // The main routing handler
  123. mux := http.NewServeMux()
  124. mux.Handle("/rest/", restMux)
  125. mux.HandleFunc("/qr/", getQR)
  126. // Serve compiled in assets unless an asset directory was set (for development)
  127. mux.Handle("/", embeddedStatic(assetDir))
  128. // Wrap everything in CSRF protection. The /rest prefix should be
  129. // protected, other requests will grant cookies.
  130. handler := csrfMiddleware("/rest", mux)
  131. // Wrap everything in basic auth, if user/password is set.
  132. if len(cfg.User) > 0 {
  133. handler = basicAuthMiddleware(cfg.User, cfg.Password, handler)
  134. }
  135. go http.Serve(listener, handler)
  136. return nil
  137. }
  138. func getPostHandler(get, post http.Handler) http.Handler {
  139. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  140. switch r.Method {
  141. case "GET":
  142. get.ServeHTTP(w, r)
  143. case "POST":
  144. post.ServeHTTP(w, r)
  145. default:
  146. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  147. }
  148. })
  149. }
  150. func noCacheMiddleware(h http.Handler) http.Handler {
  151. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  152. w.Header().Set("Cache-Control", "no-cache")
  153. h.ServeHTTP(w, r)
  154. })
  155. }
  156. func withModel(m *model.Model, h func(m *model.Model, w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
  157. return func(w http.ResponseWriter, r *http.Request) {
  158. h(m, w, r)
  159. }
  160. }
  161. func restGetVersion(w http.ResponseWriter, r *http.Request) {
  162. w.Write([]byte(Version))
  163. }
  164. func restGetCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  165. var qs = r.URL.Query()
  166. var repo = qs.Get("repo")
  167. var nodeStr = qs.Get("node")
  168. node, err := protocol.NodeIDFromString(nodeStr)
  169. if err != nil {
  170. http.Error(w, err.Error(), 500)
  171. return
  172. }
  173. res := map[string]float64{
  174. "completion": m.Completion(node, repo),
  175. }
  176. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  177. json.NewEncoder(w).Encode(res)
  178. }
  179. func restGetModelVersion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  180. var qs = r.URL.Query()
  181. var repo = qs.Get("repo")
  182. var res = make(map[string]interface{})
  183. res["version"] = m.LocalVersion(repo)
  184. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  185. json.NewEncoder(w).Encode(res)
  186. }
  187. func restGetModel(m *model.Model, w http.ResponseWriter, r *http.Request) {
  188. var qs = r.URL.Query()
  189. var repo = qs.Get("repo")
  190. var res = make(map[string]interface{})
  191. for _, cr := range cfg.Repositories {
  192. if cr.ID == repo {
  193. res["invalid"] = cr.Invalid
  194. break
  195. }
  196. }
  197. globalFiles, globalDeleted, globalBytes := m.GlobalSize(repo)
  198. res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes
  199. localFiles, localDeleted, localBytes := m.LocalSize(repo)
  200. res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes
  201. needFiles, needBytes := m.NeedSize(repo)
  202. res["needFiles"], res["needBytes"] = needFiles, needBytes
  203. res["inSyncFiles"], res["inSyncBytes"] = globalFiles-needFiles, globalBytes-needBytes
  204. res["state"], res["stateChanged"] = m.State(repo)
  205. res["version"] = m.LocalVersion(repo)
  206. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  207. json.NewEncoder(w).Encode(res)
  208. }
  209. func restPostOverride(m *model.Model, w http.ResponseWriter, r *http.Request) {
  210. var qs = r.URL.Query()
  211. var repo = qs.Get("repo")
  212. m.Override(repo)
  213. }
  214. func restGetNeed(m *model.Model, w http.ResponseWriter, r *http.Request) {
  215. var qs = r.URL.Query()
  216. var repo = qs.Get("repo")
  217. files := m.NeedFilesRepo(repo)
  218. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  219. json.NewEncoder(w).Encode(files)
  220. }
  221. func restGetConnections(m *model.Model, w http.ResponseWriter, r *http.Request) {
  222. var res = m.ConnectionStats()
  223. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  224. json.NewEncoder(w).Encode(res)
  225. }
  226. func restGetNodeStats(m *model.Model, w http.ResponseWriter, r *http.Request) {
  227. var res = m.NodeStatistics()
  228. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  229. json.NewEncoder(w).Encode(res)
  230. }
  231. func restGetConfig(w http.ResponseWriter, r *http.Request) {
  232. encCfg := cfg
  233. if encCfg.GUI.Password != "" {
  234. encCfg.GUI.Password = unchangedPassword
  235. }
  236. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  237. json.NewEncoder(w).Encode(encCfg)
  238. }
  239. func restPostConfig(m *model.Model, w http.ResponseWriter, r *http.Request) {
  240. var newCfg config.Configuration
  241. err := json.NewDecoder(r.Body).Decode(&newCfg)
  242. if err != nil {
  243. l.Warnln("decoding posted config:", err)
  244. http.Error(w, err.Error(), 500)
  245. return
  246. } else {
  247. if newCfg.GUI.Password == "" {
  248. // Leave it empty
  249. } else if newCfg.GUI.Password == unchangedPassword {
  250. newCfg.GUI.Password = cfg.GUI.Password
  251. } else {
  252. hash, err := bcrypt.GenerateFromPassword([]byte(newCfg.GUI.Password), 0)
  253. if err != nil {
  254. l.Warnln("bcrypting password:", err)
  255. http.Error(w, err.Error(), 500)
  256. return
  257. } else {
  258. newCfg.GUI.Password = string(hash)
  259. }
  260. }
  261. // Figure out if any changes require a restart
  262. if len(cfg.Repositories) != len(newCfg.Repositories) {
  263. configInSync = false
  264. } else {
  265. om := cfg.RepoMap()
  266. nm := newCfg.RepoMap()
  267. for id := range om {
  268. if !reflect.DeepEqual(om[id], nm[id]) {
  269. configInSync = false
  270. break
  271. }
  272. }
  273. }
  274. if len(cfg.Nodes) != len(newCfg.Nodes) {
  275. configInSync = false
  276. } else {
  277. om := cfg.NodeMap()
  278. nm := newCfg.NodeMap()
  279. for k := range om {
  280. if _, ok := nm[k]; !ok {
  281. // A node was removed and another added
  282. configInSync = false
  283. break
  284. }
  285. }
  286. }
  287. if newCfg.Options.URAccepted > cfg.Options.URAccepted {
  288. // UR was enabled
  289. newCfg.Options.URAccepted = usageReportVersion
  290. err := sendUsageReport(m)
  291. if err != nil {
  292. l.Infoln("Usage report:", err)
  293. }
  294. go usageReportingLoop(m)
  295. } else if newCfg.Options.URAccepted < cfg.Options.URAccepted {
  296. // UR was disabled
  297. newCfg.Options.URAccepted = -1
  298. stopUsageReporting()
  299. }
  300. if !reflect.DeepEqual(cfg.Options, newCfg.Options) || !reflect.DeepEqual(cfg.GUI, newCfg.GUI) {
  301. configInSync = false
  302. }
  303. // Activate and save
  304. cfg = newCfg
  305. saveConfig()
  306. }
  307. }
  308. func restGetConfigInSync(w http.ResponseWriter, r *http.Request) {
  309. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  310. json.NewEncoder(w).Encode(map[string]bool{"configInSync": configInSync})
  311. }
  312. func restPostRestart(w http.ResponseWriter, r *http.Request) {
  313. flushResponse(`{"ok": "restarting"}`, w)
  314. go restart()
  315. }
  316. func restPostReset(w http.ResponseWriter, r *http.Request) {
  317. flushResponse(`{"ok": "resetting repos"}`, w)
  318. resetRepositories()
  319. go restart()
  320. }
  321. func restPostShutdown(w http.ResponseWriter, r *http.Request) {
  322. flushResponse(`{"ok": "shutting down"}`, w)
  323. go shutdown()
  324. }
  325. func flushResponse(s string, w http.ResponseWriter) {
  326. w.Write([]byte(s + "\n"))
  327. f := w.(http.Flusher)
  328. f.Flush()
  329. }
  330. var cpuUsagePercent [10]float64 // The last ten seconds
  331. var cpuUsageLock sync.RWMutex
  332. func restGetSystem(w http.ResponseWriter, r *http.Request) {
  333. var m runtime.MemStats
  334. runtime.ReadMemStats(&m)
  335. res := make(map[string]interface{})
  336. res["myID"] = myID.String()
  337. res["goroutines"] = runtime.NumGoroutine()
  338. res["alloc"] = m.Alloc
  339. res["sys"] = m.Sys - m.HeapReleased
  340. res["tilde"] = expandTilde("~")
  341. if cfg.Options.GlobalAnnEnabled && discoverer != nil {
  342. res["extAnnounceOK"] = discoverer.ExtAnnounceOK()
  343. }
  344. cpuUsageLock.RLock()
  345. var cpusum float64
  346. for _, p := range cpuUsagePercent {
  347. cpusum += p
  348. }
  349. cpuUsageLock.RUnlock()
  350. res["cpuPercent"] = cpusum / 10
  351. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  352. json.NewEncoder(w).Encode(res)
  353. }
  354. func restGetErrors(w http.ResponseWriter, r *http.Request) {
  355. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  356. guiErrorsMut.Lock()
  357. json.NewEncoder(w).Encode(guiErrors)
  358. guiErrorsMut.Unlock()
  359. }
  360. func restPostError(w http.ResponseWriter, r *http.Request) {
  361. bs, _ := ioutil.ReadAll(r.Body)
  362. r.Body.Close()
  363. showGuiError(0, string(bs))
  364. }
  365. func restClearErrors(w http.ResponseWriter, r *http.Request) {
  366. guiErrorsMut.Lock()
  367. guiErrors = []guiError{}
  368. guiErrorsMut.Unlock()
  369. }
  370. func showGuiError(l logger.LogLevel, err string) {
  371. guiErrorsMut.Lock()
  372. guiErrors = append(guiErrors, guiError{time.Now(), err})
  373. if len(guiErrors) > 5 {
  374. guiErrors = guiErrors[len(guiErrors)-5:]
  375. }
  376. guiErrorsMut.Unlock()
  377. }
  378. func restPostDiscoveryHint(w http.ResponseWriter, r *http.Request) {
  379. var qs = r.URL.Query()
  380. var node = qs.Get("node")
  381. var addr = qs.Get("addr")
  382. if len(node) != 0 && len(addr) != 0 && discoverer != nil {
  383. discoverer.Hint(node, []string{addr})
  384. }
  385. }
  386. func restGetDiscovery(w http.ResponseWriter, r *http.Request) {
  387. json.NewEncoder(w).Encode(discoverer.All())
  388. }
  389. func restGetReport(m *model.Model, w http.ResponseWriter, r *http.Request) {
  390. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  391. json.NewEncoder(w).Encode(reportData(m))
  392. }
  393. func restGetEvents(w http.ResponseWriter, r *http.Request) {
  394. qs := r.URL.Query()
  395. sinceStr := qs.Get("since")
  396. limitStr := qs.Get("limit")
  397. since, _ := strconv.Atoi(sinceStr)
  398. limit, _ := strconv.Atoi(limitStr)
  399. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  400. // Flush before blocking, to indicate that we've received the request
  401. // and that it should not be retried.
  402. f := w.(http.Flusher)
  403. f.Flush()
  404. evs := eventSub.Since(since, nil)
  405. if 0 < limit && limit < len(evs) {
  406. evs = evs[len(evs)-limit:]
  407. }
  408. json.NewEncoder(w).Encode(evs)
  409. }
  410. func restGetUpgrade(w http.ResponseWriter, r *http.Request) {
  411. rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta"))
  412. if err != nil {
  413. http.Error(w, err.Error(), 500)
  414. return
  415. }
  416. res := make(map[string]interface{})
  417. res["running"] = Version
  418. res["latest"] = rel.Tag
  419. res["newer"] = upgrade.CompareVersions(rel.Tag, Version) == 1
  420. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  421. json.NewEncoder(w).Encode(res)
  422. }
  423. func restGetNodeID(w http.ResponseWriter, r *http.Request) {
  424. qs := r.URL.Query()
  425. idStr := qs.Get("id")
  426. id, err := protocol.NodeIDFromString(idStr)
  427. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  428. if err == nil {
  429. json.NewEncoder(w).Encode(map[string]string{
  430. "id": id.String(),
  431. })
  432. } else {
  433. json.NewEncoder(w).Encode(map[string]string{
  434. "error": err.Error(),
  435. })
  436. }
  437. }
  438. func restGetLang(w http.ResponseWriter, r *http.Request) {
  439. lang := r.Header.Get("Accept-Language")
  440. var langs []string
  441. for _, l := range strings.Split(lang, ",") {
  442. parts := strings.SplitN(l, ";", 2)
  443. langs = append(langs, strings.TrimSpace(parts[0]))
  444. }
  445. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  446. json.NewEncoder(w).Encode(langs)
  447. }
  448. func restPostUpgrade(w http.ResponseWriter, r *http.Request) {
  449. rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta"))
  450. if err != nil {
  451. l.Warnln("getting latest release:", err)
  452. http.Error(w, err.Error(), 500)
  453. return
  454. }
  455. if upgrade.CompareVersions(rel.Tag, Version) == 1 {
  456. err = upgrade.UpgradeTo(rel, GoArchExtra)
  457. if err != nil {
  458. l.Warnln("upgrading:", err)
  459. http.Error(w, err.Error(), 500)
  460. return
  461. }
  462. restPostRestart(w, r)
  463. }
  464. }
  465. func restPostScan(m *model.Model, w http.ResponseWriter, r *http.Request) {
  466. qs := r.URL.Query()
  467. repo := qs.Get("repo")
  468. sub := qs.Get("sub")
  469. err := m.ScanRepoSub(repo, sub)
  470. if err != nil {
  471. http.Error(w, err.Error(), 500)
  472. }
  473. }
  474. func getQR(w http.ResponseWriter, r *http.Request) {
  475. var qs = r.URL.Query()
  476. var text = qs.Get("text")
  477. code, err := qr.Encode(text, qr.M)
  478. if err != nil {
  479. http.Error(w, "Invalid", 500)
  480. return
  481. }
  482. w.Header().Set("Content-Type", "image/png")
  483. w.Write(code.PNG())
  484. }
  485. func restGetPeerCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  486. tot := map[string]float64{}
  487. count := map[string]float64{}
  488. for _, repo := range cfg.Repositories {
  489. for _, node := range repo.NodeIDs() {
  490. nodeStr := node.String()
  491. if m.ConnectedTo(node) {
  492. tot[nodeStr] += m.Completion(node, repo.ID)
  493. } else {
  494. tot[nodeStr] = 0
  495. }
  496. count[nodeStr]++
  497. }
  498. }
  499. comp := map[string]int{}
  500. for node := range tot {
  501. comp[node] = int(tot[node] / count[node])
  502. }
  503. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  504. json.NewEncoder(w).Encode(comp)
  505. }
  506. func basicAuthMiddleware(username string, passhash string, next http.Handler) http.Handler {
  507. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  508. if validAPIKey(r.Header.Get("X-API-Key")) {
  509. next.ServeHTTP(w, r)
  510. return
  511. }
  512. error := func() {
  513. time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
  514. w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  515. http.Error(w, "Not Authorized", http.StatusUnauthorized)
  516. }
  517. hdr := r.Header.Get("Authorization")
  518. if !strings.HasPrefix(hdr, "Basic ") {
  519. error()
  520. return
  521. }
  522. hdr = hdr[6:]
  523. bs, err := base64.StdEncoding.DecodeString(hdr)
  524. if err != nil {
  525. error()
  526. return
  527. }
  528. fields := bytes.SplitN(bs, []byte(":"), 2)
  529. if len(fields) != 2 {
  530. error()
  531. return
  532. }
  533. if string(fields[0]) != username {
  534. error()
  535. return
  536. }
  537. if err := bcrypt.CompareHashAndPassword([]byte(passhash), fields[1]); err != nil {
  538. error()
  539. return
  540. }
  541. next.ServeHTTP(w, r)
  542. })
  543. }
  544. func validAPIKey(k string) bool {
  545. return len(apiKey) > 0 && k == apiKey
  546. }
  547. func embeddedStatic(assetDir string) http.Handler {
  548. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  549. file := r.URL.Path
  550. if file[0] == '/' {
  551. file = file[1:]
  552. }
  553. if len(file) == 0 {
  554. file = "index.html"
  555. }
  556. if assetDir != "" {
  557. p := filepath.Join(assetDir, filepath.FromSlash(file))
  558. _, err := os.Stat(p)
  559. if err == nil {
  560. http.ServeFile(w, r, p)
  561. return
  562. }
  563. }
  564. bs, ok := auto.Assets[file]
  565. if !ok {
  566. http.NotFound(w, r)
  567. return
  568. }
  569. mtype := mime.TypeByExtension(filepath.Ext(r.URL.Path))
  570. if len(mtype) != 0 {
  571. w.Header().Set("Content-Type", mtype)
  572. }
  573. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  574. w.Header().Set("Last-Modified", modt)
  575. w.Write(bs)
  576. })
  577. }