| 1 |
// Copyright (c) 2021 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 |
"io/ioutil" |
| 14 |
"net/http" |
| 15 |
"strings" |
| 16 |
"time" |
| 17 |
|
| 18 |
"github.com/gorilla/mux" |
| 19 |
|
| 20 |
"maunium.net/go/mautrix" |
| 21 |
"maunium.net/go/mautrix/event" |
| 22 |
"maunium.net/go/mautrix/id" |
| 23 |
) |
| 24 |
|
| 25 |
// Start starts the HTTP server that listens for calls from the Matrix homeserver. |
| 26 |
func (as *AppService) Start() { |
| 27 |
as.Router.HandleFunc("/transactions/{txnID}", as.PutTransaction).Methods(http.MethodPut) |
| 28 |
as.Router.HandleFunc("/rooms/{roomAlias}", as.GetRoom).Methods(http.MethodGet) |
| 29 |
as.Router.HandleFunc("/users/{userID}", as.GetUser).Methods(http.MethodGet) |
| 30 |
as.Router.HandleFunc("/_matrix/app/v1/transactions/{txnID}", as.PutTransaction).Methods(http.MethodPut) |
| 31 |
as.Router.HandleFunc("/_matrix/app/v1/rooms/{roomAlias}", as.GetRoom).Methods(http.MethodGet) |
| 32 |
as.Router.HandleFunc("/_matrix/app/v1/users/{userID}", as.GetUser).Methods(http.MethodGet) |
| 33 |
as.Router.HandleFunc("/_matrix/mau/live", as.GetLive).Methods(http.MethodGet) |
| 34 |
as.Router.HandleFunc("/_matrix/mau/ready", as.GetReady).Methods(http.MethodGet) |
| 35 |
|
| 36 |
var err error |
| 37 |
as.server = &http.Server{ |
| 38 |
Addr: as.Host.Address(), |
| 39 |
Handler: as.Router, |
| 40 |
} |
| 41 |
as.Log.Infoln("Listening on", as.Host.Address()) |
| 42 |
if len(as.Host.TLSCert) == 0 || len(as.Host.TLSKey) == 0 { |
| 43 |
err = as.server.ListenAndServe() |
| 44 |
} else { |
| 45 |
err = as.server.ListenAndServeTLS(as.Host.TLSCert, as.Host.TLSKey) |
| 46 |
} |
| 47 |
if err != nil && err.Error() != "http: Server closed" { |
| 48 |
as.Log.Fatalln("Error while listening:", err) |
| 49 |
} else { |
| 50 |
as.Log.Debugln("Listener stopped.") |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func (as *AppService) Stop() { |
| 55 |
if as.server == nil { |
| 56 |
return |
| 57 |
} |
| 58 |
|
| 59 |
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 60 |
defer cancel() |
| 61 |
_ = as.server.Shutdown(ctx) |
| 62 |
as.server = nil |
| 63 |
} |
| 64 |
|
| 65 |
// CheckServerToken checks if the given request originated from the Matrix homeserver. |
| 66 |
func (as *AppService) CheckServerToken(w http.ResponseWriter, r *http.Request) (isValid bool) { |
| 67 |
authHeader := r.Header.Get("Authorization") |
| 68 |
if len(authHeader) > 0 && strings.HasPrefix(authHeader, "Bearer ") { |
| 69 |
isValid = authHeader[len("Bearer "):] == as.Registration.ServerToken |
| 70 |
} else { |
| 71 |
queryToken := r.URL.Query().Get("access_token") |
| 72 |
if len(queryToken) > 0 { |
| 73 |
isValid = queryToken == as.Registration.ServerToken |
| 74 |
} else { |
| 75 |
Error{ |
| 76 |
ErrorCode: ErrUnknownToken, |
| 77 |
HTTPStatus: http.StatusForbidden, |
| 78 |
Message: "Missing access token", |
| 79 |
}.Write(w) |
| 80 |
return |
| 81 |
} |
| 82 |
} |
| 83 |
if !isValid { |
| 84 |
Error{ |
| 85 |
ErrorCode: ErrUnknownToken, |
| 86 |
HTTPStatus: http.StatusForbidden, |
| 87 |
Message: "Incorrect access token", |
| 88 |
}.Write(w) |
| 89 |
} |
| 90 |
return |
| 91 |
} |
| 92 |
|
| 93 |
// PutTransaction handles a /transactions PUT call from the homeserver. |
| 94 |
func (as *AppService) PutTransaction(w http.ResponseWriter, r *http.Request) { |
| 95 |
if !as.CheckServerToken(w, r) { |
| 96 |
return |
| 97 |
} |
| 98 |
|
| 99 |
vars := mux.Vars(r) |
| 100 |
txnID := vars["txnID"] |
| 101 |
if len(txnID) == 0 { |
| 102 |
Error{ |
| 103 |
ErrorCode: ErrNoTransactionID, |
| 104 |
HTTPStatus: http.StatusBadRequest, |
| 105 |
Message: "Missing transaction ID", |
| 106 |
}.Write(w) |
| 107 |
return |
| 108 |
} |
| 109 |
defer r.Body.Close() |
| 110 |
body, err := ioutil.ReadAll(r.Body) |
| 111 |
if err != nil || len(body) == 0 { |
| 112 |
Error{ |
| 113 |
ErrorCode: ErrNotJSON, |
| 114 |
HTTPStatus: http.StatusBadRequest, |
| 115 |
Message: "Missing request body", |
| 116 |
}.Write(w) |
| 117 |
return |
| 118 |
} |
| 119 |
if as.txnIDC.IsProcessed(txnID) { |
| 120 |
// Duplicate transaction ID: no-op |
| 121 |
WriteBlankOK(w) |
| 122 |
as.Log.Debugfln("Ignoring duplicate transaction %s", txnID) |
| 123 |
return |
| 124 |
} |
| 125 |
|
| 126 |
var txn Transaction |
| 127 |
err = json.Unmarshal(body, &txn) |
| 128 |
if err != nil { |
| 129 |
as.Log.Warnfln("Failed to parse JSON of transaction %s: %v", txnID, err) |
| 130 |
Error{ |
| 131 |
ErrorCode: ErrBadJSON, |
| 132 |
HTTPStatus: http.StatusBadRequest, |
| 133 |
Message: "Failed to parse body JSON", |
| 134 |
}.Write(w) |
| 135 |
} else { |
| 136 |
as.handleTransaction(txnID, &txn) |
| 137 |
WriteBlankOK(w) |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
func (as *AppService) handleTransaction(id string, txn *Transaction) { |
| 142 |
as.Log.Debugfln("Starting handling of transaction %s (%s)", id, txn.ContentString()) |
| 143 |
if as.Registration.EphemeralEvents { |
| 144 |
if txn.EphemeralEvents != nil { |
| 145 |
as.handleEvents(txn.EphemeralEvents, event.EphemeralEventType) |
| 146 |
} else if txn.MSC2409EphemeralEvents != nil { |
| 147 |
as.handleEvents(txn.MSC2409EphemeralEvents, event.EphemeralEventType) |
| 148 |
} |
| 149 |
} |
| 150 |
as.handleEvents(txn.Events, event.UnknownEventType) |
| 151 |
if txn.DeviceLists != nil { |
| 152 |
as.handleDeviceLists(txn.DeviceLists) |
| 153 |
} else if txn.MSC3202DeviceLists != nil { |
| 154 |
as.handleDeviceLists(txn.MSC3202DeviceLists) |
| 155 |
} |
| 156 |
if txn.DeviceOTKCount != nil { |
| 157 |
as.handleOTKCounts(txn.DeviceOTKCount) |
| 158 |
} else if txn.MSC3202DeviceOTKCount != nil { |
| 159 |
as.handleOTKCounts(txn.MSC3202DeviceOTKCount) |
| 160 |
} |
| 161 |
as.txnIDC.MarkProcessed(id) |
| 162 |
} |
| 163 |
|
| 164 |
func (as *AppService) handleOTKCounts(otks map[id.UserID]mautrix.OTKCount) { |
| 165 |
for userID, otkCounts := range otks { |
| 166 |
otkCounts.UserID = userID |
| 167 |
select { |
| 168 |
case as.OTKCounts <- &otkCounts: |
| 169 |
default: |
| 170 |
as.Log.Warnfln("Dropped OTK count update for %s because channel is full", userID) |
| 171 |
} |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
func (as *AppService) handleDeviceLists(dl *mautrix.DeviceLists) { |
| 176 |
select { |
| 177 |
case as.DeviceLists <- dl: |
| 178 |
default: |
| 179 |
as.Log.Warnln("Dropped device list update because channel is full") |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
func (as *AppService) handleEvents(evts []*event.Event, defaultTypeClass event.TypeClass) { |
| 184 |
for _, evt := range evts { |
| 185 |
if len(evt.ToUserID) > 0 { |
| 186 |
evt.Type.Class = event.ToDeviceEventType |
| 187 |
} else if defaultTypeClass != event.UnknownEventType { |
| 188 |
evt.Type.Class = defaultTypeClass |
| 189 |
} else if evt.StateKey != nil { |
| 190 |
evt.Type.Class = event.StateEventType |
| 191 |
} else { |
| 192 |
evt.Type.Class = event.MessageEventType |
| 193 |
} |
| 194 |
err := evt.Content.ParseRaw(evt.Type) |
| 195 |
if errors.Is(err, event.ErrUnsupportedContentType) { |
| 196 |
as.Log.Debugfln("Not parsing content of %s: %v", evt.ID, err) |
| 197 |
} else if err != nil { |
| 198 |
as.Log.Debugfln("Failed to parse content of %s (type %s): %v", evt.ID, evt.Type.Type, err) |
| 199 |
} |
| 200 |
|
| 201 |
if _, ok := CheckpointTypes[evt.Type]; ok { |
| 202 |
go as.SendMessageSendCheckpoint(evt, StepBridge, 0) |
| 203 |
} |
| 204 |
|
| 205 |
if evt.Type.IsState() { |
| 206 |
// TODO remove this check after https://github.com/matrix-org/synapse/pull/11265 |
| 207 |
historical, ok := evt.Content.Raw["org.matrix.msc2716.historical"].(bool) |
| 208 |
if !ok || !historical { |
| 209 |
as.UpdateState(evt) |
| 210 |
} |
| 211 |
} |
| 212 |
as.Events <- evt |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
// GetRoom handles a /rooms GET call from the homeserver. |
| 217 |
func (as *AppService) GetRoom(w http.ResponseWriter, r *http.Request) { |
| 218 |
if !as.CheckServerToken(w, r) { |
| 219 |
return |
| 220 |
} |
| 221 |
|
| 222 |
vars := mux.Vars(r) |
| 223 |
roomAlias := vars["roomAlias"] |
| 224 |
ok := as.QueryHandler.QueryAlias(roomAlias) |
| 225 |
if ok { |
| 226 |
WriteBlankOK(w) |
| 227 |
} else { |
| 228 |
Error{ |
| 229 |
ErrorCode: ErrUnknown, |
| 230 |
HTTPStatus: http.StatusNotFound, |
| 231 |
}.Write(w) |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// GetUser handles a /users GET call from the homeserver. |
| 236 |
func (as *AppService) GetUser(w http.ResponseWriter, r *http.Request) { |
| 237 |
if !as.CheckServerToken(w, r) { |
| 238 |
return |
| 239 |
} |
| 240 |
|
| 241 |
vars := mux.Vars(r) |
| 242 |
userID := id.UserID(vars["userID"]) |
| 243 |
ok := as.QueryHandler.QueryUser(userID) |
| 244 |
if ok { |
| 245 |
WriteBlankOK(w) |
| 246 |
} else { |
| 247 |
Error{ |
| 248 |
ErrorCode: ErrUnknown, |
| 249 |
HTTPStatus: http.StatusNotFound, |
| 250 |
}.Write(w) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
func (as *AppService) GetLive(w http.ResponseWriter, r *http.Request) { |
| 255 |
w.Header().Add("Content-Type", "application/json") |
| 256 |
if as.Live { |
| 257 |
w.WriteHeader(http.StatusOK) |
| 258 |
} else { |
| 259 |
w.WriteHeader(http.StatusInternalServerError) |
| 260 |
} |
| 261 |
w.Write([]byte("{}")) |
| 262 |
} |
| 263 |
|
| 264 |
func (as *AppService) GetReady(w http.ResponseWriter, r *http.Request) { |
| 265 |
w.Header().Add("Content-Type", "application/json") |
| 266 |
if as.Ready { |
| 267 |
w.WriteHeader(http.StatusOK) |
| 268 |
} else { |
| 269 |
w.WriteHeader(http.StatusInternalServerError) |
| 270 |
} |
| 271 |
w.Write([]byte("{}")) |
| 272 |
} |