From 4818998e502ad9f0d6c2fa260474a99118dcc5fa Mon Sep 17 00:00:00 2001 From: Sorunome Date: Thu, 7 Oct 2021 14:33:36 +0200 Subject: [PATCH] feat: advertise the low-bandwidth proxy in the /versions response --- cmd/proxy/proxy.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/cmd/proxy/proxy.go b/cmd/proxy/proxy.go index fdc392d..e392b32 100644 --- a/cmd/proxy/proxy.go +++ b/cmd/proxy/proxy.go @@ -19,11 +19,13 @@ import ( "bytes" "context" "crypto/tls" + "fmt" "io" "io/ioutil" "net/http" "net/http/httputil" "net/url" + "strings" "sync/atomic" "time" @@ -165,6 +167,25 @@ func writeResponse(cfg *Config, res *http.Response, w http.ResponseWriter) []byt } } } + if res.Request.URL.Path == "/_matrix/client/versions" { + dtlsPortParts := strings.Split(cfg.ListenDTLS, ":") + tuples := []struct { + Key string + Value interface{} + }{ + {`org\.matrix\.msc3079\.low_bandwidth.dtls`, dtlsPortParts[len(dtlsPortParts) - 1]}, + {`org\.matrix\.msc3079\.low_bandwidth.cbor_enum_version`, 1}, + {`org\.matrix\.msc3079\.low_bandwidth.coap_enum_version`, 1}, + } + for _, t := range tuples { + jsonBody2, err := sjson.SetBytes(jsonBody, t.Key, t.Value) + if err != nil { + logrus.WithError(err).Error("failed to advertise low-bandwidth support") + } else { + jsonBody = jsonBody2 + } + } + } if len(jsonBody) > 0 { resBody, err = cfg.CBORCodec.JSONToCBOR(bytes.NewBuffer(jsonBody)) if err != nil { @@ -291,6 +312,39 @@ func RunProxyServer(cfg *Config) error { logrus.Infof("TCP proxy %v", req.URL.String()) req.Host = localURL.Host }, + ModifyResponse: func(res *http.Response) error { + if res.Request.URL.Path == "/_matrix/client/versions" { + logrus.Info("Got versions response....") + jsonBody, err := ioutil.ReadAll(res.Body) + if err != nil { + logrus.WithError(err).Error("failed to read the remote response body") + return nil + } + dtlsPortParts := strings.Split(cfg.ListenDTLS, ":") + tuples := []struct { + Key string + Value interface{} + }{ + {`org\.matrix\.msc3079\.low_bandwidth.dtls`, dtlsPortParts[len(dtlsPortParts) - 1]}, + {`org\.matrix\.msc3079\.low_bandwidth.cbor_enum_version`, 1}, + {`org\.matrix\.msc3079\.low_bandwidth.coap_enum_version`, 1}, + } + for _, t := range tuples { + jsonBody2, err := sjson.SetBytes(jsonBody, t.Key, t.Value) + if err != nil { + logrus.WithError(err).Error("failed to advertise low-bandwidth support") + } else { + jsonBody = jsonBody2 + } + } + buf := bytes.NewBufferString("") + buf.Write(jsonBody) + res.Body = ioutil.NopCloser(buf) + res.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())} + logrus.Info("Done modifying response") + } + return nil + }, } if cfg.AdvertiseOnHTTPS { tlsServer := &http.Server{