2 31ba2236 2022-01-05 thomas * Copyright (c) 2022 Stefan Sperling <stsp@openbsd.org>
4 31ba2236 2022-01-05 thomas * Permission to use, copy, modify, and distribute this software for any
5 31ba2236 2022-01-05 thomas * purpose with or without fee is hereby granted, provided that the above
6 31ba2236 2022-01-05 thomas * copyright notice and this permission notice appear in all copies.
8 31ba2236 2022-01-05 thomas * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 31ba2236 2022-01-05 thomas * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 31ba2236 2022-01-05 thomas * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 31ba2236 2022-01-05 thomas * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 31ba2236 2022-01-05 thomas * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 31ba2236 2022-01-05 thomas * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 31ba2236 2022-01-05 thomas * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 31ba2236 2022-01-05 thomas #include <sys/time.h>
19 31ba2236 2022-01-05 thomas #include <stdio.h>
20 31ba2236 2022-01-05 thomas #include <limits.h>
21 31ba2236 2022-01-05 thomas #include <string.h>
22 31ba2236 2022-01-05 thomas #include <time.h>
24 31ba2236 2022-01-05 thomas #include "got_lib_ratelimit.h"
26 de1dbfe9 2022-01-05 thomas #include "got_compat.h"
27 31ba2236 2022-01-05 thomas #include "got_error.h"
30 31ba2236 2022-01-05 thomas got_ratelimit_init(struct got_ratelimit *rl, time_t interval_sec,
31 31ba2236 2022-01-05 thomas unsigned int interval_msec)
33 31ba2236 2022-01-05 thomas memset(rl, 0, sizeof(*rl));
34 31ba2236 2022-01-05 thomas rl->interval.tv_sec = interval_sec;
35 31ba2236 2022-01-05 thomas rl->interval.tv_nsec = interval_msec * 1000000UL;
38 31ba2236 2022-01-05 thomas const struct got_error *
39 31ba2236 2022-01-05 thomas got_ratelimit_check(int *elapsed, struct got_ratelimit *rl)
41 31ba2236 2022-01-05 thomas struct timespec now, delta;
43 31ba2236 2022-01-05 thomas if (clock_gettime(CLOCK_MONOTONIC, &now) == -1)
44 31ba2236 2022-01-05 thomas return got_error_from_errno("clock_gettime");
46 31ba2236 2022-01-05 thomas if (timespecisset(&rl->last)) {
47 31ba2236 2022-01-05 thomas timespecsub(&now, &rl->last, &delta);
48 31ba2236 2022-01-05 thomas *elapsed = timespeccmp(&delta, &rl->interval, >=) ? 1 : 0;
50 31ba2236 2022-01-05 thomas *elapsed = 1;
52 31ba2236 2022-01-05 thomas if (*elapsed)
53 31ba2236 2022-01-05 thomas rl->last = now;
55 31ba2236 2022-01-05 thomas return NULL;