1 /* Copyright (c) 2014-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 
4 #include "core/or/or.h"
5 #include "test/test.h"
6 #define HIBERNATE_PRIVATE
7 #include "feature/hibernate/hibernate.h"
8 #include "app/config/config.h"
9 #define STATEFILE_PRIVATE
10 #include "app/config/statefile.h"
11 
12 #include "app/config/or_state_st.h"
13 
14 /*
15  * Test to make sure accounting triggers hibernation
16  * correctly with both sum or max rules set
17  */
18 
19 static or_state_t *or_state;
20 static or_state_t * acct_limits_get_or_state(void);
21 ATTR_UNUSED static int acct_limits_get_or_state_called = 0;
22 static or_state_t *
acct_limits_get_or_state(void)23 acct_limits_get_or_state(void)
24 {
25   return or_state;
26 }
27 
28 static void
test_accounting_limits(void * arg)29 test_accounting_limits(void *arg)
30 {
31   or_options_t *options = get_options_mutable();
32   time_t fake_time = time(NULL);
33   (void) arg;
34 
35   MOCK(get_or_state,
36        acct_limits_get_or_state);
37   or_state = or_state_new();
38 
39   options->AccountingMax = 100;
40   options->AccountingRule = ACCT_MAX;
41 
42   tor_assert(accounting_is_enabled(options));
43   configure_accounting(fake_time);
44 
45   accounting_add_bytes(10, 0, 1);
46   fake_time += 1;
47   consider_hibernation(fake_time);
48   tor_assert(we_are_hibernating() == 0);
49 
50   accounting_add_bytes(90, 0, 1);
51   fake_time += 1;
52   consider_hibernation(fake_time);
53   tor_assert(we_are_hibernating() == 1);
54 
55   options->AccountingMax = 200;
56   options->AccountingRule = ACCT_SUM;
57 
58   accounting_add_bytes(0, 10, 1);
59   fake_time += 1;
60   consider_hibernation(fake_time);
61   tor_assert(we_are_hibernating() == 0);
62 
63   accounting_add_bytes(0, 90, 1);
64   fake_time += 1;
65   consider_hibernation(fake_time);
66   tor_assert(we_are_hibernating() == 1);
67 
68   options->AccountingRule = ACCT_OUT;
69 
70   accounting_add_bytes(100, 10, 1);
71   fake_time += 1;
72   consider_hibernation(fake_time);
73   tor_assert(we_are_hibernating() == 0);
74 
75   accounting_add_bytes(0, 90, 1);
76   fake_time += 1;
77   consider_hibernation(fake_time);
78   tor_assert(we_are_hibernating() == 1);
79 
80   options->AccountingMax = 300;
81   options->AccountingRule = ACCT_IN;
82 
83   accounting_add_bytes(10, 100, 1);
84   fake_time += 1;
85   consider_hibernation(fake_time);
86   tor_assert(we_are_hibernating() == 0);
87 
88   accounting_add_bytes(90, 0, 1);
89   fake_time += 1;
90   consider_hibernation(fake_time);
91   tor_assert(we_are_hibernating() == 1);
92 
93   goto done;
94  done:
95   UNMOCK(get_or_state);
96   or_state_free(or_state);
97 }
98 
99 struct testcase_t accounting_tests[] = {
100   { "bwlimits", test_accounting_limits, TT_FORK, NULL, NULL },
101   END_OF_TESTCASES
102 };
103