2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2015 Tatsuhiro Tsujikawa
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #include "shrpx_rate_limit.h"
32 void regencb(struct ev_loop *loop, ev_timer *w, int revents) {
33 auto r = static_cast<RateLimit *>(w->data);
38 RateLimit::RateLimit(struct ev_loop *loop, ev_io *w, size_t rate, size_t burst,
40 : w_(w), loop_(loop), ssl_(ssl), rate_(rate), burst_(burst), avail_(burst),
42 ev_timer_init(&t_, regencb, 0., 1.);
45 ev_timer_again(loop_, &t_);
49 RateLimit::~RateLimit() { ev_timer_stop(loop_, &t_); }
51 size_t RateLimit::avail() const {
53 return std::numeric_limits<ssize_t>::max();
58 void RateLimit::drain(size_t n) {
62 n = std::min(avail_, n);
65 ev_io_stop(loop_, w_);
69 void RateLimit::regen() {
73 if (avail_ + rate_ > burst_) {
79 if (avail_ > 0 && startw_req_) {
80 ev_io_start(loop_, w_);
81 handle_tls_pending_read();
85 void RateLimit::startw() {
87 if (rate_ == 0 || avail_ > 0) {
88 ev_io_start(loop_, w_);
89 handle_tls_pending_read();
94 void RateLimit::stopw() {
96 ev_io_stop(loop_, w_);
99 void RateLimit::handle_tls_pending_read() {
100 if (!ssl_ || SSL_pending(ssl_) == 0) {
104 // Note that ev_feed_event works without starting watcher, but we
105 // only call this function if watcher is active.
106 ev_feed_event(loop_, w_, EV_READ);