Coverage Report

Created: 2026-12-01 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/ratelimit.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#include "urldata.h"
27
#include "ratelimit.h"
28
29
0
#define CURL_RLIMIT_MIN_RATE    (4 * 1024)  /* minimum step rate */
30
0
#define CURL_RLIMIT_STEP_MIN_MS 2  /* minimum step duration */
31
32
static void rlimit_update(struct Curl_rlimit *r,
33
                          const struct curltime *pts)
34
0
{
35
0
  timediff_t elapsed_us, elapsed_steps;
36
0
  int64_t token_gain;
37
38
0
  DEBUGASSERT(r->rate_per_step);
39
0
  if((r->ts.tv_sec == pts->tv_sec) && (r->ts.tv_usec == pts->tv_usec))
40
0
    return;
41
42
0
  elapsed_us = curlx_ptimediff_us(pts, &r->ts);
43
0
  if(elapsed_us < 0) { /* not going back in time */
44
0
    DEBUGASSERT(0);
45
0
    return;
46
0
  }
47
48
0
  elapsed_us += r->spare_us;
49
0
  if(elapsed_us < r->step_us)
50
0
    return;
51
52
  /* we do the update */
53
0
  r->ts = *pts;
54
0
  elapsed_steps = elapsed_us / r->step_us;
55
0
  r->spare_us = elapsed_us % r->step_us;
56
57
  /* How many tokens did we gain since the last update? */
58
0
  if(r->rate_per_step > (INT64_MAX / elapsed_steps))
59
0
    token_gain = INT64_MAX;
60
0
  else {
61
0
    token_gain = r->rate_per_step * elapsed_steps;
62
0
  }
63
64
0
  if((INT64_MAX - token_gain) > r->tokens)
65
0
    r->tokens += token_gain;
66
0
  else
67
0
    r->tokens = INT64_MAX;
68
69
  /* Limit the token again by the burst rate (if set), so we
70
   * do not suddenly have a huge number of tokens after inactivity. */
71
0
  if(r->burst_per_step && (r->tokens > r->burst_per_step)) {
72
0
    r->tokens = r->burst_per_step;
73
0
  }
74
0
}
75
76
static void rlimit_tune_steps(struct Curl_rlimit *r,
77
                              int64_t tokens_total)
78
4.94k
{
79
4.94k
  int64_t tokens_last, tokens_main, msteps;
80
81
  /* Tune the ratelimit at the start *if* we know how many tokens
82
   * are expected to be consumed in total.
83
   * The reason for tuning is that rlimit provides tokens to be consumed
84
   * per "step" which starts out to be a second. The tokens may be consumed
85
   * in full at the beginning of a step. The remainder of the second will
86
   * have no tokens available, effectively blocking the consumption and
87
   * so keeping the "step average" in line.
88
   * This works will up to the last step. When no more tokens are needed,
89
   * no wait will happen and the last step would be too fast. This is
90
   * especially noticeable when only a few steps are needed.
91
   *
92
   * Example: downloading 1.5kb with a ratelimit of 1k could be done in
93
   * roughly 1 second (1k in the first second and the 0.5 at the start of
94
   * the second one).
95
   *
96
   * The tuning tries to make the last step small, using only
97
   * 1 percent of the total tokens (at least 1). The rest of the tokens
98
   * are to be consumed in the steps before by adjusting the duration of
99
   * the step and the amount of tokens it provides. */
100
4.94k
  if(!r->rate_per_step ||
101
0
     (tokens_total <= 1) ||
102
0
     (tokens_total > (INT64_MAX / 1000)))
103
4.94k
    return;
104
105
  /* Calculate tokens for the last step and the ones before. */
106
0
  tokens_last = tokens_total / 100;
107
0
  if(!tokens_last) /* less than 100 total, use 1 */
108
0
    tokens_last = 1;
109
0
  else if(tokens_last > CURL_RLIMIT_MIN_RATE)
110
0
    tokens_last = CURL_RLIMIT_MIN_RATE;
111
0
  DEBUGASSERT(tokens_last);
112
0
  tokens_main = tokens_total - tokens_last;
113
0
  DEBUGASSERT(tokens_main);
114
115
  /* how many milli-steps will it take to consume those, give the
116
  * original rate limit per second? */
117
0
  DEBUGASSERT(r->step_us == CURL_US_PER_SEC);
118
119
0
  msteps = (tokens_main * 1000 / r->rate_per_step);
120
0
  if(msteps < CURL_RLIMIT_STEP_MIN_MS) {
121
    /* Steps this small will not work. Do not tune. */
122
0
    return;
123
0
  }
124
0
  else if(msteps < 1000) {
125
    /* It needs less than one step to provide the needed tokens.
126
     * Make it exactly that long and with exactly those tokens. */
127
0
    r->step_us = (timediff_t)msteps * 1000;
128
0
    r->rate_per_step = tokens_main;
129
0
    r->tokens = r->rate_per_step;
130
0
  }
131
0
  else {
132
    /* More than 1 step. Spread the remainder milli steps and
133
     * the tokens they need to provide across all steps. If integer
134
     * arithmetic can do it. */
135
0
    curl_off_t ms_unaccounted = (msteps % 1000);
136
0
    curl_off_t mstep_inc = (ms_unaccounted / (msteps / 1000));
137
0
    if(mstep_inc) {
138
0
      curl_off_t rate_inc = ((r->rate_per_step * mstep_inc) / 1000);
139
0
      if(rate_inc) {
140
0
        r->step_us = CURL_US_PER_SEC + ((timediff_t)mstep_inc * 1000);
141
0
        r->rate_per_step += rate_inc;
142
0
        r->tokens = r->rate_per_step;
143
0
        if(r->burst_per_step) {
144
0
          curl_off_t burst_inc = ((r->burst_per_step * mstep_inc) / 1000);
145
0
          if(burst_inc)
146
0
            r->burst_per_step += burst_inc;
147
0
        }
148
0
      }
149
0
    }
150
0
  }
151
0
}
152
153
void Curl_rlimit_change(struct Curl_rlimit *r,
154
                        int64_t rate_per_sec,
155
                        int64_t burst_per_sec)
156
0
{
157
0
  DEBUGASSERT(rate_per_sec >= 0);
158
0
  DEBUGASSERT(burst_per_sec >= rate_per_sec || !burst_per_sec);
159
0
  r->rate_per_step = r->rate_per_sec = rate_per_sec;
160
0
  r->burst_per_step = r->burst_per_sec = burst_per_sec;
161
0
  r->step_us = CURL_US_PER_SEC;
162
0
  r->spare_us = 0;
163
0
  if(r->tokens > r->rate_per_step)
164
0
    r->tokens = r->rate_per_step;
165
  /* ts and blocked stay as they are, a paused transfer stays paused */
166
0
}
167
168
void Curl_rlimit_start(struct Curl_rlimit *r, const struct curltime *pts,
169
                       int64_t total_tokens)
170
4.94k
{
171
  /* A start always resets the values to initial defaults, then
172
   * fine tunes the intervals for the total_tokens expected. */
173
4.94k
  r->rate_per_step = r->rate_per_sec;
174
4.94k
  r->burst_per_step = r->burst_per_sec;
175
4.94k
  r->step_us = CURL_US_PER_SEC;
176
4.94k
  r->spare_us = 0;
177
4.94k
  r->tokens = r->rate_per_step;
178
4.94k
  r->ts = *pts;
179
4.94k
  rlimit_tune_steps(r, total_tokens);
180
4.94k
}
181
182
int64_t Curl_rlimit_per_step(struct Curl_rlimit *r)
183
0
{
184
0
  return r->rate_per_step;
185
0
}
186
187
bool Curl_rlimit_active(struct Curl_rlimit *r)
188
61
{
189
61
  return (r->rate_per_step > 0) || r->blocked;
190
61
}
191
192
bool Curl_rlimit_is_blocked(struct Curl_rlimit *r)
193
3.19k
{
194
3.19k
  return (bool)r->blocked;
195
3.19k
}
196
197
int64_t Curl_rlimit_avail(struct Curl_rlimit *r,
198
                          const struct curltime *pts)
199
0
{
200
0
  struct curltime ts;
201
202
0
  if(r->blocked)
203
0
    return 0;
204
0
  else if(r->rate_per_step) {
205
0
    if(!pts) {
206
0
      curlx_pnow(&ts);
207
0
      pts = &ts;
208
0
    }
209
0
    rlimit_update(r, pts);
210
0
    return r->tokens;
211
0
  }
212
0
  else
213
0
    return INT64_MAX;
214
0
}
215
216
void Curl_rlimit_drain(struct Curl_rlimit *r, size_t tokens,
217
                       const struct curltime *pts)
218
8
{
219
8
  struct curltime ts;
220
221
8
  if(r->blocked || !r->rate_per_step)
222
8
    return;
223
224
0
  if(!pts) {
225
0
    curlx_pnow(&ts);
226
0
    pts = &ts;
227
0
  }
228
0
  rlimit_update(r, pts);
229
0
#if 8 <= SIZEOF_SIZE_T
230
0
  if(tokens > INT64_MAX) {
231
0
    r->tokens = INT64_MAX;
232
0
  }
233
0
  else
234
0
#endif
235
0
  {
236
0
    int64_t val = (int64_t)tokens;
237
0
    if((INT64_MIN + val) < r->tokens)
238
0
      r->tokens -= val;
239
0
    else
240
0
      r->tokens = INT64_MIN;
241
0
  }
242
0
}
243
244
timediff_t Curl_rlimit_wait_ms(struct Curl_rlimit *r,
245
                               const struct curltime *pts)
246
0
{
247
0
  timediff_t wait_us, elapsed_us;
248
249
0
  if(r->blocked || !r->rate_per_step)
250
0
    return 0;
251
0
  rlimit_update(r, pts);
252
0
  if(r->tokens > 0)
253
0
    return 0;
254
255
  /* How much time will it take tokens to become positive again?
256
   * Deduct `spare_us` and check against already elapsed time */
257
0
  wait_us = r->step_us - r->spare_us;
258
0
  if(r->tokens < 0) {
259
0
    curl_off_t debt_pct = ((-r->tokens) * 100 / r->rate_per_step);
260
0
    if(debt_pct)
261
0
      wait_us += (r->step_us * debt_pct / 100);
262
0
  }
263
264
0
  elapsed_us = curlx_ptimediff_us(pts, &r->ts);
265
0
  if(elapsed_us >= wait_us)
266
0
    return 0;
267
0
  wait_us -= elapsed_us;
268
0
  return (wait_us + 999) / 1000; /* in milliseconds */
269
0
}
270
271
timediff_t Curl_rlimit_next_step_ms(struct Curl_rlimit *r,
272
                                    const struct curltime *pts)
273
0
{
274
0
  if(!r->blocked && r->rate_per_step) {
275
0
    timediff_t elapsed_us, next_us;
276
277
0
    elapsed_us = curlx_ptimediff_us(pts, &r->ts) + r->spare_us;
278
0
    if(r->step_us > elapsed_us) {
279
0
      next_us = r->step_us - elapsed_us;
280
0
      return (next_us + 999) / 1000; /* in milliseconds */
281
0
    }
282
0
  }
283
0
  return 0;
284
0
}
285
286
void Curl_rlimit_block(struct Curl_rlimit *r,
287
                       bool activate,
288
                       const struct curltime *pts)
289
4.93k
{
290
4.93k
  if(!activate == !r->blocked)
291
4.93k
    return;
292
293
0
  r->ts = *pts;
294
0
  r->blocked = activate;
295
0
  if(!r->blocked) {
296
    /* Start rate limiting fresh. The amount of time this was blocked
297
     * does not generate extra tokens. */
298
0
    Curl_rlimit_start(r, pts, -1);
299
0
  }
300
0
  else {
301
0
    r->tokens = 0;
302
0
  }
303
0
}