123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- #ifndef KEYSTORE_CONFIRMATIONUI_RATE_LIMITING_H_
- #define KEYSTORE_CONFIRMATIONUI_RATE_LIMITING_H_
- #include <android/hardware/confirmationui/1.0/types.h>
- #include <chrono>
- #include <stdint.h>
- #include <sys/types.h>
- #include <tuple>
- #include <unordered_map>
- namespace keystore {
- using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
- using std::chrono::time_point;
- using std::chrono::duration;
- template <typename Clock = std::chrono::steady_clock> class RateLimiting {
- private:
- struct Slot {
- Slot() : previous_start{}, prompt_start{}, counter(0) {}
- typename Clock::time_point previous_start;
- typename Clock::time_point prompt_start;
- uint32_t counter;
- };
- std::unordered_map<uid_t, Slot> slots_;
- uint_t latest_requester_;
- static std::chrono::seconds getBackoff(uint32_t counter) {
- using namespace std::chrono_literals;
- switch (counter) {
- case 0:
- case 1:
- case 2:
- return 0s;
- case 3:
- case 4:
- case 5:
- return 30s;
- default:
- return 60s * (1ULL << (counter - 6));
- }
- }
- public:
-
-
- size_t usedSlots() const { return slots_.size(); }
- void doGC() {
- using namespace std::chrono_literals;
- using std::chrono::system_clock;
- using std::chrono::time_point_cast;
- auto then = Clock::now() - 24h;
- auto iter = slots_.begin();
- while (iter != slots_.end()) {
- if (iter->second.prompt_start <= then) {
- iter = slots_.erase(iter);
- } else {
- ++iter;
- }
- }
- }
- bool tryPrompt(uid_t id) {
- using namespace std::chrono_literals;
-
- doGC();
- auto& slot = slots_[id];
- auto now = Clock::now();
- if (!slot.counter || slot.prompt_start <= now - getBackoff(slot.counter)) {
- latest_requester_ = id;
- slot.counter += 1;
- slot.previous_start = slot.prompt_start;
- slot.prompt_start = now;
- return true;
- }
- return false;
- }
- void processResult(ConfirmationResponseCode rc) {
- switch (rc) {
- case ConfirmationResponseCode::OK:
-
- slots_.erase(latest_requester_);
- return;
- case ConfirmationResponseCode::Canceled:
-
- return;
- default:;
- }
-
- auto& slot = slots_[latest_requester_];
- if (slot.counter <= 1) {
- slots_.erase(latest_requester_);
- return;
- }
- slot.counter -= 1;
- slot.prompt_start = slot.previous_start;
- }
- };
- }
- #endif
|