neko/server/internal/websocket/websocket.go

373 lines
8.9 KiB
Go
Raw Normal View History

2020-01-25 04:47:37 +13:00
package websocket
import (
"fmt"
"net/http"
2021-09-12 04:21:28 +12:00
"sync"
2021-03-20 09:33:49 +13:00
"sync/atomic"
2020-01-25 04:47:37 +13:00
"time"
"github.com/gorilla/websocket"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2021-10-06 09:38:24 +13:00
"m1k1o/neko/internal/types"
"m1k1o/neko/internal/types/config"
"m1k1o/neko/internal/types/event"
"m1k1o/neko/internal/types/message"
"m1k1o/neko/internal/utils"
2020-01-25 04:47:37 +13:00
)
2021-11-17 11:48:40 +13:00
const CONTROL_PROTECTION_SESSION = "control_protection"
2020-09-27 11:10:34 +13:00
func New(sessions types.SessionManager, remote types.RemoteManager, broadcast types.BroadcastManager, webrtc types.WebRTCManager, conf *config.WebSocket) *WebSocketHandler {
2020-01-25 04:47:37 +13:00
logger := log.With().Str("module", "websocket").Logger()
2021-11-17 11:00:24 +13:00
locks := make(map[string]string)
for _, lock := range conf.Locks {
locks[lock] = "" // empty session ID
}
if len(conf.Locks) > 0 {
logger.Info().Msgf("locked resources: %+v", conf.Locks)
}
2021-11-17 11:48:40 +13:00
// if control protection is enabled
if conf.ControlProtection {
locks["control"] = CONTROL_PROTECTION_SESSION
logger.Info().Msgf("control locked on behalf of control protection")
}
2020-01-25 04:47:37 +13:00
return &WebSocketHandler{
2021-04-05 08:37:33 +12:00
logger: logger,
2021-09-12 04:21:28 +12:00
shutdown: make(chan interface{}),
2021-04-05 08:37:33 +12:00
conf: conf,
sessions: sessions,
remote: remote,
upgrader: websocket.Upgrader{
2020-01-25 04:47:37 +13:00
CheckOrigin: func(r *http.Request) bool {
return true
},
},
handler: &MessageHandler{
2020-09-27 11:10:34 +13:00
logger: logger.With().Str("subsystem", "handler").Logger(),
remote: remote,
broadcast: broadcast,
sessions: sessions,
webrtc: webrtc,
banned: make(map[string]bool),
2021-11-17 11:00:24 +13:00
locked: locks,
2020-01-25 04:47:37 +13:00
},
2021-03-20 09:33:49 +13:00
conns: 0,
2020-01-25 04:47:37 +13:00
}
}
// Send pings to peer with this period. Must be less than pongWait.
const pingPeriod = 60 * time.Second
type WebSocketHandler struct {
2021-04-05 08:37:33 +12:00
logger zerolog.Logger
2021-09-12 04:21:28 +12:00
wg sync.WaitGroup
shutdown chan interface{}
2021-04-05 08:37:33 +12:00
upgrader websocket.Upgrader
sessions types.SessionManager
remote types.RemoteManager
conf *config.WebSocket
handler *MessageHandler
conns uint32
2020-01-25 04:47:37 +13:00
}
2021-10-06 10:10:10 +13:00
func (ws *WebSocketHandler) Start() {
2020-01-25 04:47:37 +13:00
ws.sessions.OnCreated(func(id string, session types.Session) {
if err := ws.handler.SessionCreated(id, session); err != nil {
ws.logger.Warn().Str("id", id).Err(err).Msg("session created with and error")
} else {
ws.logger.Debug().Str("id", id).Msg("session created")
}
})
ws.sessions.OnConnected(func(id string, session types.Session) {
if err := ws.handler.SessionConnected(id, session); err != nil {
ws.logger.Warn().Str("id", id).Err(err).Msg("session connected with and error")
} else {
ws.logger.Debug().Str("id", id).Msg("session connected")
}
2021-11-17 11:48:40 +13:00
// if control protection is enabled and at least one admin
// and if room was locked on behalf control protection, unlock
sess, ok := ws.handler.locked["control"]
if ok && ws.conf.ControlProtection && sess == CONTROL_PROTECTION_SESSION && len(ws.sessions.Admins()) > 0 {
delete(ws.handler.locked, "control")
ws.logger.Info().Msgf("control unlocked on behalf of control protection")
if err := ws.sessions.Broadcast(
message.AdminLock{
Event: event.ADMIN_UNLOCK,
ID: id,
Resource: "control",
}, nil); err != nil {
ws.logger.Warn().Err(err).Msgf("broadcasting event %s has failed", event.ADMIN_UNLOCK)
}
}
2020-01-25 04:47:37 +13:00
})
2020-04-07 08:14:30 +12:00
ws.sessions.OnDestroy(func(id string, session types.Session) {
2020-01-25 04:47:37 +13:00
if err := ws.handler.SessionDestroyed(id); err != nil {
ws.logger.Warn().Str("id", id).Err(err).Msg("session destroyed with and error")
} else {
ws.logger.Debug().Str("id", id).Msg("session destroyed")
}
2021-11-17 11:48:40 +13:00
// if control protection is enabled and no admin
if ws.conf.ControlProtection && len(ws.sessions.Admins()) == 0 {
ws.handler.locked["control"] = CONTROL_PROTECTION_SESSION
ws.logger.Info().Msgf("control locked and released on behalf of control protection")
ws.handler.adminRelease(id, session)
if err := ws.sessions.Broadcast(
message.AdminLock{
Event: event.ADMIN_LOCK,
ID: id,
Resource: "control",
}, nil); err != nil {
ws.logger.Warn().Err(err).Msgf("broadcasting event %s has failed", event.ADMIN_LOCK)
}
}
2020-01-25 04:47:37 +13:00
})
2021-09-12 04:21:28 +12:00
ws.wg.Add(1)
2020-01-26 03:29:52 +13:00
go func() {
defer func() {
ws.logger.Info().Msg("shutdown")
2021-09-12 04:21:28 +12:00
ws.wg.Done()
2020-01-26 03:29:52 +13:00
}()
2020-04-06 10:34:51 +12:00
current := ws.remote.ReadClipboard()
2020-01-26 03:29:52 +13:00
for {
select {
case <-ws.shutdown:
return
default:
2021-10-06 10:10:10 +13:00
time.Sleep(100 * time.Millisecond)
if !ws.sessions.HasHost() {
continue
}
text := ws.remote.ReadClipboard()
if text == current {
continue
}
session, ok := ws.sessions.GetHost()
if ok {
err := session.Send(message.Clipboard{
Event: event.CONTROL_CLIPBOARD,
Text: text,
})
if err != nil {
ws.logger.Err(err).Msg("unable to synchronize clipboard")
2020-01-26 03:29:52 +13:00
}
}
2021-10-06 10:10:10 +13:00
current = text
2020-01-26 03:29:52 +13:00
}
}
}()
2020-01-25 04:47:37 +13:00
}
func (ws *WebSocketHandler) Shutdown() error {
2021-09-12 04:21:28 +12:00
close(ws.shutdown)
ws.wg.Wait()
2020-01-25 04:47:37 +13:00
return nil
}
func (ws *WebSocketHandler) Upgrade(w http.ResponseWriter, r *http.Request) error {
ws.logger.Debug().Msg("attempting to upgrade connection")
connection, err := ws.upgrader.Upgrade(w, r, nil)
if err != nil {
ws.logger.Error().Err(err).Msg("failed to upgrade connection")
return err
}
2020-04-05 15:49:43 +12:00
id, ip, admin, err := ws.authenticate(r)
2020-01-25 04:47:37 +13:00
if err != nil {
ws.logger.Warn().Err(err).Msg("authentication failed")
2020-01-25 04:47:37 +13:00
2021-08-16 02:05:26 +12:00
if err = connection.WriteJSON(message.SystemMessage{
2020-01-25 04:47:37 +13:00
Event: event.SYSTEM_DISCONNECT,
Message: "invalid_password",
2020-01-25 04:47:37 +13:00
}); err != nil {
ws.logger.Error().Err(err).Msg("failed to send disconnect")
}
if err = connection.Close(); err != nil {
return err
}
return nil
}
socket := &WebSocket{
id: id,
ws: ws,
2020-04-05 15:49:43 +12:00
address: ip,
2020-01-25 04:47:37 +13:00
connection: connection,
}
2021-01-15 09:41:00 +13:00
ok, reason, err := ws.handler.Connected(admin, socket)
2020-01-25 04:47:37 +13:00
if err != nil {
ws.logger.Error().Err(err).Msg("connection failed")
return err
}
if !ok {
2021-08-16 02:05:26 +12:00
if err = connection.WriteJSON(message.SystemMessage{
2020-01-25 04:47:37 +13:00
Event: event.SYSTEM_DISCONNECT,
Message: reason,
}); err != nil {
ws.logger.Error().Err(err).Msg("failed to send disconnect")
}
if err = connection.Close(); err != nil {
return err
}
return nil
}
ws.sessions.New(id, admin, socket)
ws.logger.
Debug().
Str("session", id).
Str("address", connection.RemoteAddr().String()).
Msg("new connection created")
2021-03-20 09:33:49 +13:00
atomic.AddUint32(&ws.conns, uint32(1))
2020-01-25 04:47:37 +13:00
defer func() {
ws.logger.
Debug().
Str("session", id).
Str("address", connection.RemoteAddr().String()).
Msg("session ended")
2021-03-20 09:33:49 +13:00
atomic.AddUint32(&ws.conns, ^uint32(0))
2020-01-25 04:47:37 +13:00
}()
ws.handle(connection, id)
return nil
}
2021-03-20 10:06:40 +13:00
func (ws *WebSocketHandler) Stats() types.Stats {
host := ""
session, ok := ws.sessions.GetHost()
if ok {
host = session.ID()
}
return types.Stats{
Connections: atomic.LoadUint32(&ws.conns),
Host: host,
Members: ws.sessions.Members(),
}
2021-03-20 09:33:49 +13:00
}
func (ws *WebSocketHandler) IsAdmin(password string) (bool, error) {
if password == ws.conf.AdminPassword {
return true, nil
}
if password == ws.conf.Password {
return false, nil
}
return false, fmt.Errorf("invalid password")
}
2020-04-05 15:49:43 +12:00
func (ws *WebSocketHandler) authenticate(r *http.Request) (string, string, bool, error) {
2020-04-07 08:14:30 +12:00
ip := r.RemoteAddr
if ws.conf.Proxy {
ip = utils.ReadUserIP(r)
}
2020-04-05 15:49:43 +12:00
2020-01-25 04:47:37 +13:00
id, err := utils.NewUID(32)
if err != nil {
2020-04-05 15:49:43 +12:00
return "", ip, false, err
2020-01-25 04:47:37 +13:00
}
passwords, ok := r.URL.Query()["password"]
if !ok || len(passwords[0]) < 1 {
2020-04-05 15:49:43 +12:00
return "", ip, false, fmt.Errorf("no password provided")
2020-01-25 04:47:37 +13:00
}
2021-03-20 09:33:49 +13:00
isAdmin, err := ws.IsAdmin(passwords[0])
return id, ip, isAdmin, err
2020-01-25 04:47:37 +13:00
}
func (ws *WebSocketHandler) handle(connection *websocket.Conn, id string) {
bytes := make(chan []byte)
cancel := make(chan struct{})
ticker := time.NewTicker(pingPeriod)
2021-09-12 04:21:28 +12:00
ws.wg.Add(1)
2020-01-25 04:47:37 +13:00
go func() {
defer func() {
ticker.Stop()
ws.logger.Debug().Str("address", connection.RemoteAddr().String()).Msg("handle socket ending")
ws.handler.Disconnected(id)
2021-09-12 04:21:28 +12:00
ws.wg.Done()
2020-01-25 04:47:37 +13:00
}()
for {
_, raw, err := connection.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
ws.logger.Warn().Err(err).Msg("read message error")
} else {
ws.logger.Debug().Err(err).Msg("read message error")
}
close(cancel)
break
}
bytes <- raw
}
}()
for {
select {
case raw := <-bytes:
ws.logger.Debug().
Str("session", id).
2020-02-13 17:45:29 +13:00
Str("address", connection.RemoteAddr().String()).
2020-01-25 04:47:37 +13:00
Str("raw", string(raw)).
Msg("received message from client")
2020-01-25 04:47:37 +13:00
if err := ws.handler.Message(id, raw); err != nil {
ws.logger.Error().Err(err).Msg("message handler has failed")
}
2021-09-12 04:21:28 +12:00
case <-ws.shutdown:
if err := connection.WriteJSON(message.SystemMessage{
Event: event.SYSTEM_DISCONNECT,
Message: "server_shutdown",
}); err != nil {
ws.logger.Err(err).Msg("failed to send disconnect")
}
if err := connection.Close(); err != nil {
ws.logger.Err(err).Msg("connection closed with an error")
}
return
2020-01-25 04:47:37 +13:00
case <-cancel:
return
2021-07-23 06:58:15 +12:00
case <-ticker.C:
2020-01-25 04:47:37 +13:00
if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}