middleware: add sanitization hook

This commit is contained in:
Leo Balduf
2016-11-28 20:55:04 +01:00
parent 91ce2aaf77
commit 3c098c0703
15 changed files with 248 additions and 63 deletions
+17 -2
View File
@@ -13,6 +13,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/tylerb/graceful"
"github.com/chihaya/chihaya/bittorrent"
"github.com/chihaya/chihaya/frontend"
"github.com/chihaya/chihaya/middleware"
)
@@ -22,6 +23,9 @@ func init() {
recordResponseDuration("action", nil, time.Second)
}
// ErrInvalidIP indicates an invalid IP.
var ErrInvalidIP = bittorrent.ClientError("invalid IP")
var promResponseDurationMilliseconds = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "chihaya_http_response_duration_milliseconds",
@@ -172,8 +176,19 @@ func (t *Frontend) scrapeRoute(w http.ResponseWriter, r *http.Request, _ httprou
return
}
ip := net.ParseIP(host)
ctx := context.WithValue(context.Background(), middleware.ScrapeIsIPv6Key, len(ip) == net.IPv6len)
reqIP := net.ParseIP(host)
af := bittorrent.IPv4
if reqIP.To4() != nil {
af = bittorrent.IPv4
} else if len(reqIP) == net.IPv6len { // implies reqIP.To4() == nil
af = bittorrent.IPv6
} else {
log.Errorln("http: invalid IP: neither v4 nor v6, RemoteAddr was", r.RemoteAddr)
WriteError(w, ErrInvalidIP)
return
}
ctx := context.WithValue(context.Background(), middleware.ScrapeIsIPv6Key, af == bittorrent.IPv6)
resp, err := t.logic.HandleScrape(ctx, req)
if err != nil {
+2 -7
View File
@@ -74,16 +74,11 @@ func ParseAnnounce(r *http.Request, realIPHeader string, allowIPSpoofing bool) (
}
request.Peer.Port = uint16(port)
request.Peer.IP = requestedIP(r, qp, realIPHeader, allowIPSpoofing)
if request.Peer.IP == nil {
request.Peer.IP.IP = requestedIP(r, qp, realIPHeader, allowIPSpoofing)
if request.Peer.IP.IP == nil {
return nil, bittorrent.ClientError("failed to parse peer IP address")
}
// Sanitize IPv4 addresses to 4 bytes.
if ip := request.Peer.IP.To4(); ip != nil {
request.Peer.IP = ip
}
return request, nil
}