aboutsummaryrefslogtreecommitdiff
path: root/internal/net/web.go
blob: e573aba0614a798d539c9c85c7c98f709b72fcd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package net

import (
	"embed"
	"log"
	"net"
	"net/http"
	"strings"

	"github.com/gorilla/websocket"
)

//go:embed terminal.html
var terminalHTML embed.FS

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		origin := r.Header.Get("Origin")
		if origin == "" {
			return true
		}
		host := r.Host
		hostname, _, err := net.SplitHostPort(host)
		if err != nil {
			hostname = host
		}
		if strings.EqualFold(origin, "http://"+host) ||
			strings.EqualFold(origin, "https://"+host) ||
			strings.EqualFold(origin, "http://"+hostname) ||
			strings.EqualFold(origin, "https://"+hostname) {
			return true
		}
		if hn, _, err := net.SplitHostPort(r.RemoteAddr); err == nil &&
			(hn == "127.0.0.1" || hn == "::1") {
			return true
		}
		log.Printf("ws rejected origin: %s (host: %s)", origin, r.Host)
		return false
	},
}

func newHTTPMux(s *Server) *http.ServeMux {
	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		data, err := terminalHTML.ReadFile("terminal.html")
		if err != nil {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(data)
	})

	mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		ws, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Printf("ws upgrade error: %v", err)
			return
		}
		sess := &Session{
			Conn:  newWSConn(ws),
			State: StateAccountName,
		}
		s.hub.Add(sess)
		go s.handleSession(sess, s.handler)
	})

	return mux
}