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"
29 #include "shrpx_connection.h"
30 #include "shrpx_log.h"
35 void regencb(struct ev_loop *loop, ev_timer *w, int revents) {
36 auto r = static_cast<RateLimit *>(w->data);
41 RateLimit::RateLimit(struct ev_loop *loop, ev_io *w, size_t rate, size_t burst,
50 ev_timer_init(&t_, regencb, 0., 1.);
53 ev_timer_again(loop_, &t_);
57 RateLimit::~RateLimit() { ev_timer_stop(loop_, &t_); }
59 size_t RateLimit::avail() const {
61 return std::numeric_limits<ssize_t>::max();
66 void RateLimit::drain(size_t n) {
70 n = std::min(avail_, n);
73 ev_io_stop(loop_, w_);
77 void RateLimit::regen() {
81 if (avail_ + rate_ > burst_) {
87 if (w_->fd >= 0 && avail_ > 0 && startw_req_) {
88 ev_io_start(loop_, w_);
89 handle_tls_pending_read();
93 void RateLimit::startw() {
98 if (rate_ == 0 || avail_ > 0) {
99 ev_io_start(loop_, w_);
100 handle_tls_pending_read();
105 void RateLimit::stopw() {
107 ev_io_stop(loop_, w_);
110 void RateLimit::handle_tls_pending_read() {
111 if (!conn_ || !conn_->tls.ssl ||
112 (SSL_pending(conn_->tls.ssl) == 0 && conn_->tls.rbuf.rleft() == 0 &&
113 (!conn_->tls.initial_handshake_done ||
114 conn_->tls.earlybuf.rleft() == 0))) {
118 // Note that ev_feed_event works without starting watcher, but we
119 // only call this function if watcher is active.
120 ev_feed_event(loop_, w_, EV_READ);