diff --git a/api/_auth_cache/auth_cache.go b/api/_auth_cache/auth_cache.go index da1f2d5c..f3721496 100644 --- a/api/_auth_cache/auth_cache.go +++ b/api/_auth_cache/auth_cache.go @@ -103,25 +103,25 @@ func GetUserId(ctx rcontext.RequestContext, accessToken string, appserviceUserId return checkTokenWithHomeserver(ctx, accessToken, appserviceUserId, true) } - for _, r := range ctx.Config.AccessTokens.Appservices { - if r.AppserviceToken != accessToken { + for _, appSrv := range ctx.Config.AccessTokens.Appservices { + if appSrv.AppserviceToken != accessToken { continue } - if r.SenderUserId != "" && (r.SenderUserId == appserviceUserId || appserviceUserId == "") { - ctx.Log.Debugf("Access token belongs to appservice (sender user ID): %s", r.Id) - cacheToken(ctx, accessToken, appserviceUserId, r.SenderUserId, nil) - return r.SenderUserId, nil + if appSrv.SenderUserId != "" && (appSrv.SenderUserId == appserviceUserId || appserviceUserId == "") { + ctx.Log.Debugf("Access token belongs to appservice (sender user ID): %s", appSrv.Id) + cacheToken(ctx, accessToken, appserviceUserId, appSrv.SenderUserId, nil) + return appSrv.SenderUserId, nil } - for _, n := range r.UserNamespaces { + for _, n := range appSrv.UserNamespaces { regex, ok := regexCache[n.Regex] if !ok { regex = regexp.MustCompile(n.Regex) regexCache[n.Regex] = regex } if regex.MatchString(appserviceUserId) { - ctx.Log.Debugf("Access token belongs to appservice: %s", r.Id) + ctx.Log.Debugf("Access token belongs to appservice: %s", appSrv.Id) cacheToken(ctx, accessToken, appserviceUserId, appserviceUserId, nil) return appserviceUserId, nil } @@ -133,13 +133,13 @@ func GetUserId(ctx rcontext.RequestContext, accessToken string, appserviceUserId } func cacheToken(ctx rcontext.RequestContext, accessToken string, appserviceUserId string, userId string, err error) { - v := cachedToken{ + token := cachedToken{ userId: userId, err: err, } t := time.Duration(ctx.Config.AccessTokens.MaxCacheTimeSeconds) * time.Second rwLock.Lock() - tokenCache.Set(cacheKey(accessToken, appserviceUserId), v, t) + tokenCache.Set(cacheKey(accessToken, appserviceUserId), token, t) rwLock.Unlock() } diff --git a/api/_routers/00-install-params.go b/api/_routers/00-install-params.go index 2f58f178..b289ed63 100644 --- a/api/_routers/00-install-params.go +++ b/api/_routers/00-install-params.go @@ -12,11 +12,11 @@ var ServerNameRegex = regexp.MustCompile("[a-zA-Z0-9.:\\-_]+") // var NumericIdRegex = regexp.MustCompile("[0-9]+") func GetParam(name string, r *http.Request) string { - p := httprouter.ParamsFromContext(r.Context()) - if p == nil { + parameter := httprouter.ParamsFromContext(r.Context()) + if parameter == nil { return "" } - return p.ByName(name) + return parameter.ByName(name) } func ForceSetParam(name string, val string, r *http.Request) *http.Request { diff --git a/api/_routers/01-install_metadata.go b/api/_routers/01-install_metadata.go index db3fa1d0..dc6fa9d2 100644 --- a/api/_routers/01-install_metadata.go +++ b/api/_routers/01-install_metadata.go @@ -37,8 +37,8 @@ func NewInstallMetadataRouter(ignoreHost bool, actionName string, counter *Reque } } -func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { - requestId := i.counter.NextId() +func (router *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { + requestId := router.counter.NextId() logger := logrus.WithFields(logrus.Fields{ "method": r.Method, "host": r.Host, @@ -54,44 +54,44 @@ func (i *InstallMetadataRouter) ServeHTTP(w http.ResponseWriter, r *http.Request ctx := r.Context() ctx = context.WithValue(ctx, common.ContextRequestStartTime, util.NowMillis()) ctx = context.WithValue(ctx, common.ContextRequestId, requestId) - ctx = context.WithValue(ctx, common.ContextAction, i.actionName) - ctx = context.WithValue(ctx, common.ContextIgnoreHost, i.ignoreHost) + ctx = context.WithValue(ctx, common.ContextAction, router.actionName) + ctx = context.WithValue(ctx, common.ContextIgnoreHost, router.ignoreHost) ctx = context.WithValue(ctx, common.ContextLogger, logger) r = r.WithContext(ctx) - if i.next != nil { - i.next.ServeHTTP(w, r) + if router.next != nil { + router.next.ServeHTTP(w, r) } } func GetActionName(r *http.Request) string { - x, ok := r.Context().Value(common.ContextAction).(string) + action, ok := r.Context().Value(common.ContextAction).(string) if !ok { return "" } - return x + return action } func ShouldIgnoreHost(r *http.Request) bool { - x, ok := r.Context().Value(common.ContextIgnoreHost).(bool) + ignoreHost, ok := r.Context().Value(common.ContextIgnoreHost).(bool) if !ok { return false } - return x + return ignoreHost } func GetLogger(r *http.Request) *logrus.Entry { - x, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry) + log, ok := r.Context().Value(common.ContextLogger).(*logrus.Entry) if !ok { return nil } - return x + return log } func GetRequestDuration(r *http.Request) float64 { - x, ok := r.Context().Value(common.ContextRequestStartTime).(int64) + duration, ok := r.Context().Value(common.ContextRequestStartTime).(int64) if !ok { return -1 } - return float64(util.NowMillis()-x) / 1000.0 + return float64(util.NowMillis()-duration) / 1000.0 } diff --git a/api/branched_route.go b/api/branched_route.go index 6dc9c98f..04090e30 100644 --- a/api/branched_route.go +++ b/api/branched_route.go @@ -19,10 +19,10 @@ type splitBranch struct { func branchedRoute(branches []branch) http.Handler { sbranches := make([]splitBranch, len(branches)) - for i, b := range branches { + for i, branch := range branches { sbranches[i] = splitBranch{ - segments: strings.Split(b.string, "/"), - handler: b.Handler, + segments: strings.Split(branch.string, "/"), + handler: branch.Handler, } } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -31,17 +31,17 @@ func branchedRoute(branches []branch) http.Handler { catchAll = catchAll[1:] } params := strings.Split(catchAll, "/") - for _, b := range sbranches { - if b.segments[0][0] == ':' || b.segments[0] == params[0] { - if len(b.segments) != len(params) { + for _, branch := range sbranches { + if branch.segments[0][0] == ':' || branch.segments[0] == params[0] { + if len(branch.segments) != len(params) { continue } - for i, s := range b.segments { - if s[0] == ':' { - r = _routers.ForceSetParam(s[1:], params[i], r) + for i, segment := range branch.segments { + if segment[0] == ':' { + r = _routers.ForceSetParam(segment[1:], params[i], r) } } - b.handler.ServeHTTP(w, r) + branch.handler.ServeHTTP(w, r) return } } diff --git a/api/custom/datastores.go b/api/custom/datastores.go index f5b858e0..d685b3bd 100644 --- a/api/custom/datastores.go +++ b/api/custom/datastores.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "strconv" + "time" "github.com/getsentry/sentry-go" "github.com/t2bot/matrix-media-repo/api/_apimeta" @@ -16,7 +17,6 @@ import ( "github.com/sirupsen/logrus" "github.com/t2bot/matrix-media-repo/common/rcontext" - "github.com/t2bot/matrix-media-repo/util" ) type DatastoreMigration struct { @@ -26,17 +26,17 @@ type DatastoreMigration struct { func GetDatastores(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} { response := make(map[string]interface{}) - for _, ds := range config.UniqueDatastores() { - uri, err := datastores.GetUri(ds) + for _, store := range config.UniqueDatastores() { + uri, err := datastores.GetUri(store) if err != nil { sentry.CaptureException(err) rctx.Log.Error("Error getting datastore URI: ", err) return _responses.InternalServerError(errors.New("unexpected error getting datastore information")) } - dsMap := make(map[string]interface{}) - dsMap["type"] = ds.Type - dsMap["uri"] = uri - response[ds.Id] = dsMap + dataStoreMap := make(map[string]interface{}) + dataStoreMap["type"] = store.Type + dataStoreMap["uri"] = uri + response[store.Id] = dataStoreMap } return &_responses.DoNotCacheResponse{Payload: response} @@ -44,7 +44,7 @@ func GetDatastores(r *http.Request, rctx rcontext.RequestContext, user _apimeta. func MigrateBetweenDatastores(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} { beforeTsStr := r.URL.Query().Get("before_ts") - beforeTs := util.NowMillis() + beforeTs := time.Now().UnixNano() / int64(time.Millisecond) var err error if beforeTsStr != "" { beforeTs, err = strconv.ParseInt(beforeTsStr, 10, 64) @@ -97,7 +97,7 @@ func MigrateBetweenDatastores(r *http.Request, rctx rcontext.RequestContext, use func GetDatastoreStorageEstimate(r *http.Request, rctx rcontext.RequestContext, user _apimeta.UserInfo) interface{} { beforeTsStr := r.URL.Query().Get("before_ts") - beforeTs := util.NowMillis() + beforeTs := time.Now().UnixNano() / int64(time.Millisecond) var err error if beforeTsStr != "" { beforeTs, err = strconv.ParseInt(beforeTsStr, 10, 64) diff --git a/api/router.go b/api/router.go index d43d5b75..588d81f9 100644 --- a/api/router.go +++ b/api/router.go @@ -25,23 +25,23 @@ func buildPrimaryRouter() *httprouter.Router { func methodNotAllowedFn(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusMethodNotAllowed) - b, err := json.Marshal(_responses.MethodNotAllowed()) + reponse, err := json.Marshal(_responses.MethodNotAllowed()) if err != nil { sentry.CaptureException(fmt.Errorf("error preparing MethodNotAllowed: %v", err)) return } - w.Write(b) + w.Write(reponse) } func notFoundFn(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusNotFound) - b, err := json.Marshal(_responses.NotFoundError()) + reponse, err := json.Marshal(_responses.NotFoundError()) if err != nil { sentry.CaptureException(fmt.Errorf("error preparing NotFound: %v", err)) return } - w.Write(b) + w.Write(reponse) } func finishCorsFn(w http.ResponseWriter, r *http.Request) { @@ -61,10 +61,10 @@ func panicFn(w http.ResponseWriter, r *http.Request, i interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) - b, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error"))) + reponse, err := json.Marshal(_responses.InternalServerError(errors.New("unexpected error"))) if err != nil { sentry.CaptureException(fmt.Errorf("error preparing InternalServerError: %v", err)) return } - w.Write(b) + w.Write(reponse) } diff --git a/api/webserver.go b/api/webserver.go index c5024ec0..25c761bc 100644 --- a/api/webserver.go +++ b/api/webserver.go @@ -18,9 +18,11 @@ import ( "github.com/t2bot/matrix-media-repo/common/config" ) -var srv *http.Server -var waitGroup = &sync.WaitGroup{} -var reload = false +var ( + srv *http.Server + waitGroup = &sync.WaitGroup{} + reload = false +) func Init() *sync.WaitGroup { address := net.JoinHostPort(config.Get().General.BindAddress, strconv.Itoa(config.Get().General.Port)) @@ -35,8 +37,8 @@ func Init() *sync.WaitGroup { limiter.SetBurst(config.Get().RateLimit.BurstCount) limiter.SetMax(config.Get().RateLimit.RequestsPerSecond) - b, _ := json.Marshal(_responses.RateLimitReached()) - limiter.SetMessage(string(b)) + reponse, _ := json.Marshal(_responses.RateLimitReached()) + limiter.SetMessage(string(reponse)) limiter.SetMessageContentType("application/json") handler = tollbooth.LimitHandler(limiter, handler) diff --git a/database/table_url_previews.go b/database/table_url_previews.go index b4e76461..3306deb6 100644 --- a/database/table_url_previews.go +++ b/database/table_url_previews.go @@ -65,8 +65,8 @@ func (s *urlPreviewsTableStatements) Prepare(ctx rcontext.RequestContext) *urlPr } } -func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader string) (*DbUrlPreview, error) { - row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, ts, languageHeader) +func (s *urlPreviewsTableWithContext) Get(url string, timestamp int64, languageHeader string) (*DbUrlPreview, error) { + row := s.statements.selectUrlPreview.QueryRowContext(s.ctx, url, timestamp, languageHeader) val := &DbUrlPreview{} err := row.Scan(&val.Url, &val.ErrorCode, &val.BucketTs, &val.SiteUrl, &val.SiteName, &val.ResourceType, &val.Description, &val.Title, &val.ImageMxc, &val.ImageType, &val.ImageSize, &val.ImageWidth, &val.ImageHeight, &val.LanguageHeader) if errors.Is(err, sql.ErrNoRows) { @@ -75,8 +75,8 @@ func (s *urlPreviewsTableWithContext) Get(url string, ts int64, languageHeader s return val, err } -func (s *urlPreviewsTableWithContext) Insert(p *DbUrlPreview) error { - _, err := s.statements.insertUrlPreview.ExecContext(s.ctx, p.Url, p.ErrorCode, p.BucketTs, p.SiteUrl, p.SiteName, p.ResourceType, p.Description, p.Title, p.ImageMxc, p.ImageType, p.ImageSize, p.ImageWidth, p.ImageHeight, p.LanguageHeader) +func (s *urlPreviewsTableWithContext) Insert(preview *DbUrlPreview) error { + _, err := s.statements.insertUrlPreview.ExecContext(s.ctx, preview.Url, preview.ErrorCode, preview.BucketTs, preview.SiteUrl, preview.SiteName, preview.ResourceType, preview.Description, preview.Title, preview.ImageMxc, preview.ImageType, preview.ImageSize, preview.ImageWidth, preview.ImageHeight, preview.LanguageHeader) return err } @@ -89,7 +89,7 @@ func (s *urlPreviewsTableWithContext) InsertError(url string, errorCode string) }) } -func (s *urlPreviewsTableWithContext) DeleteOlderThan(ts int64) error { - _, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, ts) +func (s *urlPreviewsTableWithContext) DeleteOlderThan(timestamp int64) error { + _, err := s.statements.deleteOldUrlPreviews.ExecContext(s.ctx, timestamp) return err } diff --git a/matrix/server_discovery.go b/matrix/server_discovery.go index e8a0b808..2d85869f 100644 --- a/matrix/server_discovery.go +++ b/matrix/server_discovery.go @@ -49,11 +49,11 @@ func GetServerApiUrl(hostname string) (string, string, error) { } addrErr := &net.AddrError{} - h, p, err := net.SplitHostPort(hostname) + host, port, err := net.SplitHostPort(hostname) defPort := false switch { case errors.As(err, &addrErr) && addrErr.Err == "missing port in address": - h, p, err = net.SplitHostPort(hostname + ":8448") + host, port, err = net.SplitHostPort(hostname + ":8448") if err != nil { return "", "", fmt.Errorf("failed to parse hostname: %w", err) } @@ -62,9 +62,9 @@ func GetServerApiUrl(hostname string) (string, string, error) { } // Step 1 of the discovery process: if the hostname is an IP, use that with explicit or default port - logrus.Debug("Testing if " + h + " is an IP address") - if is.IP(h) { - url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p)) + logrus.Debug("Testing if " + host + " is an IP address") + if is.IP(host) { + url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port)) server := cachedServer{url, hostname} apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration) logrus.Debug("Server API URL for " + hostname + " is " + url + " (IP address)") @@ -74,17 +74,17 @@ func GetServerApiUrl(hostname string) (string, string, error) { // Step 2: if the hostname is not an IP address, and an explicit port is given, use that logrus.Debug("Testing if a default port was used. Using default = ", defPort) if !defPort { - url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p)) - server := cachedServer{url, h} + url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port)) + server := cachedServer{url, host} apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration) logrus.Debugf("Server API URL for %s is %s (explicit port)", hostname, url) - return url, h, nil + return url, host, nil } // Step 3: if the hostname is not an IP address and no explicit port is given, do .well-known // Note that we have sprawling branches here because we need to fall through to step 4 if parsing fails - logrus.Debug("Doing .well-known lookup on " + h) - r, err := http.Get(fmt.Sprintf("https://%s/.well-known/matrix/server", h)) + logrus.Debug("Doing .well-known lookup on " + host) + r, err := http.Get(fmt.Sprintf("https://%s/.well-known/matrix/server", host)) if r != nil { defer r.Body.Close() } @@ -183,10 +183,10 @@ func GetServerApiUrl(hostname string) (string, string, error) { realAddr = realAddr[0 : len(realAddr)-1] } url := fmt.Sprintf("https://%s", net.JoinHostPort(realAddr, strconv.Itoa(int(addrs[0].Port)))) - server := cachedServer{url, h} + server := cachedServer{url, host} apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration) logrus.Debugf("Server API URL for %s is %s (SRV)", hostname, url) - return url, h, nil + return url, host, nil } // Step 5: try resolving a hostname using DEPRECATED SRV records and use it @@ -200,17 +200,17 @@ func GetServerApiUrl(hostname string) (string, string, error) { realAddr = realAddr[0 : len(realAddr)-1] } url := fmt.Sprintf("https://%s", net.JoinHostPort(realAddr, strconv.Itoa(int(addrs[0].Port)))) - server := cachedServer{url, h} + server := cachedServer{url, host} apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration) logrus.Debugf("Server API URL for %s is %s (SRV-Deprecated)", hostname, url) - return url, h, nil + return url, host, nil } // Step 6: use the target host as-is logrus.Debug("Using host as-is: ", hostname) - url := fmt.Sprintf("https://%s", net.JoinHostPort(h, p)) - server := cachedServer{url, h} + url := fmt.Sprintf("https://%s", net.JoinHostPort(host, port)) + server := cachedServer{url, host} apiUrlCacheInstance.Set(hostname, server, cache.DefaultExpiration) logrus.Debugf("Server API URL for %s is %s (fallback)", hostname, url) - return url, h, nil + return url, host, nil } diff --git a/util/strings.go b/util/strings.go index 9ecc3ead..f7e5d46f 100644 --- a/util/strings.go +++ b/util/strings.go @@ -5,8 +5,8 @@ import ( ) func HasAnyPrefix(val string, prefixes []string) bool { - for _, p := range prefixes { - if strings.HasPrefix(val, p) { + for _, prefix := range prefixes { + if strings.HasPrefix(val, prefix) { return true } } diff --git a/util/time.go b/util/time.go index 2b8d5a30..058ea221 100644 --- a/util/time.go +++ b/util/time.go @@ -5,10 +5,6 @@ import ( "time" ) -func NowMillis() int64 { - return time.Now().UnixNano() / 1000000 -} - func FromMillis(m int64) time.Time { return time.Unix(0, m*int64(time.Millisecond)) }