agent: Improving UI file serving

This commit is contained in:
Armon Dadgar 2014-04-23 13:10:18 -07:00 committed by Jack Pearkes
parent 4983f66e75
commit 6f833a5a73
4 changed files with 36 additions and 3 deletions

View File

@ -42,6 +42,7 @@ func NewHTTPServer(agent *Agent, uiDir string, enableDebug bool, logOutput io.Wr
mux: mux, mux: mux,
listener: list, listener: list,
logger: log.New(logOutput, "", log.LstdFlags), logger: log.New(logOutput, "", log.LstdFlags),
uiDir: uiDir,
} }
srv.registerHandlers(enableDebug) srv.registerHandlers(enableDebug)

View File

@ -19,7 +19,9 @@ func makeHTTPServer(t *testing.T) (string, *HTTPServer) {
conf := nextConfig() conf := nextConfig()
dir, agent := makeAgent(t, conf) dir, agent := makeAgent(t, conf)
uiDir := filepath.Join(dir, "ui") uiDir := filepath.Join(dir, "ui")
println(uiDir) if err := os.Mkdir(uiDir, 755); err != nil {
t.Fatalf("err: %v", err)
}
addr, _ := agent.config.ClientListener(agent.config.Ports.HTTP) addr, _ := agent.config.ClientListener(agent.config.Ports.HTTP)
server, err := NewHTTPServer(agent, uiDir, true, agent.logOutput, addr.String()) server, err := NewHTTPServer(agent, uiDir, true, agent.logOutput, addr.String())
if err != nil { if err != nil {

View File

@ -2,6 +2,7 @@ package agent
import ( import (
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
@ -15,10 +16,37 @@ func (s *HTTPServer) UiIndex(resp http.ResponseWriter, req *http.Request) {
s.logger.Printf("[DEBUG] http: Request %v (%v)", req.URL, time.Now().Sub(start)) s.logger.Printf("[DEBUG] http: Request %v (%v)", req.URL, time.Now().Sub(start))
}() }()
// Determine the file path
file := strings.TrimPrefix(req.URL.Path, "/ui/") file := strings.TrimPrefix(req.URL.Path, "/ui/")
if file == "" { if file == "" {
file = "index.html" file = "index.html"
} }
// Reject if it is relative
if strings.Contains(file, "..") {
s.logger.Printf("[WARN] http: Invalid file %s", file)
resp.WriteHeader(404)
return
}
path := filepath.Join(s.uiDir, file) path := filepath.Join(s.uiDir, file)
http.ServeFile(resp, req, path)
// Attempt to open
fh, err := os.Open(path)
if err != nil {
s.logger.Printf("[WARN] http: Failed to serve file %s: %v", path, err)
resp.WriteHeader(404)
return
}
defer fh.Close()
// Get the file info
info, err := fh.Stat()
if err != nil {
s.logger.Printf("[WARN] http: Failed to stat file %s: %v", path, err)
resp.WriteHeader(404)
return
}
// Serve the file
http.ServeContent(resp, req, path, info.ModTime(), fh)
} }

View File

@ -19,7 +19,9 @@ func TestUiIndex(t *testing.T) {
// Create file // Create file
path := filepath.Join(srv.uiDir, "my-file") path := filepath.Join(srv.uiDir, "my-file")
ioutil.WriteFile(path, []byte("test"), 777) if err := ioutil.WriteFile(path, []byte("test"), 777); err != nil {
t.Fatalf("err: %v", err)
}
// Register node // Register node
req, err := http.NewRequest("GET", "/ui/my-file", nil) req, err := http.NewRequest("GET", "/ui/my-file", nil)