2023-06-19 23:42:47 +02:00
|
|
|
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2018-09-24 06:02:26 +02:00
|
|
|
|
2023-08-11 04:46:45 +02:00
|
|
|
package request // import "miniflux.app/v2/internal/http/request"
|
2018-09-24 06:02:26 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-03-12 05:36:52 +01:00
|
|
|
// FindClientIP returns the client real IP address based on trusted Reverse-Proxy HTTP headers.
|
2018-09-24 06:02:26 +02:00
|
|
|
func FindClientIP(r *http.Request) string {
|
|
|
|
headers := []string{"X-Forwarded-For", "X-Real-Ip"}
|
|
|
|
for _, header := range headers {
|
|
|
|
value := r.Header.Get(header)
|
|
|
|
|
|
|
|
if value != "" {
|
|
|
|
addresses := strings.Split(value, ",")
|
|
|
|
address := strings.TrimSpace(addresses[0])
|
2021-02-07 22:50:06 +01:00
|
|
|
address = dropIPv6zone(address)
|
2018-09-24 06:02:26 +02:00
|
|
|
|
|
|
|
if net.ParseIP(address) != nil {
|
|
|
|
return address
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fallback to TCP/IP source IP address.
|
2023-03-12 05:36:52 +01:00
|
|
|
return FindRemoteIP(r)
|
|
|
|
}
|
|
|
|
|
2023-12-06 19:48:05 +01:00
|
|
|
// FindRemoteIP returns remote client IP address without considering HTTP headers.
|
2023-03-12 05:36:52 +01:00
|
|
|
func FindRemoteIP(r *http.Request) string {
|
2021-02-07 22:50:06 +01:00
|
|
|
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if err != nil {
|
2018-09-24 06:02:26 +02:00
|
|
|
remoteIP = r.RemoteAddr
|
|
|
|
}
|
2023-12-06 19:48:05 +01:00
|
|
|
return dropIPv6zone(remoteIP)
|
2018-09-24 06:02:26 +02:00
|
|
|
}
|
2023-03-12 05:36:52 +01:00
|
|
|
|
|
|
|
func dropIPv6zone(address string) string {
|
|
|
|
i := strings.IndexByte(address, '%')
|
|
|
|
if i != -1 {
|
|
|
|
address = address[:i]
|
|
|
|
}
|
|
|
|
return address
|
|
|
|
}
|