neko/server/internal/websocket/websocket.go

346 lines
7.9 KiB
Go
Raw Permalink 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"
2022-09-13 08:18:18 +12:00
"m1k1o/neko/internal/config"
2021-10-06 09:38:24 +13:00
"m1k1o/neko/internal/types"
"m1k1o/neko/internal/types/event"
"m1k1o/neko/internal/types/message"
"m1k1o/neko/internal/utils"
2022-09-13 08:36:56 +12:00
"m1k1o/neko/internal/websocket/handler"
2022-09-14 06:04:43 +12:00
"m1k1o/neko/internal/websocket/state"
2020-01-25 04:47:37 +13:00
)
2022-09-17 22:43:17 +12:00
func New(sessions types.SessionManager, desktop types.DesktopManager, capture types.CaptureManager, webrtc types.WebRTCManager, conf *config.WebSocket) *WebSocketHandler {
2020-01-25 04:47:37 +13:00
logger := log.With().Str("module", "websocket").Logger()
2024-04-20 21:08:17 +12:00
state := state.New()
2021-11-18 10:10:55 +13:00
2022-09-13 08:36:56 +12:00
handler := handler.New(
sessions,
desktop,
capture,
webrtc,
2022-09-14 06:04:43 +12:00
state,
2022-09-13 08:36:56 +12:00
)
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,
2022-09-13 08:12:47 +12:00
desktop: desktop,
2022-09-13 08:36:56 +12:00
webrtc: webrtc,
2022-09-14 06:04:43 +12:00
state: state,
2021-04-05 08:37:33 +12:00
upgrader: websocket.Upgrader{
2020-01-25 04:47:37 +13:00
CheckOrigin: func(r *http.Request) bool {
return true
},
},
2022-09-13 08:36:56 +12:00
handler: handler,
2021-11-18 10:10:55 +13:00
serverStartedAt: time.Now(),
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
2022-09-13 08:12:47 +12:00
desktop types.DesktopManager
2022-09-13 08:36:56 +12:00
webrtc types.WebRTCManager
2022-09-14 06:04:43 +12:00
state *state.State
2021-04-05 08:37:33 +12:00
conf *config.WebSocket
2022-09-13 08:36:56 +12:00
handler *handler.MessageHandler
2021-11-18 10:10:55 +13:00
// stats
conns uint32
serverStartedAt time.Time
lastAdminLeftAt *time.Time
lastUserLeftAt *time.Time
2020-01-25 04:47:37 +13:00
}
2021-10-06 10:10:10 +13:00
func (ws *WebSocketHandler) Start() {
2023-01-29 10:08:36 +13:00
go func() {
2023-01-22 11:43:04 +13:00
for {
2023-01-30 06:18:37 +13:00
e, ok := <-ws.sessions.GetEventsChannel()
if !ok {
ws.logger.Info().Msg("session channel was closed")
return
}
2023-01-22 11:43:04 +13:00
2023-01-30 06:18:37 +13:00
switch e.Type {
case types.SESSION_CREATED:
if err := ws.handler.SessionCreated(e.Id, e.Session); err != nil {
ws.logger.Warn().Str("id", e.Id).Err(err).Msg("session created with and error")
2023-01-22 11:43:04 +13:00
} else {
2023-01-30 06:18:37 +13:00
ws.logger.Debug().Str("id", e.Id).Msg("session created")
2023-01-22 11:43:04 +13:00
}
2023-01-30 06:18:37 +13:00
case types.SESSION_CONNECTED:
if err := ws.handler.SessionConnected(e.Id, e.Session); err != nil {
ws.logger.Warn().Str("id", e.Id).Err(err).Msg("session connected with and error")
2023-01-22 11:43:04 +13:00
} else {
2023-01-30 06:18:37 +13:00
ws.logger.Debug().Str("id", e.Id).Msg("session connected")
2023-01-22 11:43:04 +13:00
}
2020-01-25 04:47:37 +13:00
2023-01-22 11:43:04 +13:00
// remove outdated stats
2023-01-30 06:18:37 +13:00
if e.Session.Admin() {
2023-01-22 11:43:04 +13:00
ws.lastAdminLeftAt = nil
} else {
ws.lastUserLeftAt = nil
}
2023-01-30 06:18:37 +13:00
case types.SESSION_DESTROYED:
if err := ws.handler.SessionDestroyed(e.Id); err != nil {
ws.logger.Warn().Str("id", e.Id).Err(err).Msg("session destroyed with and error")
2023-01-22 11:43:04 +13:00
} else {
2023-01-30 06:18:37 +13:00
ws.logger.Debug().Str("id", e.Id).Msg("session destroyed")
2023-01-22 11:43:04 +13:00
}
2021-11-18 10:10:55 +13:00
2023-01-22 11:43:04 +13:00
membersCount := len(ws.sessions.Members())
adminCount := len(ws.sessions.Admins())
// if this was the last admin
2023-01-30 06:18:37 +13:00
if e.Session.Admin() && adminCount == 0 {
2023-01-22 11:43:04 +13:00
now := time.Now()
ws.lastAdminLeftAt = &now
}
2021-11-17 11:48:40 +13:00
2023-01-22 11:43:04 +13:00
// if this was the last user
2023-01-30 06:18:37 +13:00
if !e.Session.Admin() && membersCount-adminCount == 0 {
2023-01-22 11:43:04 +13:00
now := time.Now()
ws.lastUserLeftAt = &now
}
2023-01-30 06:18:37 +13:00
case types.SESSION_HOST_SET:
// TODO: Unused.
case types.SESSION_HOST_CLEARED:
// TODO: Unused.
2021-11-17 11:48:40 +13:00
}
}
2023-01-22 11:43:04 +13:00
}()
go func() {
for {
_, ok := <-ws.desktop.GetClipboardUpdatedChannel()
if !ok {
ws.logger.Info().Msg("clipboard update channel closed")
return
}
2023-01-22 11:43:04 +13:00
session, ok := ws.sessions.GetHost()
if !ok {
return
}
2021-11-18 10:10:55 +13:00
2023-01-22 11:43:04 +13:00
err := session.Send(message.Clipboard{
Event: event.CONTROL_CLIPBOARD,
Text: ws.desktop.ReadClipboard(),
})
2020-01-25 04:47:37 +13:00
2023-01-22 11:43:04 +13:00
ws.logger.Err(err).Msg("sync clipboard")
2020-01-26 03:29:52 +13:00
}
2023-01-22 11:43:04 +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")
2021-11-18 06:00:27 +13:00
id, err := utils.NewUID(32)
if err != nil {
ws.logger.Error().Err(err).Msg("failed to generate user id")
return err
}
2020-01-25 04:47:37 +13:00
connection, err := ws.upgrader.Upgrade(w, r, nil)
if err != nil {
ws.logger.Error().Err(err).Msg("failed to upgrade connection")
return err
}
2021-11-18 06:00:27 +13:00
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,
2023-11-20 02:50:23 +13:00
address: r.RemoteAddr,
2020-01-25 04:47:37 +13:00
connection: connection,
}
2022-09-13 08:36:56 +12:00
ok, reason := ws.handler.Connected(admin, socket.Address())
2020-01-25 04:47:37 +13:00
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-11-18 10:10:55 +13:00
2022-09-14 06:04:43 +12:00
Banned: ws.state.AllBanned(),
2021-11-18 10:10:55 +13:00
ServerStartedAt: ws.serverStartedAt,
LastAdminLeftAt: ws.lastAdminLeftAt,
LastUserLeftAt: ws.lastUserLeftAt,
2024-04-22 06:16:09 +12:00
ImplicitControl: ws.webrtc.ImplicitControl(),
2021-03-20 10:06:40 +13:00
}
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")
}
2021-11-18 06:00:27 +13:00
func (ws *WebSocketHandler) authenticate(r *http.Request) (bool, error) {
2020-01-25 04:47:37 +13:00
passwords, ok := r.URL.Query()["password"]
if !ok || len(passwords[0]) < 1 {
2021-11-18 06:00:27 +13:00
return false, fmt.Errorf("no password provided")
2020-01-25 04:47:37 +13:00
}
2021-11-18 06:00:27 +13:00
return ws.IsAdmin(passwords[0])
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
}
}
}
}