每一行一個ip address, 可以用 # 當作註解.
以下是程式碼:
diff --git a/tools/server/server-http.cpp b/tools/server/server-http.cpp
index 5bdece55..2be80164 100644
--- a/tools/server/server-http.cpp
+++ b/tools/server/server-http.cpp
@@ -16,6 +16,57 @@
#include <thread>
#include <mutex>
+static std::string trim(const std::string& str) {
+ auto start = str.begin();
+ bool found = false;
+ for (auto it = str.begin(); it < str.end(); it++) {
+ if (found == false) {
+ if (*it == ' '|| *it == '\t' || *it == '\r' || *it == '\n') {
+ } else if (*it == '#') {
+ return "";
+ } else {
+ start = it;
+ found = true;
+ }
+ } else {
+ if (*it == '#' || *it == ' '|| *it == '\t' || *it == '\r' || *it == '\n') {
+ return std::string(start, it);
+ }
+ }
+ }
+ if (found == true) {
+ return std::string(start, str.end());
+ } else {
+ return std::string(str.begin(), str.end());
+ }
+}
+
+// 從檔案載入 IP 名單
+static std::unordered_set<std::string> load_allowed_ips(const std::string& filepath) {
+ std::unordered_set<std::string> ips;
+ std::ifstream file(filepath);
+
+ if (!file.is_open()) {
+ std::cerr << "Error: Cannot open file " << filepath << std::endl;
+ return ips;
+ }
+
+ std::string line;
+ while (std::getline(file, line)) {
+ line = trim(line);
+ // 略過空白行與 '#' 開頭的註解
+ if (line.empty() || line[0] == '#') {
+ continue;
+ }
+ ips.insert(line);
+ std::cout << "Loaded allowed IP: " << line << std::endl;
+ }
+ return ips;
+}
+
+// 定義允許連線的 IP 白名單
+const std::unordered_set<std::string> allowed_ips = load_allowed_ips("allowed_ips.txt");
+
//
// HTTP implementation using cpp-httplib
//
@@ -419,6 +470,15 @@ bool server_http_context::init_listener(const common_params & params) {
// register server middlewares
srv->set_pre_routing_handler([¶ms, managed_by_router, middleware_validate_api_key, middleware_server_state](const httplib::Request & req, httplib::Response & res) {
+ // 檢查 IP 是否在白名單中
+ if (allowed_ips.find(req.remote_addr) == allowed_ips.end()) {
+ std::cout << "Blocked request from IP: " << req.remote_addr << std::endl;
+ // 拒絕連線,回傳 403 Forbidden
+ res.status = 403;
+ res.set_content("403 Forbidden: Access Denied", "text/plain");
+ // 回傳 Handled,通知 cpp-httplib 已經處理完畢,不要再往後尋找路由
+ return httplib::Server::HandlerResponse::Handled;
+ }
if (managed_by_router && (req.has_header("Origin") || req.has_header("Sec-Fetch-Site") || req.has_header("Sec-Fetch-Mode"))) {
SRV_WRN("rejected browser request on router child: %s %s\n", req.method.c_str(), req.path.c_str());
res.status = 403;