-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
websocket.go
172 lines (160 loc) · 4.78 KB
/
websocket.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// mautrix-wsproxy - A simple HTTP push -> websocket proxy for Matrix appservices.
// Copyright (C) 2021 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"maunium.net/go/mautrix/appservice"
)
type AppService struct {
ID string `yaml:"id"`
AS string `yaml:"as"`
HS string `yaml:"hs"`
conn *websocket.Conn `yaml:"-"`
connLock sync.Mutex `yaml:"-"`
writeLock sync.Mutex `yaml:"-"`
}
func (az *AppService) Conn() *websocket.Conn {
return az.conn
}
const CloseConnReplaced = 4001
var upgrader = websocket.Upgrader{}
func syncWebsocket(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
errMissingToken.Write(w)
return
}
az, ok := cfg.byASToken[authHeader[len("Bearer "):]]
if !ok {
errUnknownToken.Write(w)
return
}
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Failed to upgrade websocket request:", err)
return
}
log.Println(az.ID, "connected to websocket")
defer func() {
log.Println(az.ID, "disconnected from websocket")
az.connLock.Lock()
if az.conn == ws {
az.conn = nil
err := az.stopSyncProxy()
if err != nil {
log.Println("Error requesting syncproxy stop after", az.ID, "disconnected:", err)
}
}
az.connLock.Unlock()
_ = ws.Close()
}()
err = ws.WriteMessage(websocket.TextMessage, []byte(`{"status": "connected"}`))
if err != nil {
log.Printf("Failed to write welcome status message to %s: %v", az.ID, err)
}
az.connLock.Lock()
if az.conn != nil {
go func(oldConn *websocket.Conn) {
msg := websocket.FormatCloseMessage(CloseConnReplaced, `{"command": "disconnect", "status": "conn_replaced"}`)
_ = oldConn.WriteControl(websocket.CloseMessage, msg, time.Now().Add(3*time.Second))
_ = oldConn.Close()
}(az.conn)
}
az.conn = ws
az.connLock.Unlock()
for {
var msg appservice.WebsocketCommand
err = ws.ReadJSON(&msg)
if err != nil {
log.Println("Error reading from websocket:", err)
break
}
go handleCommand(az, ws, &msg)
}
}
func handleCommand(az *AppService, ws *websocket.Conn, msg *appservice.WebsocketCommand) {
defer func() {
panicErr := recover()
if panicErr != nil {
log.Printf("Panic while responding to command %s in request #%d: %v\n%s", msg.Command, msg.ReqID, panicErr, debug.Stack())
}
}()
resp, err := actuallyHandleCommand(az, msg)
if msg.ReqID != 0 {
respPayload := appservice.WebsocketRequest{
ReqID: msg.ReqID,
Command: "response",
Data: resp,
}
if err != nil {
respPayload.Command = "error"
respPayload.Data = map[string]interface{}{
"message": err.Error(),
}
}
az.writeLock.Lock()
log.Printf("Sending response %+v", respPayload)
err = ws.WriteJSON(&respPayload)
az.writeLock.Unlock()
if err != nil {
log.Printf("Failed to send response to req #%d: %v", msg.ReqID, err)
}
}
}
type PingData struct {
Timestamp int64 `json:"timestamp"`
}
func actuallyHandleCommand(az *AppService, msg *appservice.WebsocketCommand) (resp interface{}, err error) {
defer func() {
panicErr := recover()
if panicErr != nil {
log.Printf("Panic while handling command %s in request #%d: %v\n%s", msg.Command, msg.ReqID, panicErr, debug.Stack())
if err == nil {
err = fmt.Errorf("internal server error")
}
}
}()
switch msg.Command {
case "start_sync":
err = az.startSyncProxy(msg.Data)
if err != nil {
log.Println("Error forwarding", az.ID, "sync proxy start request:", err)
}
case "ping":
var req PingData
jsonErr := json.Unmarshal(msg.Data, &req)
now := time.Now()
if req.Timestamp > 0 {
pingStart := time.Unix(0, req.Timestamp * int64(time.Millisecond))
log.Printf("Received ping from %s in %s", az.ID, now.Sub(pingStart))
} else {
log.Printf("Received ping from %s with no timestamp (json error: %v)", az.ID, jsonErr)
}
resp = &PingData{now.UnixNano() / int64(time.Millisecond)}
default:
log.Printf("Unknown command %s in request #%d from websocket. Data: %s", msg.Command, msg.ReqID, msg.Data)
err = fmt.Errorf("unknown command %s", msg.Command)
}
return
}