From d36773088314d5fed5940c620480a5d991ff1226 Mon Sep 17 00:00:00 2001 From: winlin Date: Thu, 26 Dec 2019 11:33:26 +0800 Subject: [PATCH] For #1488, support parsing original ip from header for proxy --- trunk/src/app/srs_app_http_conn.cpp | 6 ++++++ trunk/src/app/srs_app_utility.cpp | 32 +++++++++++++++++++++++++++++ trunk/src/app/srs_app_utility.hpp | 4 ++++ 3 files changed, 42 insertions(+) diff --git a/trunk/src/app/srs_app_http_conn.cpp b/trunk/src/app/srs_app_http_conn.cpp index ccc4db4c73..2813a70e43 100644 --- a/trunk/src/app/srs_app_http_conn.cpp +++ b/trunk/src/app/srs_app_http_conn.cpp @@ -875,6 +875,12 @@ SrsRequest* SrsHttpMessage::to_request(string vhost) if (conn) { req->ip = conn->remote_ip(); } + + // Overwrite by ip from proxy. + string oip = srs_get_original_ip(this); + if (!oip.empty()) { + req->ip = oip; + } return req; } diff --git a/trunk/src/app/srs_app_utility.cpp b/trunk/src/app/srs_app_utility.cpp index a64587fa3a..cf5aabdcc8 100644 --- a/trunk/src/app/srs_app_utility.cpp +++ b/trunk/src/app/srs_app_utility.cpp @@ -47,6 +47,7 @@ using namespace std; #include #include #include +#include // the longest time to wait for a process to quit. #define SRS_PROCESS_QUIT_TIMEOUT_MS 1000 @@ -1541,3 +1542,34 @@ void srs_api_dump_summaries(std::stringstream& ss) << SRS_JOBJECT_END; } +string srs_get_original_ip(ISrsHttpMessage* r) +{ + string x_forwarded_for, x_real_ip; + for (int i = 0; i < r->request_header_count(); i++) { + string k = r->request_header_key_at(i); + if (k == "X-Forwarded-For") { + x_forwarded_for = r->request_header_value_at(i); + } else if (k == "X-Real-IP") { + x_real_ip = r->request_header_value_at(i); + } + } + + if (!x_forwarded_for.empty()) { + size_t pos = string::npos; + if ((pos = x_forwarded_for.find(",")) == string::npos) { + return x_forwarded_for; + } + return x_forwarded_for.substr(0, pos); + } + + if (!x_real_ip.empty()) { + size_t pos = string::npos; + if ((pos = x_real_ip.find(":")) == string::npos) { + return x_real_ip; + } + return x_real_ip.substr(0, pos); + } + + return ""; +} + diff --git a/trunk/src/app/srs_app_utility.hpp b/trunk/src/app/srs_app_utility.hpp index 87340a24bb..2083494746 100644 --- a/trunk/src/app/srs_app_utility.hpp +++ b/trunk/src/app/srs_app_utility.hpp @@ -41,6 +41,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. class SrsKbps; class SrsStream; +class ISrsHttpMessage; // client open socket and connect to server. extern int srs_socket_connect(std::string server, int port, int64_t timeout, st_netfd_t* pstfd); @@ -689,5 +690,8 @@ extern bool srs_is_boolean(const std::string& str); // dump summaries for /api/v1/summaries. extern void srs_api_dump_summaries(std::stringstream& ss); +// Get the original ip from query and header by proxy. +extern std::string srs_get_original_ip(ISrsHttpMessage* r); + #endif