| 1 |
// Copyright (c) 2022 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package appservice |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"encoding/json" |
| 12 |
"errors" |
| 13 |
"fmt" |
| 14 |
"net/http" |
| 15 |
"net/url" |
| 16 |
"path/filepath" |
| 17 |
"strings" |
| 18 |
"sync" |
| 19 |
"sync/atomic" |
| 20 |
"time" |
| 21 |
|
| 22 |
"github.com/gorilla/websocket" |
| 23 |
"github.com/tidwall/gjson" |
| 24 |
"github.com/tidwall/sjson" |
| 25 |
) |
| 26 |
|
| 27 |
type WebsocketRequest struct { |
| 28 |
ReqID int `json:"id,omitempty"` |
| 29 |
Command string `json:"command"` |
| 30 |
Data interface{} `json:"data"` |
| 31 |
|
| 32 |
Deadline time.Duration `json:"-"` |
| 33 |
} |
| 34 |
|
| 35 |
type WebsocketCommand struct { |
| 36 |
ReqID int `json:"id,omitempty"` |
| 37 |
Command string `json:"command"` |
| 38 |
Data json.RawMessage `json:"data"` |
| 39 |
} |
| 40 |
|
| 41 |
func (wsc *WebsocketCommand) MakeResponse(ok bool, data interface{}) *WebsocketRequest { |
| 42 |
if wsc.ReqID == 0 { |
| 43 |
return nil |
| 44 |
} |
| 45 |
cmd := "response" |
| 46 |
if !ok { |
| 47 |
cmd = "error" |
| 48 |
} |
| 49 |
if err, isError := data.(error); isError { |
| 50 |
var errorData json.RawMessage |
| 51 |
var jsonErr error |
| 52 |
unwrappedErr := err |
| 53 |
var prefixMessage string |
| 54 |
for unwrappedErr != nil { |
| 55 |
errorData, jsonErr = json.Marshal(unwrappedErr) |
| 56 |
if errorData != nil && len(errorData) > 2 && jsonErr == nil { |
| 57 |
prefixMessage = strings.Replace(err.Error(), unwrappedErr.Error(), "", 1) |
| 58 |
prefixMessage = strings.TrimRight(prefixMessage, ": ") |
| 59 |
break |
| 60 |
} |
| 61 |
unwrappedErr = errors.Unwrap(unwrappedErr) |
| 62 |
} |
| 63 |
if errorData != nil { |
| 64 |
if !gjson.GetBytes(errorData, "message").Exists() { |
| 65 |
errorData, _ = sjson.SetBytes(errorData, "message", err.Error()) |
| 66 |
} // else: marshaled error contains a message already |
| 67 |
} else { |
| 68 |
errorData, _ = sjson.SetBytes(nil, "message", err.Error()) |
| 69 |
} |
| 70 |
if len(prefixMessage) > 0 { |
| 71 |
errorData, _ = sjson.SetBytes(errorData, "prefix_message", prefixMessage) |
| 72 |
} |
| 73 |
data = errorData |
| 74 |
} |
| 75 |
return &WebsocketRequest{ |
| 76 |
ReqID: wsc.ReqID, |
| 77 |
Command: cmd, |
| 78 |
Data: data, |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
type WebsocketTransaction struct { |
| 83 |
Status string `json:"status"` |
| 84 |
TxnID string `json:"txn_id"` |
| 85 |
Transaction |
| 86 |
} |
| 87 |
|
| 88 |
type WebsocketMessage struct { |
| 89 |
WebsocketTransaction |
| 90 |
WebsocketCommand |
| 91 |
} |
| 92 |
|
| 93 |
type MeowWebsocketCloseCode string |
| 94 |
|
| 95 |
const ( |
| 96 |
MeowServerShuttingDown MeowWebsocketCloseCode = "server_shutting_down" |
| 97 |
MeowConnectionReplaced MeowWebsocketCloseCode = "conn_replaced" |
| 98 |
) |
| 99 |
|
| 100 |
var ( |
| 101 |
ErrWebsocketManualStop = errors.New("the websocket was disconnected manually") |
| 102 |
ErrWebsocketOverridden = errors.New("a new call to StartWebsocket overrode the previous connection") |
| 103 |
ErrWebsocketUnknownError = errors.New("an unknown error occurred") |
| 104 |
|
| 105 |
ErrWebsocketNotConnected = errors.New("websocket not connected") |
| 106 |
ErrWebsocketClosed = errors.New("websocket closed before response received") |
| 107 |
) |
| 108 |
|
| 109 |
func (mwcc MeowWebsocketCloseCode) String() string { |
| 110 |
switch mwcc { |
| 111 |
case MeowServerShuttingDown: |
| 112 |
return "the server is shutting down" |
| 113 |
case MeowConnectionReplaced: |
| 114 |
return "the connection was replaced by another client" |
| 115 |
default: |
| 116 |
return string(mwcc) |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
type CloseCommand struct { |
| 121 |
Code int `json:"-"` |
| 122 |
Command string `json:"command"` |
| 123 |
Status MeowWebsocketCloseCode `json:"status"` |
| 124 |
} |
| 125 |
|
| 126 |
func (cc CloseCommand) Error() string { |
| 127 |
return fmt.Sprintf("websocket: close %d: %s", cc.Code, cc.Status.String()) |
| 128 |
} |
| 129 |
|
| 130 |
func parseCloseError(err error) error { |
| 131 |
closeError := &websocket.CloseError{} |
| 132 |
if !errors.As(err, &closeError) { |
| 133 |
return err |
| 134 |
} |
| 135 |
var closeCommand CloseCommand |
| 136 |
closeCommand.Code = closeError.Code |
| 137 |
closeCommand.Command = "disconnect" |
| 138 |
if len(closeError.Text) > 0 { |
| 139 |
jsonErr := json.Unmarshal([]byte(closeError.Text), &closeCommand) |
| 140 |
if jsonErr != nil { |
| 141 |
return err |
| 142 |
} |
| 143 |
} |
| 144 |
if len(closeCommand.Status) == 0 { |
| 145 |
if closeCommand.Code == 4001 { |
| 146 |
closeCommand.Status = MeowConnectionReplaced |
| 147 |
} else if closeCommand.Code == websocket.CloseServiceRestart { |
| 148 |
closeCommand.Status = MeowServerShuttingDown |
| 149 |
} |
| 150 |
} |
| 151 |
return &closeCommand |
| 152 |
} |
| 153 |
|
| 154 |
func (as *AppService) HasWebsocket() bool { |
| 155 |
return as.ws != nil |
| 156 |
} |
| 157 |
|
| 158 |
func (as *AppService) SendWebsocket(cmd *WebsocketRequest) error { |
| 159 |
ws := as.ws |
| 160 |
if cmd == nil { |
| 161 |
return nil |
| 162 |
} else if ws == nil { |
| 163 |
return ErrWebsocketNotConnected |
| 164 |
} |
| 165 |
as.wsWriteLock.Lock() |
| 166 |
defer as.wsWriteLock.Unlock() |
| 167 |
if cmd.Deadline == 0 { |
| 168 |
cmd.Deadline = 3 * time.Minute |
| 169 |
} |
| 170 |
_ = ws.SetWriteDeadline(time.Now().Add(cmd.Deadline)) |
| 171 |
return ws.WriteJSON(cmd) |
| 172 |
} |
| 173 |
|
| 174 |
func (as *AppService) clearWebsocketResponseWaiters() { |
| 175 |
as.websocketRequestsLock.Lock() |
| 176 |
for _, waiter := range as.websocketRequests { |
| 177 |
waiter <- &WebsocketCommand{Command: "__websocket_closed"} |
| 178 |
} |
| 179 |
as.websocketRequests = make(map[int]chan<- *WebsocketCommand) |
| 180 |
as.websocketRequestsLock.Unlock() |
| 181 |
} |
| 182 |
|
| 183 |
func (as *AppService) addWebsocketResponseWaiter(reqID int, waiter chan<- *WebsocketCommand) { |
| 184 |
as.websocketRequestsLock.Lock() |
| 185 |
as.websocketRequests[reqID] = waiter |
| 186 |
as.websocketRequestsLock.Unlock() |
| 187 |
} |
| 188 |
|
| 189 |
func (as *AppService) removeWebsocketResponseWaiter(reqID int, waiter chan<- *WebsocketCommand) { |
| 190 |
as.websocketRequestsLock.Lock() |
| 191 |
existingWaiter, ok := as.websocketRequests[reqID] |
| 192 |
if ok && existingWaiter == waiter { |
| 193 |
delete(as.websocketRequests, reqID) |
| 194 |
} |
| 195 |
close(waiter) |
| 196 |
as.websocketRequestsLock.Unlock() |
| 197 |
} |
| 198 |
|
| 199 |
type ErrorResponse struct { |
| 200 |
Code string `json:"code"` |
| 201 |
Message string `json:"message"` |
| 202 |
} |
| 203 |
|
| 204 |
func (er *ErrorResponse) Error() string { |
| 205 |
return fmt.Sprintf("%s: %s", er.Code, er.Message) |
| 206 |
} |
| 207 |
|
| 208 |
func (as *AppService) RequestWebsocket(ctx context.Context, cmd *WebsocketRequest, response interface{}) error { |
| 209 |
cmd.ReqID = int(atomic.AddInt32(&as.websocketRequestID, 1)) |
| 210 |
respChan := make(chan *WebsocketCommand, 1) |
| 211 |
as.addWebsocketResponseWaiter(cmd.ReqID, respChan) |
| 212 |
defer as.removeWebsocketResponseWaiter(cmd.ReqID, respChan) |
| 213 |
err := as.SendWebsocket(cmd) |
| 214 |
if err != nil { |
| 215 |
return err |
| 216 |
} |
| 217 |
select { |
| 218 |
case resp := <-respChan: |
| 219 |
if resp.Command == "__websocket_closed" { |
| 220 |
return ErrWebsocketClosed |
| 221 |
} else if resp.Command == "error" { |
| 222 |
var respErr ErrorResponse |
| 223 |
err = json.Unmarshal(resp.Data, &respErr) |
| 224 |
if err != nil { |
| 225 |
return fmt.Errorf("failed to parse error JSON: %w", err) |
| 226 |
} |
| 227 |
return &respErr |
| 228 |
} else if response != nil { |
| 229 |
err = json.Unmarshal(resp.Data, &response) |
| 230 |
if err != nil { |
| 231 |
return fmt.Errorf("failed to parse response JSON: %w", err) |
| 232 |
} |
| 233 |
return nil |
| 234 |
} else { |
| 235 |
return nil |
| 236 |
} |
| 237 |
case <-ctx.Done(): |
| 238 |
return ctx.Err() |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
func (as *AppService) unknownCommandHandler(cmd WebsocketCommand) (bool, interface{}) { |
| 243 |
as.Log.Warnfln("No handler for websocket command %s (%d)", cmd.Command, cmd.ReqID) |
| 244 |
return false, fmt.Errorf("unknown request type") |
| 245 |
} |
| 246 |
|
| 247 |
func (as *AppService) SetWebsocketCommandHandler(cmd string, handler WebsocketHandler) { |
| 248 |
as.websocketHandlersLock.Lock() |
| 249 |
as.websocketHandlers[cmd] = handler |
| 250 |
as.websocketHandlersLock.Unlock() |
| 251 |
} |
| 252 |
|
| 253 |
func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn) { |
| 254 |
defer stopFunc(ErrWebsocketUnknownError) |
| 255 |
for { |
| 256 |
var msg WebsocketMessage |
| 257 |
err := ws.ReadJSON(&msg) |
| 258 |
if err != nil { |
| 259 |
as.Log.Debugln("Error reading from websocket:", err) |
| 260 |
stopFunc(parseCloseError(err)) |
| 261 |
return |
| 262 |
} |
| 263 |
if msg.Command == "" || msg.Command == "transaction" { |
| 264 |
if msg.TxnID == "" || !as.txnIDC.IsProcessed(msg.TxnID) { |
| 265 |
as.handleTransaction(msg.TxnID, &msg.Transaction) |
| 266 |
} else { |
| 267 |
as.Log.Debugfln("Ignoring duplicate transaction %s (%s)", msg.TxnID, msg.Transaction.ContentString()) |
| 268 |
} |
| 269 |
go func() { |
| 270 |
err = as.SendWebsocket(msg.MakeResponse(true, map[string]interface{}{"txn_id": msg.TxnID})) |
| 271 |
if err != nil { |
| 272 |
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err) |
| 273 |
} |
| 274 |
}() |
| 275 |
} else if msg.Command == "connect" { |
| 276 |
as.Log.Debugln("Websocket connect confirmation received") |
| 277 |
} else if msg.Command == "response" || msg.Command == "error" { |
| 278 |
as.websocketRequestsLock.RLock() |
| 279 |
respChan, ok := as.websocketRequests[msg.ReqID] |
| 280 |
if ok { |
| 281 |
select { |
| 282 |
case respChan <- &msg.WebsocketCommand: |
| 283 |
default: |
| 284 |
as.Log.Warnfln("Failed to handle response to %d: channel didn't accept response", msg.ReqID) |
| 285 |
} |
| 286 |
} else { |
| 287 |
as.Log.Warnfln("Dropping response to %d: unknown request ID", msg.ReqID) |
| 288 |
} |
| 289 |
as.websocketRequestsLock.RUnlock() |
| 290 |
} else { |
| 291 |
as.websocketHandlersLock.RLock() |
| 292 |
handler, ok := as.websocketHandlers[msg.Command] |
| 293 |
as.websocketHandlersLock.RUnlock() |
| 294 |
if !ok { |
| 295 |
handler = as.unknownCommandHandler |
| 296 |
} |
| 297 |
go func() { |
| 298 |
okResp, data := handler(msg.WebsocketCommand) |
| 299 |
err = as.SendWebsocket(msg.MakeResponse(okResp, data)) |
| 300 |
if err != nil { |
| 301 |
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err) |
| 302 |
} else if okResp { |
| 303 |
as.Log.Debugfln("Sent success response to %s %d", msg.Command, msg.ReqID) |
| 304 |
} else { |
| 305 |
as.Log.Debugfln("Sent error response to %s %d", msg.Command, msg.ReqID) |
| 306 |
} |
| 307 |
}() |
| 308 |
} |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
func (as *AppService) StartWebsocket(baseURL string, onConnect func()) error { |
| 313 |
parsed, err := url.Parse(baseURL) |
| 314 |
if err != nil { |
| 315 |
return fmt.Errorf("failed to parse URL: %w", err) |
| 316 |
} |
| 317 |
parsed.Path = filepath.Join(parsed.Path, "_matrix/client/unstable/fi.mau.as_sync") |
| 318 |
if parsed.Scheme == "http" { |
| 319 |
parsed.Scheme = "ws" |
| 320 |
} else if parsed.Scheme == "https" { |
| 321 |
parsed.Scheme = "wss" |
| 322 |
} |
| 323 |
ws, resp, err := websocket.DefaultDialer.Dial(parsed.String(), http.Header{ |
| 324 |
"Authorization": []string{fmt.Sprintf("Bearer %s", as.Registration.AppToken)}, |
| 325 |
"User-Agent": []string{as.BotClient().UserAgent}, |
| 326 |
|
| 327 |
"X-Mautrix-Process-ID": []string{as.ProcessID}, |
| 328 |
"X-Mautrix-Websocket-Version": []string{"3"}, |
| 329 |
}) |
| 330 |
if resp != nil && resp.StatusCode >= 400 { |
| 331 |
var errResp Error |
| 332 |
err = json.NewDecoder(resp.Body).Decode(&errResp) |
| 333 |
if err != nil { |
| 334 |
return fmt.Errorf("websocket request returned HTTP %d with non-JSON body", resp.StatusCode) |
| 335 |
} else { |
| 336 |
return fmt.Errorf("websocket request returned %s (HTTP %d): %s", errResp.ErrorCode, resp.StatusCode, errResp.Message) |
| 337 |
} |
| 338 |
} else if err != nil { |
| 339 |
return fmt.Errorf("failed to open websocket: %w", err) |
| 340 |
} |
| 341 |
if as.StopWebsocket != nil { |
| 342 |
as.StopWebsocket(ErrWebsocketOverridden) |
| 343 |
} |
| 344 |
closeChan := make(chan error) |
| 345 |
closeChanOnce := sync.Once{} |
| 346 |
stopFunc := func(err error) { |
| 347 |
closeChanOnce.Do(func() { |
| 348 |
closeChan <- err |
| 349 |
}) |
| 350 |
} |
| 351 |
as.ws = ws |
| 352 |
as.StopWebsocket = stopFunc |
| 353 |
as.PrepareWebsocket() |
| 354 |
as.Log.Debugln("Appservice transaction websocket connected") |
| 355 |
|
| 356 |
go as.consumeWebsocket(stopFunc, ws) |
| 357 |
|
| 358 |
if onConnect != nil { |
| 359 |
onConnect() |
| 360 |
} |
| 361 |
|
| 362 |
closeErr := <-closeChan |
| 363 |
|
| 364 |
if as.ws == ws { |
| 365 |
as.clearWebsocketResponseWaiters() |
| 366 |
as.ws = nil |
| 367 |
} |
| 368 |
|
| 369 |
err = ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, "")) |
| 370 |
if err != nil && !errors.Is(err, websocket.ErrCloseSent) { |
| 371 |
as.Log.Warnln("Error writing close message to websocket:", err) |
| 372 |
} |
| 373 |
err = ws.Close() |
| 374 |
if err != nil { |
| 375 |
as.Log.Warnln("Error closing websocket:", err) |
| 376 |
} |
| 377 |
return closeErr |
| 378 |
} |