Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
1.7 kB
1
Indexable
Never
void saveConnectionData() {
    nlohmann::json j;
    for (const auto& connection : connection_data) {
        nlohmann::json entry;
        entry["ip"] = connection.ip;
        entry["attempts"] = connection.attempts;
        j.push_back(entry);
    }

    ofstream w("connection.json");
    w << setw(2) << j;
}

void append_reset(string ip) {
    while (true) {
        for (auto& connection : connection_data) {
            if (connection.ip == ip) {
                if (connection.attempts > 3) {
                    this_thread::sleep_for(4s);
                    connection.attempts -= 3;
                }
                else {
                    if (connection.attempts <= 0) continue;
                    this_thread::sleep_for(1800ms);
                    connection.attempts -= 1;
                }

                saveConnectionData();
            }
        }
        this_thread::sleep_for(5ms);
    }
}

bool handle_request(const httplib::Request req) {
    bool new_connection = true;

    for (auto& connection : connection_data) {
        if (connection.ip == req.remote_addr) {
            new_connection = false;
            connection.attempts++;
            if (connection.attempts > 3) {
                backtasks.emplace_back(append_reset, req.remote_addr);
                return false;
            }

            saveConnectionData();
            break;
        }
    }

    if (new_connection) {
        Connection new_data;
        new_data.ip = req.remote_addr;
        new_data.attempts = 1;
        connection_data.push_back(new_data);
        saveConnectionData();
    }

    return true;
}
Leave a Comment