2024-10-17 16:16:37 +01:00
|
|
|
// Copyright 2024 New Vector Ltd.
|
2017-05-26 08:57:09 +01:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
2024-10-17 16:16:37 +01:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
// Please see LICENSE in the repository root for full details.
|
2017-05-26 08:57:09 +01:00
|
|
|
|
|
|
|
package routing
|
|
|
|
|
|
|
|
import (
|
2021-11-24 12:55:44 +00:00
|
|
|
"encoding/json"
|
2017-05-26 08:57:09 +01:00
|
|
|
"net/http"
|
2020-06-16 18:31:38 +01:00
|
|
|
"strings"
|
2017-05-26 08:57:09 +01:00
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
2024-08-16 11:37:59 +01:00
|
|
|
"github.com/matrix-org/dendrite/federationapi/routing"
|
2020-06-12 14:55:57 +01:00
|
|
|
"github.com/matrix-org/dendrite/internal/httputil"
|
2017-05-26 15:49:54 +01:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/storage"
|
2017-05-26 08:57:09 +01:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/types"
|
2020-12-02 17:41:00 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2021-11-24 12:55:44 +00:00
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
2024-08-16 11:37:59 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-06 09:55:01 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/fclient"
|
2023-04-19 15:50:33 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2017-05-26 08:57:09 +01:00
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2019-12-17 16:47:45 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2017-05-26 08:57:09 +01:00
|
|
|
)
|
|
|
|
|
2021-11-24 12:55:44 +00:00
|
|
|
// configResponse is the response to GET /_matrix/media/r0/config
|
|
|
|
// https://matrix.org/docs/spec/client_server/latest#get-matrix-media-r0-config
|
|
|
|
type configResponse struct {
|
2023-03-20 08:24:00 +00:00
|
|
|
UploadSize *config.FileSizeBytes `json:"m.upload.size,omitempty"`
|
2021-11-24 12:55:44 +00:00
|
|
|
}
|
|
|
|
|
2017-08-03 15:10:39 +01:00
|
|
|
// Setup registers the media API HTTP handlers
|
2019-07-03 16:38:50 +01:00
|
|
|
//
|
|
|
|
// Due to Setup being used to call many other functions, a gocyclo nolint is
|
|
|
|
// applied:
|
|
|
|
// nolint: gocyclo
|
2017-09-21 16:20:10 +01:00
|
|
|
func Setup(
|
2024-08-16 11:37:59 +01:00
|
|
|
routers httputil.Routers,
|
2023-03-22 08:21:32 +00:00
|
|
|
cfg *config.Dendrite,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2022-05-05 13:17:38 +01:00
|
|
|
userAPI userapi.MediaUserAPI,
|
2023-04-06 09:55:01 +01:00
|
|
|
client *fclient.Client,
|
2024-08-16 11:37:59 +01:00
|
|
|
federationClient fclient.FederationClient,
|
|
|
|
keyRing gomatrixserverlib.JSONVerifier,
|
2017-09-21 16:20:10 +01:00
|
|
|
) {
|
2023-03-22 08:21:32 +00:00
|
|
|
rateLimits := httputil.NewRateLimits(&cfg.ClientAPI.RateLimiting)
|
2021-11-24 12:55:44 +00:00
|
|
|
|
2024-08-16 11:37:59 +01:00
|
|
|
v3mux := routers.Media.PathPrefix("/{apiversion:(?:r0|v1|v3)}/").Subrouter()
|
|
|
|
v1mux := routers.Client.PathPrefix("/v1/media/").Subrouter()
|
|
|
|
v1fedMux := routers.Federation.PathPrefix("/v1/media/").Subrouter()
|
2017-06-07 00:12:49 +01:00
|
|
|
|
|
|
|
activeThumbnailGeneration := &types.ActiveThumbnailGeneration{
|
|
|
|
PathToResult: map[string]*types.ThumbnailGenerationResult{},
|
|
|
|
}
|
2020-07-08 16:39:50 +01:00
|
|
|
|
|
|
|
uploadHandler := httputil.MakeAuthAPI(
|
2020-06-16 14:10:55 +01:00
|
|
|
"upload", userAPI,
|
2020-08-26 15:38:34 +01:00
|
|
|
func(req *http.Request, dev *userapi.Device) util.JSONResponse {
|
2022-06-07 14:24:04 +01:00
|
|
|
if r := rateLimits.Limit(req, dev); r != nil {
|
2021-11-24 12:55:44 +00:00
|
|
|
return *r
|
|
|
|
}
|
2023-03-22 08:21:32 +00:00
|
|
|
return Upload(req, &cfg.MediaAPI, dev, db, activeThumbnailGeneration)
|
2017-09-28 14:50:40 +01:00
|
|
|
},
|
2020-07-08 16:39:50 +01:00
|
|
|
)
|
|
|
|
|
2021-11-24 12:55:44 +00:00
|
|
|
configHandler := httputil.MakeAuthAPI("config", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
|
2022-06-07 14:24:04 +01:00
|
|
|
if r := rateLimits.Limit(req, device); r != nil {
|
2021-11-24 12:55:44 +00:00
|
|
|
return *r
|
|
|
|
}
|
2023-03-22 08:21:32 +00:00
|
|
|
respondSize := &cfg.MediaAPI.MaxFileSizeBytes
|
|
|
|
if cfg.MediaAPI.MaxFileSizeBytes == 0 {
|
2022-05-02 09:47:16 +01:00
|
|
|
respondSize = nil
|
|
|
|
}
|
2021-11-24 12:55:44 +00:00
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusOK,
|
2022-05-02 09:47:16 +01:00
|
|
|
JSON: configResponse{UploadSize: respondSize},
|
2021-11-24 12:55:44 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-03-02 11:35:35 +00:00
|
|
|
v3mux.Handle("/upload", uploadHandler).Methods(http.MethodPost, http.MethodOptions)
|
|
|
|
v3mux.Handle("/config", configHandler).Methods(http.MethodGet, http.MethodOptions)
|
2017-05-26 08:57:09 +01:00
|
|
|
|
|
|
|
activeRemoteRequests := &types.ActiveRemoteRequests{
|
2017-05-31 16:56:11 +01:00
|
|
|
MXCToResult: map[string]*types.RemoteRequestResult{},
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
2020-06-16 14:29:11 +01:00
|
|
|
|
2024-08-16 11:37:59 +01:00
|
|
|
downloadHandler := makeDownloadAPI("download_unauthed", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, false)
|
2022-03-02 11:35:35 +00:00
|
|
|
v3mux.Handle("/download/{serverName}/{mediaId}", downloadHandler).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
v3mux.Handle("/download/{serverName}/{mediaId}/{downloadName}", downloadHandler).Methods(http.MethodGet, http.MethodOptions)
|
2020-06-16 14:29:11 +01:00
|
|
|
|
2022-03-02 11:35:35 +00:00
|
|
|
v3mux.Handle("/thumbnail/{serverName}/{mediaId}",
|
2024-08-16 11:37:59 +01:00
|
|
|
makeDownloadAPI("thumbnail_unauthed", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, false),
|
2018-03-13 15:55:45 +00:00
|
|
|
).Methods(http.MethodGet, http.MethodOptions)
|
2024-08-16 11:37:59 +01:00
|
|
|
|
|
|
|
// v1 client endpoints requiring auth
|
|
|
|
downloadHandlerAuthed := httputil.MakeHTTPAPI("download", userAPI, cfg.Global.Metrics.Enabled, makeDownloadAPI("download_authed_client", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, false), httputil.WithAuth())
|
|
|
|
v1mux.Handle("/config", configHandler).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
v1mux.Handle("/download/{serverName}/{mediaId}", downloadHandlerAuthed).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
v1mux.Handle("/download/{serverName}/{mediaId}/{downloadName}", downloadHandlerAuthed).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
|
|
|
|
v1mux.Handle("/thumbnail/{serverName}/{mediaId}",
|
|
|
|
httputil.MakeHTTPAPI("thumbnail", userAPI, cfg.Global.Metrics.Enabled, makeDownloadAPI("thumbnail_authed_client", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, false), httputil.WithAuth()),
|
|
|
|
).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
|
|
|
|
// same, but for federation
|
|
|
|
v1fedMux.Handle("/download/{mediaId}", routing.MakeFedHTTPAPI(cfg.Global.ServerName, cfg.Global.IsLocalServerName, keyRing,
|
|
|
|
makeDownloadAPI("download_authed_federation", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, true),
|
|
|
|
)).Methods(http.MethodGet, http.MethodOptions)
|
|
|
|
v1fedMux.Handle("/thumbnail/{mediaId}", routing.MakeFedHTTPAPI(cfg.Global.ServerName, cfg.Global.IsLocalServerName, keyRing,
|
|
|
|
makeDownloadAPI("thumbnail_authed_federation", &cfg.MediaAPI, rateLimits, db, client, federationClient, activeRemoteRequests, activeThumbnailGeneration, true),
|
|
|
|
)).Methods(http.MethodGet, http.MethodOptions)
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
2017-06-07 00:12:49 +01:00
|
|
|
|
2024-08-16 11:37:59 +01:00
|
|
|
var thumbnailCounter = promauto.NewCounterVec(
|
|
|
|
prometheus.CounterOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Subsystem: "mediaapi",
|
|
|
|
Name: "thumbnail",
|
|
|
|
Help: "Total number of media_api requests for thumbnails",
|
|
|
|
},
|
|
|
|
[]string{"code", "type"},
|
|
|
|
)
|
|
|
|
|
|
|
|
var thumbnailSize = promauto.NewHistogramVec(
|
|
|
|
prometheus.HistogramOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Subsystem: "mediaapi",
|
|
|
|
Name: "thumbnail_size_bytes",
|
|
|
|
Help: "Total size of media_api requests for thumbnails",
|
|
|
|
Buckets: []float64{50, 100, 200, 500, 900, 1500, 3000, 6000},
|
|
|
|
},
|
|
|
|
[]string{"code", "type"},
|
|
|
|
)
|
|
|
|
|
|
|
|
var downloadCounter = promauto.NewCounterVec(
|
|
|
|
prometheus.CounterOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Subsystem: "mediaapi",
|
|
|
|
Name: "download",
|
|
|
|
Help: "Total size of media_api requests for full downloads",
|
|
|
|
},
|
|
|
|
[]string{"code", "type"},
|
|
|
|
)
|
|
|
|
|
|
|
|
var downloadSize = promauto.NewHistogramVec(
|
|
|
|
prometheus.HistogramOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Subsystem: "mediaapi",
|
|
|
|
Name: "download_size_bytes",
|
|
|
|
Help: "Total size of media_api requests for full downloads",
|
|
|
|
Buckets: []float64{1500, 3000, 6000, 10_000, 50_000, 100_000},
|
|
|
|
},
|
|
|
|
[]string{"code", "type"},
|
|
|
|
)
|
|
|
|
|
2017-09-21 16:20:10 +01:00
|
|
|
func makeDownloadAPI(
|
|
|
|
name string,
|
2020-08-10 14:18:04 +01:00
|
|
|
cfg *config.MediaAPI,
|
2021-11-24 12:55:44 +00:00
|
|
|
rateLimits *httputil.RateLimits,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2023-04-06 09:55:01 +01:00
|
|
|
client *fclient.Client,
|
2024-08-16 11:37:59 +01:00
|
|
|
fedClient fclient.FederationClient,
|
2017-09-21 16:20:10 +01:00
|
|
|
activeRemoteRequests *types.ActiveRemoteRequests,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
2024-08-16 11:37:59 +01:00
|
|
|
forFederation bool,
|
2017-09-21 16:20:10 +01:00
|
|
|
) http.HandlerFunc {
|
2023-01-23 17:55:12 +00:00
|
|
|
var counterVec *prometheus.CounterVec
|
2024-08-16 11:37:59 +01:00
|
|
|
var sizeVec *prometheus.HistogramVec
|
|
|
|
var requestType string
|
2023-01-23 17:55:12 +00:00
|
|
|
if cfg.Matrix.Metrics.Enabled {
|
2024-08-16 11:37:59 +01:00
|
|
|
split := strings.Split(name, "_")
|
|
|
|
// The first part of the split is either "download" or "thumbnail"
|
|
|
|
name = split[0]
|
|
|
|
// The remainder of the split is something like "authed_download" or "unauthed_thumbnail", etc.
|
|
|
|
// This is used to curry the metrics with the given types.
|
|
|
|
requestType = strings.Join(split[1:], "_")
|
|
|
|
|
|
|
|
counterVec = thumbnailCounter
|
|
|
|
sizeVec = thumbnailSize
|
|
|
|
if name != "thumbnail" {
|
|
|
|
counterVec = downloadCounter
|
|
|
|
sizeVec = downloadSize
|
|
|
|
}
|
2023-01-23 17:55:12 +00:00
|
|
|
}
|
2019-12-18 15:10:53 +00:00
|
|
|
httpHandler := func(w http.ResponseWriter, req *http.Request) {
|
|
|
|
req = util.RequestWithLogging(req)
|
|
|
|
|
2020-05-21 14:40:13 +01:00
|
|
|
// Set internal headers returned regardless of the outcome of the request
|
2019-12-18 15:10:53 +00:00
|
|
|
util.SetCORSHeaders(w)
|
2024-01-10 08:39:13 +00:00
|
|
|
w.Header().Set("Cross-Origin-Resource-Policy", "cross-origin")
|
2019-12-18 15:10:53 +00:00
|
|
|
// Content-Type will be overridden in case of returning file data, else we respond with JSON-formatted errors
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2020-06-16 18:31:38 +01:00
|
|
|
|
2021-11-24 12:55:44 +00:00
|
|
|
// Ratelimit requests
|
2022-03-04 11:03:51 +00:00
|
|
|
// NOTSPEC: The spec says everything at /media/ should be rate limited, but this causes issues with thumbnails (#2243)
|
|
|
|
if name != "thumbnail" {
|
2022-06-07 14:24:04 +01:00
|
|
|
if r := rateLimits.Limit(req, nil); r != nil {
|
2022-03-04 11:03:51 +00:00
|
|
|
if err := json.NewEncoder(w).Encode(r); err != nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.WriteHeader(http.StatusTooManyRequests)
|
2021-11-24 12:55:44 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-12 14:55:57 +01:00
|
|
|
vars, _ := httputil.URLDecodeMapValues(mux.Vars(req))
|
2023-04-19 15:50:33 +01:00
|
|
|
serverName := spec.ServerName(vars["serverName"])
|
2020-06-16 18:31:38 +01:00
|
|
|
|
|
|
|
// For the purposes of loop avoidance, we will return a 404 if allow_remote is set to
|
|
|
|
// false in the query string and the target server name isn't our own.
|
|
|
|
// https://github.com/matrix-org/matrix-doc/pull/1265
|
|
|
|
if allowRemote := req.URL.Query().Get("allow_remote"); strings.ToLower(allowRemote) == "false" {
|
|
|
|
if serverName != cfg.Matrix.ServerName {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-03 09:55:21 +01:00
|
|
|
// Cache media for at least one day.
|
|
|
|
w.Header().Set("Cache-Control", "public,max-age=86400,s-maxage=86400")
|
|
|
|
|
2019-12-18 15:10:53 +00:00
|
|
|
Download(
|
|
|
|
w,
|
|
|
|
req,
|
2020-06-16 18:31:38 +01:00
|
|
|
serverName,
|
2019-12-18 15:10:53 +00:00
|
|
|
types.MediaID(vars["mediaId"]),
|
|
|
|
cfg,
|
|
|
|
db,
|
|
|
|
client,
|
2024-08-16 11:37:59 +01:00
|
|
|
fedClient,
|
2019-12-18 15:10:53 +00:00
|
|
|
activeRemoteRequests,
|
|
|
|
activeThumbnailGeneration,
|
2024-08-16 11:37:59 +01:00
|
|
|
strings.HasPrefix(name, "thumbnail"),
|
2020-06-17 11:53:26 +01:00
|
|
|
vars["downloadName"],
|
2024-08-16 11:37:59 +01:00
|
|
|
forFederation,
|
2019-12-18 15:10:53 +00:00
|
|
|
)
|
|
|
|
}
|
2023-01-23 17:55:12 +00:00
|
|
|
|
|
|
|
var handlerFunc http.HandlerFunc
|
|
|
|
if counterVec != nil {
|
2024-08-16 11:37:59 +01:00
|
|
|
counterVec = counterVec.MustCurryWith(prometheus.Labels{"type": requestType})
|
|
|
|
sizeVec2 := sizeVec.MustCurryWith(prometheus.Labels{"type": requestType})
|
2023-01-23 17:55:12 +00:00
|
|
|
handlerFunc = promhttp.InstrumentHandlerCounter(counterVec, http.HandlerFunc(httpHandler))
|
2024-08-16 11:37:59 +01:00
|
|
|
handlerFunc = promhttp.InstrumentHandlerResponseSize(sizeVec2, handlerFunc).ServeHTTP
|
2023-01-23 17:55:12 +00:00
|
|
|
} else {
|
|
|
|
handlerFunc = http.HandlerFunc(httpHandler)
|
|
|
|
}
|
|
|
|
return handlerFunc
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|