1
Fork 0
mirror of https://github.com/jech/galene.git synced 2024-11-14 04:35:57 +01:00
galene/sfu.go

274 lines
5.9 KiB
Go
Raw Normal View History

2020-04-24 19:38:21 +02:00
// Copyright (c) 2020 by Juliusz Chroboczek.
// This is not open source software. Copy it, and I'll break into your
// house and tell your three year-old that Santa doesn't exist.
package main
import (
2020-04-29 16:08:07 +02:00
"bufio"
2020-04-24 19:38:21 +02:00
"encoding/json"
2020-04-29 16:08:07 +02:00
"errors"
2020-04-24 19:38:21 +02:00
"flag"
2020-04-29 16:08:07 +02:00
"fmt"
"html"
"io"
2020-04-24 19:38:21 +02:00
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
2020-05-20 23:04:31 +02:00
"runtime"
"runtime/pprof"
2020-04-29 16:08:07 +02:00
"strings"
2020-04-24 19:38:21 +02:00
"syscall"
"time"
"github.com/gorilla/websocket"
)
var httpAddr string
var staticRoot string
var dataDir string
2020-04-25 02:25:51 +02:00
var groupsDir string
2020-04-24 19:38:21 +02:00
var iceFilename string
func main() {
2020-05-20 23:04:31 +02:00
var cpuprofile, memprofile, mutexprofile string
2020-04-24 19:38:21 +02:00
flag.StringVar(&httpAddr, "http", ":8443", "web server `address`")
flag.StringVar(&staticRoot, "static", "./static/",
"web server root `directory`")
flag.StringVar(&dataDir, "data", "./data/",
"data `directory`")
2020-04-25 02:25:51 +02:00
flag.StringVar(&groupsDir, "groups", "./groups/",
"group description `directory`")
2020-05-20 23:04:31 +02:00
flag.StringVar(&cpuprofile, "cpuprofile", "",
"store CPU profile in `file`")
flag.StringVar(&memprofile, "memprofile", "",
"store memory profile in `file`")
flag.StringVar(&mutexprofile, "mutexprofile", "",
"store mutex profile in `file`")
2020-04-24 19:38:21 +02:00
flag.Parse()
2020-05-20 23:04:31 +02:00
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Printf("Create(cpuprofile): %v", err)
return
}
pprof.StartCPUProfile(f)
defer func() {
pprof.StopCPUProfile()
f.Close()
}()
}
if memprofile != "" {
defer func() {
f, err := os.Create(memprofile)
if err != nil {
log.Printf("Create(memprofile): %v", err)
return
}
pprof.WriteHeapProfile(f)
f.Close()
}()
}
if mutexprofile != "" {
runtime.SetMutexProfileFraction(1)
defer func() {
f, err := os.Create(mutexprofile)
if err != nil {
log.Printf("Create(mutexprofile): %v", err)
return
}
pprof.Lookup("mutex").WriteTo(f, 0)
f.Close()
}()
}
2020-04-24 19:38:21 +02:00
iceFilename = filepath.Join(staticRoot, "ice-servers.json")
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)
2020-04-29 16:08:07 +02:00
http.HandleFunc("/stats", statsHandler)
2020-04-24 19:38:21 +02:00
2020-04-25 04:08:43 +02:00
go readPublicGroups()
2020-04-24 19:38:21 +02:00
go func() {
server := &http.Server{
Addr: httpAddr,
ReadTimeout: 60 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
var err error
log.Printf("Listening on %v", httpAddr)
err = server.ListenAndServeTLS(
filepath.Join(dataDir, "cert.pem"),
filepath.Join(dataDir, "key.pem"),
)
log.Fatalf("ListenAndServeTLS: %v", err)
}()
terminate := make(chan os.Signal, 1)
signal.Notify(terminate, syscall.SIGINT)
<-terminate
}
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
}
2020-04-29 16:08:07 +02:00
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, "<!DOCTYPE html>\n<html><head>\n")
fmt.Fprintf(w, "<title>Stats</title>\n")
fmt.Fprintf(w, "<head><body>\n")
2020-04-30 20:33:04 +02:00
printBitrate := func(w io.Writer, rate, maxRate uint64) error {
2020-04-29 16:08:07 +02:00
var err error
2020-04-30 20:33:04 +02:00
if maxRate != 0 && maxRate != ^uint64(0) {
_, err = fmt.Fprintf(w, "%v/%v", rate, maxRate)
} else {
2020-04-29 16:08:07 +02:00
_, err = fmt.Fprintf(w, "%v", rate)
}
return err
}
printTrack := func(w io.Writer, t trackStats) {
fmt.Fprintf(w, "<tr><td></td><td></td><td></td>")
fmt.Fprintf(w, "<td>")
2020-04-30 20:33:04 +02:00
printBitrate(w, t.bitrate, t.maxBitrate)
2020-04-29 16:08:07 +02:00
fmt.Fprintf(w, "</td>")
2020-05-02 16:32:34 +02:00
fmt.Fprintf(w, "<td>%d%%</td>",
2020-04-29 16:08:07 +02:00
t.loss,
)
2020-05-02 16:32:34 +02:00
if t.jitter > 0 {
fmt.Fprintf(w, "<td>%v</td>", t.jitter)
} else {
fmt.Fprintf(w, "<td></td>")
}
fmt.Fprintf(w, "</tr>")
2020-04-29 16:08:07 +02:00
}
for _, gs := range stats {
fmt.Fprintf(w, "<p>%v</p>\n", html.EscapeString(gs.name))
fmt.Fprintf(w, "<table>")
for _, cs := range gs.clients {
fmt.Fprintf(w, "<tr><td>%v</td></tr>\n", cs.id)
for _, up := range cs.up {
fmt.Fprintf(w, "<tr><td></td><td>Up</td><td>%v</td></tr>\n",
up.id)
for _, t := range up.tracks {
printTrack(w, t)
}
}
for _, up := range cs.down {
fmt.Fprintf(w, "<tr><td></td><td>Down</td><td> %v</td></tr>\n",
up.id)
for _, t := range up.tracks {
printTrack(w, t)
}
}
}
fmt.Fprintf(w, "</table>\n")
}
fmt.Fprintf(w, "</body></html>\n")
}
2020-04-24 19:38:21 +02:00
var upgrader websocket.Upgrader
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Websocket upgrade: %v", err)
return
}
go func() {
err := startClient(conn)
if err != nil {
log.Printf("client: %v", err)
}
}()
}