package main import ( "bufio" "encoding/json" "errors" "fmt" "html" "io" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/gorilla/websocket" ) func webserver() { http.Handle("/", mungeHandler{http.FileServer(http.Dir(staticRoot))}) http.HandleFunc("/group/", func(w http.ResponseWriter, r *http.Request) { mungeHeader(w) http.ServeFile(w, r, staticRoot+"/sfu.html") }) http.HandleFunc("/ws", wsHandler) http.HandleFunc("/public-groups.json", publicHandler) http.HandleFunc("/stats", statsHandler) go func() { server := &http.Server{ Addr: httpAddr, ReadHeaderTimeout: 60 * time.Second, IdleTimeout: 120 * time.Second, } var err error err = server.ListenAndServeTLS( filepath.Join(dataDir, "cert.pem"), filepath.Join(dataDir, "key.pem"), ) if err != nil { log.Printf("ListenAndServeTLS: %v", err) } }() } func mungeHeader(w http.ResponseWriter) { w.Header().Add("Content-Security-Policy", "connect-src ws: wss: 'self'; img-src data: 'self'; default-src 'self'") } type mungeHandler struct { h http.Handler } func (h mungeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { mungeHeader(w) h.h.ServeHTTP(w, r) } func publicHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", "application/json") w.Header().Set("cache-control", "no-cache") if r.Method == "HEAD" { return } g := getPublicGroups() e := json.NewEncoder(w) e.Encode(g) return } func getPassword() (string, string, error) { f, err := os.Open(filepath.Join(dataDir, "passwd")) if err != nil { return "", "", err } defer f.Close() r := bufio.NewReader(f) s, err := r.ReadString('\n') if err != nil { return "", "", err } l := strings.SplitN(strings.TrimSpace(s), ":", 2) if len(l) != 2 { return "", "", errors.New("couldn't parse passwords") } return l[0], l[1], nil } func statsHandler(w http.ResponseWriter, r *http.Request) { bail := func() { w.Header().Set("www-authenticate", "basic realm=\"stats\"") http.Error(w, "Haha!", http.StatusUnauthorized) } u, p, err := getPassword() if err != nil { log.Printf("Passwd: %v", err) bail() return } username, password, ok := r.BasicAuth() if !ok || username != u || password != p { bail() return } w.Header().Set("content-type", "text/html; charset=utf-8") w.Header().Set("cache-control", "no-cache") if r.Method == "HEAD" { return } stats := getGroupStats() fmt.Fprintf(w, "\n
\n") fmt.Fprintf(w, "%v
\n", html.EscapeString(gs.name)) fmt.Fprintf(w, "%v | ||
Up | %v | |
Down | %v |