aboutsummaryrefslogtreecommitdiff
path: root/src/test
diff options
context:
space:
mode:
Diffstat (limited to 'src/test')
-rw-r--r--src/test/Makefile.nmake12
-rw-r--r--src/test/bench.c160
-rwxr-xr-xsrc/test/bt_test.py19
-rw-r--r--src/test/ed25519_exts_ref.py234
-rw-r--r--src/test/ed25519_vectors.inc150
-rw-r--r--src/test/example_extrainfo.inc425
-rw-r--r--src/test/failing_routerdescs.inc1569
-rw-r--r--src/test/fakechans.h26
-rw-r--r--src/test/include.am195
-rw-r--r--src/test/log_test_helpers.c113
-rw-r--r--src/test/log_test_helpers.h56
-rwxr-xr-xsrc/test/ntor_ref.py6
-rw-r--r--src/test/rend_test_helpers.c73
-rw-r--r--src/test/rend_test_helpers.h15
-rw-r--r--src/test/slow_ed25519.py115
-rw-r--r--src/test/test-child.c2
-rw-r--r--src/test/test-memwipe.c209
-rwxr-xr-xsrc/test/test-network.sh68
-rw-r--r--src/test/test.c737
-rw-r--r--src/test/test.h41
-rw-r--r--src/test/test_accounting.c102
-rw-r--r--src/test/test_addr.c548
-rw-r--r--src/test/test_address.c1137
-rwxr-xr-xsrc/test/test_bt.sh10
-rw-r--r--src/test/test_bt_cl.c23
-rw-r--r--src/test/test_buffers.c427
-rw-r--r--src/test/test_cell_formats.c785
-rw-r--r--src/test/test_cell_queue.c76
-rw-r--r--src/test/test_channel.c1784
-rw-r--r--src/test/test_channeltls.c333
-rw-r--r--src/test/test_checkdir.c149
-rw-r--r--src/test/test_circuitlist.c146
-rw-r--r--src/test/test_circuitmux.c20
-rwxr-xr-xsrc/test/test_cmdline_args.py292
-rw-r--r--src/test/test_compat_libevent.c224
-rw-r--r--src/test/test_config.c4204
-rw-r--r--src/test/test_connection.c858
-rw-r--r--src/test/test_containers.c820
-rw-r--r--src/test/test_controller.c163
-rw-r--r--src/test/test_controller_events.c163
-rw-r--r--src/test/test_crypto.c1659
-rw-r--r--src/test/test_crypto_slow.c532
-rw-r--r--src/test/test_data.c2
-rw-r--r--src/test/test_descriptors.inc305
-rw-r--r--src/test/test_dir.c3560
-rw-r--r--src/test/test_dir_common.c425
-rw-r--r--src/test/test_dir_common.h52
-rw-r--r--src/test/test_dir_handle_get.c2538
-rw-r--r--src/test/test_dns.c765
-rw-r--r--src/test/test_entryconn.c769
-rw-r--r--src/test/test_entrynodes.c875
-rw-r--r--src/test/test_extorport.c198
-rw-r--r--src/test/test_guardfraction.c418
-rw-r--r--src/test/test_helpers.c86
-rw-r--r--src/test/test_helpers.h17
-rw-r--r--src/test/test_hs.c377
-rw-r--r--src/test/test_introduce.c78
-rwxr-xr-xsrc/test/test_keygen.sh368
-rw-r--r--src/test/test_keypin.c256
-rw-r--r--src/test/test_link_handshake.c928
-rw-r--r--src/test/test_logging.c38
-rw-r--r--src/test/test_microdesc.c613
-rw-r--r--src/test/test_nodelist.c51
-rwxr-xr-xsrc/test/test_ntor.sh9
-rw-r--r--src/test/test_ntor_cl.c9
-rw-r--r--src/test/test_oom.c96
-rw-r--r--src/test/test_options.c4248
-rw-r--r--src/test/test_policy.c1589
-rw-r--r--src/test/test_procmon.c58
-rw-r--r--src/test/test_pt.c214
-rw-r--r--src/test/test_relay.c126
-rw-r--r--src/test/test_relaycell.c68
-rw-r--r--src/test/test_rendcache.c1269
-rw-r--r--src/test/test_replay.c153
-rw-r--r--src/test/test_routerkeys.c566
-rw-r--r--src/test/test_routerlist.c511
-rw-r--r--src/test/test_routerset.c2221
-rw-r--r--src/test/test_scheduler.c774
-rw-r--r--src/test/test_slow.c29
-rw-r--r--src/test/test_socks.c393
-rw-r--r--src/test/test_status.c367
-rw-r--r--src/test/test_switch_id.c192
-rwxr-xr-xsrc/test/test_switch_id.sh25
-rw-r--r--src/test/test_threads.c320
-rw-r--r--src/test/test_tortls.c2836
-rw-r--r--src/test/test_util.c4134
-rw-r--r--src/test/test_util_format.c302
-rw-r--r--src/test/test_util_process.c82
-rw-r--r--src/test/test_util_slow.c391
-rw-r--r--src/test/test_workqueue.c453
-rwxr-xr-xsrc/test/test_zero_length_keys.sh10
-rw-r--r--src/test/testing_common.c315
-rw-r--r--src/test/vote_descriptors.inc94
-rwxr-xr-xsrc/test/zero_length_keys.sh126
94 files changed, 47570 insertions, 5809 deletions
diff --git a/src/test/Makefile.nmake b/src/test/Makefile.nmake
index 822431f3b8..0ba56d7036 100644
--- a/src/test/Makefile.nmake
+++ b/src/test/Makefile.nmake
@@ -11,11 +11,13 @@ LIBS = ..\..\..\build-alpha\lib\libevent.lib \
ws2_32.lib advapi32.lib shell32.lib \
crypt32.lib gdi32.lib user32.lib
-TEST_OBJECTS = test.obj test_addr.obj test_containers.obj \
- test_controller_events.ogj test_crypto.obj test_data.obj test_dir.obj \
- test_microdesc.obj test_pt.obj test_util.obj test_config.obj \
- test_cell_formats.obj test_replay.obj test_introduce.obj tinytest.obj \
- test_hs.obj
+TEST_OBJECTS = test.obj test_addr.obj test_channel.obj test_channeltls.obj \
+ test_containers.obj \
+ test_controller_events.obj test_crypto.obj test_data.obj test_dir.obj \
+ test_checkdir.obj test_microdesc.obj test_pt.obj test_util.obj \
+ test_config.obj test_connection.obj \
+ test_cell_formats.obj test_relay.obj test_replay.obj \
+ test_scheduler.obj test_introduce.obj test_hs.obj tinytest.obj
tinytest.obj: ..\ext\tinytest.c
$(CC) $(CFLAGS) /D snprintf=_snprintf /c ..\ext\tinytest.c
diff --git a/src/test/bench.c b/src/test/bench.c
index f6c33626f2..5aefda5ff2 100644
--- a/src/test/bench.c
+++ b/src/test/bench.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/* Ordinarily defined in tor_main.c; this bit is just here to provide one
@@ -19,17 +19,14 @@ const char tor_git_revision[] = "";
#include "relay.h"
#include <openssl/opensslv.h>
#include <openssl/evp.h>
-#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#include <openssl/ecdh.h>
#include <openssl/obj_mac.h>
-#endif
#include "config.h"
-#ifdef CURVE25519_ENABLED
#include "crypto_curve25519.h"
#include "onion_ntor.h"
-#endif
+#include "crypto_ed25519.h"
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
static uint64_t nanostart;
@@ -79,6 +76,9 @@ perftime(void)
#define NANOCOUNT(start,end,iters) \
( ((double)((end)-(start))) / (iters) )
+#define MICROCOUNT(start,end,iters) \
+ ( NANOCOUNT((start), (end), (iters)) / 1000.0 )
+
/** Run AES performance benchmarks. */
static void
bench_aes(void)
@@ -162,7 +162,8 @@ bench_onion_TAP(void)
char key_out[CPATH_KEY_MATERIAL_LEN];
int s;
dh = crypto_dh_dup(dh_out);
- s = onion_skin_TAP_client_handshake(dh, or, key_out, sizeof(key_out));
+ s = onion_skin_TAP_client_handshake(dh, or, key_out, sizeof(key_out),
+ NULL);
crypto_dh_free(dh);
tor_assert(s == 0);
}
@@ -175,9 +176,8 @@ bench_onion_TAP(void)
crypto_pk_free(key2);
}
-#ifdef CURVE25519_ENABLED
static void
-bench_onion_ntor(void)
+bench_onion_ntor_impl(void)
{
const int iters = 1<<10;
int i;
@@ -222,7 +222,8 @@ bench_onion_ntor(void)
for (i = 0; i < iters; ++i) {
uint8_t key_out[CPATH_KEY_MATERIAL_LEN];
int s;
- s = onion_skin_ntor_client_handshake(state, or, key_out, sizeof(key_out));
+ s = onion_skin_ntor_client_handshake(state, or, key_out, sizeof(key_out),
+ NULL);
tor_assert(s == 0);
}
end = perftime();
@@ -232,7 +233,89 @@ bench_onion_ntor(void)
ntor_handshake_state_free(state);
dimap_free(keymap, NULL);
}
-#endif
+
+static void
+bench_onion_ntor(void)
+{
+ int ed;
+
+ for (ed = 0; ed <= 1; ++ed) {
+ printf("Ed25519-based basepoint multiply = %s.\n",
+ (ed == 0) ? "disabled" : "enabled");
+ curve25519_set_impl_params(ed);
+ bench_onion_ntor_impl();
+ }
+}
+
+static void
+bench_ed25519_impl(void)
+{
+ uint64_t start, end;
+ const int iters = 1<<12;
+ int i;
+ const uint8_t msg[] = "but leaving, could not tell what they had heard";
+ ed25519_signature_t sig;
+ ed25519_keypair_t kp;
+ curve25519_keypair_t curve_kp;
+ ed25519_public_key_t pubkey_tmp;
+
+ ed25519_secret_key_generate(&kp.seckey, 0);
+ start = perftime();
+ for (i = 0; i < iters; ++i) {
+ ed25519_public_key_generate(&kp.pubkey, &kp.seckey);
+ }
+ end = perftime();
+ printf("Generate public key: %.2f usec\n",
+ MICROCOUNT(start, end, iters));
+
+ start = perftime();
+ for (i = 0; i < iters; ++i) {
+ ed25519_sign(&sig, msg, sizeof(msg), &kp);
+ }
+ end = perftime();
+ printf("Sign a short message: %.2f usec\n",
+ MICROCOUNT(start, end, iters));
+
+ start = perftime();
+ for (i = 0; i < iters; ++i) {
+ ed25519_checksig(&sig, msg, sizeof(msg), &kp.pubkey);
+ }
+ end = perftime();
+ printf("Verify signature: %.2f usec\n",
+ MICROCOUNT(start, end, iters));
+
+ curve25519_keypair_generate(&curve_kp, 0);
+ start = perftime();
+ for (i = 0; i < iters; ++i) {
+ ed25519_public_key_from_curve25519_public_key(&pubkey_tmp,
+ &curve_kp.pubkey, 1);
+ }
+ end = perftime();
+ printf("Convert public point from curve25519: %.2f usec\n",
+ MICROCOUNT(start, end, iters));
+
+ curve25519_keypair_generate(&curve_kp, 0);
+ start = perftime();
+ for (i = 0; i < iters; ++i) {
+ ed25519_public_blind(&pubkey_tmp, &kp.pubkey, msg);
+ }
+ end = perftime();
+ printf("Blind a public key: %.2f usec\n",
+ MICROCOUNT(start, end, iters));
+}
+
+static void
+bench_ed25519(void)
+{
+ int donna;
+
+ for (donna = 0; donna <= 1; ++donna) {
+ printf("Ed25519-donna = %s.\n",
+ (donna == 0) ? "disabled" : "enabled");
+ ed25519_set_impl_params(donna);
+ bench_ed25519_impl();
+ }
+}
static void
bench_cell_aes(void)
@@ -360,6 +443,45 @@ bench_siphash(void)
}
static void
+bench_digest(void)
+{
+ char buf[8192];
+ char out[DIGEST512_LEN];
+ const int lens[] = { 1, 16, 32, 64, 128, 512, 1024, 2048, -1 };
+ const int N = 300000;
+ uint64_t start, end;
+ crypto_rand(buf, sizeof(buf));
+
+ for (int alg = 0; alg < N_DIGEST_ALGORITHMS; alg++) {
+ for (int i = 0; lens[i] > 0; ++i) {
+ reset_perftime();
+ start = perftime();
+ for (int j = 0; j < N; ++j) {
+ switch (alg) {
+ case DIGEST_SHA1:
+ crypto_digest(out, buf, lens[i]);
+ break;
+ case DIGEST_SHA256:
+ case DIGEST_SHA3_256:
+ crypto_digest256(out, buf, lens[i], alg);
+ break;
+ case DIGEST_SHA512:
+ case DIGEST_SHA3_512:
+ crypto_digest512(out, buf, lens[i], alg);
+ break;
+ default:
+ tor_assert(0);
+ }
+ }
+ end = perftime();
+ printf("%s(%d): %.2f ns per call\n",
+ crypto_digest_algorithm_get_name(alg),
+ lens[i], NANOCOUNT(start,end,N));
+ }
+ }
+}
+
+static void
bench_cell_ops(void)
{
const int iters = 1<<16;
@@ -443,9 +565,6 @@ bench_dh(void)
" %f millisec each.\n", NANOCOUNT(start, end, iters)/1e6);
}
-#if (!defined(OPENSSL_NO_EC) \
- && OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0))
-#define HAVE_EC_BENCHMARKS
static void
bench_ecdh_impl(int nid, const char *name)
{
@@ -495,7 +614,6 @@ bench_ecdh_p224(void)
{
bench_ecdh_impl(NID_secp224r1, "P-224");
}
-#endif
typedef void (*bench_fn)(void);
@@ -510,18 +628,17 @@ typedef struct benchmark_t {
static struct benchmark_t benchmarks[] = {
ENT(dmap),
ENT(siphash),
+ ENT(digest),
ENT(aes),
ENT(onion_TAP),
-#ifdef CURVE25519_ENABLED
ENT(onion_ntor),
-#endif
+ ENT(ed25519),
+
ENT(cell_aes),
ENT(cell_ops),
ENT(dh),
-#ifdef HAVE_EC_BENCHMARKS
ENT(ecdh_p256),
ENT(ecdh_p224),
-#endif
{NULL,NULL,0}
};
@@ -566,10 +683,13 @@ main(int argc, const char **argv)
reset_perftime();
- crypto_seed_rng(1);
+ if (crypto_seed_rng() < 0) {
+ printf("Couldn't seed RNG; exiting.\n");
+ return 1;
+ }
crypto_init_siphash_key();
options = options_new();
- init_logging();
+ init_logging(1);
options->command = CMD_RUN_UNITTESTS;
options->DataDirectory = tor_strdup("");
options_init(options);
diff --git a/src/test/bt_test.py b/src/test/bt_test.py
index 8290509fa7..30591453b9 100755
--- a/src/test/bt_test.py
+++ b/src/test/bt_test.py
@@ -1,4 +1,4 @@
-# Copyright 2013, The Tor Project, Inc
+# Copyright 2013-2015, The Tor Project, Inc
# See LICENSE for licensing information
"""
@@ -15,6 +15,7 @@ OK
"""
+from __future__ import print_function
import sys
@@ -36,7 +37,17 @@ LINES = sys.stdin.readlines()
for I in range(len(LINES)):
if matches(LINES[I:], FUNCNAMES):
print("OK")
- break
-else:
- print("BAD")
+ sys.exit(0)
+print("BAD")
+
+for l in LINES:
+ print("{}".format(l), end="")
+
+if sys.platform.startswith('freebsd'):
+ # See bug #17808 if you know how to fix this.
+ print("Test failed; but FreeBSD is known to have backtrace problems.\n"
+ "Treating as 'SKIP'.")
+ sys.exit(77)
+
+sys.exit(1)
diff --git a/src/test/ed25519_exts_ref.py b/src/test/ed25519_exts_ref.py
new file mode 100644
index 0000000000..d5a3a79910
--- /dev/null
+++ b/src/test/ed25519_exts_ref.py
@@ -0,0 +1,234 @@
+#!/usr/bin/python
+# Copyright 2014-2015, The Tor Project, Inc
+# See LICENSE for licensing information
+
+"""
+ Reference implementations for the ed25519 tweaks that Tor uses.
+
+ Includes self-tester and test vector generator.
+"""
+
+import slow_ed25519
+from slow_ed25519 import *
+
+import os
+import random
+import slownacl_curve25519
+import unittest
+import binascii
+import textwrap
+
+#define a synonym that doesn't look like 1
+ell = l
+
+# This replaces expmod above and makes it go a lot faster.
+slow_ed25519.expmod = pow
+
+def curve25519ToEd25519(c, sign):
+ u = decodeint(c)
+ y = ((u - 1) * inv(u + 1)) % q
+ x = xrecover(y)
+ if x & 1 != sign: x = q-x
+ return encodepoint([x,y])
+
+def blindESK(esk, param):
+ h = H("Derive temporary signing key" + param)
+ mult = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
+ s = decodeint(esk[:32])
+ s_prime = (s * mult) % ell
+ k = esk[32:]
+ assert(len(k) == 32)
+ k_prime = H("Derive temporary signing key hash input" + k)[:32]
+ return encodeint(s_prime) + k_prime
+
+def blindPK(pk, param):
+ h = H("Derive temporary signing key" + param)
+ mult = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
+ P = decodepoint(pk)
+ return encodepoint(scalarmult(P, mult))
+
+def expandSK(sk):
+ h = H(sk)
+ a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
+ k = ''.join([h[i] for i in range(b/8,b/4)])
+ assert len(k) == 32
+ return encodeint(a)+k
+
+def publickeyFromESK(h):
+ a = decodeint(h[:32])
+ A = scalarmult(B,a)
+ return encodepoint(A)
+
+def signatureWithESK(m,h,pk):
+ a = decodeint(h[:32])
+ r = Hint(''.join([h[i] for i in range(b/8,b/4)]) + m)
+ R = scalarmult(B,r)
+ S = (r + Hint(encodepoint(R) + pk + m) * a) % l
+ return encodepoint(R) + encodeint(S)
+
+def newSK():
+ return os.urandom(32)
+
+# ------------------------------------------------------------
+
+MSG = "This is extremely silly. But it is also incredibly serious business!"
+
+class SelfTest(unittest.TestCase):
+
+ def _testSignatures(self, esk, pk):
+ sig = signatureWithESK(MSG, esk, pk)
+ checkvalid(sig, MSG, pk)
+ bad = False
+ try:
+ checkvalid(sig, MSG*2, pk)
+ bad = True
+ except Exception:
+ pass
+
+ self.failIf(bad)
+
+ def testExpand(self):
+ sk = newSK()
+ pk = publickey(sk)
+ esk = expandSK(sk)
+ sig1 = signature(MSG, sk, pk)
+ sig2 = signatureWithESK(MSG, esk, pk)
+ self.assertEquals(sig1, sig2)
+
+ def testSignatures(self):
+ sk = newSK()
+ esk = expandSK(sk)
+ pk = publickeyFromESK(esk)
+ pk2 = publickey(sk)
+ self.assertEquals(pk, pk2)
+
+ self._testSignatures(esk, pk)
+
+ def testDerivation(self):
+ priv = slownacl_curve25519.Private()
+ pub = priv.get_public()
+
+ ed_pub0 = publickeyFromESK(priv.private)
+ sign = (ord(ed_pub0[31]) & 255) >> 7
+ ed_pub1 = curve25519ToEd25519(pub.public, sign)
+
+ self.assertEquals(ed_pub0, ed_pub1)
+
+ def testBlinding(self):
+ sk = newSK()
+ esk = expandSK(sk)
+ pk = publickeyFromESK(esk)
+ param = os.urandom(32)
+ besk = blindESK(esk, param)
+ bpk = blindPK(pk, param)
+ bpk2 = publickeyFromESK(besk)
+ self.assertEquals(bpk, bpk2)
+
+ self._testSignatures(besk, bpk)
+
+# ------------------------------------------------------------
+
+# From pprint.pprint([ binascii.b2a_hex(os.urandom(32)) for _ in xrange(8) ])
+RAND_INPUTS = [
+ '26c76712d89d906e6672dafa614c42e5cb1caac8c6568e4d2493087db51f0d36',
+ 'fba7a5366b5cb98c2667a18783f5cf8f4f8d1a2ce939ad22a6e685edde85128d',
+ '67e3aa7a14fac8445d15e45e38a523481a69ae35513c9e4143eb1c2196729a0e',
+ 'd51385942033a76dc17f089a59e6a5a7fe80d9c526ae8ddd8c3a506b99d3d0a6',
+ '5c8eac469bb3f1b85bc7cd893f52dc42a9ab66f1b02b5ce6a68e9b175d3bb433',
+ 'eda433d483059b6d1ff8b7cfbd0fe406bfb23722c8f3c8252629284573b61b86',
+ '4377c40431c30883c5fbd9bc92ae48d1ed8a47b81d13806beac5351739b5533d',
+ 'c6bbcce615839756aed2cc78b1de13884dd3618f48367a17597a16c1cd7a290b']
+
+# From pprint.pprint([ binascii.b2a_hex(os.urandom(32)) for _ in xrange(8) ])
+BLINDING_PARAMS = [
+ '54a513898b471d1d448a2f3c55c1de2c0ef718c447b04497eeb999ed32027823',
+ '831e9b5325b5d31b7ae6197e9c7a7baf2ec361e08248bce055908971047a2347',
+ 'ac78a1d46faf3bfbbdc5af5f053dc6dc9023ed78236bec1760dadfd0b2603760',
+ 'f9c84dc0ac31571507993df94da1b3d28684a12ad14e67d0a068aba5c53019fc',
+ 'b1fe79d1dec9bc108df69f6612c72812755751f21ecc5af99663b30be8b9081f',
+ '81f1512b63ab5fb5c1711a4ec83d379c420574aedffa8c3368e1c3989a3a0084',
+ '97f45142597c473a4b0e9a12d64561133ad9e1155fe5a9807fe6af8a93557818',
+ '3f44f6a5a92cde816635dfc12ade70539871078d2ff097278be2a555c9859cd0']
+
+PREFIX = "ED25519_"
+
+def writeArray(name, array):
+ print "static const char *{prefix}{name}[] = {{".format(
+ prefix=PREFIX,name=name)
+ for a in array:
+ h = binascii.b2a_hex(a)
+ if len(h) > 70:
+ h1 = h[:70]
+ h2 = h[70:]
+ print ' "{0}"\n "{1}",'.format(h1,h2)
+ else:
+ print ' "{0}",'.format(h)
+ print "};\n"
+
+def comment(text, initial="/**"):
+ print initial
+ print textwrap.fill(text,initial_indent=" * ",subsequent_indent=" * ")
+ print " */"
+
+def makeTestVectors():
+ comment("""Test vectors for our ed25519 implementation and related
+ functions. These were automatically generated by the
+ ed25519_exts_ref.py script.""", initial="/*")
+
+
+ comment("""Secret key seeds used as inputs for the ed25519 test vectors.
+ Randomly generated. """)
+ secretKeys = [ binascii.a2b_hex(r) for r in RAND_INPUTS ]
+ writeArray("SECRET_KEYS", secretKeys)
+
+ comment("""Secret ed25519 keys after expansion from seeds. This is how Tor
+ represents them internally.""")
+ expandedSecretKeys = [ expandSK(sk) for sk in secretKeys ]
+ writeArray("EXPANDED_SECRET_KEYS", expandedSecretKeys)
+
+ comment("""Public keys derived from the above secret keys""")
+ publicKeys = [ publickey(sk) for sk in secretKeys ]
+ writeArray("PUBLIC_KEYS", publicKeys)
+
+ comment("""The curve25519 public keys from which the ed25519 keys can be
+ derived. Used to test our 'derive ed25519 from curve25519'
+ code.""")
+ writeArray("CURVE25519_PUBLIC_KEYS",
+ (slownacl_curve25519.smult_curve25519_base(sk[:32])
+ for sk in expandedSecretKeys))
+
+ comment("""Parameters used for key blinding tests. Randomly generated.""")
+ blindingParams = [ binascii.a2b_hex(r) for r in BLINDING_PARAMS ]
+ writeArray("BLINDING_PARAMS", blindingParams)
+
+ comment("""Blinded secret keys for testing key blinding. The nth blinded
+ key corresponds to the nth secret key blidned with the nth
+ blinding parameter.""")
+ writeArray("BLINDED_SECRET_KEYS",
+ (blindESK(expandSK(sk), bp)
+ for sk,bp in zip(secretKeys,blindingParams)))
+
+ comment("""Blinded public keys for testing key blinding. The nth blinded
+ key corresponds to the nth public key blidned with the nth
+ blinding parameter.""")
+ writeArray("BLINDED_PUBLIC_KEYS",
+ (blindPK(pk, bp) for pk,bp in zip(publicKeys,blindingParams)))
+
+ comment("""Signatures of the public keys, made with their corresponding
+ secret keys.""")
+ writeArray("SELF_SIGNATURES",
+ (signature(pk, sk, pk) for pk,sk in zip(publicKeys,secretKeys)))
+
+
+
+if __name__ == '__main__':
+ import sys
+ if len(sys.argv) == 1 or sys.argv[1] not in ("SelfTest", "MakeVectors"):
+ print "You should specify one of 'SelfTest' or 'MakeVectors'"
+ sys.exit(1)
+ if sys.argv[1] == 'SelfTest':
+ unittest.main()
+ else:
+ makeTestVectors()
+
+
diff --git a/src/test/ed25519_vectors.inc b/src/test/ed25519_vectors.inc
new file mode 100644
index 0000000000..760bafb971
--- /dev/null
+++ b/src/test/ed25519_vectors.inc
@@ -0,0 +1,150 @@
+/*
+ * Test vectors for our ed25519 implementation and related
+ * functions. These were automatically generated by the
+ * ed25519_exts_ref.py script.
+ */
+/**
+ * Secret key seeds used as inputs for the ed25519 test vectors.
+ * Randomly generated.
+ */
+static const char *ED25519_SECRET_KEYS[] = {
+ "26c76712d89d906e6672dafa614c42e5cb1caac8c6568e4d2493087db51f0d36",
+ "fba7a5366b5cb98c2667a18783f5cf8f4f8d1a2ce939ad22a6e685edde85128d",
+ "67e3aa7a14fac8445d15e45e38a523481a69ae35513c9e4143eb1c2196729a0e",
+ "d51385942033a76dc17f089a59e6a5a7fe80d9c526ae8ddd8c3a506b99d3d0a6",
+ "5c8eac469bb3f1b85bc7cd893f52dc42a9ab66f1b02b5ce6a68e9b175d3bb433",
+ "eda433d483059b6d1ff8b7cfbd0fe406bfb23722c8f3c8252629284573b61b86",
+ "4377c40431c30883c5fbd9bc92ae48d1ed8a47b81d13806beac5351739b5533d",
+ "c6bbcce615839756aed2cc78b1de13884dd3618f48367a17597a16c1cd7a290b",
+};
+
+/**
+ * Secret ed25519 keys after expansion from seeds. This is how Tor
+ * represents them internally.
+ */
+static const char *ED25519_EXPANDED_SECRET_KEYS[] = {
+ "c0a4de23cc64392d85aa1da82b3defddbea946d13bb053bf8489fa9296281f495022f1"
+ "f7ec0dcf52f07d4c7965c4eaed121d5d88d0a8ff546b06116a20e97755",
+ "18a8a69a06790dac778e882f7e868baacfa12521a5c058f5194f3a729184514a2a656f"
+ "e7799c3e41f43d756da8d9cd47a061316cfe6147e23ea2f90d1ca45f30",
+ "58d84f8862d2ecfa30eb491a81c36d05b574310ea69dae18ecb57e992a896656b98218"
+ "7ee96c15bf4caeeab2d0b0ae4cd0b8d17470fc7efa98bb26428f4ef36d",
+ "50702d20b3550c6e16033db5ad4fba16436f1ecc7485be6af62b0732ceb5d173c47ccd"
+ "9d044b6ea99dd99256adcc9c62191be194e7cb1a5b58ddcec85d876a2b",
+ "7077464c864c2ed5ed21c9916dc3b3ba6256f8b742fec67658d8d233dadc8d5a7a82c3"
+ "71083cc86892c2c8782dda2a09b6baf016aec51b689183ae59ce932ff2",
+ "8883c1387a6c86fc0bd7b9f157b4e4cd83f6885bf55e2706d2235d4527a2f05311a359"
+ "5953282e436df0349e1bb313a19b3ddbf7a7b91ecce8a2c34abadb38b3",
+ "186791ac8d03a3ac8efed6ac360467edd5a3bed2d02b3be713ddd5be53b3287ee37436"
+ "e5fd7ac43794394507ad440ecfdf59c4c255f19b768a273109e06d7d8e",
+ "b003077c1e52a62308eef7950b2d532e1d4a7eea50ad22d8ac11b892851f1c40ffb9c9"
+ "ff8dcd0c6c233f665a2e176324d92416bfcfcd1f787424c0c667452d86",
+};
+
+/**
+ * Public keys derived from the above secret keys
+ */
+static const char *ED25519_PUBLIC_KEYS[] = {
+ "c2247870536a192d142d056abefca68d6193158e7c1a59c1654c954eccaff894",
+ "1519a3b15816a1aafab0b213892026ebf5c0dc232c58b21088d88cb90e9b940d",
+ "081faa81992e360ea22c06af1aba096e7a73f1c665bc8b3e4e531c46455fd1dd",
+ "73cfa1189a723aad7966137cbffa35140bb40d7e16eae4c40b79b5f0360dd65a",
+ "66c1a77104d86461b6f98f73acf3cd229c80624495d2d74d6fda1e940080a96b",
+ "d21c294db0e64cb2d8976625786ede1d9754186ae8197a64d72f68c792eecc19",
+ "c4d58b4cf85a348ff3d410dd936fa460c4f18da962c01b1963792b9dcc8a6ea6",
+ "95126f14d86494020665face03f2d42ee2b312a85bc729903eb17522954a1c4a",
+};
+
+/**
+ * The curve25519 public keys from which the ed25519 keys can be
+ * derived. Used to test our 'derive ed25519 from curve25519'
+ * code.
+ */
+static const char *ED25519_CURVE25519_PUBLIC_KEYS[] = {
+ "17ba77846e04c7ee5ca17cade774ac1884408f9701f439d4df32cbd8736c6a1f",
+ "022be2124bc1899a78ba2b4167d191af3b59cadf94f0382bc31ce183a117f161",
+ "bf4fd38ef22f718f03c0a12ba5127bd1e3afd494793753f519728b29cc577571",
+ "56c493e490261cef31633efd2461d2b896908e90459e4eecde950a895aef681d",
+ "089675a3e8ff2a7d8b2844a79269c95b7f97a4b8b5ea0cbeec669c6f2dea9b39",
+ "59e20dcb691c4a345fe86c8a79ac817e5b514d84bbf0512a842a08e43f7f087e",
+ "9e43b820b320eda35f66f122c155b2bf8e2192c468617b7115bf067d19e08369",
+ "861f33296cb57f8f01e4a5e8a7e5d5d7043a6247586ab36dea8a1a3c4403ee30",
+};
+
+/**
+ * Parameters used for key blinding tests. Randomly generated.
+ */
+static const char *ED25519_BLINDING_PARAMS[] = {
+ "54a513898b471d1d448a2f3c55c1de2c0ef718c447b04497eeb999ed32027823",
+ "831e9b5325b5d31b7ae6197e9c7a7baf2ec361e08248bce055908971047a2347",
+ "ac78a1d46faf3bfbbdc5af5f053dc6dc9023ed78236bec1760dadfd0b2603760",
+ "f9c84dc0ac31571507993df94da1b3d28684a12ad14e67d0a068aba5c53019fc",
+ "b1fe79d1dec9bc108df69f6612c72812755751f21ecc5af99663b30be8b9081f",
+ "81f1512b63ab5fb5c1711a4ec83d379c420574aedffa8c3368e1c3989a3a0084",
+ "97f45142597c473a4b0e9a12d64561133ad9e1155fe5a9807fe6af8a93557818",
+ "3f44f6a5a92cde816635dfc12ade70539871078d2ff097278be2a555c9859cd0",
+};
+
+/**
+ * Blinded secret keys for testing key blinding. The nth blinded
+ * key corresponds to the nth secret key blidned with the nth
+ * blinding parameter.
+ */
+static const char *ED25519_BLINDED_SECRET_KEYS[] = {
+ "014e83abadb2ca9a27e0ffe23920333d817729f48700e97656ec2823d694050e171d43"
+ "f24e3f53e70ec7ac280044ac77d4942dee5d6807118a59bdf3ee647e89",
+ "fad8cca0b4335847795288b1452508752b253e64e6c7c78d4a02dbbd7d46aa0eb8ceff"
+ "20dfcf53eb52b891fc078c934efbf0353af7242e7dc51bb32a093afa29",
+ "116eb0ae0a4a91763365bdf86db427b00862db448487808788cc339ac10e5e089217f5"
+ "2e92797462bd890fc274672e05c98f2c82970d640084781334aae0f940",
+ "bd1fbb0ee5acddc4adbcf5f33e95d9445f40326ce579fdd764a24483a9ccb20f509ece"
+ "e77082ce088f7c19d5a00e955eeef8df6fa41686abc1030c2d76807733",
+ "237f5345cefe8573ce9fa7e216381a1172796c9e3f70668ab503b1352952530fb57b95"
+ "a440570659a440a3e4771465022a8e67af86bdf2d0990c54e7bb87ff9a",
+ "ba8ff23bc4ad2b739e1ccffc9fbc7837053ea81cdfdb15073f56411cfbae1d0ec492fc"
+ "87d5ec2a1b185ca5a40541fdef0b1e128fd5c2380c888bfa924711bcab",
+ "0fa68f969de038c7a90a4a74ee6167c77582006f2dedecc1956501ba6b6fb10391b476"
+ "8f8e556d78f4bdcb9a13b6f6066fe81d3134ae965dc48cd0785b3af2b8",
+ "deaa3456d1c21944d5dcd361a646858c6cf9336b0a6851d925717eb1ae186902053d9c"
+ "00c81e1331c06ab50087be8cfc7dc11691b132614474f1aa9c2503cccd",
+};
+
+/**
+ * Blinded public keys for testing key blinding. The nth blinded
+ * key corresponds to the nth public key blidned with the nth
+ * blinding parameter.
+ */
+static const char *ED25519_BLINDED_PUBLIC_KEYS[] = {
+ "722d6da6348e618967ef782e71061e27163a8b35f21856475d9d2023f65b6495",
+ "1dffa0586da6cbfcff2024eedf4fc6c818242d9a82dbbe635d6da1b975a1160d",
+ "5ed81f98fed5a6acda4ea6da2c34fab0ab359d950c510c256473f1f33ff438b4",
+ "6e6f92a54fb282120c46d9603df41135f025bc1f58f283809d04be96aeb04040",
+ "cda236f28edc4c7e02d18007b8dab49d669265b0f7aefb1824d7cc8e73a2cd63",
+ "367b03b17b67ca7329b89a520bdab91782402a41cd67264e34b5541a4b3f875b",
+ "8d486b03ac4e3b486b7a1d563706c7fdac75aee789a7cf6f22789eedeff61a31",
+ "9f297ff0aa2ceda91c5ab1b6446f12533d145940de6d850dc323417afde0cb78",
+};
+
+/**
+ * Signatures of the public keys, made with their corresponding
+ * secret keys.
+ */
+static const char *ED25519_SELF_SIGNATURES[] = {
+ "d23188eac3773a316d46006fa59c095060be8b1a23582a0dd99002a82a0662bd246d84"
+ "49e172e04c5f46ac0d1404cebe4aabd8a75a1457aa06cae41f3334f104",
+ "3a785ac1201c97ee5f6f0d99323960d5f264c7825e61aa7cc81262f15bef75eb4fa572"
+ "3add9b9d45b12311b6d403eb3ac79ff8e4e631fc3cd51e4ad2185b200b",
+ "cf431fd0416bfbd20c9d95ef9b723e2acddffb33900edc72195dea95965d52d888d30b"
+ "7b8a677c0bd8ae1417b1e1a0ec6700deadd5d8b54b6689275e04a04509",
+ "2375380cd72d1a6c642aeddff862be8a5804b916acb72c02d9ed052c1561881aa658a5"
+ "af856fcd6d43113e42f698cd6687c99efeef7f2ce045824440d26c5d00",
+ "2385a472f599ca965bbe4d610e391cdeabeba9c336694b0d6249e551458280be122c24"
+ "41dd9746a81bbfb9cd619364bab0df37ff4ceb7aefd24469c39d3bc508",
+ "e500cd0b8cfff35442f88008d894f3a2fa26ef7d3a0ca5714ae0d3e2d40caae58ba7cd"
+ "f69dd126994dad6be536fcda846d89dd8138d1683cc144c8853dce7607",
+ "d187b9e334b0050154de10bf69b3e4208a584e1a65015ec28b14bcc252cf84b8baa9c9"
+ "4867daa60f2a82d09ba9652d41e8dde292b624afc8d2c26441b95e3c0e",
+ "815213640a643d198bd056e02bba74e1c8d2d931643e84497adf3347eb485079c9afe0"
+ "afce9284cdc084946b561abbb214f1304ca11228ff82702185cf28f60d",
+};
+
diff --git a/src/test/example_extrainfo.inc b/src/test/example_extrainfo.inc
new file mode 100644
index 0000000000..e096afd6c4
--- /dev/null
+++ b/src/test/example_extrainfo.inc
@@ -0,0 +1,425 @@
+static const char EX_EI_MINIMAL[] =
+ "extra-info bob 3E1B2DC141F2B7C6A0F3C4ED9A14A9C35762E24B\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "K5GAkVjpUlofL78NIOE1VDxFn8yYbHK50rVuZG2HxqG/727bon+uMprv4MHjfDcP\n"
+ "V3l9u1uUdGiUPOl8j+hRNw4z/ODeCj/24r2+L32MTjyfUhK49Ld2IlK9iZKlgKYi\n"
+ "zyoatxdAjU8Xc5WPX692HO4/R9CGLsUfYcEEFU2R3EA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_MINIMAL_FP[] = "3E1B2DC141F2B7C6A0F3C4ED9A14A9C35762E24B";
+static const char EX_EI_MINIMAL_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALSppIF3t3wOAm4fzxRvK+q/wh1gGAWwS0JEn8d+c/x+rt1oQabGkqsB\n"
+ "GU6rz1z1AN02W0P2+EcyJQVBjGR3gHQNoDGx0KIdnr3caGAw3XmQXrJLPaViEk28\n"
+ "RJMxx6umpP27YKSyEMHgVTDXblKImT0mE7fVOx8tD0EWRYazmp4NAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_MAXIMAL[] =
+ "extra-info bob FF8248FE780A7236D3FA5D62DEA642055135F942\n"
+ "published 2014-10-05 20:07:00\n"
+ "opt foobarbaz\n"
+ "read-history 900 1,2,3\n"
+ "write-history 900 1,2,3\n"
+ "dirreq-v2-ips 1\n"
+ "dirreq-v3-ips 100\n"
+ "dirreq-v3-reqs blahblah\n"
+ "dirreq-v2-share blahblah\n"
+ "dirreq-v3-share blahblah\n"
+ "dirreq-v2-resp djfkdj\n"
+ "dirreq-v3-resp djfkdj\n"
+ "dirreq-v2-direct-dl djfkdj\n"
+ "dirreq-v3-direct-dl djfkdj\n"
+ "dirreq-v2-tunneled-dl djfkdj\n"
+ "dirreq-v3-tunneled-dl djfkdj\n"
+ "dirreq-stats-end foobar\n"
+ "entry-ips jfsdfds\n"
+ "entry-stats-end ksdflkjfdkf\n"
+ "cell-stats-end FOO\n"
+ "cell-processed-cells FOO\n"
+ "cell-queued-cells FOO\n"
+ "cell-time-in-queue FOO\n"
+ "cell-circuits-per-decile FOO\n"
+ "exit-stats-end FOO\n"
+ "exit-kibibytes-written FOO\n"
+ "exit-kibibytes-read FOO\n"
+ "exit-streams-opened FOO\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "ZO79bLlWVNIruCnWW9duDcOKydPWbL5DfrpUv5IRLF4MMFoacMUdJPDUs9e+wY2C\n"
+ "zndHe6i2JK7yKJj+uCOSC8cx61OLG+kVxMLJ/qhA4H5thrYb+GpzMKwbHzQc3PTH\n"
+ "zHRzj041iWXTL7/DMaQlpJOBoac/wTSIKzoV2B00jBw=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_MAXIMAL_FP[] = "FF8248FE780A7236D3FA5D62DEA642055135F942";
+static const char EX_EI_MAXIMAL_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANSpkYhHUW1EqodY4d3JRbvEM1vjjR/vEE8gjONiJ5t2Sten53jzt8bh\n"
+ "8/VJn7pQGs8zR5CIxCw4P68xMtZJJedS3hhjqubheOE/yW1DtpkiCf+zVEaLpeA8\n"
+ "fYQChkRICnR/BZd4W9bbohLVII5ym2PaJt2ihB3FeVZIsGXm4wxhAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_BAD_SIG1[] =
+ "extra-info bob 3E1B2DC141F2B7C6A0F3C4ED9A14A9C35762E24B\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "K5GAkVjpUlofL78NIOE1VDxFn8yYbHK50rVuZG2HxqG/727bon+uMprv4MHjfDcP\n"
+ "V3l9u1uUdGiUPOl8j+hXXw4z/ODeCj/24r2+L32MTjyfUhK49Ld2IlK9iZKlgKYi\n"
+ "zyoatxdAjU8Xc5WPX692HO4/R9CGLsUfYcEEFU2R3EA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_SIG2[] =
+ "extra-info bob 3E1B2DC141F2B7C6A0F3C4ED9A14A9C35762E24B\n"
+ "published 2014-10-06 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "K5GAkVjpUlofL78NIOE1VDxFn8yYbHK50rVuZG2HxqG/727bon+uMprv4MHjfDcP\n"
+ "V3l9u1uUdGiUPOl8j+hRNw4z/ODeCj/24r2+L32MTjyfUhK49Ld2IlK9iZKlgKYi\n"
+ "zyoatxdAjU8Xc5WPX692HO4/R9CGLsUfYcEEFU2R3EA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_SIG3[] =
+ "extra-info bob 3E1B2DC141F2B7C6A0F3C4ED9A14A9C35762E24B\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "K5GAkVjpUlofL78NIOE1VDxFn8yYbHK50rVuZG2HxqG/727bon+uMprv4MHjfDcP\n"
+ "V3l9u1uUdGiUPOl8j+hRNw4z/ODeCj/24r2+L32MTjyfUhK49Ld2IlK9iZKlgKYi\n"
+ "zyoatxdAjU8Xc5WPX692HO4/R9CGLsUfYcEEFU2=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_FP[] =
+ "extra-info bob C34293303F0F1E42CB14E593717B834E8E53797D8888\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "IDA8ryUYeMx7+Au/xQmX7Y8fXksoHUOXmePND2JYM4rPfishQJ1LpQ15KrolOZDH\n"
+ "FVIk3RmCefNlJeS1/UgWPcU8u2nGw1YQuRBHF4ViTmZ0OevI1pTsSApl4+oIx2dy\n"
+ "DGgCQmKfMbaOixIK8Ioh1Z2NUfMkjbUUE2WWgFTAsac=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_FP_FP[] = "C34293303F0F1E42CB14E593717B834E8E53797D";
+static const char EX_EI_BAD_FP_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKXMSbif4fG+BW/5lIq5V1tMRondIUfKiNizp0E6EcBw5LvYfQV6zrj8\n"
+ "HmMFbB/WGf9XGVMxIBzxzeQBRvCQJh+0QH7+ju5/isIHJZsACMILepr6ywmCcjVU\n"
+ "iYRtC8zGQLqfkf2cNoo7AhcI5i/YzyW2u1zmbPX5J+8sUErfxydbAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_BAD_NICKNAME[] =
+ "extra-info bobhasaverylongnameandidontthinkweshouldlethim A4EA2389A52459B3F7C7121A46012F098BDFC2A4\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "e2wLJFThRMGawxKrQPuH2XCLek/LJsg4XOB8waAjE0xdHOrzjur9x1jIxy7DVU6t\n"
+ "z1edbIoL24qucMJvFy2xjSQhFRX4OsyNc0nWr3LfJnTW9aEmxuwXM+mltUD2uFN1\n"
+ "2vYOIQjUmJwS2yfeSKnhXEl2PWVUmgzYL3r4S5kHco4=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_NICKNAME_FP[] = "A4EA2389A52459B3F7C7121A46012F098BDFC2A4";
+static const char EX_EI_BAD_NICKNAME_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKfq7oxD1kMu1+zeG2UVXN4vOu6FDp0V/olA3ttmXpUCgCiBxWTgtwNl\n"
+ "nPf0HcKMaCp/0D9XrbhvIoOsg0OTf1TcJfGsA/zPG7jrWYa4xhD50KYvty9EINK9\n"
+ "/UBWNSyXCFDMqnddb/LZ8+VgttmxfYkpeRzSSmDijN3RbOvYJhhBAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+const char EX_EI_BAD_TOKENS[] =
+ "extra-info bob 6F314FB01A31162BD5E473D4977AC570DC5B86BB\n"
+ "published 2014-10-05 20:07:00\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "lhRIafrkKoQmnUoBLiq4XC8XKXrleGJZ5vefkLcgjOJ5IffsvVdIA7Vqq/ISbPrG\n"
+ "b/Zs0sJNL6naHPxJBglgHJqksSyiYHaeOetXg2Rb+vZ1v2S5BrVgk1nPMDhyIzqc\n"
+ "zU7eCxFf/1sXKtWlEKxGdX4LmVfnIln5aI31Bc4xRrE=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+const char EX_EI_BAD_TOKENS_FP[] = "6F314FB01A31162BD5E473D4977AC570DC5B86BB";
+const char EX_EI_BAD_TOKENS_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL7Z8tz45Tb4tnEFS2sAyjubBV/giSfZdmXRkDV8Jo4xqWqhWFJn7+zN\n"
+ "AXBWBThGeVH2WXrpz5seNJXgZJPxMTMsrnSCGcRXZw0Npti2MkLuQ6+prZa+OPwE\n"
+ "OyC6jivtAaY/o9iYQjDC2avLXD3N4LvoygyF418KnNcjbzuFygffAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_BAD_START[] =
+ "published 2014-10-05 20:07:00\n"
+ "extra-info bob 5CCCACE71A9BDB5E8E0C942AB3407452350434C0\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "BOiWgexqCAMZ8uyJ7jwBwRkz7Ox8cT4BImkmkV3bQiZgcWvPiYA3EnCm2ye48Ldg\n"
+ "zBST2p6zJM5o4MEDYGMxfViS86Abj/z7DOY1gtLhjmAaVjIIpXc3koxEZtzCecqy\n"
+ "JQz6xEg9/KoEuoT0DRrfYQ+KtQfzBDWrotfOvEa1rvc=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_START_FP[] = "5CCCACE71A9BDB5E8E0C942AB3407452350434C0";
+static const char EX_EI_BAD_START_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAK2OCIfM6Cin/lq99Z3w9tl6HeyGlkBZu9MQEPHxqGIHTq78lIC1UkrC\n"
+ "6NTqlrHBV9dmfzdwJn4GgMWsCZafL0FPIH3HNyNKUxLgyjixyKljHx2rfErSfOxI\n"
+ "bMoOGBKv7m1EZZ0O5uG9ly9MBiNGdJyLdlnVvH7wSCnYciizpO4lAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_BAD_PUBLISHED[] =
+ "extra-info bob E67C477E3536BDE348BD407426D9679E5AE0BC16\n"
+ "published 2014-99-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "l45IziBaXRKIjPAIUogMFNjQgH6k6Vm0+6r5+oByr4sP+B3ufNdUA6+WqBs43F0Z\n"
+ "IqcJiT9nFn0DuNd/liOyOCixppDLx5h5NrhoGqcT3ySADEEXhzjlmc35TI3YBNVO\n"
+ "v98fotmwIEg9YRWVGPg6XuIn2PRyiboFyjUpaYGCV0Q=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_EI_BAD_PUBLISHED_FP[] = "E67C477E3536BDE348BD407426D9679E5AE0BC16";
+static const char EX_EI_BAD_PUBLISHED_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL7q8GEI18iv8Fo0QbNHmFatQ2FNacalPldpmKUdMJYEVZtdOR0nhcrY\n"
+ "BvG6303md3INygg+KP49RvWEJR/cU4RZ9QfHpORxH2OocMyRedw2rLex2E7jNNSi\n"
+ "52yd1sHFYI8ZQ4aff+ZHUjJUGKRyqpbc8okVbq/Rl7vug0dd12eHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static const char EX_EI_GOOD_ED_EI[] =
+ "extra-info emma A692FE045C32B5E3A54B52882EF678A9DAC46A73\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AYgHn/OKR8GHBlscN5VkO73wA9jSci8QgTM30615ZT44AQAgBAC08woT\n"
+ "MBZpKzRcaoEJhEG7+RmuYtnB2+nODk9IRIs8ZoyYPTZ6dLzI+MLMmtzUuo/Wmvw0\n"
+ "PflTyCb2RlWitOEhAErWH3Z9UmYGnzM/COId0Fe3ScSriyvRoFnJY1+GVAQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 a7K8nwfg+HrdlSGQwr9rnLBq0qozkyZZs6d6aiLEiXGdhV1r9KJncmlQ5SNoY/zMQlyQm8EV5rCyBiVliKQ1Bw\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "GvmCmIGgbC1DeawRyRuChy62VmBOG0EviryG/a2qSZiFy0iPPwqSp5ZyZDQEIEId\n"
+ "kkk1zPzK1+S3fmgOAXyXGH0r4YFkoLGnhMk07BoEwi6HEXzjJsabmcNkOHfaOWgs\n"
+ "/5nvnLfcmxL4c6FstZ7t9VQpE06y3GU0zwBeIy1qjp0=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ ;
+const char EX_EI_GOOD_ED_EI_FP[] = "A692FE045C32B5E3A54B52882EF678A9DAC46A73";
+static const char EX_EI_GOOD_ED_EI_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM3jdYwjwGxDWYj/vyFkQT7RgeCNIn89Ei6D2+L/fdtFnqrMXOreFFHL\n"
+ "C7CK2v2uN3v+uXxfb5lADz3NcalxJrCfGTGtaBk7PwMZraTSh2luFKOvSRBQCmB1\n"
+ "yD5N0QqnIhBJoGr6NITpbWyiTKWvYLjl9PZd9af8e8jQCAa5P1j1AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+
+static const char EX_EI_ED_MISSING_SIG[] =
+ "extra-info rachel 2A7521497B91A8437021515308A47491164EDBA1\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AT2/T71LFYHiI1ppwNiuaewIu2Hq+GWWQ85O8gpWcUxeAQAgBAC2dgYu\n"
+ "moxhtuip7GVlthT9iomZKba1IllVa7uE1u2uO9BUYZQWXciFt7OnNzMH5mlffwxB\n"
+ "1dWCl+G5nbOsV5jYLbfhrF5afZotf+EQTfob4cCH79AV223LPcySbTHTtQ4=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "oypRD2IZQ5EttOE8dvofrW80nnBfijSkvYzBrM6H4KVeayRYvWfmi96dYO6ybMqm\n"
+ "Yp7Gs3ngqeeNdfHtkRPuQVUXUGYZgBTvYItuagnFlFgRqaHy0knwUIVOL35eqWYx\n"
+ "xSbQKA7fglxEDMFs/RK7FRP4dWc731ZMt5wzzfJHZ8E=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ ;
+const char EX_EI_ED_MISSING_SIG_FP[] = "2A7521497B91A8437021515308A47491164EDBA1";
+static const char EX_EI_ED_MISSING_SIG_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOOB8ccxbtk2dB5FuKFhGndDcO6STNjB6KiG0b9X2QwKrOZMfmXSigto\n"
+ "mtC1JfPTxECayRjLSiP/9UD8iTVvlcnc8mMWBGM12Pa/KoCZRn7McHI3JJ7n9lfn\n"
+ "qw9+iZ9b/rBimzOb3W6k3uxzg9r8secdq4jJwTnwSjTObgxZtC8/AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+
+static const char EX_EI_ED_MISSING_CERT[] =
+ "extra-info lynne E88E43E86015345A323D93D825C33E4AD1028F65\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 H4gKIKm5K9Pfkriy7SlMUD6BdYVp6B5mXKzR/rTyYlpH0tEZ4Fx2hlHNfNNdWXJieXzKZQZo8e7SOVzvrAC3CQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "dIrbQjK5T9t5KM8CpsMF85hh2i060oPIxzYQMgE1q4j99dtb/n7SE8nhj1Sjij4D\n"
+ "7JvTjGdLHi3bFSxXaSmla0wxD9PUYFN7VsBQmwSaDrqrzJFb1SGwZuzW1IEZ7BBi\n"
+ "H0czsxEteg5hcNRwISj5WVthuWmau9v13MijtZGSK40=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ "\n"
+ ;
+const char EX_EI_ED_MISSING_CERT_FP[] = "E88E43E86015345A323D93D825C33E4AD1028F65";
+static const char EX_EI_ED_MISSING_CERT_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALjA/geb0TR9rp/UPvLhABQpB0XUDYuZAnLkrv+i7AAV7FemTDveEGnc\n"
+ "XdXNSusO1mHOquvr0YYKPhwauInxD56S8QOzLYiWWajGq8XHARQ33b4/9K2TUrAx\n"
+ "W9HTHV1U1zrPlCJtrkbjxsYoHpUg5ljzM7FGYGY5xuvyHu18SQvzAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+static const char EX_EI_ED_BAD_CERT1[] =
+ "extra-info marcie F78D8A655607D32281D02144817A4F1D26AE520F\n"
+ "identity-ed25519\n"
+ "-----BEGIN PLAGICAL SPELL-----\n"
+ "aaaa\n"
+ "-----END PLAGICAL SPELL\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 KQJ+2AH7EkkjrD0RtDtUAIr+Vc7wndwILYnoUxFLSJiTP+5fMi54eFF/f1OgkG8gYyTh8phMij9WOxK/dsOpBg\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "XWD+P25AH6moi79j20Si3hqKGcJDws+FORL1MTu+GeJLV1mp5CR9N83UH4ffulcL\n"
+ "CpSSBDL/j74HqapzW7QvBx3FilaNT55GvcobZDFK4TKkCEyEmcuWKpEceBS7JTTV\n"
+ "SvwZeOObTjWPafELbsc/gI9Rh5Idwu7mZt3ZVntCGaQ=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+const char EX_EI_ED_BAD_CERT1_FP[] = "F78D8A655607D32281D02144817A4F1D26AE520F";
+static const char EX_EI_ED_BAD_CERT1_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMlR46JhxsCmWYtmIB/JjTV2TUYIhJLmHy+X7FfkK3ZVQvvl9/3GSXFL\n"
+ "3USfyf3j34XLh8An7pJBi9LAHkIXgnRbglCud7dXoexabmC+c2mSbw5RnuxDGEwz\n"
+ "krXUph/r2b+2UY1CgEt28nFigaHrIQbCmF4szFX/2GPYCLi5SrRNAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+static const char EX_EI_ED_BAD_CERT2[] =
+ "extra-info jaeger 7C2B42E783C4E0EB0CC3BDB37385D16737BACFBD\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55Acpw27GZBdwGCgawCj2F/DPadt8F/9DnEWywEew1Yi3qAOtLpCB8KXL7\n"
+ "4w5deFW2RBg8qTondNSUvAmwYLbLjNXMmgA3+nkoJOP3fcmQMHz1jm5xzgs2lCVP\n"
+ "t5txApaBIA4=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 DRQ4MLOGosBbW8M+17klNu8uWVkPxErmmEYoSo6OuH2Tzrcs6sUY+8Xi2qLoV1SbOugJ214Htl0I+6ceag+vBA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "DfdA+DbuN9nVJNujuSY5wNCDLk7Hfzkrde/sK0hVmZRvivtpF/Fy/dVQHHGNFY5i\n"
+ "L1cESAgq9HLdbHU+hcc08XXxTIaGwvoklcJClcG3ENVBWkTXbJNT+ifr7chEagIi\n"
+ "cVrtU6RVmzldSbyir8V/Z4S/Cm67gYAgjM5gfoFUqDs=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+const char EX_EI_ED_BAD_CERT2_FP[] = "7C2B42E783C4E0EB0CC3BDB37385D16737BACFBD";
+static const char EX_EI_ED_BAD_CERT2_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALAM1F/0XJEsbxIQqb3+ObX/yGVnq9of8Q9sLsmxffD6hwVpCqnV3lTg\n"
+ "iC6+xZ/bSlTGLPi0k8QLCaTmYxgKwmlMPpbQZ4kpZUrsb9flKdChMN7w8hd48pY9\n"
+ "lu8QiAEgErsl5rCCJIHHjrxxM/Cnd0TnedRnj/Z2YqpNx/ggsmsRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+static const char EX_EI_ED_BAD_SIG1[] =
+ "extra-info vary 5AC3A538FEEFC6F9FCC5FA0CE64704396C30D62A\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AbPp++GrRb6WphSu+PkMaYsqY/beiLBmtiV3YP5i2JkKAQAgBABKXjg1\n"
+ "aiz2JfQpNOG308i2EojnUAZEk0C0x9g2BAAXGL63sv3eO/qrlytsG1x2hkcamxFn\n"
+ "LmfZBb/prqe1Vy4wABuhqWHAUtM29vXR6lpiCJeddt9Pa8XVy/tgWLX6TAw=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 a7K8nwfg+HrdlSGQwr9rnLBq0qozkyZZs6d6aiLEiXGdhV1r9KJncmlQ5SNoY/zMQlyQm8EV5rCyBiVliKQ1Bw\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "xhZX8Qmgft51NJ7eMd4vrESzf/VdxDrBz7hgn8K+5bLtZUksG0s6s7IyGRYWQtp4\n"
+ "/7oc9sYe3lcQiUN2K7DkeBDlL8Pcsl8aIlKuujWomCE3j0TIu+8XK6oJeo7eYic+\n"
+ "IA7EwVbdZsKsW5/eJVzbX2eO0a5zyJ5RIYotFNYNCSE=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+const char EX_EI_ED_BAD_SIG1_FP[] = "5AC3A538FEEFC6F9FCC5FA0CE64704396C30D62A";
+static const char EX_EI_ED_BAD_SIG1_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMvb6SuoIkPfBkJgQuo5aQDepAs1kEETZ9VXotMlhB0JJikrqBrAAz+7\n"
+ "rjIJ4JsBaeQuN0Z5ksXk2ebxtef7oMIUs37NfekLQHbNR0VsXkFXPEGmOAqpZjW0\n"
+ "P524eHqybWYZTckvZtUvKI3xYGD6kEEkz4qmV6dcExU1OiAYO9jrAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+static const char EX_EI_ED_BAD_SIG2[] =
+ "extra-info coward 7F1D4DD477E340C6D6B389FAC26EDC746113082F\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf56AZkSDiFZ1QaiLJhcKdFDE5Kei/sPaPEIEoPMGP4BvOVXAQAgBAAlRLzx\n"
+ "U029tgIL9BRe47MVgcPJGy48db6ntzhjil7iOnWKT70z2LorUD5CZoLJs72TjB6r\n"
+ "8+HYNyFLEM6dvytWZf9NA5gLdhogbFcUk/R3gbNepmCF7XoZjbhPIp8zOwg=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-sig-ed25519 yfV+GySMIP1fw1oVa1C1de4XOWBqT4pUtEmSHq1h+WrLBNCh3/HZWvNC/denf2YVntuQrMLCJEv5ZaFKU+AIDQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "g+BWq69i9CP19va2cYMAXCQ6jK3IG0VmNYspjjUFgmFpJKGG6bHeOkuy1GXp47fG\n"
+ "LzZ3OPfJLptxU5AOQDUUYf25hu9uSl6gyknCzsszFs5n6ticuNejvcpzw6UfO1LP\n"
+ "5u+mGJlgpcMtmSraImDZrRipmZ3oRWvEULltlvzGQcQ=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+const char EX_EI_ED_BAD_SIG2_FP[] = "7F1D4DD477E340C6D6B389FAC26EDC746113082F";
+static const char EX_EI_ED_BAD_SIG2_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALzOyfCEUZnvCyhlyMctPkdXg/XRE3Cr6QgyzdKf5kQbUiu2n0FgSHOX\n"
+ "iP5gfq8sO9eVeTPZtjE7/+KiR8aQJECy+eoye+lpsfm3tXpLxnpOIgL4DlURxlo/\n"
+ "rfCyv30SYBN9j62qgU9m6U2ydI0tH7/9Ep8yIY/QL8me8VAjLbf/AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+
+static const char EX_EI_ED_MISPLACED_CERT[] =
+ "extra-info msselene 3B788BD0CE348BC5CED48313307C78175EB6D0F3\n"
+ "published 2014-10-05 20:07:00\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AWBcqjzLESDuLNGsqQ/tHn32XueXwj2fDlgEy/kQNVf/AQAgBAAFOegg\n"
+ "XY1LR82xE9ohAYJxYpwJJw0YfXsBhGHqfakEoBtSgFJ3cQAUXZQX4lX6G8IxAlQB\n"
+ "7Rj7dPQuQRUmqD1yyKb/ScBgCa8esxlhNlATz47kRNR38A3TcoJ4c1Zv6AE=\n"
+ "-----END ED25519 CERT-----\n"
+ "router-sig-ed25519 Q52JKH9/iMsr1jIPlWHHxakSBvyqjT1gzL944vad4OhzCZuNuAYGWyWSGzTb1DVmBqqbAUq73TiZKAz77YLNCQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "YplvAIwExGf5/L8AoroVQXtGm+26EffrxKBArMKn0zS1NOOie1p0oF/+qJg+rNWU\n"
+ "6cv3Anf188EXGlkUOddavgVH8CQbvve2nHSfIAPxjgEX9QNXbM5CiaMwgpCewXnF\n"
+ "UoNBVo5tydeLHVns15MBg/JNIxUQMd6svMoPp2WqmaE=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+const char EX_EI_ED_MISPLACED_CERT_FP[] = "3B788BD0CE348BC5CED48313307C78175EB6D0F3";
+static const char EX_EI_ED_MISPLACED_CERT_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALTwNqhTprg1oC6bEbDqwIYBoER6prqUXQFbwbFDn+ekXhZj8vltgGwp\n"
+ "aDGl9ceZWDKfi+reR6rZXjAJGctmv0VHkfe7maUX4FC/d2T8N8DvS+3IvJzFMpbT\n"
+ "O0fFrDTrCSnPikqFfQWnlP8yoF5vO7wo0jRRY432fLRXg9WqVzdrAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+static const char EX_EI_ED_MISPLACED_SIG[] =
+ "extra-info grazie 384E40A5DEED4AB1D8A74F1FCBDB18B7C24A8284\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AcGuIBoa6TBqD8Gg5atcwp/+r9ThxIBkULmPv9OSGhv+AQAgBACXH13y\n"
+ "mUvdpcN6oRN1nX6mnH40LyfYR5um8xogJZk3oINse5cRNrfMgVWiBpDlJZAwlDDa\n"
+ "lx99hzuZBong+CiOcnEvLMsBaVJmNTm5mpdetYclZpl0g8QEXznXXeRBMgM=\n"
+ "-----END ED25519 CERT-----\n"
+ "router-sig-ed25519 TxuO86dQ3pUaIY2raQ3hoDBmh4TTPC0OVgY98T5cf6Y+sHyiELCkkKQ3lqqXCjqnbTLr1/4riH980JoWPpR+Dw\n"
+ "published 2014-10-05 20:07:00\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "kV2CtArl1VF1nUSyHL00mO3nEdNxlQU5N7/hZNTd+45lej5Veb+6vb4ujelsFERJ\n"
+ "YoxwIs6SuKAR4orQytCL0e+GgZsrg8zGTveEtMX/+u//OcCwQBYEevR5duBZjVw/\n"
+ "yzpEHwdIdB2PPyDBLkf1VKnP7uDj059tXiQRWl7LXgE=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+const char EX_EI_ED_MISPLACED_SIG_FP[] = "384E40A5DEED4AB1D8A74F1FCBDB18B7C24A8284";
+static const char EX_EI_ED_MISPLACED_SIG_KEY[] =
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAK0HgOCG/6433VCrwz/vhk3cKmyOfenCp0GZ4DIUwPWt4DeyP4nTbN6T\n"
+ "1HJ1H8+hXC9bMuI4m43IWrzgLycQ9UaskUn372ZjHP9InPqHMJU6GQ7vZUe9Tgza\n"
+ "qnBdRPoxnrZzUOzlvatGrePt0hDiOZaMtDAkeEojFp9Wp2ZN7+tZAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ ;
+
diff --git a/src/test/failing_routerdescs.inc b/src/test/failing_routerdescs.inc
new file mode 100644
index 0000000000..e2b72c58a0
--- /dev/null
+++ b/src/test/failing_routerdescs.inc
@@ -0,0 +1,1569 @@
+/* This one actually succeeds */
+static const char EX_RI_MINIMAL[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAObzT4opT9uaThByupbb96tYxVpGxzL9CRPKUcU0beGpHyognD9USHWc\n"
+ "SpSpKfBL5P3xr2i/XTs34M4UTbT9PE7bVyxv7RD/BZmI4gc8R3PMU77xxbpEU5bK\n"
+ "LF3QUPpuB88m/2fXUGgMNVDc5MIq6pod2NRoDpeU7WA8T3ewXzK5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM1QKsQiup9DNMCgNeE2FkAhCWzpMZKCn1nNlZbDGfE3Z22ex6bdWWY6\n"
+ "ocEZ3JZDsZsnaZrdYxrL3Mquq7MbHdfx90EdlOvDRP1SAIbZ55mLR77fZTu4BKd/\n"
+ "h9BC6I26uZE0QavFq3+BhoVVhVn5Mqv05nR9CeUMSSZLxw/RJm4DAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Ft/y3JXowjItgfTHwYcZzuUgXrskluoINW5sr+GQoNYE2F4sT8o0tBBJwqJ6FwKd\n"
+ "fkIprv9UXqkv5iY+pXSYSI12mY1K5GMNkXiObk46NjuoNNP9l8oidhO6eNfcE+k3\n"
+ "CRIYS4FbBaD0fWUSwgMuo0Bp83/Wzp3B9ytEBh0/624=\n"
+ "-----END SIGNATURE-----\n";
+
+/* So does this, and it's bigger. */
+static const char EX_RI_MAXIMAL[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANNI56H+b7SW5LMzvXyY5NJzXszsHZZ4O1CPm4CePhBsAz1r0s1JYJ1F\n"
+ "Anrc0mEcLtmj0c5+HnhPBNrfpjO6G94Wp3NZMVykHDhfNVDBRyFZMroG8/GlysYB\n"
+ "MQPGQYR0xBgiuclNHoyk/vygQhZekumamu2O86EIPcfg9LhGIgEbAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALvuNVSmg6R9USFbQcNbRjMCJAV0Rwdv0DlS6Rl02ibJgb01G7v391xE\n"
+ "d9Njzgf93n8gOrE195bkUbvS6k/DM3HFGgArq6q9AZ2LTbu3KbAYy1YPsSIh07kB\n"
+ "/8kkvRRGx37X9WGZU3j5VUEuzqI//xDE9lbanlnnFXpnb6ymehDJAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject 127.0.0.1:*\n"
+ "accept *:80\n"
+ "reject *:*\n"
+ "ipv6-policy accept 80,100,101\n"
+ "ntor-onion-key s7rSohmz9SXn8WWh1EefTHIsWePthsEntQi0WL+ScVw\n"
+ "uptime 1000\n"
+ "hibernating 0\n"
+ "unrecognized-keywords are just dandy in this format\n"
+ "platform Tor 0.2.4.23 on a Banana PC Jr 6000 Series\n"
+ "contact O.W.Jones\n"
+ "fingerprint CC43 DC8E 8C9E 3E6D 59CD 0399 2491 0C8C E1E4 50D2\n"
+ "read-history 900 1,2,3,4\n"
+ "write-history 900 1,2,3,4\n"
+ "extra-info-digest AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
+ "hidden-service-dir\n"
+ "allow-single-hop-exits\n"
+ "family $AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA $BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
+ "caches-extra-info\n"
+ "or-address [::1:2:3:4]:9999\n"
+ "or-address 127.0.0.99:10000\n"
+ "opt fred is a fine router\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "x5cxL2h2UsEKk2OVnCTxOF8a89HAe/HwQnSlrBy8+l0YdVCcePDJhm1WyWU7ToHZ\n"
+ "K8auwreuw+u/n14sQHPYrM9NQE689hP4LC9AYOnrCnMHysfVqKuou+DSKYYRgs0D\n"
+ "ySCmJ9p+xekfmms+JBmS5o5DVo48VGlG0VksegoB264=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+/* I've messed with 12 bits of the signature on this one */
+static const char EX_RI_BAD_SIG1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAObzT4opT9uaThByupbb96tYxVpGxzL9CRPKUcU0beGpHyognD9USHWc\n"
+ "SpSpKfBL5P3xr2i/XTs34M4UTbT9PE7bVyxv7RD/BZmI4gc8R3PMU77xxbpEU5bK\n"
+ "LF3QUPpuB88m/2fXUGgMNVDc5MIq6pod2NRoDpeU7WA8T3ewXzK5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM1QKsQiup9DNMCgNeE2FkAhCWzpMZKCn1nNlZbDGfE3Z22ex6bdWWY6\n"
+ "ocEZ3JZDsZsnaZrdYxrL3Mquq7MbHdfx90EdlOvDRP1SAIbZ55mLR77fZTu4BKd/\n"
+ "h9BC6I26uZE0QavFq3+BhoVVhVn5Mqv05nR9CeUMSSZLxw/RJm4DAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Ft/y3JXowjItgfTHwYcZzuUgXrskluoINW5sr+GQoNYE2F4sT8o0tBBJwqJ6FwKd\n"
+ "fkIprv9UXqkv5iY+pXSYXX12mY1K5GMNkXiObk46NjuoNNP9l8oidhO6eNfcE+k3\n"
+ "CRIYS4FbBaD0fWUSwgMuo0Bp83/Wzp3B9ytEBh0/624=\n"
+ "-----END SIGNATURE-----\n";
+
+/* This is a good signature of the wrong data: I changed 'published' */
+static const char EX_RI_BAD_SIG2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAObzT4opT9uaThByupbb96tYxVpGxzL9CRPKUcU0beGpHyognD9USHWc\n"
+ "SpSpKfBL5P3xr2i/XTs34M4UTbT9PE7bVyxv7RD/BZmI4gc8R3PMU77xxbpEU5bK\n"
+ "LF3QUPpuB88m/2fXUGgMNVDc5MIq6pod2NRoDpeU7WA8T3ewXzK5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM1QKsQiup9DNMCgNeE2FkAhCWzpMZKCn1nNlZbDGfE3Z22ex6bdWWY6\n"
+ "ocEZ3JZDsZsnaZrdYxrL3Mquq7MbHdfx90EdlOvDRP1SAIbZ55mLR77fZTu4BKd/\n"
+ "h9BC6I26uZE0QavFq3+BhoVVhVn5Mqv05nR9CeUMSSZLxw/RJm4DAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:01\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Ft/y3JXowjItgfTHwYcZzuUgXrskluoINW5sr+GQoNYE2F4sT8o0tBBJwqJ6FwKd\n"
+ "fkIprv9UXqkv5iY+pXSYSI12mY1K5GMNkXiObk46NjuoNNP9l8oidhO6eNfcE+k3\n"
+ "CRIYS4FbBaD0fWUSwgMuo0Bp83/Wzp3B9ytEBh0/624=\n"
+ "-----END SIGNATURE-----\n";
+
+/* This one will fail while tokenizing the first line. */
+static const char EX_RI_BAD_TOKENS[] =
+ "router bob\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANGCgvZc+JRtAzuzk3gBD2rH9SHrXzjJ1wqdU3tLKr7FamKCMI2pLwSA\n"
+ "FZUpTuSqB9wJ/iVcYws+/kA3FjLqgPtzJFI0SVLvQcz5oIC1rEWpuP6t88duMlO9\n"
+ "flOUzmYu29sBffrXkQr8pesYvakyXArOJVeRR7fSvouneV5aDYWrAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAML+pYZoYc+whKLijupd63xn0gzlEQqe7k07x/lWMqWFT37FfG6YeNr5\n"
+ "fpFoo77FDfuFaL+VfPfI8i88g157hcPKBVX6OyRH54+l5By0tN91S0H+abXjXQpv\n"
+ "U/Bvmul+5QpUeVJa1nPg71HRIauoDnBNexUQ7Xf/Bwb2xCt+IJ6DAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "tbxtYYzyVqi6w6jz1k8NPjFvZaSNR0WzixVTTvKKGoMPx/6+Z8QAFK1ILzRUVucB\n"
+ "nRhmZMFaPr3vREMErLRE47ODAzwoBCE9C+vYFvROhgfzuQ3cYXla+4sMaRXYZzjH\n"
+ "PQ82bTwvSbHsR8fTTgePD/Ac082WxXTGpx6HOLBfNsQ=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_BAD_PUBLISHED[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMoipSwZgTG6SpSOm6ENbyALS1Ljqqa1LSGmtHSRfGYgUQGWZXERXKQj\n"
+ "P5ql6o7EbGr1wnispGW/KB8Age09jGDvd/oGhQ9TDFluhLZon3obkZSFw7f9iA7Q\n"
+ "s29rNxoeXXLZVyS7+sux70b8x2Dt4CeG8GA8nQLljy1euwU+qYYJAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPzfzQ+2WFMUvnB3z0xD+zwczWcFyYYNW8Lj7/aRGSNN2DICp5uzSjKq\n"
+ "qkYQ+C8jG21+MR2PE+ZBmq6CL5mvlFKlWKouXUlN7BejwWf2gw0UYag0SYctae1b\n"
+ "bu8NuUEvdeGWg5Odgs+abH7U9S0hEtjKrmE5vvJS5L841IcaPLCFAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 99:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "G92pnwCIXGJ9Q0fI9y4m/fHpWCsD0Hnk81/6T4TmRH3jt77fc0uRdomUOC5id4kz\n"
+ "J2M4vqXwRs5OK+eaPbtxf8Yv6FPmB3OBNCIhwNHIIqzKQStHUhPxD3P6j8uJFwot\n"
+ "/CNGciDN+owZ2DzwrXpszDfzcyp/nmwhApbi3W601vY=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+/* Bandwidth field isn't an integer. */
+static const char EX_RI_BAD_BANDWIDTH[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAN32LAvXQaq0p554FcL4LVwnxyiZvscfuFnfpXwWTDRJJHd2+JCttWIx\n"
+ "v+eW7dNq+rq/tzSzaZwnp8b4V2skLRojSt6UUHD234eZcsPwUNhSr0y1eMuoZbnV\n"
+ "UBBPevpuXea85aSFEXXRlIpQfvFc43y3/UFoRzo5iMPqReo2uQ4BAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMBuF1GvOyVcRDNjzlEmGHJkTA7qkaWgTp33NSY/DPEJoahg0Qswuh2w\n"
+ "1YCBqem6Txp+/Vl9hoUoUGwb7Vwq0+YDMSyr0z3Ih2NcNjOMZPVtjJuv+3wXrQC8\n"
+ "LPpCpfU9m9QvhQ7f9zprEqUHOQTT0v5j2a5bpfd++6LFxrMUNwbfAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth hello world today\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "svABTGDNJOgaiPLqDlkRU6ldYJcoEe2qHlr4O30lVM2hS3Gg6o4QARL7QRt7VepT\n"
+ "SruR6pE83xOr7/5Ijq5PlamS4WtODMJSH3DXT2hM5dYYrEX5jsJNZTQ+cYwPQI3y\n"
+ "ykuvQIutH6ipz5MYc9n0GWAzDjLq1G8wlcEfFXQLD10=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+/* Onion key is actually a signature. */
+static const char EX_RI_BAD_ONIONKEY1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANByIdFOKA3r2nnWyLjdZE8oGHqJE62T1zjW/nsCzCJQ8/kBMRYeGDu4\n"
+ "SeUJJ2rsh2t3PNzkqJM14f4DKmc2q76STsOW0Zcj70Bjhxb9r/OfyELVsi+x3CsE\n"
+ "Zo/W4JtdlVFjqevhODJdyFNLKOvqwG7sZo/K++Hx01Iu0zXLeg8nAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "svABTGDNJOgaiPLqDlkRU6ldYJcoEe2qHlr4O30lVM2hS3Gg6o4QARL7QRt7VepT\n"
+ "SruR6pE83xOr7/5Ijq5PlamS4WtODMJSH3DXT2hM5dYYrEX5jsJNZTQ+cYwPQI3y\n"
+ "ykuvQIutH6ipz5MYc9n0GWAzDjLq1G8wlcEfFXQLD10=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Cc/Y22KFvxXPXZtjvGIyQdjm4EMhXVXJEBwt8PvK7qlO1AgiVjEBPkUrTQQ/paLQ\n"
+ "lmeCN6jEVcZ8lNiVZgzRQ/2mTO3xLBPj26UNSDuouUwZ01tZ4wPENylNYnLKv5hg\n"
+ "gYARg/nXEJiTVe9LHl99Hr9EWWruRG2wFQjjTILaWzI=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+/* Onion key has exponent 3 */
+static const char EX_RI_BAD_ONIONKEY2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKP1kWHsH/BZhNSZmn0FyzIrAHtMl1IVPzc7ABbx+kK+IIEMD9k1fy2h\n"
+ "AP2JTm2UmJDUwutVxPsxmndI+9QsRDpu33E5Ai4U1Rb6Qu+2BRj43YAyg414caIu\n"
+ "J5LLn6bOzt7gtz0+q69WHbnwgI4zUgUbwYpwoB7k0dRY97xip9fHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGHAoGBANBKlyoqApWzG7UzmXcxhXM4T370FbN1edPbw4WAczBDXJslXCU9Xk1r\n"
+ "fKfoi/+WiTGvH7RcZWPm7wnThq2u2EAO/IPPcLE9cshLBkK28EvDg5K/WsYedbY9\n"
+ "1Gou+7ZSwMEPv2b13c7eWnSW1YvFa64pVDKu2sKnIjX6Bm0HZGbXAgED\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "cYcBOlapA+R4xq3nn5CjpnzNXdDArMlHuXv4MairjleF1n755ecH8A/R8YIc2ioV\n"
+ "n/C1TACzFVQ12Q9P3iikVOjIXNxYzaz4Lm/L/Lq4sEOPRJC38QEXeIHEaeM51lE6\n"
+ "p6kCqXcGu/51p5vAFCSiXI1ciucmx93N+TH1yGKRLV0=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_BAD_PORTS[] =
+ "router fred 127.0.0.1 900001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANVi/MVWhzT5uo3Jxw4ElS7UGmA24dnckdkCLetMhZOcE9e9mg4WcImL\n"
+ "NuBe2L/9YaL4PFVchCGlq73phKG6yFdqJdjDV8Qh9MJdAYWW2ORrjRvCrspPaYPN\n"
+ "BGJrkD2Gd4u3sq7f26TIkzmBx0Acd/FD4PQf8+XOt9YYd36ooS4vAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALtP4cIpAYp9nqo1ak4SxALcndFw4o51U36R4oa+uJS/lYQPHkMMOj6K\n"
+ "+AVnj9sxkDJ1POaU5lsCQ5JPG1t+Tkh7vDlJb6RCUy25vJOuaQCb9GVVY7KQTJqA\n"
+ "E0fU73JdKACNjMlbF36aliQhrG4Fq2Uv+y7yp8qsRxQ8jvzEMES/AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "xzu2T+pMZtdsS5q1cwXM2hMIH2c8mpAV31G2hKIuiQRwtPD1ne4iJsnoVCXhFakd\n"
+ "QTq7eTXM174fGWyIT93wvQx/Uqnp29dGZp/VaNOsxHFdYVB4VIVqkBh757h+PSJ+\n"
+ "VNV5JUm4XQ1QbmniJGdTQp4PLBM++fOXMR3ZNd6rt4o=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_NEG_BANDWIDTH[] =
+ "router fred 100.127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMCG/ZCXNCF02uXRSCP7qWBN75jDMQZ363ubnQWhF9KDDNWWiwj3UiZR\n"
+ "zqsM4zKRgjtarWZvp2qxKABFAODd+j9iq5DvUGRbbXv+aR8TT/ifMtwwxHZQBk1F\n"
+ "1hbsLdwWzGIiyz5k2MVhXnt6JTlklH2hgT++gt9YTHYKxkssaq5TAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM3vk/4kOTB1VXrve29JeHOzNUsPwKruBcjxJf+aatxjf6KO2/RW41bM\n"
+ "gRYq9V7VAYeZTsbS727fy03F5rk3QIBhMJxm9FHatQ6rT/iEDD4Q1UZQsNtm+OLf\n"
+ "/TkZZhgfB3MiDQ4ld/+GKd7qww8HXTE+m/g1rXNyZPKozn8K7YUHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 -1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "bUBBZYZWqCbsH4/7fNXtC/HgIZNGOfDF9v4d9YfKaDs5xDYf2o67hRcwx5imhrgC\n"
+ "IU7n9AI4AGxkFoN6g3Y/t4pqebxdkF678rRDCtrlwwreAiUktgrwnetp9Tpo16xj\n"
+ "V7Uf6LcqQdvu78lRh1dsrY78sf7sb90vusFMPLXGUKM=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_IP[] =
+ "router fred 100.127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMtMrM24AJpJCevxnseIpRlSuAIMksfkfky2+noe7Rok8xn6AMQzMrwx\n"
+ "AiCJ8Jy4DBzIKUiJK4/y1FimyM08qZGR0xeqblCxZ1lbSiXv6OYxoaD2xmWw8zEP\n"
+ "Zgu4jKReHh+gan1D+XpAbFNY0KrANhjRo96ZZ3AQsZQcWBiPKCynAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOPclmBO/amw1RWTSI1y80qY/EPjc0I+sk9HKr0BQOovxqJ0lmy9Gaue\n"
+ "y+MOejQ9H2hNev0nd7z1fPxEogt7SCe22qJHHX3xDf+D9RpKsvVzDYZsk7hVL7T1\n"
+ "mwHzuiV/dtRa7yAMp7+q0vTUGesU2PYFYMOyPvz5skNLSWrXOm05AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "g6besL/zxOp0N6Q5/7QZgai2kmCU5EAWJlvZrf5jyrjKhsv2a4LDkap07m9QRFqW\n"
+ "GGe7g5iiABIqnl0kzv7NLX7ah+d/xxv+IILXyZfVTxSw0e+zFb3uPlQ7f9JsGJ8i\n"
+ "a+w8wyyDBpOAmi8Ny866Cnp9ojVzCyIErUYHFaPvKao=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_BAD_DIRPORT[] =
+ "router fred 127.0.0.1 9001 0 bob\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANKcD6DJ16X3yvdq05jatdwgjO+hyoIpckW9sV/OkdfIZwf+S6Q4pZGC\n"
+ "doMw5XeOM52gjpx42kUp6M2WlTGDFEpaNU0VyeZYG/M1CM1xvfj3+1PoebioAGdf\n"
+ "GuhNBCHZdaYNiOGnh9t2GgUomgpE6njdS/lovSrDeTL469hfcUghAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANWeGHig5wE9UijaNnEW5au3B3hZKSlzCi+T6MYDPbbYhm8qJaVoXUXF\n"
+ "EP1EUgzDcX3dPEo9upUA1+91GkjGQCo9eOYlqGib8kHIwKnHZK+hernBc/DnOeUp\n"
+ "Wyk9SW5s+fi12OQhr3NGjbSn76FMY9XU3Qt7m3EviTwWpI3Jr5eRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "t77wEoLjyfMf9LKgBfjveosgwvJ8Go0nb27Ae3Ng9tGtR4qaJQfmwZ5fOOuVU9QC\n"
+ "3s8ww3aY91KD3NTcN3v3FKngxWtRM8AIfwh4pqT3zW6OSP4+nO3xml7ql0Zf6wfj\n"
+ "TPFV2941O3yplAsmBJ41sRSWizF04wTtZAIgzY7dMLA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_NAME2[] =
+ "router verylongnamethatnevereverendsandgoesontoolong 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL0mcUxg7GJ6oxgciLiBCbo+NuZ/OVKRrERCSM6j6iHERcB9+ciSRgQ5\n"
+ "H6o6FUX2LoRmHYzBk1x7kIjHa9kx9g6CAbBamdZrQbdVnc1y2NrdHB/jvwLj3C48\n"
+ "PgzFIrLg9OlkuoWck/E+YpPllONfF65e0+ualgVjPgpQpXwmz+ktAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOgHvvTAxyjJtHx9W2X7aOI05H9sYDDY+sxhovT/8EpAHrioex54tsMT\n"
+ "ifgtoXTjGIBEOTDi/1ry39nEW5WPbowqvyzRfR2M43pc96WV7e1nhmD/JrnTYgtR\n"
+ "5/15KxcMJxoDhod7WZ/wlXBnHc2VevX8JTaeOe9KYORCj5iNbtVZAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "j/nFT5gyj20cLHWv94O1jmnqy3n6qkO8Av0OdvvfNeXsMK2UHxk84vzFvEwpUF/Y\n"
+ "i+VR3LXY4CjTpuliMtjt7BQGtmJSvB8W0CeIUenIGzfwDxW9dG2o7spDldKDB/OU\n"
+ "C1wyHvKaA6Yss/02RIDa4AxyjsfbgdJ91qK+aAnYAtA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_BANDWIDTH2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALQDCm9VEopiYILmt4X9kP6DQazfgKnLXv+6rHbc4qtmvQQD3TVYbxMP\n"
+ "F4sEUaz+YHAPnomfDVW3a0YFRYXwDzUm1n47YYCyhUzEaD2f69Mcl/gLpKdg+QOy\n"
+ "boGB1oD4CStWL3y05KhxxTNiTrg+veMzXTqNwryCYm+GoihIAM9fAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALYHwdx6bmYy09AW5ElN/DWh0fHh3mBK97ryiIMi8FImYfzbw2BR6xuT\n"
+ "aQT5omqS3PNJJcNWZt5gOyDtA9kLh03cch7t1PenXSYJshbME2bDrZDJKVJMN6vV\n"
+ "B1v/9HjXsVF50jBzZsJo3j26XCPT5s6u9wqUFWW09QR3E/1HInHVAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 -1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "p09ijyuvcW+WKRj4mJA/nkLCvZkRcMzykAWheJi1IHCoqhXFdkFLiIRqjaeDVHRr\n"
+ "zBtD+YCQiGvFcaQJ9IUhh7IleHcyyljmDYlvuBAxWiKvVZstJac0kclCU4W+g8yK\n"
+ "0Qug3PmGKk115x2TllHaCZqMo5OkK4I/WAsKp+DnJ1A=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_UPTIME[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMM0Nubr1VXQ/FcgIQTFxZpZDlAEh2XN8FoJ8d+X5S46VDGijmMoYmyN\n"
+ "oLXqMTGmOaR0RGZOeGLgDzeY8tLrfF821IjfkXeAANZibUjdsHwqHO3wlWD2v+GN\n"
+ "0GBocWXEdAp/os229mQQKgYAATJ0Ib3jKhBdtgm5R444u8VX5XnbAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMpyOr4kEtSTZw4H9eSkH2+WmwIlO4VBpY2HkPS00l6L5fM2REjt50Xi\n"
+ "lsNOz8Q6mAn5cMYmsGlv61kg01mCvYc7Z715jGh+1hhVAxMaNS3ED/nSPnslyjhq\n"
+ "BUm51LhYNHD4ktISIqPMurx6aC8B68UYgKzLgCYNzkathFXSBpjRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "uptime forever-and-a-day\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "NHYeiQOu0nZdrhSy31Xz4F0T6OTU23hPQDzoLax1/zq6iTVrz9xi3HGm7HhOMW1j\n"
+ "YgFGK3+Xm4iJL+DwriunsAIuL5axr3z2hlmFDQHYItP//KyPpOqSrfEOhwcuj/PE\n"
+ "VbWsiVYwz9VJLO8SfHoBeHI6PsjQRQFt2REBKZhYdxA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_BAD_BANDWIDTH3[] =
+ "router lucy 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAO6HrITQTEjV/v/rInQ2REmCFZa4dZg8zIh6+B51U/I6hDiZaKGwpNey\n"
+ "9OfjoRqT2DwyLEe3ORm9A2RAz2twLBixrpt5IvC0sbGustmW964BHW7k9VvRupwl\n"
+ "ovujHpLIj5dkLxD15jGXHoTp1yHUVk9NkMGN+ahg6y+QhTbIrWbRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOEpciJFXauEqs31GMTUTzu6edBj9WtV+sIflhGKvU1KKRfwCgOcuKMx\n"
+ "QiLHHD9AjhMAFGT/qtNbPFkzfYxHKLHw+NLJsxmNtdkYM26FX3ButPiX+69sq9fI\n"
+ "PCHqQy6z/A7hHwtEk6niWgK2PLhAZCg9duAv+mqFVXe2QEBjax/lAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 electric\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Jk0Xk1RMJSjEflNRcp4qznaHKcfe2r0kOc7TdLAnM8zyNDVj6+Bn8HWmyp/oFmf6\n"
+ "xtWKKgkKxriAVIJgqZMchPbr9RuZS+i+cad++FCwpTVkyBP920XWC47jA3ZXSBee\n"
+ "HK6FaoK5LfmUm8XEU9BVhiwISXaUfTdkR8HfzugFbWk=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_NTOR_KEY[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKYDCSr0Jh9d/mJKjnGYAHKNBcxR3EJk6GGLwKUrRpN8z/aHRxdWlZF2\n"
+ "lBml6yQNK/VPftcvOekxrKq3/dISrIFBzFYj6XHNtg31d09UgitVkk0VfRarZiGu\n"
+ "O6Yv55GSJ9a3AZDE4YmIp5eBjVuChyVkeDFYKVn0ed4sj9gg35rjAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALXdUQuq1pYHyYP0qU6Ik+oOmwl0eOsuwiLWf9Vd+dsgEszICX4DRWPx\n"
+ "syDxfxyA/g9FEPvlI7Nglx6cKe2MT0AutSRLbbML4smfuRZNIF35Cnfu5qTGVVzL\n"
+ "GWVSA2Ip7p+9S9xLhLBdc6qmrxEXCPL6anEhCR4f8AeybXAsz2JLAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "ntor-onion-key s7rSohmz9SXn8WWh1EefTHIsWePthsEntQi0WL+ScVfjdklsdfjkf\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Yf9axWyzPudnRvQstNdbtBYo7pGpUEIdECMGcJtFb6v/00pxk4Tt3RiOKa84cOBV\n"
+ "7V9NjOLdqlx88pGz0DNCJKqToIrwjZDeQ8Q1yi9XClLDkC32fQRX4y6vNBZ3LXLe\n"
+ "ayVrdRrb41/DP+E7FP4RNPA5czujTfs8xLBMbGew8AA=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_FINGERPRINT[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM0wDWF2dBLzsmoIDHRugzosCSR9TSvEE0TkvKu6+agfogGtkQJwQ5zO\n"
+ "sGzZbRR+okO7d+QCED2i3rUs1iikoMUT+pwgvOm8Bxg9R64GK7fl9K5WuAiG11Uj\n"
+ "DQAfSx5Fo30+rhOhe16c9CT7xJhj//ZKDbXUW7BrJI8zpuOnvgD5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKACg1nWM/WjpUiGwlLQsY3Tq1h0RTz/HmOMx/6rTRxS5HLz0KnLg5zV\n"
+ "dvmfhxqQVKBkt1N2+y+qO7x71oFzIsFMfHYWSxOCEo8Nkff1BqAPqxxUHvM0HwJo\n"
+ "d7lswJ/UT1j4+WZNZ4sFIujsIW2/zZqKlxG9xaw0GXJ082Cj9XkPAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "fingerprint 5555\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "mlqyJ/ZGBINKwSNEi7GpNBCMqIVbL0pGAOBYHJF1GbRlU28uRyNyeELIxIK5ZIet\n"
+ "ZzKr7KPvlBxlyolScPhTJfP98TFSubrwYz7NnQv0vLI0bD0OyoBf/9/1GYlzgTso\n"
+ "3mKfnV7THUalpxe9EjQ/x61Yqf26Co0+jYpt8/Ck6tg=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_MISMATCHED_FINGERPRINT[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANUAvwbpGbsAyA+mBwjFkvurtRzdw9btDqNKtPImufIE+q+AFTaCnwPr\n"
+ "kA7vm/O6h6OhgfdYEC2GfYJfwPGM7MDuz+NnuKxUb3qb2DQN2laqow6qWs9La/if\n"
+ "oHKUjC5mNeAgHcbWapx9CygwaFeVW6FBPl6Db6GIRAlywPSX+XMJAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANlSGd+Vm9nLiUk6zgu8dPnSFfw4F0R2GYfmzncIGJWtRFTF9ThW/0av\n"
+ "/9vZAWyVBjjtnpAP5R1BzdJYV2RwimC/6tqoHtkSbCBhdq5Cb/EHG7Xgb8KwNWVJ\n"
+ "NV1EESDwvWnRfSPGTreRw9+2LkdXri17FhDo2GjRxAq/N7YkLK5hAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "fingerprint CC43 DC8E 8C9E 3E6D 59CD 0399 2491 0C8C E1E4 50D2\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Y8MwYBeEfMhoAABK/FgpVRYolZ7jQ2BJL+8Lb6i4yAuk+HeVmPKTX7MqQoekUuin\n"
+ "/HdPKP+g/9HPMS5pCiW4FMwnXAF0ZocPXF0ndmsTuh0/7VWVOUGgvBpPbIW6guvt\n"
+ "sLLQ3Cq9a4Kwmd+koatfLB6xSZjhXmOn7nRy7gOdwJ8=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_HAS_ACCEPT6[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAJfPJNA3zZ77v2nlX2j5dXImcB/NhRtkG8XQgF7z+3H17sqoXgBgZ1dq\n"
+ "IbyJmAy2Lrvk/8VkXNFrT5/ErThn1B98V/PsJOOW1x7jGcix6X4zDYn/MvwC+AxA\n"
+ "zNP0ozNcVZ6BzVYq8w4I1V4O3Cd6VJesxRVX6mUeSeNawOb7fBY7AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKBzfB4mDEJjFTnmtqZxDG8G1yAiccVgAtq9ECEREL/BOQyukixUBeBe\n"
+ "j/FgXzbMJ7DZAuopuJZU2ma6h14G63fZs7eNFceDtmdLpuCOsFuvJ5Mlkf3hDZ1u\n"
+ "1KK5q+tiG7MKxgnGrqjPBUO2uubs2Cpx0HmsqBNUalXd/KAkFJbXAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "accept6 *:80\n"
+ "reject6 *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Dp9dLgs9s5beMPxfD0m96as9gNBvlmKhH1RQ/kcOKscia4R8Q42CnUtIqLkCdjOu\n"
+ "zErc2Vj9QzjKOvlqUqHxP+J+l+ZJez6F+E1tcmK/Ydz3exL8cg9f4sAOCSXcpBey\n"
+ "llTFDibz6GkQ2j3/Uc4bN/uLzoyZKunpJbSKZP5nt8Q=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_NO_EXIT_POLICY[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAK4fbjTKYqv2fygfjzY53sVTdtbNMjq293/uffKKxFYnOVvPzrHlP6Go\n"
+ "2S19ZcyDxOuH1unbBChPnV0GpxXX6+bgfDkaFh7+jef0RQ3fpJl84hSvdM8J8SCt\n"
+ "Q/F4Oqk3NeKKs+zAHDjhAU1G4LkF9/SZ9WZVXlH4a4pf7xgQtaShAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKahvyDkmh33ob/bLVO1icgz2ntOZN6ZQUfgpMU4Cd6DQtOEwFUGhbVt\n"
+ "gvtMHv2+VbxM31ZfUsyBqJ1rJBLpOqlPvSoYwSac2+twa+w/qjfGqcJYhBjP9TV9\n"
+ "n9y8DzBX85p6vRcCzcuZ4qUJ2nRzdLHwjdgzeLmmCHuPO2dQxQhXAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "ntgCtMC0VrsY42dKts8igGQ2Nu1BpuzUltisIsJz75dDx2LCqTn7p4VpWbTrj1sH\n"
+ "MRNOvEPFxVMs0Lu50ZUGRzeV6GrHmzIRnOIWanb3I/jyrJLM0jTIjCOLwdMRA298\n"
+ "tw8Y9Hnwj4K7K6VvgU8LP4l7MAJNfR6UT46AJ6vkgL0=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_IPV6_EXIT_POLICY[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKHJKLHqjYoW9M+1q0CGHJRT5u2CnZWb8Qr1DpLkkusQ6ru+cDAG12so\n"
+ "IpDQh7IyB2JosVJi9ogekYxJ3O1p5WlFUi0X19DMoer9FJ9J7/3s4enGJ/yMBeuu\n"
+ "jLVRkjMJhsfhj3Cykon+8Rrf520wSmBg1dpJQCXTwtb7DARgYRpZAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPJH61Ir6XSu9/Q9tXGaINbXO1GWQQUXtwh6TX9lxnaCNDLGnxiY+ZZw\n"
+ "+Vqj3LAQoMrz1PpPsF5e0VIxok10Vc8y4cWC+kIitcecut4vWC5FYTtVVP9wtlyg\n"
+ "YCcVOVhtFQxtLiGqprl84+EVxrR7RQVCMLNDUXIgxAfdnS24eBPDAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "ipv6-policy kfdslfdfj sdjfk sdfjsdf\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "XWorzVT5Owg+QcsBtksiUNtpQQ5+IdvbsN+0O9FbFtGZeaeBAbPJ3Poz+KFCUjZY\n"
+ "DeDAiu1cVgODx2St+99LpwEuIBx78HaD8RYU8tHx8LoA+mGC43ogQQS9lmfxzvP5\n"
+ "eT5WXhkOS5AZ8LZOCOmT+tj/LkSXev2x/NC9+Vc1HPo=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_FAMILY[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM62QoRxSPnm+ZM4fv9p03Qqbz5SzhXYSNjKWqylBruaofTw6oIM8DtX\n"
+ "7QnrEe/ou/WtfB+swV/2rt/r0EzmeWBWuDmuSUrN5TC2AdOi9brSJMgXVW6VW77X\n"
+ "fuIlLd5DVSId2zs3cKLDqp36CUsooA9sS6I5HrvW9QDf3VS3pGBtAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANg1trpnRzkCi4t4Z4qnBKF612H5A3Zrjg7Jo2b3ajUnON/KEuLPTc3t\n"
+ "PPN0W4qqeCMmVQEuxf3DRbTPS20ycy4B/JDWYfxCNwuj5YAx04REf7T0Hlx7Aee/\n"
+ "sHEQBhIBfasA2idhTh3cAm4DMYn+00BqjxF6jmyRA0hyntEABabrAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "family aaaa,bbbb\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "xOgP3liKF/WEvwbbGzUUVRZ5WPrOI7jex8pZU/02UEnHjit7vCf9fsUcvkeo0xjz\n"
+ "n3FQHIO1iAJS7dEaEM4nz6wtPUb2iXSU9QajkGBkJ9/V7NHMFIU3FGfP47PIJJkd\n"
+ "nz5INoS+AsE7PmnDjUMm1H45TCCl8N8y4FO6TtN7p8I=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_BAD_EI_DIGEST[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAJ8Sn8AxBRbeIAHUvaKjqmcYOvXz7YFlpYFiVHp/cn+l+KUkIYTOFQXf\n"
+ "K8AtwjmJ4R2qJIbNlY/6oZGFbizt/B+WPuWsTj+8ACEEDlxx0ibg3EJRB8AZYiWv\n"
+ "0zC/loiUvHm6fXF5ghvDr9BQzEUo9kBk5haoHwROtGawr1+vOEiNAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMzok3ZJtLjXOC8RKltXI8xulwn/ctCvQFHImR0+ccA1uBxaZNYgiIcc\n"
+ "q8XngROfV8xEgDbYPiWiLXJOMSwOd7hfs3YzRWF+LKftYs8PuRyMJcCoBjOPZ4QX\n"
+ "HRfTetEvu2SijZMby+lkqpZg2nuF/ipsXUjrabRZdNiIGhC451vdAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "extra-info-digest not-a-digest\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "c/6zAxO04izQvqdM4bZVGE+ak0nna5pz9XZizFkieZEDWGzWQuVMhXyL5sbsFbsx\n"
+ "6Hn7DvNRYR/2nA0teDeRyIHMoMHi76te5X9OFDgaeUVCbyJ8h/KZYfPnN86IDbsR\n"
+ "dCSmj9kX55keu64ccCAH1CqwcN/UsbplXiJJVG5pTfI=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+static const char EX_RI_ZERO_ORPORT[] =
+ "router fred 127.0.0.1 0 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMc4MOhLG3PKPgc+xYVf4eScWzeOf8wq7Cb/JxZm50G0LuvVbhHtHEZX\n"
+ "VOSHI7mLE1ifakJvCFJRLobMU7lU0yhn18/nKl2Cu5NfFHHeF/NieUBSxBGb2wD6\n"
+ "aM1azheXrRqvDVVfbI0DLc/XfQC/YNiohOsQ/c9C6wuffA4+Sg85AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALBWdl9/Vft+NQKQlg5kgvZo+krnhNTRVQojWtUEzom4TFIT+NNKJyMG\n"
+ "reQXcNdzNptTB0aOBGGwqAesqzsZ2Hje699NsDe7hdl7Sb5yhKDqtdQY6yDXJUFt\n"
+ "zqpAUkmYMLe2p3kPiWefNso56KYXrZrlNAiIS/FhQ5cmuMC2jPydAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "gFg08P9A6QNQjURlebfdhU3DSV0BeM0j2SFza1jF9JcBOWDRmT8FvYFK1B3js6jK\n"
+ "8LNV8JOUssv14z5CnUY9CO1BD0xSl+vGlSS4VOXD7rxui8IoWgnqnZsitq+Qzs95\n"
+ "wgFKhHI/49NHyWHX5IMQpeicg0T7Qa6qwnUvspH62p8=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_MINIMAL_ED[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf5iAa+2yD5ryD5kXaWbpmzaTyuTjRfjMTFleDuFGkHe26wrAQAgBABFTAHm\n"
+ "hdZriC+6BRCCMYu48cYc9tUN1adfEROqSHZN3HHP4k/fYgncoxrS3OYDX1x8Ysm/\n"
+ "sqxAXBY4NhCMswWvuDYgtQpro9YaFohiorJkHjyLQXjUeZikCfDrlxyR8AM=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOsjlHgM/lPQgjJyfrq0y+cR+iipcAeS2HAU8CK9SATETOTZYrxoL5vH\n"
+ "1BNteT+JxAxpjva+j7r7XZV41xPDx7alVr8G3zQsjqkAt5NnleTfUREUbg0+OSMV\n"
+ "10gU+DgcZJTMehfGYJnuJsF4eQHio/ZTdJLaZML7qwq0iWg3sZfBAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAK9NjRY7GtAZnlxrAZlImChXmGzml0uk2KlCugvju+eIsjSA/zW3LuqW\n"
+ "wqp7Kh488Ak5nUFSlCaV9GjAexT134pynst8P0m/ofrejwlzl5DHd6sFbR33Fkzl\n"
+ "H48zic0QDY+8tKXI732dA4GveEwZDlxxy8sPcvUDaVyTsuZLHR4zAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key 71DgscFrk4i58O5GuTerI9g3JL0kz+6QaCstAllz9xw=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf5iAUVMAeaF1muIL7oFEIIxi7jxxhz21Q3Vp18RE6pIdk3cAH5ijeKqa+LM\n"
+ "T5Nb0I42Io4Z7BVjXG7sYVSxrospCOI4dqkl2ln3BKNuEFFT42xJwt+XGz3aMyK2\n"
+ "Cpp8w8I8nwU=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "lAZwD6YVic61NvJ0Iy62cSPuzJl5hJOFYNh9iSG/vn4/lVfnnCik+Gqi2v9pwItC\n"
+ "acwmutCSrMprmmFAW1dgzoU7GzUtdbxaGaOJdg8WwtO4JjFSzScTDB8R6sp0SCAI\n"
+ "PdbzAzJyiMqYcynyyCTiL77iwhUOBPzs2fXlivMtW2E=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 Oyo/eES+/wsgse1f+YSiJDGatBDaiB4fASf7vJ7GxFeD4OfLbB7OYa4hYNEo5NBssNt/PA55AQVSL8hvzBE3Cg\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "wdk26ZtS1H81IxcUThyirANLoszrnYYhOMP57YRAUDEzUr88X6yNDZ5S0tLl+FoT\n"
+ "9XlEVrpN7Z3k4N9WloWb0o/zVVidPMRVwt8YQakSgR8axzMQg6QhQ6zXTiYhiXa4\n"
+ "mawlwYFXsaVDSIIqYA2CudIyF3UBRZuTbw0CFZElMWc=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+
+static const char EX_RI_ED_MISSING_CROSSCERT[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AfsyyHhGluzfESzL4LP8AhFEm83+GkFoHbe1KnssVngHAQAgBABNzJRw\n"
+ "BLXT3QMlic0QZ4eG612wkfSRS4yzONIbATKLHIgyzgGiGl4gaSX0JTeHeGfIlu7P\n"
+ "5SKocZVNxm1mp55PG+tgBqHObDRJRSgbOyUbUgfOtcbQGUeVgUlFKWZ9FAY=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMqT7K8cEzWIaPNXbNgvoZ5ejavoszI2OjW9XXetPD/S2f+N7TfQXHBW\n"
+ "bnjpgj87gmk59w0OXTMCv+XofZ0xOy2YR/jG5l1VJIvqgJhhFJ8oSEGVzy+97Ekn\n"
+ "Lb1FEYuVfVxSxnU2jhHW6KPtee/gvuyRI/TvZuwmYWxLRpikVn4pAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM4nITNe8UykgsIuo5czSSSl3Okr1K+UVWTzDGLznDg77MkLy7mydmk9\n"
+ "vf51OB+ogQhozYKIh9uHvecOzY4EhSIuKhui4hNyQklD9juGoW7RVTSpGdYT1ymp\n"
+ "dDYS30JBPwCZ7KjdMtXiU8ch2WgbzYBuI+JfjwOhfcsuNC9QPfbfAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key lx8o212IYw5Ly2KbH2ua1+fr4YvDq5nKd7LHMdPzTGo=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AU3MlHAEtdPdAyWJzRBnh4brXbCR9JFLjLM40hsBMoscAJ8cHMIc71+p\n"
+ "Qa+lg5JiYb551mLgtPWLy12xdhog7SXiJl3NvnMgbMZXHDqkU2YZCidnVz+xqMdh\n"
+ "mjQFK4AtRwg=\n"
+ "-----END ED25519 CERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dg\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "cv1yL8HhQzQfjzkSosziu2kMecNUQGle4d103h6tVMoZS1ua1xiDpVKeuWPl9Z0+\n"
+ "wpFwRkOmK0HpNeOXCNHJwfJaWBGQXunB3WQ6Oi1BLilwLtWQixGTYG0hZ6xYLTnX\n"
+ "PdSQIbsohSgCzo9HLTAgTnkyBgklIO1PHJBJsaNOwfI=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+
+static const char EX_RI_ED_MISSING_CROSSCERT2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AXXgm0CUWQr+rxvgdIslqaFdBiwosT+9PaC8zOxYGIsZAQAgBAA6yeH7\n"
+ "3AfGIGuDpVihVUUo0QwguWDPwk2dBJan7B0qgPWF5Y4YL5XDh2nMatskUrtUGCr1\n"
+ "abLYlJPozmYd6QBSv6eyBfITS/oNOMyZpjDiIjcLQD08tVQ2Jho+WmN64wc=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMdyTK/VPZloLUaLsvj1+NOFs33/E9HmA0VgvZ1nNUrR+PxSR71QF7Tw\n"
+ "DKz+/p2rJE+MPfQ/Na3dH0vH4CDZ+FH2m4A8SB9emF8aKxdc/7KCjQNDQCNlEQYn\n"
+ "O9WvZJhbNPHUmX0z4OotI+Sk3qBzVHu0BGDsPYC9gwszIumDUILxAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL8o6CJiLfW4vdRFvJ2nFt/H/ei0ov83rilOuwSmNORmL9lvnHY++HrD\n"
+ "dmEEvBv74xqWJxGbJ6OQ3VOwRpf2X/cb4gAvsQDqDmNwpJsrPYRQVXp/KY/8z7bJ\n"
+ "dM4CjcsuJHHmj3yc3iCzgqt/Xr6vR24X4bee12/bP7R8IETvWoiHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key qpNEGrLMVn28Odonk/nDtZq1ljy0fBshwgoAm4X1yzQ=\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "i4RKGIeaUrO6nzfdtb6j+ijYJh1Vgc9bsHMpW9cVCOjoJKFW9xljgl9xp6LytviN\n"
+ "ppKYCt9/JflbZUZjny34ESltPGrdquvHe8TtdQazjiZBWQok/kKnx2i+PioRF/xI\n"
+ "P8D0512kbJjXSuuq9tGl94RKPM/ySGjkTJPevN4TaJE=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 pMAOpepn5Q9MxcV9+Yiftu50oBzBsItQcBV9qdZCIt3lvSFqFY9+wJjaShvW3N9ICHkunrC0h/w5VEfx4SQdDA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Du5fJYDzvEeGqKTJwgaQsJJgz39K/J4qEM2TZ3Mh0XuDM1ZWDtjyzP03PaPQqbJ1\n"
+ "FsN5IStjOqN3O1IWuLzGaZGpGVuqcyYOxjs7REkGQn2LfqCjpzjaAdcsL0fI4ain\n"
+ "o/in8GQ6S/qhsx8enKlN0tffTmWmH9bmmVz0+yYmBSo=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_MISSING_CROSSCERT_SIGN[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AfoVFYuJnDNBWbjbTqfXACUtXWPipmqEYC++Ok/+4VoFAQAgBADH7JzI\n"
+ "fjSMV158AMiftgNY+KyHYIECuL9SnV3CSO+8+I7+r9n+A3DQQmGLULo/uZnkbteJ\n"
+ "+uy6uRG4kW0fnuBlKhseJQm9hjNGWzC8hmebp1M+bxwG41EGI7BZvnTrRgM=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALEqlijoFIDX1y1i5zfei8DuDIsFtSw56PGgnMRGcybwD1PRQCheCUZM\n"
+ "erQgFCWjgLgvGJERBK/oILW1dFXp4MAR5RgnrPGTfWTinCj32obMLN1gIczpq6a9\n"
+ "P9uv6Cz0ApSxpA/AuvjyAZwQKbUXuMvIY4aTprAKSqqVohk6E+E1AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMZbbBjGV7xPri4XNmejq4add93p+XsWlsfbM930bcC2JZiwg4g4cq6W\n"
+ "idl8VDmCXeaWg5y3kb82Ch/Q9vPG0QYQbXxUA3JxQKKbcEK3QsEvqQh8Nb7krILK\n"
+ "YnSGAnLG2Nc3PnKb7Wpb8M3rAysC5O99Gq1mSfm8ntj3zlIM7NSHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key CYcpfIF4T9PJcfROfVJTUYl0zNd4Ia5u0L9eng/EBSo=\n"
+ "ntor-onion-key-crosscert\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AcfsnMh+NIxXXnwAyJ+2A1j4rIdggQK4v1KdXcJI77z4AMRc2LxiKbyr\n"
+ "fqRVynHuB031C4TN/HAlNPBjVoRvQRgzpiyyoyCqMDxLZdM8KtzdLLeqZJOXtWod\n"
+ "UXbYG3L70go=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "BRwRAK2lWxWGS49k8gXFHLEQ/h4k8gOQxM0WgCaN4LjAOilLHFjsjXkmKgttVpHl\n"
+ "f0V9ebSf+HgkpQnDSD8ittnr/0QaohUbD4lzslW4e/tQYEiM46soSoFft85J6U3G\n"
+ "D3D63+GmaOfIaa4nv7CD0Rw/Jz0zTuyEuARsdJIr1IY=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 7XfV5r7FXbXPEvrxlecWmAJxat/6VT+/4tE5cHrQnvLM4zslysstWH6/AfIfcmUuDlQ0watmfg1MvVnjavcfDA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "eigLL3S/oMGL2tJULt9bl3S0iY+YIxdKeGFCcKZci59zD786m+n+BpGM3yPpvrXr\n"
+ "bGvl4IBqCa1I+TqPP1rM9lIEcUWaBT7Zo5uMcL1o+zZl1ZWPWVVKP5hC5ehDueu8\n"
+ "/blzNhTEFAp23ftDK9PnFf+bXxqbgKkEoZsxnd3e9Ns=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+
+static const char EX_RI_ED_BAD_SIG1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AR8QC+SNBpPOTVY198IQBANNwZjy+SBqQNxfzjEmo204AQAgBABjz4FP\n"
+ "zW/G+fu7YirvANvvqJeb7S1YYJnf6IrPaPsPRzDqJcO3/sTzFC5OSb9iJmzQAWnn\n"
+ "ADPOl+nOJC58XJnJ7CUJdPtyoVdMvUiUT/Jtg4RuCN1iDaDYaTh2VavImAY=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKuLC0kzCBTV6+WPZcAOQPKjqbjvMIyaehIQS1o90dYM+Tosrhtk3bw8\n"
+ "QBLMaiWL3kfIWPZuWi2ai40dmqAXMrXH3yBgKRNZ6zZSbUUuJ1IknqmrQ2PKjC/p\n"
+ "sIW2awC6Tq+zrZ7vntDb02zY857vP59j8eolTDg1Vvn6l2ieL+WhAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMnBQPOJBQLZ3NAa70n6lGZGvS3DYZFNOZ2QnHVeVvOSFIFsuvHtnUdX\n"
+ "svDafznYAuRFRVqJS2xtKKGu0cmy6ulEbBF+4uAEMwQY7dGRPMgVF1Z33U0CSd08\n"
+ "ChCJGPTE7tGGuoeSIGN3mfC4z2v9SP3McBdAiLHisPzaUjfRTcwRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key W8fUvBpKBoePmqb70rdJUcRT0NhELDWH7/BSXJtkXS0=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AWPPgU/Nb8b5+7tiKu8A2++ol5vtLVhgmd/ois9o+w9HAAPwWqmL0HXa\n"
+ "bYKrKPWQYnpQHQ3Ty0MmCgj3ABF940JURnV161RlN8CRAOJaeQ0Z8wBRLFC1NqLT\n"
+ "+GVdtewGeQA=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "x0vT5Wv7Guc0/Vu2BqomWwenh8oda9+8K/7ILi5GQL/WC29Tj51i0EE7PVSnSMJ7\n"
+ "33I/V+N5neauqWnbg7TxYaLsPfr6SpPTpBL1Xt0OiwT1//PvPYZ1gCcF3ig3KcfI\n"
+ "mreQd5C5Vri6ukWkMtz/zNDaDpDanzaNXTdaUXmFHF4=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dg\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Hci/Br1+NNymDZBmQy1QWMlCeLe8Z1vtZ2ZTj42jDhWg1OC/v72ptI072x4x5cmi\n"
+ "X3EONy8wQUvTNowkfG6/V/B768C7FYJYBId1GAFZZymXnON9zUYnE3z1J20eu6l6\n"
+ "QepmmdvRmteIHMQ7HLSrBuDuXZUDJD0yXm6g8bMT+Ek=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_SIG2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AW8fyx54c7vQQA/AmShAitFP7XI1CLdifEVPSrFKwYq6AQAgBAChqjVA\n"
+ "/wKKJZ30BIQoXe5+QMiPR6meNxF1lBttQ2t5AhauZbH5XzRhZkdGo114wuyPNEM9\n"
+ "PrBwp5akTtari9doVy6gs3McqdoIbRdWevpaGj5g5oOEOtA9b5UNWQSwUAs=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALp0Croi9zhpGxi9sUj54jr/flZdzxVVS+8VNldJG2c1soSx8kwlwotu\n"
+ "7mGGudJDAzDHGo5F5CCPEfQov2OmDehpefYUz/AaMLly6PrLRJlcUcpLogGf1+KU\n"
+ "1lLwE8kanXUkgvDhVQiFvNjy2Dxxuv3AHH4WdZZfbMbm8FJRGoHzAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMoI9vQT4g2sV2dViGOWOzxckk367T9sMjVwcYfJCmnixGxjWeKScQFB\n"
+ "K9v1uK73cfZR8AxiUGK4/iOX/9en14mJOGF7fftAqypFLAt1TBvb07IgXljOBoHc\n"
+ "Paw4oZoJQzEoazt0Oa181LyNnNIoaZpHVZd1+a1Gs1gKoM4xDBv1AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key KjyvXYkMcpke5ZsUYf2gZAUNeEoz8NAwYoQvvbcDGiw=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AaGqNUD/AoolnfQEhChd7n5AyI9HqZ43EXWUG21Da3kCAI6MRHm7GpCF\n"
+ "/3zDGR/6jKe625uFZX9HpLt6FgAdGSJeMQ9W4Np9VkrFXAB3gvh7xxRzSgZ1rXgR\n"
+ "lUomgi7N1gc=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "xJXvCCpP4ExBuT3OTsdn2HJB0HidupmQq5zBh8fx/ox6+047ZBOM7+hVxxWapcMg\n"
+ "PMXbcLD4L/FCBpA/rjnFUE/9kztdq7FH/rOdi0nB6FZWhwDcsZuyfvbnDTxz5iHJ\n"
+ "87gd5nXA5PE649SRCxW5LX0OtSiPFPazu4KyyBgnTIM=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dgxx\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "tk4kBNYqB8utOmX30HrV8YfnwBXYODIiL3M/juRS6nPn0uvbW7pjoZ3ck/ahgW+6\n"
+ "FNQsgTJnEADCWS1r6v7PcvzQjtrOUUpNxGJxYw1r8yZkvmIxSQD6GMzuTxq7o1VA\n"
+ "/wZYDLonLhCWRdPjxnrl12+z92NdyISJCHMLRVqs2QY=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_SIG3[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf54AYYiKZrFWZ/Cj5mZbfK11MZHYbwchllsUl4qPqY9gfi6AQAgBAB4irxT\n"
+ "86FYA0NbZssSTmfyG6Edcf0ge61OwB4QD35kHCrvuZk2HnmL+63Tj4QoFqIVnwVC\n"
+ "3wRGJGcmS7y+vS64GUXbuyTgqgpl/KuoHo5Aqe6IxJlVWYtU6W0M6FV9tAM=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMUEvXTVTl5xkQ2MTEsB4sXQ3MQkz8sQrU63rlqglpi1yUv24fotjzvE\n"
+ "oJpeKJBwwg5WBW/fW0bUDJF2cOHRHkj/R4Is3m+2PR1Kn3UbYfxNkFkTE11l099V\n"
+ "H6xlsi0TJOJKlgrcbSuB7se2QctZVhwsdsJvFRptC9Qd+klAPb7tAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMooTeSUX7GPoyklSd1/6cF1u8e2LbjOLIpZrMon0Xt7c/aNwlrG9rVo\n"
+ "TSokHs3AQ2H2XIceySVRRWR4AdX9KApO4CX0gGTuVUmq6hFJWMnHdAs2mKL0kt1w\n"
+ "I+YWzjUqn4jIVa2nMbyHVQWzIysWwWiO4yduIjAYpBbWd9Biew4BAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key BN0I+pLmFkDQD5iRsdkcped4eZwGIuXnLiX2K0Zoi2I=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AXiKvFPzoVgDQ1tmyxJOZ/IboR1x/SB7rU7AHhAPfmQcAOrIvaG/xJqe\n"
+ "adM6mai+FlV8Dbt6QrXTcNHJU1m+CUDthA9TPTAYz9D8W0mTEQ6KEAKGfQrNLy2r\n"
+ "G1B+9wWSpA4=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "BpLBsl6Yo64QzczJn0TjdcXC1Jv9IhUG2m/Re3v0voCELOP+t5vkZXXLoVL23oKv\n"
+ "JheSkWiuAIEPsatb4afXZ8wZxPcQjwy3zTOBM7p9CG5fA+KYpqKTxAi+dhVYlcDo\n"
+ "M7S5nMV63FclkZIT70FFTHwWed1sAKwEO3/Ny24eppc=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 abcdvEzGFYMcJ/Ea7sbessW1qRJmnNNo2Khkkl0rEEgtLX0b4L4MMhK/ktS52Y6jX3PRQWK5PZc6gjV7Jaldh+g0Aw\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Vyj7g3eQ3K4+tm49fJkAtsAYnYHcEiMnlucYCEPeKojzYStNfZwQO2SG5gsoBIif\n"
+ "urgQZ/heaF4uiGFg64UFw08doXqQkd5SHO3B4astslITvmq0jyaqzSXhdB5uUzvp\n"
+ "QCR0fqGLVS1acUiqGbRr4PiZ9G7OJkm230N3rGdet+0=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_SIG4[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AaEnncX/t0cbLm1xrtlUpkXghaA8fVuV7g1VF3YNfCaIAQAgBAC7Ki3S\n"
+ "zzH9Aezz5X4fbwHeF+BQEDfVasfyTxTI4fhRi7t3RxHzBJd60uEMXy2FchD8VO5d\n"
+ "j4Dl7R4btrohPVSVBQZuemBQSW6g3ufNl0txpFWu0R7vBPTFH6oyXYfY9gQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALGKwzhOui2/jJPjU1ngW5IZRPcoDk7RAfGDO4xaef4VfAFHCV9CQO1c\n"
+ "/wQ09CcRdggTvUcv9hJTGJhSObUUooCkxw4/35f/A6/NoW1Gi0JqF9EsQWHpuAfr\n"
+ "n/ATlJQ9oGdTCNDq/BXSPWXhoI6UhUe0wiD4P4x4QwaYHcZh+lE5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOKrizVm2h5/jE/HqqLCBLWJZVVoGspasCtDDqHhSqsPzyjpqa52iMKi\n"
+ "q/deJ92le3J2NJRGKxPmPQqWxwhIjnMS5kUMoW182iLpO/G9qyPZ0dh6jXB0NBLF\n"
+ "ySfW6V2s3h4G4D2P+fqnsnzQnAX7YufkvgDau/qTWi2CqD0CjavDAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key A9h8jY9dPbhHTDbIc/NYWXmRP65wwSMrkY1MN8dV3BM=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AbsqLdLPMf0B7PPlfh9vAd4X4FAQN9Vqx/JPFMjh+FGLAN8xr/w3KFVi\n"
+ "yXoP/az6hIbJh0HYCwH8D1rPoQLcdpe8XVwFSrHGarZesdslIwc9dZa/D1dx3OGO\n"
+ "UhJOrdv51QY=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "bLmdO7ME5vq+c9y/Hd8EyBviMBTeo85sHZF/z6Pehc3Wg3i1BJ8DHSd1cK24Pg48\n"
+ "4WUrGTfonewuzJBDd3MLkKe6epXmvUgvuQN5wQszq1+u9ap/mRf6b3nEG0MHxMlO\n"
+ "FLx5MBsScuo+Q+pwXZa8vPuKTtEjqbVZivdKExJuIX0=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ " router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dgxx\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "LqNGEa10zwSPeomBXTfgvBnnWAdWyiR7KYZq9T++jK4ctR6hUaWngH8qSteUrkMx\n"
+ "gyWb6UMmlxdfOG0sdcU463HsqV7zObaKya8/WwQ9elj3FfsToswUCeOaLR/Rg7wC\n"
+ "zcUjI5VsneQoXT2WVZbZBLsLB3+7QfezVHRMB377GAY=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_ED_BAD_CROSSCERT1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AV1AfOvQWKlWsbzoBdJc5m72ShIJuA8eNV15basjhXYdAQAgBABy+KQK\n"
+ "3oLDGtqL5kwRmjAsls/+C6SAoAALll7U7wNSH7en5RVBal4RUzCf57ea/KG0c9V8\n"
+ "2DmZ3PdOt2aY/M2bWGmmH/tyyapOoV98dhDwFU7zcx/pMfRnJTDRSDwl8QE=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMP6xbqbj+x1mq5XImjeT0rUzqKZTgBd5zvK4Xcy9IifJuFC9+mMzrY4\n"
+ "WhYbdClxKUkDMkit9MVhek+P/w5TSHKl6AuqGaO09ID+hZpoUSdoBUYktynxfGsx\n"
+ "kIDu0XvgtAeSyJaVvoV1SKVChY0IBbzUqbHt4O2Q1BhzFCKEJTEzAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANwWlBh7e/eSLlhto5YUdj1iGYOq+yAmlosDItVfYrSPJuUfM2ocMBAn\n"
+ "udbRbWiADoqsbKn/gwwHCC/f1HX2FkRXxxnOlJKLo+NEi8tGmOlcQXSQol1pCpvK\n"
+ "sA9TxtYr+Ft4LRpxNrexF+pIBxqzwetqQrZbKYr0CFJi8q1qlMynAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key cs1AP+xF5cXTLuKeOeItdoDAzfALTJkwk9lB4mtC4QI=\n"
+ "ntor-onion-key-crosscert 3\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AXL4pAregsMa2ovmTBGaMCyWz/4LpICgAAuWXtTvA1IfAKo6ANUq+hi+\n"
+ "xb3J4aYafnszlj87oi/DR+SDf29wzwNw8gmaqGzJ5GbfISfABuTUCzlilZyVnLxi\n"
+ "BHcCH6PWiAQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "qC9Kph/kGtONR2DxZDoIFFgnDFC+/7H07EgCiYQdIFIROc+gGK9qBOgeFEptrkXF\n"
+ "XdE35xxox5xSASQvp7hjFwxUtJRGOtf2O98regqeeaz6O9VPXHkLf51uqX3bVgq8\n"
+ "KvFAsFFS66GxhtbrVjpyRgIwHAYvse1WVESfLuZZTn0=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 3uW8Q1aetIQLOsqSco128ZUaHlhqdYiBvrxV7x75BGNS5RzIMTEwYDNtEX1LNPFJ5N0YOV0HEEOLhrJUV9QCBA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "WuD7S/saTYBxKvItITbHRi8n+e6g/oVbosicfbRbafYPzPp4Prb+RK03UTafzXrV\n"
+ "QEQIzDNhfePcIMH8qX+qrogLMXFqiXx6TVQ0GqNvqirokk8ar3AgtRtewhChAuAj\n"
+ "8pmQTj2JpZn/iB3PCE2l/93O9LHZfp44hc8QOWKs6BE=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CROSSCERT4[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AW5TTGF9jCMl7aALZzqypD9Bj8WYnAPIrKCoIJdgMbY0AQAgBAB7eCn8\n"
+ "rukx7t/egZUdqU7+FYqsnO4wdmOkLZkp0+gpF3jjk6N1Q0037NNVNZBjONB0Nm2F\n"
+ "CpB3nWSJliSSKr5tOYsuBPFy5VVGYeKPakpOoxanQ1UcqevMBAQy0zf9hwA=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALeS5YbeDuKQ5iiuUvh3REoyJ47/YU9lslWmTrVBf9b66pMnYJv/awPu\n"
+ "m2HredUAJ3VzwQ38VJA39w3fQXUhQDnQ0OPpKzeAmIiuG+6WdW/mBSK7uKcezC23\n"
+ "LA1d6Afyl79LjZz/n+ENXqNMlJk4QPcPHuRnAvwBl3t8YVRPJmxhAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPprokY7utWuO/0252dBB5MCxmVD/dROaIBDyFtpdH+YVv04rkOlDzYD\n"
+ "W4mgHVBMxEm/cspTgQmJ4exRHJPpcSe1RYHt1ONZdLYr6D7OOWf0y1IUrVSzF6K4\n"
+ "lqlmNuH1H4+TKGbkvixYc5GU/2ZmAy6gFEuphYnBbsN2Ywc38mnfAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key Cgo6xniGfEiuYoLSPUdE4Vb2D4zj2NQzC1lRjysRRXs=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf54AU3MlHAEtdPdAyWJzRBnh4brXbCR9JFLjLM40hsBMoscAJ8cHMIc71+p\n"
+ "Qa+lg5JiYb551mLgtPWLy12xdhog7SXiJl3NvnMgbMZXHDqkU2YZCidnVz+xqMdh\n"
+ "mjQFK4AtRwg=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "bi4M/AJLZF7/vSNmOj4uhrgKBQA/KfcZy5e58mhGL4owxd9vaWfl3aelvb9jf9zN\n"
+ "Q7FMv8f9aXzeVIoXIpRJxSKIJgBtG2wnMumIc80pqBvTyGInharszb6njfm0bg1u\n"
+ "PfJkbQYyf/dA5l5UwCrjFs06ImDmjFTAdsSWf6DfZ/k=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dgxx\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "io16v+e0pK3sbFzPGnkQrAjrRgIOJHrVZ1RXcxZ1+UNXagWM/MOLhQpkU/cw49Wd\n"
+ "4rQeZD3JQh16330eXbxc97AyDgp0b30He846SI0MfW/DnmGI8ZNeYfLbMv2bmbs9\n"
+ "QULzyIH8C+5mnMI1arcuiAua+Dpa34F79vgqPuvw5fU=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CROSSCERT3[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AVB+j+B2yPgGywvp7nvejyhMh9ejKmw7LCwufV83Zl9eAQAgBAConA3B\n"
+ "jJ3X2tES40jd94rRUFS2/s/Yv7E4LEQ9z0+jz8horNivzK3O/t7IGxJggi+b41/9\n"
+ "Uaqt+wqtVuKj0xJ9jwBlCXFt28G2P9s4ZyXYgGZqo7MlJlboybnOMvmoTQA=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPWuEWckT4aYAVNrZzLA8xVwfXp0wzfXeTWBztLS8VzssN6w/+cwXdeY\n"
+ "N1YNc2DiD3u8f+7kmuZIqL1EFQUwTvRwEzQXm2dqGM7qkm5ZGNMb5FKu+QwO2ImI\n"
+ "FLNiO5zO/LqP3cf/2L8/DuvruLenUrhRtecGFaHmhDYl+2brHIiPAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMtHTfk0gDvp9+PtIG8Ks7rgCiJZ2aihSvr6WaKHYuIprgspFuga98cg\n"
+ "D//J80CrgH5Dw68YnkG+gU40IxP7YzhQ4glFlJGu3s2y7Qazcv5ww1XtHur+GDoA\n"
+ "cY0zCLhltNQFxIsoVUepY97XA6Y2ejYJjyqNXQcAmoPNoVhnTdkhAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key ibZf57LptdOK3WpVFXkYMatEEqPhuVWxsnkwF6638V4=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AaicDcGMndfa0RLjSN33itFQVLb+z9i/sTgsRD3PT6PPAEbkxCdI/bH/\n"
+ "B06DAjRuoDiv1HKsGuW+UN1iGEiWu2ieFzf3m0Z7BL9p2u2zIbHYkP50b3T3sebD\n"
+ "1AksemmMdA0=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "BpLBsl6Yo64QzczJn0TjdcXC1Jv9IhUG2m/Re3v0voCELOP+t5vkZXXLoVL23oKv\n"
+ "JheSkWiuAIEPsatb4afXZ8wZxPcQjwy3zTOBM7p9CG5fA+KYpqKTxAi+dhVYlcDo\n"
+ "M7S5nMV63FclkZIT70FFTHwWed1sAKwEO3/Ny24eppc=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 XS4zVi46Xl3xKhuozPCDlW0QRFD4qUhJmkefonQNsRlMVsrPkALnP2tfnfdfTc69hbNa22pOjJNf6Gm505EnAw\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "Q+R3OpO8VhfvFbXuE5qolhVbgosBHy2A5QS91TMzCbsxa8pBA6Li4QdPR37wvdLq\n"
+ "KayfmmNCMKU5qiZMyXqJZm4fdpxiSi50Z0tYlXM3b2OVfza3+pSOEBl89fN6G4Qc\n"
+ "pAmM14eEo1UzXrqZw76tMS2CwOYF5vR2xFGCYC0b5hM=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CROSSCERT5[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AaCfOaispi7dJhK0c8HXJHIwoBkMgRpmmHu+3Zce/soMAQAgBAB5bAIo\n"
+ "5i4TSY/bV2KQAyziRwvgJm+nEiECClflPbP9Um+zOzOgxtDmNnR5UFQj+VWNG4uf\n"
+ "5lnaryN+PfUXZMTcs8AARof3fFz9tVPINHDrsGvKt8gpzgZEHkVioAXOFwg=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL3Fr/ovZ9SMGYrAM24taKBm/NpemZaXdD/JeBXFYm5Zs3szLwJC4Etm\n"
+ "zjNL6tVy+I21O1g3cs16TkflcidsjPXNx//PHAn7bqWMekjrt3SQdkHW2gDPgT2c\n"
+ "zYJ/hBR96JYG796jP3pkfJz6Iz5uT/ci3A/cdaVbzM1uZbMUgYGzAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMHB+1dWa8BBrKE94vTqfbkSEuysG5LyyZF/WrqHq/3W+ocDLz795k8O\n"
+ "2Zvgr9im/Ib4hD7IyrtRexcuBdwujdG7cBALdCcWiUTGAMkl96HNETSX+lUVIpJ9\n"
+ "pMsc9O7+yz+/0Cl2RpILZCdE/7I96qHpZl3tzlRKSu15WeIm5U77AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key GXi0a2VLcRHQMMYys85zu3IPqOn5ZTsOixYyQvTGnQs=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN BUTTERED CRUMPET-----\n"
+ "AQoABf54AU3MlHAEtdPdAyWJzRBnh4brXbCR9JFLjLM40hsBMoscAJ8cHMIc71+p\n"
+ "Qa+lg5JiYb551mLgtPWLy12xdhog7SXiJl3NvnMgbMZXHDqkU2YZCidnVz+xqMdh\n"
+ "mjQFK4AtRwg=\n"
+ "-----END BUTTERED CRUMPET-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "T9NHMBhuJo+TlfU3TztNgCc9fK1naNRwPOyoqr5R6lJvJ40jkHnIVOFuvuzvZ35O\n"
+ "QgPbyFcMjv6leV5xcW+/I9tWaBUFXiRGI27qjCFth4Gxq2B6B2dIcQliLXSvW9b+\n"
+ "CMTgDwVa4h2R2PMh18TRx1596ywE09YhCgBF3CwYsiM=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 sRpiP9kyW/DGOphp4V2VCtcKNA8i7zGuv2tnljNIPTB7r7KsTvdUk/Ha9ArRQEivO4nC2HHENtknDl3GtWIPCA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "DtORw3+gO/yUUIp70xDaWSOgQZrJAAoZTNCB7q5WCoZOngeaCiC1Gtc+Fmdn7tER\n"
+ "uPqQC5H/Kh3Mi82PCj0JxvNivnNTNY1AZVaIX5YoioXVOkWF0B2pqMvFuDSdm2oJ\n"
+ "29PqSVcklquu19EjJRTopIHvYn3sFhQL4LarMsYY11c=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ "\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CROSSCERT6[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55ARMMCtQ8pObC5bq02AUE9Lx2bqsZBBkeOsDZVaEq6JavAQAgBABtV0xF\n"
+ "CsWXL/uFIBnoEsnXBeU1MvYRFrj1vR7QHdWXnxywXvBYUAC8lu/uyc8qqLp+aQSJ\n"
+ "5JzpDYlg3hp1fl5k97iv5F9WrR6s554YpmgYy9agFaxZ4LmRgz7n0UJ8mwM=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAO5qd1TndKD2pEs1ZLWsHlvfO/E7cA0H7NKGLSioGpBf4P0rtkueX4ci\n"
+ "kJNa/4Fn/QsLECqEF2lUjkIc8YL+HMS6qteKvN8+nn16DfvnIhPDNZWTJjLl1bOI\n"
+ "sWSSiduhanoWQnhRtl3Rxg3opdNd9ApO0DLUNy4Qy18Ai6SgksfHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAJkMYNpK7eJJyGwD/xG/iNg6gzzbIwrOSvmtoP7Rot42qtBiQ9A9kdsy\n"
+ "sazwkWkM93U1+1OaAADPYxeHoyHnuia95Cnc5y2lFSH3I7gnGGSPKSTwXtdyvDWZ\n"
+ "P1LbmQ4Bnh5leTCNZ/eFC4/GjNVzqHxjbb8a11dQhA8dOk8PrUq9AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key HdSQOqvLr4YnJE1XzzVIddgKgnjaHKJqnq0GqF4wXDg=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AW1XTEUKxZcv+4UgGegSydcF5TUy9hEWuPW9HtAd1ZefACVwif1deQry\n"
+ "K5GeemRa32sGzujVDDe75WRiPKFT3l/EtjTq3oeVq2xwbVJklnG3ASejKTr3YcHt\n"
+ "ov0jOl0jywc=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN NAUGHTY MARMOSET-----\n"
+ "BpLBsl6Yo64QzczJn0TjdcXC1Jv9IhUG2m/Re3v0voCELOP+t5vkZXXLoVL23oKv\n"
+ "JheSkWiuAIEPsatb4afXZ8wZxPcQjwy3zTOBM7p9CG5fA+KYpqKTxAi+dhVYlcDo\n"
+ "M7S5nMV63FclkZIT70FFTHwWed1sAKwEO3/Ny24eppc=\n"
+ "-----END NAUGHTY MARMOSET-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 lNY8TRX/FZdH5eFbsBkFHuRi8bPDsE5P+v7zExyD/IXnKS/ffYlP8qw1XIPdEDOIzGQ14+kyPX0SotaAqHRtBA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "BHamS+epF77iozo5cBt+tbs22m9GhwY55DRXpEWAtvn67jsMnmn7qCOLONigK1RT\n"
+ "adZNezIydcCxXltgHTdKaZw4lcqv3s0KL8kI8frbBmm7PjXtWnrdXBYY+YK54MN/\n"
+ "t4N3162o9hzzKSwye0gPjgzpQ1xtEIkzWhBcmE9Vw5s=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CROSSCERT7[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AfVmH2ReTyatl4VnS5YREtCM2dwikWuAPffq6M5bysZxAQAgBAAXoqE7\n"
+ "taqwLDXLZrZukpF1eBkCwYQK9uzctHTuMdqOHChguvkfX7V4H3O76Ayqvz+Z1ut1\n"
+ "KYRdgiArn3viRaBv3ZKT4Z75suMI3bjqGOSGLAKfOa0uLkOmKblHHhSUkwQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOLNugzUezzzw+N1SuQWzILJYkUJyQDoVXSZjT0dzBplHCjlrv0WZCUP\n"
+ "/pbonE7SlCChIovHcdiASaLj7MVaGgYDq3M1Vtgt5vhgGl10/+evBAD1QEt8AVfr\n"
+ "5+PH/sbZvOWucAhNUhOlqFKAn4vdRY39VEEXC5/Jz5fsk1E/DBu5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKxzg1hsYMS+0zAIrgYxSGO0GbKRrL/VhdlMEGu7ACaoqlGnmGQS3B4B\n"
+ "gLk8xDdx9N//8+YTx0hUIxP38w08lubPl1WXMq8s7wAiFd06Nklf65mHs0sXVtS1\n"
+ "EG3f97PQqmBpEJOwYBATNcA9e6F62P8SXNkpSjOzNaE0h9wHNKk7AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key msdr3O4W4bm/xdmZLzj35363ZSFex8yQxLWsV3wRCAQ=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "VQoABx54AU3MlHAEtgPdAyWJzRBnh4brXbCR9JFLjLM40hsBMoscAJ8cHMIc71+p\n"
+ "Qa+lg5JiYb551mLgtPWLy12xdhog7SXiJl3NvnMgbMZXHDqkU2YZCidnVz+xqMdh\n"
+ "mjQFK4AtRwg=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "RJJRiU0vjVtRi3bVZru3aTvV5l56X/WOOp/ii316yPAS3aAMpOm1+piFVR5MNqcB\n"
+ "ZGyrA2Kx0hawdL2buU47iZ12GOCi4f1Es4V4N0TQgJICsKX38DsRdct9c1qMcqpp\n"
+ "1aENSRuaw0szTIr9OgR7/8stqR5c3iF1H5fOhmTi6xM=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 4DSdPePrToNx3WQ+4GfFelB8IyHu5Z9vTbbLZ02vfYEsCF9QeaeHbYagY/yjdt+9e71jmfM+W5MfRQd8FJ1+Dgxx\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "F3ZqvsyL6RRhPEnNFFIZY4WJM7LK082rseWzRkGNXjwoEwOWUK8enQ4Wjit+wozW\n"
+ "4HVIY1F+vP7gm6IiOEAFgEpB4C8FGuyoFw2q0ONA2tqTcvBJDDnqbx08FO7v2Dij\n"
+ "d3ucfc5gf7YNaoFCMMuyAzC56eyNk4U+6cSKy6wnJds=\n"
+ "-----END SIGNATURE-----\n"
+ ;
+
+static const char EX_RI_ED_MISPLACED1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKT6OIN6TsDB+xcp1uLeE0K3aiHGqa7hdxMBGpvcD0UFSyzpVv1A/fJa\n"
+ "tClDCwTpfTGbyK2L7AO75Ci0c7jf6Pq+V7L6R7o12g6WBTMrgsceC4YqXSKpXNhi\n"
+ "oudJyPfVzBfKcJUSynv89FUQOyul/WRRqWTfv0xUsJ3yjuOESfCNAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AbBV9NVz0Hdl0Uiv87LiXaTAoeSXE+bheNG4Dju1GzQHAQAgBAD16h+T\n"
+ "ygzSgPN4Qat5ITthvm+lvMwMVGbVNWMxNy9i33NGhgp8kqMp2iPAY+LhX8It2b+X\n"
+ "8H9cBmYLO5G7AlMPj7GsuWdCdP/M/ldMvFfznlqeE3pCpRas6W48CFJ+9Ao=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANMO/MepK3uCkKTLRCwIWc/8URVza2gEmDx6mDTJIB/Mw8U8VRDuu4iJ\n"
+ "v+LL3D8/HGLvT9a8OXbl5525Zszt8XueF3uePBF0Qp0fjGBL8GFqmrmFe6plurPJ\n"
+ "TfrS/m3q+KhXAUowmghciVGDY0kMiDG9X/t/zKLMKWVDYRZk+fupAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key I8yDO62Flx5O/QsFvgb2ArIRqwJLWetHMeZdxngRl2A=\n"
+ "ntor-onion-key-crosscert 1\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AfXqH5PKDNKA83hBq3khO2G+b6W8zAxUZtU1YzE3L2LfAGC1uXxN2KwW\n"
+ "w4PqRidM1UPZ5jVOHceZYNQcTzzzArfBpr9OraOO2up4TGte8GVqjJNxrZc1gfjn\n"
+ "CwPW5WxpFg0=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "jLg3D3VO4i0sN8p2qtB6+5C3tai/K4M89mP7z2abQnUTbynOacPoNXIk4o64DjBJ\n"
+ "kaR42yfA7yQZ8Rj8abwgz0Zz6zbd+JjE+s/EklrEEtOl+jZAl3i+92FaHROJojXq\n"
+ "hw+ZEPOb9zgb1UQ7S1Fo+GoqA5bdGm/Wg1kSQielkNE=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 TRKvIl/wIIRD4Xcmd6HYmy7tD0KhVGgoStpWPtX0zmXGZ7+jugItrY0frDu9n82syiruuA45ZOs1Rfi4CbOSCg\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "NYpRfurB1YhFmDAdRc2Sd77S7By2V/0kgEHpJhtySb7efiQsyOA4ZBr1zEFPAXdp\n"
+ "TviKzyS9kN2fnz3hORoqFul33BDZbiLMNLtt5tzp62TYtmIg9IZdjjczbJUgbVLt\n"
+ "KCJL0vM7fdbXkZX61GIBbMYwzwIiHvVxG7F/AS5RbtE=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_MISPLACED2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55AfJo9FIePrxeDNnWT6SWkoz0/L27018XjUNWEHfaR06MAQAgBAAMgolK\n"
+ "nLg3ZnVv0skzHCfmX+ZR9Ttwj7FNXfhXCsyr860S79OW5LD0/m1GcS9JflWhP+FO\n"
+ "ng5cRb+aqNc8Ul+/4sQudZRx8w4U3d5rOuMGCqhQXnktH9AFzQHFq0jpAAU=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPeK/znKLRvSUmCIUiZOgfhiRFt7XGN//C2GFuey4xkKiIr9LWMuVe9m\n"
+ "Wx39Ea2UGEtNGCEVvZdJMDVRl7heFTfJTN4L1YeyWx6iNRWlpAmgQOKII7slHwlq\n"
+ "seEULOLOXc9AsU/v9ba9G54DFbHfe2k44ZOwEmaQZW5VF/I0YMMdAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKFRzlrqPPxEW0nboAJ1qzKFb/vFtvRW0xNVb8RtbOY/NY5FV1hS8yfH\n"
+ "igtugkrOBmWah7cmJhiON2j+TKeBxEoXwJMZeyV+HLbr7nY/mFhad4BQ3Frkl8d6\n"
+ "1kQMhOJswMdwnnVHPNGUob4YAX0SpFA6MpBVj92zmMBeaihqUS9VAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key br8svioLcJCAQxoo3KvlT288p8rb4lQIZNLlplkIKkw=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AQyCiUqcuDdmdW/SyTMcJ+Zf5lH1O3CPsU1d+FcKzKvzAG9XqwmRm0uJ\n"
+ "E49NoHcWr9IzdIwSGo+PJSkVpk95a5p2s065BetCWxEEBJQniajQf2hZ36zmV9rq\n"
+ "a6puqkEAKAM=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "d6QGIVAJL5JjHUyV+aicLIdBYyxHwviKpPcp7uldRF8vfDGFpu0qFgJ5KT+3t36w\n"
+ "QY1r75bvUMG/ZzGKDg95dcK0X2AK6GFlcrYyCoQEVOsuPc1QEUeK9P2s7viNQE4V\n"
+ "tRwG/CvJhPfcnxErzVGfXIeYRL1r/hPNFDZSeSxPPM0=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "router-sig-ed25519 ts9pFk8PnDWtXgQad09XC/ZCbruSx1U1pNOMWF9fyoNG0CodxdDH9Vglg+BOS7Nd9fmsINfPWKCVdVuSSM7zCA\n"
+ "reject *:*\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "YMl6mpQm7UCsPQhZKMm0aZ7fzGevWzRbQO+de20HTn7fVqMWQf2hBDJe9QTN/uDK\n"
+ "/VKYT8SnIBexbrSMy1N5q8kNFKxxUtwA9GRtz620Vvc4m+lz/tnT9qucIKCDL5iJ\n"
+ "eRpnls0JoAMIHKl99zdUioYubmOZuqUaRAdT8ulWy+Y=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CERT1[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AYf+rX8a5rzdTBGPvLdQIP8XcElDDQnJIruGqfDTj+tjAP+3XOL2UTmn\n"
+ "Hu39PbLZV+m9DIj/DvG38M0hP4MmHUjP/iZG5PaCX6/aMe+nQSNuTl0IDGpIo1l8\n"
+ "dZToQTFSzAQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM4o2DrTwn3wrvUMm41S/hFL5ZtRHGRDh26o8htn14AKMC65vpygKFY7\n"
+ "fUQVClAiJthAs5fD/8sE5XDtQrLnFv5OegQx8kSPuwyS/+5pI1bdxRJvKMOUl2Tc\n"
+ "fAUhzeNBmPvW3lMi9Fksw5sCSAKQ5VH/+DlYvBGZIO49pTnOAty1AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMzIsJeEWWjN3Lp6qrzaJGn8uhJPJyjy2Wt3sp7z7iD/yBWW6Q7Jku3e\n"
+ "C5QfKmSmNi2pNjS0SqPjqZZNsbcxpq/bEOcZdysZG1lqi/QgxUevk57RWjh3EFsG\n"
+ "TwK3ougKWB5Q6/3m32dNsnnnDqzVapgZo7Zd3V/aCo0BVtL5VXZbAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key W28nwT/5FJ818M78y/5sNOkxhQ7ENBhjVhGG2j6KvFY=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AYf+rX8a5rzdTBGPvLdQIP8XcElDDQnJIruGqfDTj+tjAP+3XOL2UTmn\n"
+ "Hu39PbLZV+m9DIj/DvG38M0hP4MmHUjP/iZG5PaCX6/aMe+nQSNuTl0IDGpIo1l8\n"
+ "dZToQTFSzAQ=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "FWnEjvFob0ObgqohMT7miwGsAuioCT7Urz6tyWaGWph/TP9hbFWj4MPK5mt998mn\n"
+ "xA8zHSF5n/edu7wVX+rtnPrYPBmg+qN8+Pq6XMg64CwtWu+sqigsi6vtz/TfAIDL\n"
+ "mypENmSY32sWPvy/CA8dAZ2ASh57EH9a+WcFModpXkM=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 88YqJdGJS4O6XiUCNrc9xbOHxujvcN/TkCoRuQQeKfZGHM+4IhI6AcXFlPIfDYq0SAavMhVmzsDDw0ROl7vyCQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "cU4WDO3w9ZfVRbNUgxOQMbwS2xWXvaL+cZmIV6AAjAZVWkLEpif4g6uYu+jJUZOS\n"
+ "NUT7lNOMwTu4tE4b1YJpnD9T8iW0DlOXxlvRBMQYmKwhQuYk898BDGTSk+0AY0HJ\n"
+ "vv8wRVewDajNhW7tFY907IdHvPXG0u83GANxkYrRyUg=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CERT2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN WOBBLY RUTABAGA-----\n"
+ "helo\n"
+ "-----END WOBBLY RUTABAGA-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANZvqyqFeiekh8ApqIGK4ZtOqjaX87EzDestvAWwamVOXiPoUrzXgM3O\n"
+ "l8uuTnMA4TfnjLyyA2TnaMzJylOI1OMHuW/D9B/liWDstSxWNNIlKgLQ/Dh9xBS7\n"
+ "uQb2PYlI+iMkPKPyJQSTDdGHE7cdFPewUfhRtJU3F5ztm/3FLBFvAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANZl8U/Z8KCPS7EBDzt8i9kNETXS7vnp9gnw3BQNXfjiDtDg9eO7ChxY\n"
+ "NBwuOTXmRxfX3W9kvZ0op9Hno6hixIhHzDql+vZ+hN7yPanVVDglSUXcr31yBm5K\n"
+ "kA+ZnRvH3oVQ97E4rRzpi09dtI13Pzu7JS5jRMtH+JF1kQBoNC0dAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key lUrEL+TVXpjjHQ2BIKk34vblyDmoyMro1a6/9hJ4VRc=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55Abm5E7FBdd3F8N1xuz/vdv03zh2lABrmGjzPQ3AFJtntALNeQTgjv0JL\n"
+ "jON4+SPNi0B2Bva3yKaSsdxiHQ1rIwQqIUVkzXmmX4jmsvJK/9gERAdD7GafTKZQ\n"
+ "BaZbNXBvmQw=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "OxkqFsw1vHUQ9iPYcKC/MHUBtbLPK6JY2i81ccAai2eW118UXcTbeCRccrXyqSkl\n"
+ "RLcooZyli1D6wg9x7O8+2+HXIbUa6WcTOD1Qi7Z9wKZfk4sDUy7QHKENMRfAXwX3\n"
+ "U/gqd4BflMPp4+XrYfPzz+6yQPWp0t9wXbFv5hZ9F3k=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 fW6Bt4R3xVk5KMDyOcYg8n5ANP0OrQq2PQFK2cW0lTAdi+eX+oT/BeWnkrn0uSWOC/t4omCmH4Rdl8M9xtpfBA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "DHxiQXuLxZR0ylqwUGGePgN4KF4ItlOV/DuGmmszCO/Ut0p+5s4FP2v6Mm9M92Wj\n"
+ "75rS9xF/Ts0Kf49dvgc+c5VTvhX5I5SwGQkRk0RNJtNoP0t+qXBHaFV8BlAeaWF6\n"
+ "Lg3O+GUK325fQv9uDPCe37mFQV9jafAzsZUrO/ggb1U=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_ED_BAD_CERT3[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "BVVVnf55AW5TTGF9jCMl7aALZzqypD9Bj8WYnAPIrKCoIJdgMbY0AQAgBAB7eCn8\n"
+ "rukx7t/egZUdqU7+FYqsnO4wdmOkLZkp0+gpF3jjk6N1Q0037NNVNZBjONB0Nm2F\n"
+ "CpB3nWSJliSSKr5tOYsuBPFy5VVGYeKPakpOoxanQ1UcqevMBAQy0zf9hwA=\n"
+ "-----END ED25519 CERT-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPgeQNbKwpnTU+qW/2djh66hptS9rcy1B4vdyWkDTdREao2ECuCv691Y\n"
+ "oIw3MpTWvpC1qHIKorunusR0FKgwXw3xQTikXbDq/1ptsekzoIA1R/hltQV3UuGH\n"
+ "zdzHuQXAMX7Fdll2gyya03c3Yq5s+xSDvGdkEeaIoctKjwxp4SdNAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOzWuH4cPW9rIrfi8MrruMUg4IUVHz4BxfY4/szMIUvzeEAdHn4FYkWy\n"
+ "Vt7MDtUELZsmZeFNmkn72kLxnrdZ5XhxZBriq1Fzq11cSWRBF+SyE1MdcouY4GyG\n"
+ "drw6T8xb8ty19q0eO6C/gw27iqXPAp1clvkroLg6Nv9lGZvsedVDAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key /vYZ+9yLqG7yUnutoI57s96JBl36GTz0IDWE244rbzE=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AZ4zVBWP/fIYEgWmyj0WpO6CkXRJjtrWXtiT02k3IddiAMpYgMemGIpN\n"
+ "xj7TQRULsHHYvo4fLcKrSgndQbUUhfLTUuVhIzbnE2TBLMVOEkpxKU6mTuvTT/3h\n"
+ "MJugrwTWVg4=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "c/Vqu3wtsTsYMdnhTS9Tn1Pq6jDmH4uRD5WmbaCKKrkin2DjuYSMVpypndkdlZDE\n"
+ "He7uF7SUO3QG/UcRIXYOsg9MSLUmvn2kIwef8ykyqlRh95Csjo5DyattUhL2w4QF\n"
+ "tJkJBQAnXWaAVW1O8XimGCAvJ84cxbmZEcpN6WKjrXI=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 Ue7bkPpOoc8ca7cyQj/Vq3BP5X4vwLA5QmpLGw/WfRNVRPojJRxU3RVqWMi3JbsJFRTe6pH6ZHyXER33G5aAAA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "ifKUtbxmqHVs8A0oT5n7Te0c6D/XqWQTc0RxX9OKGspzh6wNX26h0Xa2vpK1Q9Zu\n"
+ "sj61I7vbHuZN6rxiWs9IzJgb//XaNJasX1pd9tbGSXW+yYzc9G9kaa7vp3HcnhIP\n"
+ "XVWzzS8WmOiVNGcF65j6f7yGloTgN7cHMptgJG7pWes=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
+static const char EX_RI_BAD_EI_DIGEST2[] =
+ "router fred 127.0.0.1 9001 0 9002\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf55ATrK8IVBWLO2yXKCqXLXJOTu89W2b+hREPO+tCrxjVqWAQAgBACG/vVx\n"
+ "NK8wKVZvf34d75ZObSR0ge1N2RrAIKNslNXBq/tcllIrNE4S0ZNcMpA+hxXoVFeo\n"
+ "jbxifYX7nTs5N3GrGPmkiuo82v2X6ZwoIXJGFnvWMxCjsYsUVDDxoT6h/w8=\n"
+ "-----END ED25519 CERT-----\n"
+ "extra-info-digest E5FAC29E766D63F96AD175069640E803F2723765 99oo\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAK9wHSdRalxkuAybrSCA3dlEC1ZGc7oHOzXRGLg+z6batuiCdQtus1Rk\n"
+ "LP821eZJtEMAE56aewCIHDcTiCxVa6DMqmxRjm5pfW4G5H5QCPYT6Fu0RoYck3Ef\n"
+ "vkgits5/fNYGPPVC7k8AdGax5dKj5oFVGq+JWolYFRv6tyR9AThvAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKxjxTQ/T/MHpFbk7/zwA7l5b3IW3yVcyVe6eIGFoYun8FI0fbYRmR4M\n"
+ "G5Asu07gP9Bbgt3AFPuEqrjg4u+lIkgqTcCgKWJbAgm7fslwaDTXQ36A7I1M95PD\n"
+ "GJ10Dk5v4dVbrqwoF7MSrQPFtMO91RP11nGPSvDqXZJ4XpwqwdxpAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key LuVmHxpj4F5mPXGNi4MtxbIbLMav6frJRBsRgAvpdzo=\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf55AYb+9XE0rzApVm9/fh3vlk5tJHSB7U3ZGsAgo2yU1cGrAKBcSzwi4lY/\n"
+ "salCELOLdeZzOjDNnBd6cKp2WJg7Yz5zFlbVbyNk0iwfGmucHk8vQZe5BS0Oq/Pz\n"
+ "B1u/BcJv8gk=\n"
+ "-----END ED25519 CERT-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "QsAQVdDVHtasDbhrZG4ZxImdTTMY7fz3vouAiGyZx6/jCCB5v0gHwTn4xo6pgLEW\n"
+ "LQfMhQZIr76Ky67c0hAN2hihuDlfvhfVe9c2c5UOH1BOhq3llE3Hc3xGyEy3rw7r\n"
+ "5y38YGi759CvsP2/L8JfXMuBg89OcgJYFa27Q6e6MdQ=\n"
+ "-----END CROSSCERT-----\n"
+ "published 2014-10-05 12:00:00\n"
+ "bandwidth 1000 1000 1000\n"
+ "reject *:*\n"
+ "router-sig-ed25519 5zoQ0dufeeOJ/tE/BgcWgM8JpfW1ELSXLz4dI+K8YRH/gUtaPmYJgU2QfeUHD0oy1iwv4Qvl8Ferga7aBk1+DA\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "D6KRMwkb6JmVEnpZ825SD3LMB84UmVy0i94xk44OwhoWNKLXhaSTWJgf6AqnPG5o\n"
+ "QrCypSb44bYLn+VaDN5LVUl36jeZqCT4xd+4ZwIRdPOUj7vcVmyUDg3lXcAIk97Q\n"
+ "E5PrQY1mQuLSIjjKInAR2NRBumNJtRw31Y/DTB7tODU=\n"
+ "-----END SIGNATURE-----\n"
+ "\n"
+ ;
diff --git a/src/test/fakechans.h b/src/test/fakechans.h
new file mode 100644
index 0000000000..fa0e37dbe6
--- /dev/null
+++ b/src/test/fakechans.h
@@ -0,0 +1,26 @@
+ /* Copyright (c) 2014-2016, The Tor Project, Inc. */
+ /* See LICENSE for licensing information */
+
+#ifndef TOR_FAKECHANS_H
+#define TOR_FAKECHANS_H
+
+/**
+ * \file fakechans.h
+ * \brief Declarations for fake channels for test suite use
+ */
+
+void make_fake_cell(cell_t *c);
+void make_fake_var_cell(var_cell_t *c);
+channel_t * new_fake_channel(void);
+void free_fake_channel(channel_t *c);
+
+/* Also exposes some a mock used by both test_channel.c and test_relay.c */
+void scheduler_channel_has_waiting_cells_mock(channel_t *ch);
+void scheduler_release_channel_mock(channel_t *ch);
+
+/* Query some counters used by the exposed mocks */
+int get_mock_scheduler_has_waiting_cells_count(void);
+int get_mock_scheduler_release_channel_count(void);
+
+#endif /* !defined(TOR_FAKECHANS_H) */
+
diff --git a/src/test/include.am b/src/test/include.am
index fba439a616..7d80fdf152 100644
--- a/src/test/include.am
+++ b/src/test/include.am
@@ -1,14 +1,54 @@
-TESTS += src/test/test
+# When the day comes that Tor requires Automake >= 1.12 change
+# TESTS_ENVIRONMENT to AM_TESTS_ENVIRONMENT because the former is reserved for
+# users while the later is reserved for developers.
+TESTS_ENVIRONMENT = \
+ export PYTHON="$(PYTHON)"; \
+ export SHELL="$(SHELL)"; \
+ export abs_top_srcdir="$(abs_top_srcdir)"; \
+ export builddir="$(builddir)"; \
+ export TESTING_TOR_BINARY="$(TESTING_TOR_BINARY)";
+
+TESTSCRIPTS = src/test/test_zero_length_keys.sh \
+ src/test/test_switch_id.sh
+
+if USEPYTHON
+TESTSCRIPTS += src/test/test_ntor.sh src/test/test_bt.sh
+endif
+
+TESTS += src/test/test src/test/test-slow src/test/test-memwipe \
+ src/test/test_workqueue src/test/test_keygen.sh \
+ $(TESTSCRIPTS)
+
+# These flavors are run using automake's test-driver and test-network.sh
+TEST_CHUTNEY_FLAVORS = basic-min bridges-min hs-min bridges+hs
+# only run if we can ping6 ::1 (localhost)
+TEST_CHUTNEY_FLAVORS_IPV6 = bridges+ipv6-min ipv6-exit-min
+# only run if we can find a stable (or simply another) version of tor
+TEST_CHUTNEY_FLAVORS_MIXED = mixed
+
+### This is a lovely feature, but it requires automake >= 1.12, and Tor
+### doesn't require that yet.
+###
+# TEST_EXTENSIONS = .sh
+# SH_LOG_COMPILER = $(SHELL)
noinst_PROGRAMS+= src/test/bench
if UNITTESTS_ENABLED
-noinst_PROGRAMS+= src/test/test src/test/test-child
+noinst_PROGRAMS+= \
+ src/test/test \
+ src/test/test-slow \
+ src/test/test-memwipe \
+ src/test/test-child \
+ src/test/test_workqueue \
+ src/test/test-switch-id
endif
src_test_AM_CPPFLAGS = -DSHARE_DATADIR="\"$(datadir)\"" \
-DLOCALSTATEDIR="\"$(localstatedir)\"" \
-DBINDIR="\"$(bindir)\"" \
-I"$(top_srcdir)/src/or" -I"$(top_srcdir)/src/ext" \
+ -I"$(top_srcdir)/src/trunnel" \
+ -I"$(top_srcdir)/src/ext/trunnel" \
-DTOR_UNIT_TESTS
# -L flags need to go in LDFLAGS. -l flags need to go in LDADD.
@@ -16,83 +56,163 @@ src_test_AM_CPPFLAGS = -DSHARE_DATADIR="\"$(datadir)\"" \
# matters a lot there, and is quite hard to debug if you forget to do it.
src_test_test_SOURCES = \
+ src/test/log_test_helpers.c \
+ src/test/rend_test_helpers.c \
src/test/test.c \
+ src/test/test_accounting.c \
src/test/test_addr.c \
+ src/test/test_address.c \
src/test/test_buffers.c \
src/test/test_cell_formats.c \
+ src/test/test_cell_queue.c \
+ src/test/test_channel.c \
+ src/test/test_channeltls.c \
+ src/test/test_checkdir.c \
src/test/test_circuitlist.c \
src/test/test_circuitmux.c \
+ src/test/test_compat_libevent.c \
+ src/test/test_config.c \
+ src/test/test_connection.c \
src/test/test_containers.c \
+ src/test/test_controller.c \
src/test/test_controller_events.c \
src/test/test_crypto.c \
- src/test/test_cell_queue.c \
src/test/test_data.c \
src/test/test_dir.c \
+ src/test/test_dir_common.c \
+ src/test/test_dir_handle_get.c \
+ src/test/test_entryconn.c \
+ src/test/test_entrynodes.c \
+ src/test/test_guardfraction.c \
src/test/test_extorport.c \
+ src/test/test_hs.c \
src/test/test_introduce.c \
+ src/test/test_keypin.c \
+ src/test/test_link_handshake.c \
src/test/test_logging.c \
src/test/test_microdesc.c \
+ src/test/test_nodelist.c \
src/test/test_oom.c \
src/test/test_options.c \
+ src/test/test_policy.c \
+ src/test/test_procmon.c \
src/test/test_pt.c \
+ src/test/test_relay.c \
src/test/test_relaycell.c \
+ src/test/test_rendcache.c \
src/test/test_replay.c \
src/test/test_routerkeys.c \
+ src/test/test_routerlist.c \
+ src/test/test_routerset.c \
+ src/test/test_scheduler.c \
src/test/test_socks.c \
- src/test/test_util.c \
- src/test/test_config.c \
- src/test/test_hs.c \
- src/test/test_nodelist.c \
- src/test/test_policy.c \
src/test/test_status.c \
+ src/test/test_threads.c \
+ src/test/test_tortls.c \
+ src/test/test_util.c \
+ src/test/test_util_format.c \
+ src/test/test_util_process.c \
+ src/test/test_helpers.c \
+ src/test/test_dns.c \
+ src/test/testing_common.c \
+ src/ext/tinytest.c
+
+src_test_test_slow_SOURCES = \
+ src/test/test_slow.c \
+ src/test/test_crypto_slow.c \
+ src/test/test_util_slow.c \
+ src/test/testing_common.c \
src/ext/tinytest.c
+src_test_test_memwipe_SOURCES = \
+ src/test/test-memwipe.c
+
+
src_test_test_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
-src_test_test_CPPFLAGS= $(src_test_AM_CPPFLAGS)
+src_test_test_CPPFLAGS= $(src_test_AM_CPPFLAGS) $(TEST_CPPFLAGS)
src_test_bench_SOURCES = \
src/test/bench.c
+src_test_test_workqueue_SOURCES = \
+ src/test/test_workqueue.c
+src_test_test_workqueue_CPPFLAGS= $(src_test_AM_CPPFLAGS)
+src_test_test_workqueue_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
+
+src_test_test_switch_id_SOURCES = \
+ src/test/test_switch_id.c
+src_test_test_switch_id_CPPFLAGS= $(src_test_AM_CPPFLAGS)
+src_test_test_switch_id_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
+src_test_test_switch_id_LDFLAGS = @TOR_LDFLAGS_zlib@
+src_test_test_switch_id_LDADD = \
+ src/common/libor-testing.a \
+ @TOR_ZLIB_LIBS@ @TOR_LIB_MATH@
+
src_test_test_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ \
@TOR_LDFLAGS_libevent@
-src_test_test_LDADD = src/or/libtor-testing.a src/common/libor-testing.a \
- src/common/libor-crypto-testing.a $(LIBDONNA) \
+src_test_test_LDADD = src/or/libtor-testing.a \
+ src/common/libor-crypto-testing.a \
+ $(LIBKECCAK_TINY) \
+ $(LIBDONNA) \
+ src/common/libor-testing.a \
src/common/libor-event-testing.a \
+ src/trunnel/libor-trunnel-testing.a \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ \
- @TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@
+ @TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@ \
+ @TOR_SYSTEMD_LIBS@
+
+src_test_test_slow_CPPFLAGS = $(src_test_test_CPPFLAGS)
+src_test_test_slow_CFLAGS = $(src_test_test_CFLAGS)
+src_test_test_slow_LDADD = $(src_test_test_LDADD)
+src_test_test_slow_LDFLAGS = $(src_test_test_LDFLAGS)
+
+src_test_test_memwipe_CPPFLAGS = $(src_test_test_CPPFLAGS)
+src_test_test_memwipe_CFLAGS = $(src_test_test_CFLAGS)
+src_test_test_memwipe_LDADD = $(src_test_test_LDADD)
+src_test_test_memwipe_LDFLAGS = $(src_test_test_LDFLAGS)
src_test_bench_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ \
@TOR_LDFLAGS_libevent@
src_test_bench_LDADD = src/or/libtor.a src/common/libor.a \
- src/common/libor-crypto.a $(LIBDONNA) \
- src/common/libor-event.a \
+ src/common/libor-crypto.a $(LIBKECCAK_TINY) $(LIBDONNA) \
+ src/common/libor-event.a src/trunnel/libor-trunnel.a \
+ @TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ \
+ @TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@ \
+ @TOR_SYSTEMD_LIBS@
+
+src_test_test_workqueue_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ \
+ @TOR_LDFLAGS_libevent@
+src_test_test_workqueue_LDADD = src/or/libtor-testing.a \
+ src/common/libor-testing.a \
+ src/common/libor-crypto-testing.a $(LIBKECCAK_TINY) $(LIBDONNA) \
+ src/common/libor-event-testing.a \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ \
@TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@
noinst_HEADERS+= \
- src/test/test.h
+ src/test/fakechans.h \
+ src/test/log_test_helpers.h \
+ src/test/rend_test_helpers.h \
+ src/test/test.h \
+ src/test/test_helpers.h \
+ src/test/test_dir_common.h \
+ src/test/test_descriptors.inc \
+ src/test/example_extrainfo.inc \
+ src/test/failing_routerdescs.inc \
+ src/test/ed25519_vectors.inc \
+ src/test/test_descriptors.inc \
+ src/test/vote_descriptors.inc
-if CURVE25519_ENABLED
noinst_PROGRAMS+= src/test/test-ntor-cl
src_test_test_ntor_cl_SOURCES = src/test/test_ntor_cl.c
src_test_test_ntor_cl_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@
src_test_test_ntor_cl_LDADD = src/or/libtor.a src/common/libor.a \
- src/common/libor-crypto.a $(LIBDONNA) \
+ src/common/libor-crypto.a $(LIBKECCAK_TINY) $(LIBDONNA) \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ \
@TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@
src_test_test_ntor_cl_AM_CPPFLAGS = \
-I"$(top_srcdir)/src/or"
-NTOR_TEST_DEPS=src/test/test-ntor-cl
-else
-NTOR_TEST_DEPS=
-endif
-
-if COVERAGE_ENABLED
-CMDLINE_TEST_TOR = ./src/or/tor-cov
-else
-CMDLINE_TEST_TOR = ./src/or/tor
-endif
noinst_PROGRAMS += src/test/test-bt-cl
src_test_test_bt_cl_SOURCES = src/test/test_bt_cl.c
@@ -100,22 +220,15 @@ src_test_test_bt_cl_LDADD = src/common/libor-testing.a \
@TOR_LIB_MATH@ \
@TOR_LIB_WS32@ @TOR_LIB_GDI@
src_test_test_bt_cl_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
-src_test_test_bt_cl_CPPFLAGS= $(src_test_AM_CPPFLAGS)
-
-
-check-local: $(NTOR_TEST_DEPS) $(CMDLINE_TEST_TOR)
-if USEPYTHON
- $(PYTHON) $(top_srcdir)/src/test/test_cmdline_args.py $(CMDLINE_TEST_TOR) "${top_srcdir}"
-if CURVE25519_ENABLED
- $(PYTHON) $(top_srcdir)/src/test/ntor_ref.py test-tor
- $(PYTHON) $(top_srcdir)/src/test/ntor_ref.py self-test
-endif
- ./src/test/test-bt-cl assert | $(PYTHON) $(top_srcdir)/src/test/bt_test.py
- ./src/test/test-bt-cl crash | $(PYTHON) $(top_srcdir)/src/test/bt_test.py
-endif
+src_test_test_bt_cl_CPPFLAGS= $(src_test_AM_CPPFLAGS) $(TEST_CPPFLAGS)
EXTRA_DIST += \
src/test/bt_test.py \
src/test/ntor_ref.py \
src/test/slownacl_curve25519.py \
- src/test/test_cmdline_args.py
+ src/test/zero_length_keys.sh \
+ src/test/test_keygen.sh \
+ src/test/test_zero_length_keys.sh \
+ src/test/test_ntor.sh src/test/test_bt.sh \
+ src/test/test-network.sh \
+ src/test/test_switch_id.sh
diff --git a/src/test/log_test_helpers.c b/src/test/log_test_helpers.c
new file mode 100644
index 0000000000..3bb36ac36c
--- /dev/null
+++ b/src/test/log_test_helpers.c
@@ -0,0 +1,113 @@
+/* Copyright (c) 2015-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+#define LOG_PRIVATE
+#include "torlog.h"
+#include "log_test_helpers.h"
+
+static smartlist_t *saved_logs = NULL;
+
+int
+setup_capture_of_logs(int new_level)
+{
+ int previous_log = log_global_min_severity_;
+ log_global_min_severity_ = new_level;
+ mock_clean_saved_logs();
+ MOCK(logv, mock_saving_logv);
+ return previous_log;
+}
+
+void
+teardown_capture_of_logs(int prev)
+{
+ UNMOCK(logv);
+ log_global_min_severity_ = prev;
+ mock_clean_saved_logs();
+}
+
+void
+mock_clean_saved_logs(void)
+{
+ if (!saved_logs)
+ return;
+ SMARTLIST_FOREACH(saved_logs, mock_saved_log_entry_t *, m,
+ { tor_free(m->generated_msg); tor_free(m); });
+ smartlist_free(saved_logs);
+ saved_logs = NULL;
+}
+
+const smartlist_t *
+mock_saved_logs(void)
+{
+ return saved_logs;
+}
+
+int
+mock_saved_log_has_message(const char *msg)
+{
+ int has_msg = 0;
+ if (saved_logs) {
+ SMARTLIST_FOREACH(saved_logs, mock_saved_log_entry_t *, m,
+ {
+ if (msg && m->generated_msg &&
+ !strcmp(msg, m->generated_msg)) {
+ has_msg = 1;
+ }
+ });
+ }
+
+ return has_msg;
+}
+
+/* Do the saved logs have any messages with severity? */
+int
+mock_saved_log_has_severity(int severity)
+{
+ int has_sev = 0;
+ if (saved_logs) {
+ SMARTLIST_FOREACH(saved_logs, mock_saved_log_entry_t *, m,
+ {
+ if (m->severity == severity) {
+ has_sev = 1;
+ }
+ });
+ }
+
+ return has_sev;
+}
+
+/* Do the saved logs have any messages? */
+int
+mock_saved_log_has_entry(void)
+{
+ if (saved_logs) {
+ return smartlist_len(saved_logs) > 0;
+ }
+ return 0;
+}
+
+void
+mock_saving_logv(int severity, log_domain_mask_t domain,
+ const char *funcname, const char *suffix,
+ const char *format, va_list ap)
+{
+ (void)domain;
+ char *buf = tor_malloc_zero(10240);
+ int n;
+ n = tor_vsnprintf(buf,10240,format,ap);
+ tor_assert(n < 10240-1);
+ buf[n]='\n';
+ buf[n+1]='\0';
+
+ mock_saved_log_entry_t *e = tor_malloc_zero(sizeof(mock_saved_log_entry_t));
+ e->severity = severity;
+ e->funcname = funcname;
+ e->suffix = suffix;
+ e->format = format;
+ e->generated_msg = tor_strdup(buf);
+ tor_free(buf);
+
+ if (!saved_logs)
+ saved_logs = smartlist_new();
+ smartlist_add(saved_logs, e);
+}
+
diff --git a/src/test/log_test_helpers.h b/src/test/log_test_helpers.h
new file mode 100644
index 0000000000..1966f170fb
--- /dev/null
+++ b/src/test/log_test_helpers.h
@@ -0,0 +1,56 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+
+#ifndef TOR_LOG_TEST_HELPERS_H
+#define TOR_LOG_TEST_HELPERS_H
+
+typedef struct mock_saved_log_entry_t {
+ int severity;
+ const char *funcname;
+ const char *suffix;
+ const char *format;
+ char *generated_msg;
+ struct mock_saved_log_entry_t *next;
+} mock_saved_log_entry_t;
+
+void mock_saving_logv(int severity, log_domain_mask_t domain,
+ const char *funcname, const char *suffix,
+ const char *format, va_list ap)
+ CHECK_PRINTF(5, 0);
+void mock_clean_saved_logs(void);
+const smartlist_t *mock_saved_logs(void);
+int setup_capture_of_logs(int new_level);
+void teardown_capture_of_logs(int prev);
+
+int mock_saved_log_has_message(const char *msg);
+int mock_saved_log_has_severity(int severity);
+int mock_saved_log_has_entry(void);
+
+#define expect_log_msg(str) \
+ tt_assert_msg(mock_saved_log_has_message(str), \
+ "expected log to contain " # str);
+
+#define expect_no_log_msg(str) \
+ tt_assert_msg(!mock_saved_log_has_message(str), \
+ "expected log to not contain " # str);
+
+#define expect_log_severity(severity) \
+ tt_assert_msg(mock_saved_log_has_severity(severity), \
+ "expected log to contain severity " # severity);
+
+#define expect_no_log_severity(severity) \
+ tt_assert_msg(!mock_saved_log_has_severity(severity), \
+ "expected log to not contain severity " # severity);
+
+#define expect_log_entry() \
+ tt_assert_msg(mock_saved_log_has_entry(), \
+ "expected log to contain entries");
+
+#define expect_no_log_entry() \
+ tt_assert_msg(!mock_saved_log_has_entry(), \
+ "expected log to not contain entries");
+
+#endif
+
diff --git a/src/test/ntor_ref.py b/src/test/ntor_ref.py
index 7d6e43e716..df065853f3 100755
--- a/src/test/ntor_ref.py
+++ b/src/test/ntor_ref.py
@@ -1,5 +1,5 @@
#!/usr/bin/python
-# Copyright 2012-2013, The Tor Project, Inc
+# Copyright 2012-2015, The Tor Project, Inc
# See LICENSE for licensing information
"""
@@ -283,7 +283,7 @@ def client_part2(seckey_x, msg, node_id, pubkey_B, keyBytes=72):
my_auth = H_mac(auth_input)
badness = my_auth != their_auth
- badness = bad_result(yx) + bad_result(bx)
+ badness |= bad_result(yx) + bad_result(bx)
if badness:
return None
@@ -322,7 +322,7 @@ def kdf_vectors():
"""
import binascii
def kdf_vec(inp):
- k = kdf(inp, T_KEY, M_EXPAND, 100)
+ k = kdf_rfc5869(inp, T_KEY, M_EXPAND, 100)
print(repr(inp), "\n\""+ binascii.b2a_hex(k)+ "\"")
kdf_vec("")
kdf_vec("Tor")
diff --git a/src/test/rend_test_helpers.c b/src/test/rend_test_helpers.c
new file mode 100644
index 0000000000..377337bcb9
--- /dev/null
+++ b/src/test/rend_test_helpers.c
@@ -0,0 +1,73 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+#include "test.h"
+#include "rendcommon.h"
+#include "rend_test_helpers.h"
+
+void
+generate_desc(int time_diff, rend_encoded_v2_service_descriptor_t **desc,
+ char **service_id, int intro_points)
+{
+ rend_service_descriptor_t *generated = NULL;
+ smartlist_t *descs = smartlist_new();
+ time_t now;
+
+ now = time(NULL) + time_diff;
+ create_descriptor(&generated, service_id, intro_points);
+ generated->timestamp = now;
+
+ rend_encode_v2_descriptors(descs, generated, now, 0, REND_NO_AUTH, NULL,
+ NULL);
+ tor_assert(smartlist_len(descs) > 1);
+ *desc = smartlist_get(descs, 0);
+ smartlist_set(descs, 0, NULL);
+
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ rend_service_descriptor_free(generated);
+}
+
+void
+create_descriptor(rend_service_descriptor_t **generated, char **service_id,
+ int intro_points)
+{
+ crypto_pk_t *pk1 = NULL;
+ crypto_pk_t *pk2 = NULL;
+ int i;
+
+ *service_id = tor_malloc(REND_SERVICE_ID_LEN_BASE32+1);
+ pk1 = pk_generate(0);
+ pk2 = pk_generate(1);
+
+ *generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ (*generated)->pk = crypto_pk_dup_key(pk1);
+ rend_get_service_id((*generated)->pk, *service_id);
+
+ (*generated)->version = 2;
+ (*generated)->protocols = 42;
+ (*generated)->intro_nodes = smartlist_new();
+
+ for (i = 0; i < intro_points; i++) {
+ rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
+ crypto_pk_t *okey = pk_generate(2 + i);
+ intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
+ intro->extend_info->onion_key = okey;
+ crypto_pk_get_digest(intro->extend_info->onion_key,
+ intro->extend_info->identity_digest);
+ intro->extend_info->nickname[0] = '$';
+ base16_encode(intro->extend_info->nickname + 1,
+ sizeof(intro->extend_info->nickname) - 1,
+ intro->extend_info->identity_digest, DIGEST_LEN);
+ tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
+ intro->extend_info->port = 1 + crypto_rand_int(65535);
+ intro->intro_key = crypto_pk_dup_key(pk2);
+ smartlist_add((*generated)->intro_nodes, intro);
+ }
+
+ crypto_pk_free(pk1);
+ crypto_pk_free(pk2);
+}
+
diff --git a/src/test/rend_test_helpers.h b/src/test/rend_test_helpers.h
new file mode 100644
index 0000000000..180a4e8fde
--- /dev/null
+++ b/src/test/rend_test_helpers.h
@@ -0,0 +1,15 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+
+#ifndef TOR_REND_TEST_HELPERS_H
+#define TOR_REND_TEST_HELPERS_H
+
+void generate_desc(int time_diff, rend_encoded_v2_service_descriptor_t **desc,
+ char **service_id, int intro_points);
+void create_descriptor(rend_service_descriptor_t **generated,
+ char **service_id, int intro_points);
+
+#endif
+
diff --git a/src/test/slow_ed25519.py b/src/test/slow_ed25519.py
new file mode 100644
index 0000000000..f44708b200
--- /dev/null
+++ b/src/test/slow_ed25519.py
@@ -0,0 +1,115 @@
+# This is the ed25519 implementation from
+# http://ed25519.cr.yp.to/python/ed25519.py .
+# It is in the public domain.
+#
+# It isn't constant-time. Don't use it except for testing. Also, see
+# warnings about how very slow it is. Only use this for generating
+# test vectors, I'd suggest.
+#
+# Don't edit this file. Mess with ed25519_ref.py
+
+import hashlib
+
+b = 256
+q = 2**255 - 19
+l = 2**252 + 27742317777372353535851937790883648493
+
+def H(m):
+ return hashlib.sha512(m).digest()
+
+def expmod(b,e,m):
+ if e == 0: return 1
+ t = expmod(b,e/2,m)**2 % m
+ if e & 1: t = (t*b) % m
+ return t
+
+def inv(x):
+ return expmod(x,q-2,q)
+
+d = -121665 * inv(121666)
+I = expmod(2,(q-1)/4,q)
+
+def xrecover(y):
+ xx = (y*y-1) * inv(d*y*y+1)
+ x = expmod(xx,(q+3)/8,q)
+ if (x*x - xx) % q != 0: x = (x*I) % q
+ if x % 2 != 0: x = q-x
+ return x
+
+By = 4 * inv(5)
+Bx = xrecover(By)
+B = [Bx % q,By % q]
+
+def edwards(P,Q):
+ x1 = P[0]
+ y1 = P[1]
+ x2 = Q[0]
+ y2 = Q[1]
+ x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2)
+ y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2)
+ return [x3 % q,y3 % q]
+
+def scalarmult(P,e):
+ if e == 0: return [0,1]
+ Q = scalarmult(P,e/2)
+ Q = edwards(Q,Q)
+ if e & 1: Q = edwards(Q,P)
+ return Q
+
+def encodeint(y):
+ bits = [(y >> i) & 1 for i in range(b)]
+ return ''.join([chr(sum([bits[i * 8 + j] << j for j in range(8)])) for i in range(b/8)])
+
+def encodepoint(P):
+ x = P[0]
+ y = P[1]
+ bits = [(y >> i) & 1 for i in range(b - 1)] + [x & 1]
+ return ''.join([chr(sum([bits[i * 8 + j] << j for j in range(8)])) for i in range(b/8)])
+
+def bit(h,i):
+ return (ord(h[i/8]) >> (i%8)) & 1
+
+def publickey(sk):
+ h = H(sk)
+ a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
+ A = scalarmult(B,a)
+ return encodepoint(A)
+
+def Hint(m):
+ h = H(m)
+ return sum(2**i * bit(h,i) for i in range(2*b))
+
+def signature(m,sk,pk):
+ h = H(sk)
+ a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
+ r = Hint(''.join([h[i] for i in range(b/8,b/4)]) + m)
+ R = scalarmult(B,r)
+ S = (r + Hint(encodepoint(R) + pk + m) * a) % l
+ return encodepoint(R) + encodeint(S)
+
+def isoncurve(P):
+ x = P[0]
+ y = P[1]
+ return (-x*x + y*y - 1 - d*x*x*y*y) % q == 0
+
+def decodeint(s):
+ return sum(2**i * bit(s,i) for i in range(0,b))
+
+def decodepoint(s):
+ y = sum(2**i * bit(s,i) for i in range(0,b-1))
+ x = xrecover(y)
+ if x & 1 != bit(s,b-1): x = q-x
+ P = [x,y]
+ if not isoncurve(P): raise Exception("decoding point that is not on curve")
+ return P
+
+def checkvalid(s,m,pk):
+ if len(s) != b/4: raise Exception("signature length is wrong")
+ if len(pk) != b/8: raise Exception("public-key length is wrong")
+ R = decodepoint(s[0:b/8])
+ A = decodepoint(pk)
+ S = decodeint(s[b/8:b/4])
+ h = Hint(encodepoint(R) + pk + m)
+ if scalarmult(B,S) != edwards(R,scalarmult(A,h)):
+ raise Exception("signature does not pass verification")
+
diff --git a/src/test/test-child.c b/src/test/test-child.c
index 756782e70b..e2552a499d 100644
--- a/src/test/test-child.c
+++ b/src/test/test-child.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2011-2013, The Tor Project, Inc. */
+/* Copyright (c) 2011-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include <stdio.h>
diff --git a/src/test/test-memwipe.c b/src/test/test-memwipe.c
new file mode 100644
index 0000000000..5d4fcec664
--- /dev/null
+++ b/src/test/test-memwipe.c
@@ -0,0 +1,209 @@
+#include <string.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <stdlib.h>
+
+#include "crypto.h"
+#include "compat.h"
+
+#undef MIN
+#define MIN(a,b) ( ((a)<(b)) ? (a) : (b) )
+
+static unsigned fill_a_buffer_memset(void) __attribute__((noinline));
+static unsigned fill_a_buffer_memwipe(void) __attribute__((noinline));
+static unsigned fill_a_buffer_nothing(void) __attribute__((noinline));
+static unsigned fill_heap_buffer_memset(void) __attribute__((noinline));
+static unsigned fill_heap_buffer_memwipe(void) __attribute__((noinline));
+static unsigned fill_heap_buffer_nothing(void) __attribute__((noinline));
+static unsigned check_a_buffer(void) __attribute__((noinline));
+
+const char *s = NULL;
+
+#define BUF_LEN 2048
+
+#define FILL_BUFFER_IMPL() \
+ unsigned int i; \
+ unsigned sum = 0; \
+ \
+ /* Fill up a 1k buffer with a recognizable pattern. */ \
+ for (i = 0; i < BUF_LEN; i += strlen(s)) { \
+ memcpy(buf+i, s, MIN(strlen(s), BUF_LEN-i)); \
+ } \
+ \
+ /* Use the buffer as input to a computation so the above can't get */ \
+ /* optimized away. */ \
+ for (i = 0; i < BUF_LEN; ++i) { \
+ sum += (unsigned char)buf[i]; \
+ }
+
+static unsigned
+fill_a_buffer_memset(void)
+{
+ char buf[BUF_LEN];
+ FILL_BUFFER_IMPL()
+ memset(buf, 0, sizeof(buf));
+ return sum;
+}
+
+static unsigned
+fill_a_buffer_memwipe(void)
+{
+ char buf[BUF_LEN];
+ FILL_BUFFER_IMPL()
+ memwipe(buf, 0, sizeof(buf));
+ return sum;
+}
+
+static unsigned
+fill_a_buffer_nothing(void)
+{
+ char buf[BUF_LEN];
+ FILL_BUFFER_IMPL()
+ return sum;
+}
+
+static inline int
+vmemeq(volatile char *a, const char *b, size_t n)
+{
+ while (n--) {
+ if (*a++ != *b++)
+ return 0;
+ }
+ return 1;
+}
+
+static unsigned
+check_a_buffer(void)
+{
+ unsigned int i;
+ volatile char buf[1024];
+ unsigned sum = 0;
+
+ /* See if this buffer has the string in it.
+
+ YES, THIS DOES INVOKE UNDEFINED BEHAVIOR BY READING FROM AN UNINITIALIZED
+ BUFFER.
+
+ If you know a better way to figure out whether the compiler eliminated
+ the memset/memwipe calls or not, please let me know.
+ */
+ for (i = 0; i < BUF_LEN - strlen(s); ++i) {
+ if (vmemeq(buf+i, s, strlen(s)))
+ ++sum;
+ }
+
+ return sum;
+}
+
+static char *heap_buf = NULL;
+
+static unsigned
+fill_heap_buffer_memset(void)
+{
+ char *buf = heap_buf = malloc(BUF_LEN);
+ FILL_BUFFER_IMPL()
+ memset(buf, 0, BUF_LEN);
+ free(buf);
+ return sum;
+}
+
+static unsigned
+fill_heap_buffer_memwipe(void)
+{
+ char *buf = heap_buf = malloc(BUF_LEN);
+ FILL_BUFFER_IMPL()
+ memwipe(buf, 0, BUF_LEN);
+ free(buf);
+ return sum;
+}
+
+static unsigned
+fill_heap_buffer_nothing(void)
+{
+ char *buf = heap_buf = malloc(BUF_LEN);
+ FILL_BUFFER_IMPL()
+ free(buf);
+ return sum;
+}
+
+static unsigned
+check_heap_buffer(void)
+{
+ unsigned int i;
+ unsigned sum = 0;
+ volatile char *buf = heap_buf;
+
+ /* See if this buffer has the string in it.
+
+ YES, THIS DOES INVOKE UNDEFINED BEHAVIOR BY READING FROM A FREED BUFFER.
+
+ If you know a better way to figure out whether the compiler eliminated
+ the memset/memwipe calls or not, please let me know.
+ */
+ for (i = 0; i < BUF_LEN - strlen(s); ++i) {
+ if (vmemeq(buf+i, s, strlen(s)))
+ ++sum;
+ }
+
+ return sum;
+}
+
+static struct testcase {
+ const char *name;
+ /* this spacing satisfies make check-spaces */
+ unsigned
+ (*fill_fn)(void);
+ unsigned
+ (*check_fn)(void);
+} testcases[] = {
+ { "nil", fill_a_buffer_nothing, check_a_buffer },
+ { "nil-heap", fill_heap_buffer_nothing, check_heap_buffer },
+ { "memset", fill_a_buffer_memset, check_a_buffer },
+ { "memset-heap", fill_heap_buffer_memset, check_heap_buffer },
+ { "memwipe", fill_a_buffer_memwipe, check_a_buffer },
+ { "memwipe-heap", fill_heap_buffer_memwipe, check_heap_buffer },
+ { NULL, NULL, NULL }
+};
+
+int
+main(int argc, char **argv)
+{
+ unsigned x, x2;
+ int i;
+ int working = 1;
+ unsigned found[6];
+ (void) argc; (void) argv;
+
+ s = "squamous haberdasher gallimaufry";
+
+ memset(found, 0, sizeof(found));
+
+ for (i = 0; testcases[i].name; ++i) {
+ x = testcases[i].fill_fn();
+ found[i] = testcases[i].check_fn();
+
+ x2 = fill_a_buffer_nothing();
+
+ if (x != x2) {
+ working = 0;
+ }
+ }
+
+ if (!working || !found[0] || !found[1]) {
+ printf("It appears that this test case may not give you reliable "
+ "information. Sorry.\n");
+ }
+
+ if (!found[2] && !found[3]) {
+ printf("It appears that memset is good enough on this platform. Good.\n");
+ }
+
+ if (found[4] || found[5]) {
+ printf("ERROR: memwipe does not wipe data!\n");
+ return 1;
+ } else {
+ printf("OKAY: memwipe seems to work.\n");
+ return 0;
+ }
+}
+
diff --git a/src/test/test-network.sh b/src/test/test-network.sh
index 7b59864166..05080e0c52 100755
--- a/src/test/test-network.sh
+++ b/src/test/test-network.sh
@@ -1,8 +1,11 @@
#! /bin/sh
-until [ -z $1 ]
+ECHO_N="/bin/echo -n"
+use_coverage_binary=false
+
+until [ -z "$1" ]
do
- case $1 in
+ case "$1" in
--chutney-path)
export CHUTNEY_PATH="$2"
shift
@@ -11,10 +14,38 @@ do
export TOR_DIR="$2"
shift
;;
- --flavo?r|--network-flavo?r)
+ --flavor|--flavour|--network-flavor|--network-flavour)
export NETWORK_FLAVOUR="$2"
shift
;;
+ --delay|--sleep|--bootstrap-time|--time)
+ export BOOTSTRAP_TIME="$2"
+ shift
+ ;;
+ # Environmental variables used by chutney verify performance tests
+ # Send this many bytes per client connection (10 KBytes)
+ --data|--data-bytes|--data-byte|--bytes|--byte)
+ export CHUTNEY_DATA_BYTES="$2"
+ shift
+ ;;
+ # Make this many connections per client (1)
+ # Note: If you create 7 or more connections to a hidden service from
+ # a single client, you'll likely get a verification failure due to
+ # https://trac.torproject.org/projects/tor/ticket/15937
+ --connections|--connection|--connection-count|--count)
+ export CHUTNEY_CONNECTIONS="$2"
+ shift
+ ;;
+ # Make each client connect to each HS (0)
+ # 0 means a single client connects to each HS
+ # 1 means every client connects to every HS
+ --hs-multi-client|--hs-multi-clients|--hs-client|--hs-clients)
+ export CHUTNEY_HS_MULTI_CLIENT="$2"
+ shift
+ ;;
+ --coverage)
+ use_coverage_binary=true
+ ;;
*)
echo "Sorry, I don't know what to do with '$1'."
exit 2
@@ -24,24 +55,45 @@ do
done
TOR_DIR="${TOR_DIR:-$PWD}"
-NETWORK_FLAVOUR=${NETWORK_FLAVOUR:-basic}
+NETWORK_FLAVOUR=${NETWORK_FLAVOUR:-"bridges+hs"}
CHUTNEY_NETWORK=networks/$NETWORK_FLAVOUR
myname=$(basename $0)
+[ -n "$CHUTNEY_PATH" ] || {
+ echo "$myname: \$CHUTNEY_PATH not set, trying $TOR_DIR/../chutney"
+ CHUTNEY_PATH="$TOR_DIR/../chutney"
+}
+
[ -d "$CHUTNEY_PATH" ] && [ -x "$CHUTNEY_PATH/chutney" ] || {
echo "$myname: missing 'chutney' in CHUTNEY_PATH ($CHUTNEY_PATH)"
+ echo "$myname: Get chutney: git clone https://git.torproject.org/\
+chutney.git"
+ echo "$myname: Set \$CHUTNEY_PATH to a non-standard location: export CHUTNEY_PATH=\`pwd\`/chutney"
exit 1
}
+
cd "$CHUTNEY_PATH"
# For picking up the right tor binaries.
-PATH="$TOR_DIR/src/or:$TOR_DIR/src/tools:$PATH"
+tor_name=tor
+tor_gencert_name=tor-gencert
+if test "$use_coverage_binary" = true; then
+ tor_name=tor-cov
+fi
+export CHUTNEY_TOR="${TOR_DIR}/src/or/${tor_name}"
+export CHUTNEY_TOR_GENCERT="${TOR_DIR}/src/tools/${tor_gencert_name}"
+
./tools/bootstrap-network.sh $NETWORK_FLAVOUR || exit 2
# Sleep some, waiting for the network to bootstrap.
# TODO: Add chutney command 'bootstrap-status' and use that instead.
-BOOTSTRAP_TIME=18
-echo -n "$myname: sleeping for $BOOTSTRAP_TIME seconds"
+BOOTSTRAP_TIME=${BOOTSTRAP_TIME:-35}
+$ECHO_N "$myname: sleeping for $BOOTSTRAP_TIME seconds"
n=$BOOTSTRAP_TIME; while [ $n -gt 0 ]; do
- sleep 1; n=$(expr $n - 1); echo -n .
+ sleep 1; n=$(expr $n - 1); $ECHO_N .
done; echo ""
./chutney verify $CHUTNEY_NETWORK
+VERIFY_EXIT_STATUS=$?
+# work around a bug/feature in make -j2 (or more)
+# where make hangs if any child processes are still alive
+./chutney stop $CHUTNEY_NETWORK
+exit $VERIFY_EXIT_STATUS
diff --git a/src/test/test.c b/src/test/test.c
index 8bce9c91f4..ed167a3e67 100644
--- a/src/test/test.c
+++ b/src/test/test.c
@@ -1,12 +1,8 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
-/* Ordinarily defined in tor_main.c; this bit is just here to provide one
- * since we're not linking to tor_main.c */
-const char tor_git_revision[] = "";
-
/**
* \file test.c
* \brief Unit tests for many pieces of the lower level Tor modules.
@@ -32,6 +28,7 @@ const char tor_git_revision[] = "";
#define ROUTER_PRIVATE
#define CIRCUITSTATS_PRIVATE
#define CIRCUITLIST_PRIVATE
+#define MAIN_PRIVATE
#define STATEFILE_PRIVATE
/*
@@ -43,6 +40,7 @@ long int lround(double x);
double fabs(double x);
#include "or.h"
+#include "backtrace.h"
#include "buffers.h"
#include "circuitlist.h"
#include "circuitstats.h"
@@ -50,11 +48,10 @@ double fabs(double x);
#include "connection_edge.h"
#include "geoip.h"
#include "rendcommon.h"
+#include "rendcache.h"
#include "test.h"
#include "torgzip.h"
-#ifdef ENABLE_MEMPOOLS
-#include "mempool.h"
-#endif
+#include "main.h"
#include "memarea.h"
#include "onion.h"
#include "onion_ntor.h"
@@ -63,168 +60,12 @@ double fabs(double x);
#include "rephist.h"
#include "routerparse.h"
#include "statefile.h"
-#ifdef CURVE25519_ENABLED
#include "crypto_curve25519.h"
#include "onion_ntor.h"
-#endif
-
-#ifdef USE_DMALLOC
-#include <dmalloc.h>
-#include <openssl/crypto.h>
-#include "main.h"
-#endif
-
-/** Set to true if any unit test has failed. Mostly, this is set by the macros
- * in test.h */
-int have_failed = 0;
-
-/** Temporary directory (set up by setup_directory) under which we store all
- * our files during testing. */
-static char temp_dir[256];
-#ifdef _WIN32
-#define pid_t int
-#endif
-static pid_t temp_dir_setup_in_pid = 0;
-
-/** Select and create the temporary directory we'll use to run our unit tests.
- * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
- * idempotent. */
-static void
-setup_directory(void)
-{
- static int is_setup = 0;
- int r;
- char rnd[256], rnd32[256];
- if (is_setup) return;
-
-/* Due to base32 limitation needs to be a multiple of 5. */
-#define RAND_PATH_BYTES 5
- crypto_rand(rnd, RAND_PATH_BYTES);
- base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
-
-#ifdef _WIN32
- {
- char buf[MAX_PATH];
- const char *tmp = buf;
- /* If this fails, we're probably screwed anyway */
- if (!GetTempPathA(sizeof(buf),buf))
- tmp = "c:\\windows\\temp";
- tor_snprintf(temp_dir, sizeof(temp_dir),
- "%s\\tor_test_%d_%s", tmp, (int)getpid(), rnd32);
- r = mkdir(temp_dir);
- }
-#else
- tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
- (int) getpid(), rnd32);
- r = mkdir(temp_dir, 0700);
-#endif
- if (r) {
- fprintf(stderr, "Can't create directory %s:", temp_dir);
- perror("");
- exit(1);
- }
- is_setup = 1;
- temp_dir_setup_in_pid = getpid();
-}
-
-/** Return a filename relative to our testing temporary directory */
-const char *
-get_fname(const char *name)
-{
- static char buf[1024];
- setup_directory();
- if (!name)
- return temp_dir;
- tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
- return buf;
-}
-
-/* Remove a directory and all of its subdirectories */
-static void
-rm_rf(const char *dir)
-{
- struct stat st;
- smartlist_t *elements;
-
- elements = tor_listdir(dir);
- if (elements) {
- SMARTLIST_FOREACH_BEGIN(elements, const char *, cp) {
- char *tmp = NULL;
- tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
- if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
- rm_rf(tmp);
- } else {
- if (unlink(tmp)) {
- fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
- }
- }
- tor_free(tmp);
- } SMARTLIST_FOREACH_END(cp);
- SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
- smartlist_free(elements);
- }
- if (rmdir(dir))
- fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
-}
-
-/** Remove all files stored under the temporary directory, and the directory
- * itself. Called by atexit(). */
-static void
-remove_directory(void)
-{
- if (getpid() != temp_dir_setup_in_pid) {
- /* Only clean out the tempdir when the main process is exiting. */
- return;
- }
-
- rm_rf(temp_dir);
-}
-
-/** Define this if unit tests spend too much time generating public keys*/
-#undef CACHE_GENERATED_KEYS
-
-static crypto_pk_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
-#define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
-
-/** Generate and return a new keypair for use in unit tests. If we're using
- * the key cache optimization, we might reuse keys: we only guarantee that
- * keys made with distinct values for <b>idx</b> are different. The value of
- * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
-crypto_pk_t *
-pk_generate(int idx)
-{
-#ifdef CACHE_GENERATED_KEYS
- tor_assert(idx < N_PREGEN_KEYS);
- if (! pregen_keys[idx]) {
- pregen_keys[idx] = crypto_pk_new();
- tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
- }
- return crypto_pk_dup_key(pregen_keys[idx]);
-#else
- crypto_pk_t *result;
- (void) idx;
- result = crypto_pk_new();
- tor_assert(!crypto_pk_generate_key(result));
- return result;
-#endif
-}
-
-/** Free all storage used for the cached key optimization. */
-static void
-free_pregenerated_keys(void)
-{
- unsigned idx;
- for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
- if (pregen_keys[idx]) {
- crypto_pk_free(pregen_keys[idx]);
- pregen_keys[idx] = NULL;
- }
- }
-}
/** Run unit tests for the onion handshake code. */
static void
-test_onion_handshake(void)
+test_onion_handshake(void *arg)
{
/* client-side */
crypto_dh_t *c_dh = NULL;
@@ -237,12 +78,13 @@ test_onion_handshake(void)
/* shared */
crypto_pk_t *pk = NULL, *pk2 = NULL;
+ (void)arg;
pk = pk_generate(0);
pk2 = pk_generate(1);
/* client handshake 1. */
memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
- test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
+ tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
for (i = 1; i <= 3; ++i) {
crypto_pk_t *k1, *k2;
@@ -259,16 +101,17 @@ test_onion_handshake(void)
memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
memset(s_keys, 0, 40);
- test_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
+ tt_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
s_buf, s_keys, 40));
/* client handshake 2 */
memset(c_keys, 0, 40);
- test_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
+ tt_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys,
+ 40, NULL));
- test_memeq(c_keys, s_keys, 40);
+ tt_mem_op(c_keys,OP_EQ, s_keys, 40);
memset(s_buf, 0, 40);
- test_memneq(c_keys, s_buf, 40);
+ tt_mem_op(c_keys,OP_NE, s_buf, 40);
}
done:
crypto_dh_free(c_dh);
@@ -300,7 +143,7 @@ test_bad_onion_handshake(void *arg)
memset(junk_buf, 0, sizeof(junk_buf));
crypto_pk_public_hybrid_encrypt(pk, junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
s_buf, s_keys, 40));
@@ -309,46 +152,46 @@ test_bad_onion_handshake(void *arg)
memset(junk_buf2, 0, sizeof(junk_buf2));
crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
junk_buf, 48, PK_PKCS1_OAEP_PADDING);
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
s_buf, s_keys, 40));
/* client handshake 1: do it straight. */
memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
- test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
+ tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
/* Server: Case 3: we just don't have the right key. */
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
s_buf, s_keys, 40));
/* Server: Case 4: The RSA-encrypted portion is corrupt. */
c_buf[64] ^= 33;
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
onion_skin_TAP_server_handshake(c_buf, pk, NULL,
s_buf, s_keys, 40));
c_buf[64] ^= 33;
/* (Let the server procede) */
- tt_int_op(0, ==,
+ tt_int_op(0, OP_EQ,
onion_skin_TAP_server_handshake(c_buf, pk, NULL,
s_buf, s_keys, 40));
/* Client: Case 1: The server sent back junk. */
s_buf[64] ^= 33;
- tt_int_op(-1, ==,
- onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
+ tt_int_op(-1, OP_EQ,
+ onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, NULL));
s_buf[64] ^= 33;
/* Let the client finish; make sure it can. */
- tt_int_op(0, ==,
- onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
- test_memeq(s_keys, c_keys, 40);
+ tt_int_op(0, OP_EQ,
+ onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, NULL));
+ tt_mem_op(s_keys,OP_EQ, c_keys, 40);
/* Client: Case 2: The server sent back a degenerate DH. */
memset(s_buf, 0, sizeof(s_buf));
- tt_int_op(-1, ==,
- onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
+ tt_int_op(-1, OP_EQ,
+ onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, NULL));
done:
crypto_dh_free(c_dh);
@@ -356,7 +199,6 @@ test_bad_onion_handshake(void *arg)
crypto_pk_free(pk2);
}
-#ifdef CURVE25519_ENABLED
static void
test_ntor_handshake(void *arg)
{
@@ -385,34 +227,33 @@ test_ntor_handshake(void *arg)
/* client handshake 1. */
memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
- tt_int_op(0, ==, onion_skin_ntor_create(node_id, server_pubkey,
+ tt_int_op(0, OP_EQ, onion_skin_ntor_create(node_id, server_pubkey,
&c_state, c_buf));
/* server handshake */
memset(s_buf, 0, NTOR_REPLY_LEN);
memset(s_keys, 0, 40);
- tt_int_op(0, ==, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
+ tt_int_op(0, OP_EQ, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
node_id,
s_buf, s_keys, 400));
/* client handshake 2 */
memset(c_keys, 0, 40);
- tt_int_op(0, ==, onion_skin_ntor_client_handshake(c_state, s_buf,
- c_keys, 400));
+ tt_int_op(0, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
+ c_keys, 400, NULL));
- test_memeq(c_keys, s_keys, 400);
+ tt_mem_op(c_keys,OP_EQ, s_keys, 400);
memset(s_buf, 0, 40);
- test_memneq(c_keys, s_buf, 40);
+ tt_mem_op(c_keys,OP_NE, s_buf, 40);
done:
ntor_handshake_state_free(c_state);
dimap_free(s_keymap, NULL);
}
-#endif
/** Run unit tests for the onion queues. */
static void
-test_onion_queues(void)
+test_onion_queues(void *arg)
{
uint8_t buf1[TAP_ONIONSKIN_CHALLENGE_LEN] = {0};
uint8_t buf2[NTOR_ONIONSKIN_LEN] = {0};
@@ -423,6 +264,7 @@ test_onion_queues(void)
create_cell_t *onionskin = NULL, *create2_ptr;
create_cell_t *create1 = tor_malloc_zero(sizeof(create_cell_t));
create_cell_t *create2 = tor_malloc_zero(sizeof(create_cell_t));
+ (void)arg;
create2_ptr = create2; /* remember, but do not free */
create_cell_init(create1, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
@@ -430,24 +272,24 @@ test_onion_queues(void)
create_cell_init(create2, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
NTOR_ONIONSKIN_LEN, buf2);
- test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
- test_eq(0, onion_pending_add(circ1, create1));
+ tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
+ tt_int_op(0,OP_EQ, onion_pending_add(circ1, create1));
create1 = NULL;
- test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
+ tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
- test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
- test_eq(0, onion_pending_add(circ2, create2));
+ tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
+ tt_int_op(0,OP_EQ, onion_pending_add(circ2, create2));
create2 = NULL;
- test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
+ tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
- test_eq_ptr(circ2, onion_next_task(&onionskin));
- test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
- test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
- tt_ptr_op(onionskin, ==, create2_ptr);
+ tt_ptr_op(circ2,OP_EQ, onion_next_task(&onionskin));
+ tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
+ tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
+ tt_ptr_op(onionskin, OP_EQ, create2_ptr);
clear_pending_onions();
- test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
- test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
+ tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
+ tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
done:
circuit_free(TO_CIRCUIT(circ1));
@@ -458,7 +300,7 @@ test_onion_queues(void)
}
static void
-test_circuit_timeout(void)
+test_circuit_timeout(void *arg)
{
/* Plan:
* 1. Generate 1000 samples
@@ -476,6 +318,10 @@ test_circuit_timeout(void)
or_state_t *state=NULL;
int i, runs;
double close_ms;
+ (void)arg;
+
+ initialize_periodic_events();
+
circuit_build_times_init(&initial);
circuit_build_times_init(&estimate);
circuit_build_times_init(&final);
@@ -510,11 +356,11 @@ test_circuit_timeout(void)
} while (fabs(circuit_build_times_cdf(&initial, timeout0) -
circuit_build_times_cdf(&initial, timeout1)) > 0.02);
- test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
+ tt_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
circuit_build_times_update_state(&estimate, state);
circuit_build_times_free_timeouts(&final);
- test_assert(circuit_build_times_parse_state(&final, state) == 0);
+ tt_assert(circuit_build_times_parse_state(&final, state) == 0);
circuit_build_times_update_alpha(&final);
timeout2 = circuit_build_times_calculate_timeout(&final,
@@ -524,7 +370,7 @@ test_circuit_timeout(void)
log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
/* 5% here because some accuracy is lost due to histogram conversion */
- test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
+ tt_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
circuit_build_times_cdf(&initial, timeout2)) < 0.05);
for (runs = 0; runs < 50; runs++) {
@@ -547,8 +393,8 @@ test_circuit_timeout(void)
CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
}
- test_assert(!circuit_build_times_network_check_changed(&estimate));
- test_assert(!circuit_build_times_network_check_changed(&final));
+ tt_assert(!circuit_build_times_network_check_changed(&estimate));
+ tt_assert(!circuit_build_times_network_check_changed(&final));
/* Reset liveness to be non-live */
final.liveness.network_last_live = 0;
@@ -557,27 +403,27 @@ test_circuit_timeout(void)
build_times_idx = estimate.build_times_idx;
total_build_times = estimate.total_build_times;
- test_assert(circuit_build_times_network_check_live(&estimate));
- test_assert(circuit_build_times_network_check_live(&final));
+ tt_assert(circuit_build_times_network_check_live(&estimate));
+ tt_assert(circuit_build_times_network_check_live(&final));
circuit_build_times_count_close(&estimate, 0,
(time_t)(approx_time()-estimate.close_ms/1000.0-1));
circuit_build_times_count_close(&final, 0,
(time_t)(approx_time()-final.close_ms/1000.0-1));
- test_assert(!circuit_build_times_network_check_live(&estimate));
- test_assert(!circuit_build_times_network_check_live(&final));
+ tt_assert(!circuit_build_times_network_check_live(&estimate));
+ tt_assert(!circuit_build_times_network_check_live(&final));
log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
build_times_idx, estimate.build_times_idx,
total_build_times, estimate.total_build_times);
/* Check rollback index. Should match top of loop. */
- test_assert(build_times_idx == estimate.build_times_idx);
+ tt_assert(build_times_idx == estimate.build_times_idx);
// This can fail if estimate.total_build_times == 1000, because
// in that case, rewind actually causes us to lose timeouts
if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
- test_assert(total_build_times == estimate.total_build_times);
+ tt_assert(total_build_times == estimate.total_build_times);
/* Now simulate that the network has become live and we need
* a change */
@@ -592,14 +438,22 @@ test_circuit_timeout(void)
}
}
- test_assert(estimate.liveness.after_firsthop_idx == 0);
- test_assert(final.liveness.after_firsthop_idx ==
+ tt_assert(estimate.liveness.after_firsthop_idx == 0);
+ tt_assert(final.liveness.after_firsthop_idx ==
CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
- test_assert(circuit_build_times_network_check_live(&estimate));
- test_assert(circuit_build_times_network_check_live(&final));
+ tt_assert(circuit_build_times_network_check_live(&estimate));
+ tt_assert(circuit_build_times_network_check_live(&final));
circuit_build_times_count_timeout(&final, 1);
+
+ /* Ensure return value for degenerate cases are clamped correctly */
+ initial.alpha = INT32_MAX;
+ tt_assert(circuit_build_times_calculate_timeout(&initial, .99999999) <=
+ INT32_MAX);
+ initial.alpha = 0;
+ tt_assert(circuit_build_times_calculate_timeout(&initial, .5) <=
+ INT32_MAX);
}
done:
@@ -607,11 +461,12 @@ test_circuit_timeout(void)
circuit_build_times_free_timeouts(&estimate);
circuit_build_times_free_timeouts(&final);
or_state_free(state);
+ teardown_periodic_events();
}
/** Test encoding and parsing of rendezvous service descriptors. */
static void
-test_rend_fns(void)
+test_rend_fns(void *arg)
{
rend_service_descriptor_t *generated = NULL, *parsed = NULL;
char service_id[DIGEST_LEN];
@@ -634,16 +489,20 @@ test_rend_fns(void)
char address6[] = "foo.bar.abcdefghijklmnop.onion";
char address7[] = ".abcdefghijklmnop.onion";
- test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
- test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
- test_streq(address2, "aaaaaaaaaaaaaaaa");
- test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
- test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
- test_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
- test_streq(address5, "abcdefghijklmnop");
- test_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
- test_streq(address6, "abcdefghijklmnop");
- test_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
+ (void)arg;
+ tt_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
+ tt_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
+ tt_str_op(address2,OP_EQ, "aaaaaaaaaaaaaaaa");
+ tt_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
+ tt_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
+ tt_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
+ tt_str_op(address5,OP_EQ, "abcdefghijklmnop");
+ tt_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
+ tt_str_op(address6,OP_EQ, "abcdefghijklmnop");
+ tt_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
+
+ /* Initialize the service cache. */
+ rend_cache_init();
pk1 = pk_generate(0);
pk2 = pk_generate(1);
@@ -676,40 +535,41 @@ test_rend_fns(void)
intro->intro_key = crypto_pk_dup_key(pk2);
smartlist_add(generated->intro_nodes, intro);
}
- test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
+ tt_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
REND_NO_AUTH, NULL, NULL) > 0);
- test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
+ tt_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
NULL, now, 0) == 0);
- test_memeq(((rend_encoded_v2_service_descriptor_t *)
- smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
- test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
- &intro_points_encrypted,
- &intro_points_size,
- &encoded_size,
- &next_desc,
- ((rend_encoded_v2_service_descriptor_t *)
- smartlist_get(descs, 0))->desc_str) == 0);
- test_assert(parsed);
- test_memeq(((rend_encoded_v2_service_descriptor_t *)
- smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
- test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
- intro_points_size), 3);
- test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
- test_eq(parsed->timestamp, now);
- test_eq(parsed->version, 2);
- test_eq(parsed->protocols, 42);
- test_eq(smartlist_len(parsed->intro_nodes), 3);
+ tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0))->desc_id, OP_EQ,
+ computed_desc_id, DIGEST_LEN);
+ tt_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
+ &intro_points_encrypted,
+ &intro_points_size,
+ &encoded_size,
+ &next_desc,
+ ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0))->desc_str, 1) == 0);
+ tt_assert(parsed);
+ tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0))->desc_id,OP_EQ, parsed_desc_id, DIGEST_LEN);
+ tt_int_op(rend_parse_introduction_points(parsed, intro_points_encrypted,
+ intro_points_size),OP_EQ, 3);
+ tt_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
+ tt_int_op(parsed->timestamp,OP_EQ, now);
+ tt_int_op(parsed->version,OP_EQ, 2);
+ tt_int_op(parsed->protocols,OP_EQ, 42);
+ tt_int_op(smartlist_len(parsed->intro_nodes),OP_EQ, 3);
for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
*gen_intro = smartlist_get(generated->intro_nodes, i);
extend_info_t *par_info = par_intro->extend_info;
extend_info_t *gen_info = gen_intro->extend_info;
- test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
- test_memeq(gen_info->identity_digest, par_info->identity_digest,
+ tt_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
+ tt_mem_op(gen_info->identity_digest,OP_EQ, par_info->identity_digest,
DIGEST_LEN);
- test_streq(gen_info->nickname, par_info->nickname);
- test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
- test_eq(gen_info->port, par_info->port);
+ tt_str_op(gen_info->nickname,OP_EQ, par_info->nickname);
+ tt_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
+ tt_int_op(gen_info->port,OP_EQ, par_info->port);
}
rend_service_descriptor_free(parsed);
@@ -753,17 +613,17 @@ test_rend_fns(void)
} while (0)
#define CHECK_COUNTRY(country, val) do { \
/* test ipv4 country lookup */ \
- test_streq(country, \
+ tt_str_op(country, OP_EQ, \
geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
/* test ipv6 country lookup */ \
SET_TEST_IPV6(val); \
- test_streq(country, \
+ tt_str_op(country, OP_EQ, \
geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
} while (0)
/** Run unit tests for GeoIP code. */
static void
-test_geoip(void)
+test_geoip(void *arg)
{
int i, j;
time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
@@ -817,23 +677,24 @@ test_geoip(void)
/* Populate the DB a bit. Add these in order, since we can't do the final
* 'sort' step. These aren't very good IP addresses, but they're perfectly
* fine uint32_t values. */
- test_eq(0, geoip_parse_entry("10,50,AB", AF_INET));
- test_eq(0, geoip_parse_entry("52,90,XY", AF_INET));
- test_eq(0, geoip_parse_entry("95,100,AB", AF_INET));
- test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
- test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
- test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
+ (void)arg;
+ tt_int_op(0,OP_EQ, geoip_parse_entry("10,50,AB", AF_INET));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("52,90,XY", AF_INET));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("95,100,AB", AF_INET));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
/* Populate the IPv6 DB equivalently with fake IPs in the same range */
- test_eq(0, geoip_parse_entry("::a,::32,AB", AF_INET6));
- test_eq(0, geoip_parse_entry("::34,::5a,XY", AF_INET6));
- test_eq(0, geoip_parse_entry("::5f,::64,AB", AF_INET6));
- test_eq(0, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
- test_eq(0, geoip_parse_entry("::96,::be,XY", AF_INET6));
- test_eq(0, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::a,::32,AB", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::34,::5a,XY", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::5f,::64,AB", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::96,::be,XY", AF_INET6));
+ tt_int_op(0,OP_EQ, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
/* We should have 4 countries: ??, ab, xy, zz. */
- test_eq(4, geoip_get_n_countries());
+ tt_int_op(4,OP_EQ, geoip_get_n_countries());
memset(&in6, 0, sizeof(in6));
CHECK_COUNTRY("??", 3);
@@ -844,9 +705,9 @@ test_geoip(void)
CHECK_COUNTRY("xy", 190);
CHECK_COUNTRY("??", 2000);
- test_eq(0, geoip_get_country_by_ipv4(3));
+ tt_int_op(0,OP_EQ, geoip_get_country_by_ipv4(3));
SET_TEST_IPV6(3);
- test_eq(0, geoip_get_country_by_ipv6(&in6));
+ tt_int_op(0,OP_EQ, geoip_get_country_by_ipv6(&in6));
get_options_mutable()->BridgeRelay = 1;
get_options_mutable()->BridgeRecordUsageByCountry = 1;
@@ -869,41 +730,41 @@ test_geoip(void)
geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
}
geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
- test_assert(s);
- test_assert(v);
- test_streq("zz=24,ab=16,xy=8", s);
- test_streq("v4=16,v6=16", v);
+ tt_assert(s);
+ tt_assert(v);
+ tt_str_op("zz=24,ab=16,xy=8",OP_EQ, s);
+ tt_str_op("v4=16,v6=16",OP_EQ, v);
tor_free(s);
tor_free(v);
/* Now clear out all the AB observations. */
geoip_remove_old_clients(now-6000);
geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
- test_assert(s);
- test_assert(v);
- test_streq("zz=24,xy=8", s);
- test_streq("v4=16,v6=16", v);
+ tt_assert(s);
+ tt_assert(v);
+ tt_str_op("zz=24,xy=8",OP_EQ, s);
+ tt_str_op("v4=16,v6=16",OP_EQ, v);
tor_free(s);
tor_free(v);
/* Start testing bridge statistics by making sure that we don't output
* bridge stats without initializing them. */
s = geoip_format_bridge_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats and generate the bridge-stats history string out of
* the connecting clients added above. */
geoip_bridge_stats_init(now);
s = geoip_format_bridge_stats(now + 86400);
- test_assert(s);
- test_streq(bridge_stats_1, s);
+ tt_assert(s);
+ tt_str_op(bridge_stats_1,OP_EQ, s);
tor_free(s);
/* Stop collecting bridge stats and make sure we don't write a history
* string anymore. */
geoip_bridge_stats_term();
s = geoip_format_bridge_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Stop being a bridge and start being a directory mirror that gathers
* directory request statistics. */
@@ -917,7 +778,7 @@ test_geoip(void)
SET_TEST_ADDRESS(100);
geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
s = geoip_format_dirreq_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats, note one connecting client, and generate the
* dirreq-stats history string. */
@@ -925,7 +786,7 @@ test_geoip(void)
SET_TEST_ADDRESS(100);
geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
s = geoip_format_dirreq_stats(now + 86400);
- test_streq(dirreq_stats_1, s);
+ tt_str_op(dirreq_stats_1,OP_EQ, s);
tor_free(s);
/* Stop collecting stats, add another connecting client, and ensure we
@@ -934,7 +795,7 @@ test_geoip(void)
SET_TEST_ADDRESS(101);
geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
s = geoip_format_dirreq_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Re-start stats, add a connecting client, reset stats, and make sure
* that we get an all empty history string. */
@@ -943,20 +804,20 @@ test_geoip(void)
geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
geoip_reset_dirreq_stats(now);
s = geoip_format_dirreq_stats(now + 86400);
- test_streq(dirreq_stats_2, s);
+ tt_str_op(dirreq_stats_2,OP_EQ, s);
tor_free(s);
/* Note a successful network status response and make sure that it
* appears in the history string. */
geoip_note_ns_response(GEOIP_SUCCESS);
s = geoip_format_dirreq_stats(now + 86400);
- test_streq(dirreq_stats_3, s);
+ tt_str_op(dirreq_stats_3,OP_EQ, s);
tor_free(s);
/* Start a tunneled directory request. */
geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
s = geoip_format_dirreq_stats(now + 86400);
- test_streq(dirreq_stats_4, s);
+ tt_str_op(dirreq_stats_4,OP_EQ, s);
tor_free(s);
/* Stop collecting directory request statistics and start gathering
@@ -970,7 +831,7 @@ test_geoip(void)
SET_TEST_ADDRESS(100);
geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
s = geoip_format_entry_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats, note one connecting client, and generate the
* entry-stats history string. */
@@ -978,7 +839,7 @@ test_geoip(void)
SET_TEST_ADDRESS(100);
geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
s = geoip_format_entry_stats(now + 86400);
- test_streq(entry_stats_1, s);
+ tt_str_op(entry_stats_1,OP_EQ, s);
tor_free(s);
/* Stop collecting stats, add another connecting client, and ensure we
@@ -987,7 +848,7 @@ test_geoip(void)
SET_TEST_ADDRESS(101);
geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
s = geoip_format_entry_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Re-start stats, add a connecting client, reset stats, and make sure
* that we get an all empty history string. */
@@ -996,7 +857,7 @@ test_geoip(void)
geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
geoip_reset_entry_stats(now);
s = geoip_format_entry_stats(now + 86400);
- test_streq(entry_stats_2, s);
+ tt_str_op(entry_stats_2,OP_EQ, s);
tor_free(s);
/* Stop collecting entry statistics. */
@@ -1009,7 +870,7 @@ test_geoip(void)
}
static void
-test_geoip_with_pt(void)
+test_geoip_with_pt(void *arg)
{
time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
char *s = NULL;
@@ -1017,6 +878,7 @@ test_geoip_with_pt(void)
tor_addr_t addr;
struct in6_addr in6;
+ (void)arg;
get_options_mutable()->BridgeRelay = 1;
get_options_mutable()->BridgeRecordUsageByCountry = 1;
@@ -1068,7 +930,7 @@ test_geoip_with_pt(void)
/* Test the transport history string. */
s = geoip_get_transport_history();
tor_assert(s);
- test_streq(s, "<OR>=8,alpha=16,beta=8,charlie=16,ddr=136,"
+ tt_str_op(s,OP_EQ, "<OR>=8,alpha=16,beta=8,charlie=16,ddr=136,"
"entropy=8,fire=8,google=8");
/* Stop collecting entry statistics. */
@@ -1085,7 +947,7 @@ test_geoip_with_pt(void)
/** Run unit tests for stats code. */
static void
-test_stats(void)
+test_stats(void *arg)
{
time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
char *s = NULL;
@@ -1093,10 +955,11 @@ test_stats(void)
/* Start with testing exit port statistics; we shouldn't collect exit
* stats without initializing them. */
+ (void)arg;
rep_hist_note_exit_stream_opened(80);
rep_hist_note_exit_bytes(80, 100, 10000);
s = rep_hist_format_exit_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats, note some streams and bytes, and generate history
* string. */
@@ -1107,10 +970,10 @@ test_stats(void)
rep_hist_note_exit_bytes(443, 100, 10000);
rep_hist_note_exit_bytes(443, 100, 10000);
s = rep_hist_format_exit_stats(now + 86400);
- test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"exit-kibibytes-written 80=1,443=1,other=0\n"
"exit-kibibytes-read 80=10,443=20,other=0\n"
- "exit-streams-opened 80=4,443=4,other=0\n", s);
+ "exit-streams-opened 80=4,443=4,other=0\n",OP_EQ, s);
tor_free(s);
/* Add a few bytes on 10 more ports and ensure that only the top 10
@@ -1120,13 +983,13 @@ test_stats(void)
rep_hist_note_exit_stream_opened(i);
}
s = rep_hist_format_exit_stats(now + 86400);
- test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
"59=1,80=1,443=1,other=1\n"
"exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
"59=1,80=10,443=20,other=1\n"
"exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
- "59=4,80=4,443=4,other=4\n", s);
+ "59=4,80=4,443=4,other=4\n",OP_EQ, s);
tor_free(s);
/* Stop collecting stats, add some bytes, and ensure we don't generate
@@ -1134,7 +997,7 @@ test_stats(void)
rep_hist_exit_stats_term();
rep_hist_note_exit_bytes(80, 100, 10000);
s = rep_hist_format_exit_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Re-start stats, add some bytes, reset stats, and see what history we
* get when observing no streams or bytes at all. */
@@ -1143,17 +1006,17 @@ test_stats(void)
rep_hist_note_exit_bytes(80, 100, 10000);
rep_hist_reset_exit_stats(now);
s = rep_hist_format_exit_stats(now + 86400);
- test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"exit-kibibytes-written other=0\n"
"exit-kibibytes-read other=0\n"
- "exit-streams-opened other=0\n", s);
+ "exit-streams-opened other=0\n",OP_EQ, s);
tor_free(s);
/* Continue with testing connection statistics; we shouldn't collect
* conn stats without initializing them. */
rep_hist_note_or_conn_bytes(1, 20, 400, now);
s = rep_hist_format_conn_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats, note bytes, and generate history string. */
rep_hist_conn_stats_init(now);
@@ -1162,7 +1025,7 @@ test_stats(void)
rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
s = rep_hist_format_conn_stats(now + 86400);
- test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
+ tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n",OP_EQ, s);
tor_free(s);
/* Stop collecting stats, add some bytes, and ensure we don't generate
@@ -1170,7 +1033,7 @@ test_stats(void)
rep_hist_conn_stats_term();
rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
s = rep_hist_format_conn_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Re-start stats, add some bytes, reset stats, and see what history we
* get when observing no bytes at all. */
@@ -1181,26 +1044,26 @@ test_stats(void)
rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
rep_hist_reset_conn_stats(now);
s = rep_hist_format_conn_stats(now + 86400);
- test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
+ tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n",OP_EQ, s);
tor_free(s);
/* Continue with testing buffer statistics; we shouldn't collect buffer
* stats without initializing them. */
rep_hist_add_buffer_stats(2.0, 2.0, 20);
s = rep_hist_format_buffer_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Initialize stats, add statistics for a single circuit, and generate
* the history string. */
rep_hist_buffer_stats_init(now);
rep_hist_add_buffer_stats(2.0, 2.0, 20);
s = rep_hist_format_buffer_stats(now + 86400);
- test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
"cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
"0.00,0.00\n"
"cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
- "cell-circuits-per-decile 1\n", s);
+ "cell-circuits-per-decile 1\n",OP_EQ, s);
tor_free(s);
/* Add nineteen more circuit statistics to the one that's already in the
@@ -1210,12 +1073,12 @@ test_stats(void)
for (i = 20; i < 30; i++)
rep_hist_add_buffer_stats(3.5, 3.5, i);
s = rep_hist_format_buffer_stats(now + 86400);
- test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
"cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
"2.75,2.75\n"
"cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
- "cell-circuits-per-decile 2\n", s);
+ "cell-circuits-per-decile 2\n",OP_EQ, s);
tor_free(s);
/* Stop collecting stats, add statistics for one circuit, and ensure we
@@ -1223,7 +1086,7 @@ test_stats(void)
rep_hist_buffer_stats_term();
rep_hist_add_buffer_stats(2.0, 2.0, 20);
s = rep_hist_format_buffer_stats(now + 86400);
- test_assert(!s);
+ tt_assert(!s);
/* Re-start stats, add statistics for one circuit, reset stats, and make
* sure that the history has all zeros. */
@@ -1231,56 +1094,29 @@ test_stats(void)
rep_hist_add_buffer_stats(2.0, 2.0, 20);
rep_hist_reset_buffer_stats(now);
s = rep_hist_format_buffer_stats(now + 86400);
- test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
+ tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
"cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
"cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
"0.00,0.00\n"
"cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
- "cell-circuits-per-decile 0\n", s);
+ "cell-circuits-per-decile 0\n",OP_EQ, s);
done:
tor_free(s);
}
-static void *
-legacy_test_setup(const struct testcase_t *testcase)
-{
- return testcase->setup_data;
-}
-
-void
-legacy_test_helper(void *data)
-{
- void (*fn)(void) = data;
- fn();
-}
-
-static int
-legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
-{
- (void)ptr;
- (void)testcase;
- return 1;
-}
-
-const struct testcase_setup_t legacy_setup = {
- legacy_test_setup, legacy_test_cleanup
-};
-
#define ENT(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
+ { #name, test_ ## name , 0, NULL, NULL }
#define FORK(name) \
- { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
+ { #name, test_ ## name , TT_FORK, NULL, NULL }
static struct testcase_t test_array[] = {
ENT(onion_handshake),
{ "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
ENT(onion_queues),
-#ifdef CURVE25519_ENABLED
{ "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
-#endif
- ENT(circuit_timeout),
- ENT(rend_fns),
+ FORK(circuit_timeout),
+ FORK(rend_fns),
ENT(geoip),
FORK(geoip_with_pt),
FORK(stats),
@@ -1288,145 +1124,114 @@ static struct testcase_t test_array[] = {
END_OF_TESTCASES
};
+extern struct testcase_t accounting_tests[];
extern struct testcase_t addr_tests[];
+extern struct testcase_t address_tests[];
extern struct testcase_t buffer_tests[];
-extern struct testcase_t crypto_tests[];
-extern struct testcase_t container_tests[];
-extern struct testcase_t util_tests[];
-extern struct testcase_t dir_tests[];
-extern struct testcase_t microdesc_tests[];
-extern struct testcase_t pt_tests[];
-extern struct testcase_t config_tests[];
-extern struct testcase_t introduce_tests[];
-extern struct testcase_t replaycache_tests[];
-extern struct testcase_t relaycell_tests[];
extern struct testcase_t cell_format_tests[];
+extern struct testcase_t cell_queue_tests[];
+extern struct testcase_t channel_tests[];
+extern struct testcase_t channeltls_tests[];
+extern struct testcase_t checkdir_tests[];
extern struct testcase_t circuitlist_tests[];
extern struct testcase_t circuitmux_tests[];
-extern struct testcase_t cell_queue_tests[];
-extern struct testcase_t options_tests[];
-extern struct testcase_t socks_tests[];
-extern struct testcase_t extorport_tests[];
+extern struct testcase_t compat_libevent_tests[];
+extern struct testcase_t config_tests[];
+extern struct testcase_t connection_tests[];
+extern struct testcase_t container_tests[];
+extern struct testcase_t controller_tests[];
extern struct testcase_t controller_event_tests[];
-extern struct testcase_t logging_tests[];
+extern struct testcase_t crypto_tests[];
+extern struct testcase_t dir_tests[];
+extern struct testcase_t dir_handle_get_tests[];
+extern struct testcase_t entryconn_tests[];
+extern struct testcase_t entrynodes_tests[];
+extern struct testcase_t guardfraction_tests[];
+extern struct testcase_t extorport_tests[];
extern struct testcase_t hs_tests[];
+extern struct testcase_t introduce_tests[];
+extern struct testcase_t keypin_tests[];
+extern struct testcase_t link_handshake_tests[];
+extern struct testcase_t logging_tests[];
+extern struct testcase_t microdesc_tests[];
extern struct testcase_t nodelist_tests[];
-extern struct testcase_t routerkeys_tests[];
extern struct testcase_t oom_tests[];
+extern struct testcase_t options_tests[];
extern struct testcase_t policy_tests[];
+extern struct testcase_t procmon_tests[];
+extern struct testcase_t pt_tests[];
+extern struct testcase_t relay_tests[];
+extern struct testcase_t relaycell_tests[];
+extern struct testcase_t rend_cache_tests[];
+extern struct testcase_t replaycache_tests[];
+extern struct testcase_t router_tests[];
+extern struct testcase_t routerkeys_tests[];
+extern struct testcase_t routerlist_tests[];
+extern struct testcase_t routerset_tests[];
+extern struct testcase_t scheduler_tests[];
+extern struct testcase_t socks_tests[];
extern struct testcase_t status_tests[];
+extern struct testcase_t thread_tests[];
+extern struct testcase_t tortls_tests[];
+extern struct testcase_t util_tests[];
+extern struct testcase_t util_format_tests[];
+extern struct testcase_t util_process_tests[];
+extern struct testcase_t dns_tests[];
-static struct testgroup_t testgroups[] = {
+struct testgroup_t testgroups[] = {
{ "", test_array },
- { "buffer/", buffer_tests },
- { "socks/", socks_tests },
+ { "accounting/", accounting_tests },
{ "addr/", addr_tests },
- { "crypto/", crypto_tests },
- { "container/", container_tests },
- { "util/", util_tests },
- { "util/logging/", logging_tests },
+ { "address/", address_tests },
+ { "buffer/", buffer_tests },
{ "cellfmt/", cell_format_tests },
{ "cellqueue/", cell_queue_tests },
- { "dir/", dir_tests },
- { "dir/md/", microdesc_tests },
- { "pt/", pt_tests },
- { "config/", config_tests },
- { "replaycache/", replaycache_tests },
- { "relaycell/", relaycell_tests },
- { "introduce/", introduce_tests },
+ { "channel/", channel_tests },
+ { "channeltls/", channeltls_tests },
+ { "checkdir/", checkdir_tests },
{ "circuitlist/", circuitlist_tests },
{ "circuitmux/", circuitmux_tests },
- { "options/", options_tests },
+ { "compat/libevent/", compat_libevent_tests },
+ { "config/", config_tests },
+ { "connection/", connection_tests },
+ { "container/", container_tests },
+ { "control/", controller_tests },
+ { "control/event/", controller_event_tests },
+ { "crypto/", crypto_tests },
+ { "dir/", dir_tests },
+ { "dir_handle_get/", dir_handle_get_tests },
+ { "dir/md/", microdesc_tests },
+ { "entryconn/", entryconn_tests },
+ { "entrynodes/", entrynodes_tests },
+ { "guardfraction/", guardfraction_tests },
{ "extorport/", extorport_tests },
- { "control/", controller_event_tests },
{ "hs/", hs_tests },
+ { "introduce/", introduce_tests },
+ { "keypin/", keypin_tests },
+ { "link-handshake/", link_handshake_tests },
{ "nodelist/", nodelist_tests },
- { "routerkeys/", routerkeys_tests },
{ "oom/", oom_tests },
+ { "options/", options_tests },
{ "policy/" , policy_tests },
+ { "procmon/", procmon_tests },
+ { "pt/", pt_tests },
+ { "relay/" , relay_tests },
+ { "relaycell/", relaycell_tests },
+ { "rend_cache/", rend_cache_tests },
+ { "replaycache/", replaycache_tests },
+ { "routerkeys/", routerkeys_tests },
+ { "routerlist/", routerlist_tests },
+ { "routerset/" , routerset_tests },
+ { "scheduler/", scheduler_tests },
+ { "socks/", socks_tests },
{ "status/" , status_tests },
+ { "tortls/", tortls_tests },
+ { "util/", util_tests },
+ { "util/format/", util_format_tests },
+ { "util/logging/", logging_tests },
+ { "util/process/", util_process_tests },
+ { "util/thread/", thread_tests },
+ { "dns/", dns_tests },
END_OF_GROUPS
};
-/** Main entry point for unit test code: parse the command line, and run
- * some unit tests. */
-int
-main(int c, const char **v)
-{
- or_options_t *options;
- char *errmsg = NULL;
- int i, i_out;
- int loglevel = LOG_ERR;
- int accel_crypto = 0;
-
-#ifdef USE_DMALLOC
- {
- int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
- tor_assert(r);
- }
-#endif
-
- update_approx_time(time(NULL));
- options = options_new();
- tor_threads_init();
- init_logging();
-
- for (i_out = i = 1; i < c; ++i) {
- if (!strcmp(v[i], "--warn")) {
- loglevel = LOG_WARN;
- } else if (!strcmp(v[i], "--notice")) {
- loglevel = LOG_NOTICE;
- } else if (!strcmp(v[i], "--info")) {
- loglevel = LOG_INFO;
- } else if (!strcmp(v[i], "--debug")) {
- loglevel = LOG_DEBUG;
- } else if (!strcmp(v[i], "--accel")) {
- accel_crypto = 1;
- } else {
- v[i_out++] = v[i];
- }
- }
- c = i_out;
-
- {
- log_severity_list_t s;
- memset(&s, 0, sizeof(s));
- set_log_severity_config(loglevel, LOG_ERR, &s);
- add_stream_log(&s, "", fileno(stdout));
- }
-
- options->command = CMD_RUN_UNITTESTS;
- if (crypto_global_init(accel_crypto, NULL, NULL)) {
- printf("Can't initialize crypto subsystem; exiting.\n");
- return 1;
- }
- crypto_set_tls_dh_prime(NULL);
- crypto_seed_rng(1);
- rep_hist_init();
- network_init();
- setup_directory();
- options_init(options);
- options->DataDirectory = tor_strdup(temp_dir);
- options->EntryStatistics = 1;
- if (set_options(options, &errmsg) < 0) {
- printf("Failed to set initial options: %s\n", errmsg);
- tor_free(errmsg);
- return 1;
- }
-
- atexit(remove_directory);
-
- have_failed = (tinytest_main(c, v, testgroups) != 0);
-
- free_pregenerated_keys();
-#ifdef USE_DMALLOC
- tor_free_all(0);
- dmalloc_log_unfreed();
-#endif
-
- if (have_failed)
- return 1;
- else
- return 0;
-}
-
diff --git a/src/test/test.h b/src/test/test.h
index b9e4d5bdb4..e618ce1224 100644
--- a/src/test/test.h
+++ b/src/test/test.h
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2003, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#ifndef TOR_TEST_H
@@ -22,25 +22,6 @@
#define PRETTY_FUNCTION ""
#endif
-#define test_fail_msg(msg) TT_DIE((msg))
-
-#define test_fail() test_fail_msg("Assertion failed.")
-
-#define test_assert(expr) tt_assert(expr)
-
-#define test_eq(expr1, expr2) tt_int_op((expr1), ==, (expr2))
-#define test_eq_ptr(expr1, expr2) tt_ptr_op((expr1), ==, (expr2))
-#define test_neq(expr1, expr2) tt_int_op((expr1), !=, (expr2))
-#define test_neq_ptr(expr1, expr2) tt_ptr_op((expr1), !=, (expr2))
-#define test_streq(expr1, expr2) tt_str_op((expr1), ==, (expr2))
-#define test_strneq(expr1, expr2) tt_str_op((expr1), !=, (expr2))
-
-#define test_mem_op(expr1, op, expr2, len) \
- tt_mem_op((expr1), op, (expr2), (len))
-
-#define test_memeq(expr1, expr2, len) test_mem_op((expr1), ==, (expr2), len)
-#define test_memneq(expr1, expr2, len) test_mem_op((expr1), !=, (expr2), len)
-
/* As test_mem_op, but decodes 'hex' before comparing. There must be a
* local char* variable called mem_op_hex_tmp for this to work. */
#define test_mem_op_hex(expr1, op, hex) \
@@ -50,15 +31,24 @@
mem_op_hex_tmp = tor_malloc(length/2); \
tor_assert((length&1)==0); \
base16_decode(mem_op_hex_tmp, length/2, hex, length); \
- test_mem_op(expr1, op, mem_op_hex_tmp, length/2); \
+ tt_mem_op(expr1, op, mem_op_hex_tmp, length/2); \
STMT_END
-#define test_memeq_hex(expr1, hex) test_mem_op_hex(expr1, ==, hex)
+#define test_memeq_hex(expr1, hex) test_mem_op_hex(expr1, OP_EQ, hex)
#define tt_double_op(a,op,b) \
- tt_assert_test_type(a,b,#a" "#op" "#b,double,(val1_ op val2_),"%f", \
+ tt_assert_test_type(a,b,#a" "#op" "#b,double,(val1_ op val2_),"%g", \
TT_EXIT_TEST_FUNCTION)
+/* Declare "double equal" in a sneaky way, so compiler won't complain about
+ * comparing floats with == or !=. Of course, only do this if you know what
+ * you're doing. */
+#define tt_double_eq(a,b) \
+ STMT_BEGIN \
+ tt_double_op((a), >=, (b)); \
+ tt_double_op((a), <=, (b)); \
+ STMT_END
+
#ifdef _MSC_VER
#define U64_PRINTF_TYPE uint64_t
#define I64_PRINTF_TYPE int64_t
@@ -85,9 +75,6 @@
const char *get_fname(const char *name);
crypto_pk_t *pk_generate(int idx);
-void legacy_test_helper(void *data);
-extern const struct testcase_setup_t legacy_setup;
-
#define US2_CONCAT_2__(a, b) a ## __ ## b
#define US_CONCAT_2__(a, b) a ## _ ## b
#define US_CONCAT_3__(a, b, c) a ## _ ## b ## _ ## c
@@ -180,5 +167,7 @@ extern const struct testcase_setup_t legacy_setup;
#define NS_MOCK(name) MOCK(name, NS(name))
#define NS_UNMOCK(name) UNMOCK(name)
+extern const struct testcase_setup_t passthrough_setup;
+
#endif
diff --git a/src/test/test_accounting.c b/src/test/test_accounting.c
new file mode 100644
index 0000000000..7edba988a6
--- /dev/null
+++ b/src/test/test_accounting.c
@@ -0,0 +1,102 @@
+#include "or.h"
+#include "test.h"
+#define HIBERNATE_PRIVATE
+#include "hibernate.h"
+#include "config.h"
+#define STATEFILE_PRIVATE
+#include "statefile.h"
+
+#define NS_MODULE accounting
+
+#define NS_SUBMODULE limits
+
+/*
+ * Test to make sure accounting triggers hibernation
+ * correctly with both sum or max rules set
+ */
+
+static or_state_t *or_state;
+NS_DECL(or_state_t *, get_or_state, (void));
+static or_state_t *
+NS(get_or_state)(void)
+{
+ return or_state;
+}
+
+static void
+test_accounting_limits(void *arg)
+{
+ or_options_t *options = get_options_mutable();
+ time_t fake_time = time(NULL);
+ (void) arg;
+
+ NS_MOCK(get_or_state);
+ or_state = or_state_new();
+
+ options->AccountingMax = 100;
+ options->AccountingRule = ACCT_MAX;
+
+ tor_assert(accounting_is_enabled(options));
+ configure_accounting(fake_time);
+
+ accounting_add_bytes(10, 0, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 0);
+
+ accounting_add_bytes(90, 0, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 1);
+
+ options->AccountingMax = 200;
+ options->AccountingRule = ACCT_SUM;
+
+ accounting_add_bytes(0, 10, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 0);
+
+ accounting_add_bytes(0, 90, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 1);
+
+ options->AccountingRule = ACCT_OUT;
+
+ accounting_add_bytes(100, 10, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 0);
+
+ accounting_add_bytes(0, 90, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 1);
+
+ options->AccountingMax = 300;
+ options->AccountingRule = ACCT_IN;
+
+ accounting_add_bytes(10, 100, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 0);
+
+ accounting_add_bytes(90, 0, 1);
+ fake_time += 1;
+ consider_hibernation(fake_time);
+ tor_assert(we_are_hibernating() == 1);
+
+ goto done;
+ done:
+ NS_UNMOCK(get_or_state);
+ or_state_free(or_state);
+}
+
+#undef NS_SUBMODULE
+
+struct testcase_t accounting_tests[] = {
+ { "bwlimits", test_accounting_limits, TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_addr.c b/src/test/test_addr.c
index 2c126e6d14..56e79d707a 100644
--- a/src/test/test_addr.c
+++ b/src/test/test_addr.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define ADDRESSMAP_PRIVATE
@@ -10,49 +10,50 @@
#include "addressmap.h"
static void
-test_addr_basic(void)
+test_addr_basic(void *arg)
{
uint32_t u32;
uint16_t u16;
char *cp;
/* Test addr_port_lookup */
+ (void)arg;
cp = NULL; u32 = 3; u16 = 3;
- test_assert(!addr_port_lookup(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
- test_streq(cp, "1.2.3.4");
- test_eq(u32, 0x01020304u);
- test_eq(u16, 0);
+ tt_assert(!addr_port_lookup(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
+ tt_str_op(cp,OP_EQ, "1.2.3.4");
+ tt_int_op(u32,OP_EQ, 0x01020304u);
+ tt_int_op(u16,OP_EQ, 0);
tor_free(cp);
- test_assert(!addr_port_lookup(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
- test_streq(cp, "4.3.2.1");
- test_eq(u32, 0x04030201u);
- test_eq(u16, 99);
+ tt_assert(!addr_port_lookup(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
+ tt_str_op(cp,OP_EQ, "4.3.2.1");
+ tt_int_op(u32,OP_EQ, 0x04030201u);
+ tt_int_op(u16,OP_EQ, 99);
tor_free(cp);
- test_assert(!addr_port_lookup(LOG_WARN, "nonexistent.address:4040",
+ tt_assert(!addr_port_lookup(LOG_WARN, "nonexistent.address:4040",
&cp, NULL, &u16));
- test_streq(cp, "nonexistent.address");
- test_eq(u16, 4040);
+ tt_str_op(cp,OP_EQ, "nonexistent.address");
+ tt_int_op(u16,OP_EQ, 4040);
tor_free(cp);
- test_assert(!addr_port_lookup(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
- test_streq(cp, "localhost");
- test_eq(u32, 0x7f000001u);
- test_eq(u16, 9999);
+ tt_assert(!addr_port_lookup(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
+ tt_str_op(cp,OP_EQ, "localhost");
+ tt_int_op(u32,OP_EQ, 0x7f000001u);
+ tt_int_op(u16,OP_EQ, 9999);
tor_free(cp);
u32 = 3;
- test_assert(!addr_port_lookup(LOG_WARN, "localhost", NULL, &u32, &u16));
- test_eq_ptr(cp, NULL);
- test_eq(u32, 0x7f000001u);
- test_eq(u16, 0);
+ tt_assert(!addr_port_lookup(LOG_WARN, "localhost", NULL, &u32, &u16));
+ tt_ptr_op(cp,OP_EQ, NULL);
+ tt_int_op(u32,OP_EQ, 0x7f000001u);
+ tt_int_op(u16,OP_EQ, 0);
tor_free(cp);
- test_assert(addr_port_lookup(LOG_WARN, "localhost:3", &cp, &u32, NULL));
+ tt_assert(addr_port_lookup(LOG_WARN, "localhost:3", &cp, &u32, NULL));
tor_free(cp);
- test_eq(0, addr_mask_get_bits(0x0u));
- test_eq(32, addr_mask_get_bits(0xFFFFFFFFu));
- test_eq(16, addr_mask_get_bits(0xFFFF0000u));
- test_eq(31, addr_mask_get_bits(0xFFFFFFFEu));
- test_eq(1, addr_mask_get_bits(0x80000000u));
+ tt_int_op(0,OP_EQ, addr_mask_get_bits(0x0u));
+ tt_int_op(32,OP_EQ, addr_mask_get_bits(0xFFFFFFFFu));
+ tt_int_op(16,OP_EQ, addr_mask_get_bits(0xFFFF0000u));
+ tt_int_op(31,OP_EQ, addr_mask_get_bits(0xFFFFFFFEu));
+ tt_int_op(1,OP_EQ, addr_mask_get_bits(0x80000000u));
/* Test inet_ntop */
{
@@ -61,15 +62,16 @@ test_addr_basic(void)
struct in_addr in;
/* good round trip */
- test_eq(tor_inet_pton(AF_INET, ip, &in), 1);
- test_eq_ptr(tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf)), &tmpbuf);
- test_streq(tmpbuf, ip);
+ tt_int_op(tor_inet_pton(AF_INET, ip, &in), OP_EQ, 1);
+ tt_ptr_op(tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf)),
+ OP_EQ, &tmpbuf);
+ tt_str_op(tmpbuf,OP_EQ, ip);
/* just enough buffer length */
- test_streq(tor_inet_ntop(AF_INET, &in, tmpbuf, strlen(ip) + 1), ip);
+ tt_str_op(tor_inet_ntop(AF_INET, &in, tmpbuf, strlen(ip) + 1), OP_EQ, ip);
/* too short buffer */
- test_eq_ptr(tor_inet_ntop(AF_INET, &in, tmpbuf, strlen(ip)), NULL);
+ tt_ptr_op(tor_inet_ntop(AF_INET, &in, tmpbuf, strlen(ip)),OP_EQ, NULL);
}
done:
@@ -96,67 +98,68 @@ test_addr_basic(void)
/** Helper: Assert that two strings both decode as IPv6 addresses with
* tor_inet_pton(), and both decode to the same address. */
-#define test_pton6_same(a,b) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
- test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
- test_op_ip6_(&a1,==,&a2,#a,#b); \
+#define test_pton6_same(a,b) STMT_BEGIN \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &a1), OP_EQ, 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, b, &a2), OP_EQ, 1); \
+ test_op_ip6_(&a1,OP_EQ,&a2,#a,#b); \
STMT_END
/** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
* tor_inet_pton(). */
#define test_pton6_bad(a) \
- test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
+ tt_int_op(0, OP_EQ, tor_inet_pton(AF_INET6, a, &a1))
/** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
* with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
* the same value as <b>a</b>. */
-#define test_ntop6_reduces(a,b) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
- test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
- test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
- test_op_ip6_(&a1, ==, &a2, a, b); \
+#define test_ntop6_reduces(a,b) STMT_BEGIN \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &a1), OP_EQ, 1); \
+ tt_str_op(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), OP_EQ, b); \
+ tt_int_op(tor_inet_pton(AF_INET6, b, &a2), OP_EQ, 1); \
+ test_op_ip6_(&a1, OP_EQ, &a2, a, b); \
STMT_END
/** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
* passes tor_addr_is_internal() with <b>for_listening</b>. */
#define test_internal_ip(a,for_listening) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), OP_EQ, 1); \
t1.family = AF_INET6; \
if (!tor_addr_is_internal(&t1, for_listening)) \
- test_fail_msg( a "was not internal."); \
+ TT_DIE(("%s was not internal", a)); \
STMT_END
/** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
* does not pass tor_addr_is_internal() with <b>for_listening</b>. */
#define test_external_ip(a,for_listening) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), OP_EQ, 1); \
t1.family = AF_INET6; \
if (tor_addr_is_internal(&t1, for_listening)) \
- test_fail_msg(a "was not external."); \
+ TT_DIE(("%s was not internal", a)); \
STMT_END
/** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
* tor_inet_pton(), give addresses that compare in the order defined by
* <b>op</b> with tor_addr_compare(). */
#define test_addr_compare(a, op, b) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
- test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), OP_EQ, 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), OP_EQ, 1); \
t1.family = t2.family = AF_INET6; \
r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
if (!(r op 0)) \
- test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
+ TT_DIE(("Failed: tor_addr_compare(%s,%s) %s 0", a, b, #op));\
STMT_END
/** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
* tor_inet_pton(), give addresses that compare in the order defined by
* <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
#define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
- test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
- test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), OP_EQ, 1); \
+ tt_int_op(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), OP_EQ, 1); \
t1.family = t2.family = AF_INET6; \
r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
if (!(r op 0)) \
- test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
+ TT_DIE(("Failed: tor_addr_compare_masked(%s,%s,%d) %s 0", \
+ a, b, m, #op)); \
STMT_END
/** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
@@ -165,21 +168,21 @@ test_addr_basic(void)
* as <b>pt1..pt2</b>. */
#define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
STMT_BEGIN \
- test_eq(tor_addr_parse_mask_ports(xx, 0, &t1, &mask, &port1, &port2), \
- f); \
+ tt_int_op(tor_addr_parse_mask_ports(xx, 0, &t1, &mask, &port1, &port2), \
+ OP_EQ, f); \
p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
- test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
- test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
- test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
- test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
- test_eq(mask, mm); \
- test_eq(port1, pt1); \
- test_eq(port2, pt2); \
+ tt_int_op(htonl(ip1), OP_EQ, tor_addr_to_in6_addr32(&t1)[0]); \
+ tt_int_op(htonl(ip2), OP_EQ, tor_addr_to_in6_addr32(&t1)[1]); \
+ tt_int_op(htonl(ip3), OP_EQ, tor_addr_to_in6_addr32(&t1)[2]); \
+ tt_int_op(htonl(ip4), OP_EQ, tor_addr_to_in6_addr32(&t1)[3]); \
+ tt_int_op(mask, OP_EQ, mm); \
+ tt_uint_op(port1, OP_EQ, pt1); \
+ tt_uint_op(port2, OP_EQ, pt2); \
STMT_END
/** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
static void
-test_addr_ip6_helpers(void)
+test_addr_ip6_helpers(void *arg)
{
char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
char rbuf[REVERSE_LOOKUP_NAME_BUF_LEN];
@@ -194,28 +197,29 @@ test_addr_ip6_helpers(void)
struct sockaddr_in6 *sin6;
/* Test tor_inet_ntop and tor_inet_pton: IPv6 */
+ (void)arg;
{
const char *ip = "2001::1234";
const char *ip_ffff = "::ffff:192.168.1.2";
/* good round trip */
- test_eq(tor_inet_pton(AF_INET6, ip, &a1), 1);
- test_eq_ptr(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), &buf);
- test_streq(buf, ip);
+ tt_int_op(tor_inet_pton(AF_INET6, ip, &a1),OP_EQ, 1);
+ tt_ptr_op(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)),OP_EQ, &buf);
+ tt_str_op(buf,OP_EQ, ip);
/* good round trip - ::ffff:0:0 style */
- test_eq(tor_inet_pton(AF_INET6, ip_ffff, &a2), 1);
- test_eq_ptr(tor_inet_ntop(AF_INET6, &a2, buf, sizeof(buf)), &buf);
- test_streq(buf, ip_ffff);
+ tt_int_op(tor_inet_pton(AF_INET6, ip_ffff, &a2),OP_EQ, 1);
+ tt_ptr_op(tor_inet_ntop(AF_INET6, &a2, buf, sizeof(buf)),OP_EQ, &buf);
+ tt_str_op(buf,OP_EQ, ip_ffff);
/* just long enough buffer (remember \0) */
- test_streq(tor_inet_ntop(AF_INET6, &a1, buf, strlen(ip)+1), ip);
- test_streq(tor_inet_ntop(AF_INET6, &a2, buf, strlen(ip_ffff)+1),
+ tt_str_op(tor_inet_ntop(AF_INET6, &a1, buf, strlen(ip)+1),OP_EQ, ip);
+ tt_str_op(tor_inet_ntop(AF_INET6, &a2, buf, strlen(ip_ffff)+1),OP_EQ,
ip_ffff);
/* too short buffer (remember \0) */
- test_eq_ptr(tor_inet_ntop(AF_INET6, &a1, buf, strlen(ip)), NULL);
- test_eq_ptr(tor_inet_ntop(AF_INET6, &a2, buf, strlen(ip_ffff)), NULL);
+ tt_ptr_op(tor_inet_ntop(AF_INET6, &a1, buf, strlen(ip)),OP_EQ, NULL);
+ tt_ptr_op(tor_inet_ntop(AF_INET6, &a2, buf, strlen(ip_ffff)),OP_EQ, NULL);
}
/* ==== Converting to and from sockaddr_t. */
@@ -224,16 +228,16 @@ test_addr_ip6_helpers(void)
sin->sin_port = htons(9090);
sin->sin_addr.s_addr = htonl(0x7f7f0102); /*127.127.1.2*/
tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin, &port1);
- test_eq(tor_addr_family(&t1), AF_INET);
- test_eq(tor_addr_to_ipv4h(&t1), 0x7f7f0102);
- tt_int_op(port1, ==, 9090);
+ tt_int_op(tor_addr_family(&t1),OP_EQ, AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ, 0x7f7f0102);
+ tt_int_op(port1, OP_EQ, 9090);
memset(&sa_storage, 0, sizeof(sa_storage));
- test_eq(sizeof(struct sockaddr_in),
+ tt_int_op(sizeof(struct sockaddr_in),OP_EQ,
tor_addr_to_sockaddr(&t1, 1234, (struct sockaddr *)&sa_storage,
sizeof(sa_storage)));
- test_eq(1234, ntohs(sin->sin_port));
- test_eq(0x7f7f0102, ntohl(sin->sin_addr.s_addr));
+ tt_int_op(1234,OP_EQ, ntohs(sin->sin_port));
+ tt_int_op(0x7f7f0102,OP_EQ, ntohl(sin->sin_addr.s_addr));
memset(&sa_storage, 0, sizeof(sa_storage));
sin6 = (struct sockaddr_in6 *)&sa_storage;
@@ -241,37 +245,37 @@ test_addr_ip6_helpers(void)
sin6->sin6_port = htons(7070);
sin6->sin6_addr.s6_addr[0] = 128;
tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin6, &port1);
- test_eq(tor_addr_family(&t1), AF_INET6);
- tt_int_op(port1, ==, 7070);
+ tt_int_op(tor_addr_family(&t1),OP_EQ, AF_INET6);
+ tt_int_op(port1, OP_EQ, 7070);
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
- test_streq(p1, "8000::");
+ tt_str_op(p1,OP_EQ, "8000::");
memset(&sa_storage, 0, sizeof(sa_storage));
- test_eq(sizeof(struct sockaddr_in6),
+ tt_int_op(sizeof(struct sockaddr_in6),OP_EQ,
tor_addr_to_sockaddr(&t1, 9999, (struct sockaddr *)&sa_storage,
sizeof(sa_storage)));
- test_eq(AF_INET6, sin6->sin6_family);
- test_eq(9999, ntohs(sin6->sin6_port));
- test_eq(0x80000000, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
+ tt_int_op(AF_INET6,OP_EQ, sin6->sin6_family);
+ tt_int_op(9999,OP_EQ, ntohs(sin6->sin6_port));
+ tt_int_op(0x80000000,OP_EQ, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
/* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
* have a good resolver. */
- test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
- test_eq(AF_INET, tor_addr_family(&t1));
- test_eq(tor_addr_to_ipv4h(&t1), 0x7f808182);
+ tt_int_op(0,OP_EQ, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
+ tt_int_op(AF_INET,OP_EQ, tor_addr_family(&t1));
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ, 0x7f808182);
- test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
- test_eq(AF_INET6, tor_addr_family(&t1));
- test_eq(0x90, tor_addr_to_in6_addr8(&t1)[0]);
- test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
- test_eq(0x05, tor_addr_to_in6_addr8(&t1)[15]);
+ tt_int_op(0,OP_EQ, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
+ tt_int_op(AF_INET6,OP_EQ, tor_addr_family(&t1));
+ tt_int_op(0x90,OP_EQ, tor_addr_to_in6_addr8(&t1)[0]);
+ tt_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
+ tt_int_op(0x05,OP_EQ, tor_addr_to_in6_addr8(&t1)[15]);
/* === Test pton: valid af_inet6 */
/* Simple, valid parsing. */
r = tor_inet_pton(AF_INET6,
"0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
- test_assert(r==1);
- for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
+ tt_int_op(r, OP_EQ, 1);
+ for (i=0;i<16;++i) { tt_int_op(i+1,OP_EQ, (int)a1.s6_addr[i]); }
/* ipv4 ending. */
test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
"0102:0304:0506:0708:090A:0B0C:13.14.15.16");
@@ -298,6 +302,7 @@ test_addr_ip6_helpers(void)
//test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
+ test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
test_ntop6_reduces("008:0::0", "8::");
@@ -311,7 +316,7 @@ test_addr_ip6_helpers(void)
"1000:1:0:7::");
/* Bad af param */
- test_eq(tor_inet_pton(AF_UNSPEC, 0, 0), -1);
+ tt_int_op(tor_inet_pton(AF_UNSPEC, 0, 0),OP_EQ, -1);
/* === Test pton: invalid in6. */
test_pton6_bad("foobar.");
@@ -416,132 +421,134 @@ test_addr_ip6_helpers(void)
test_external_ip("::ffff:169.255.0.0", 0);
/* tor_addr_compare(tor_addr_t x2) */
- test_addr_compare("ffff::", ==, "ffff::0");
- test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
- test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
- test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
- test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
+ test_addr_compare("ffff::", OP_EQ, "ffff::0");
+ test_addr_compare("0::3:2:1", OP_LT, "0::ffff:0.3.2.1");
+ test_addr_compare("0::2:2:1", OP_LT, "0::ffff:0.3.2.1");
+ test_addr_compare("0::ffff:0.3.2.1", OP_GT, "0::0:0:0");
+ test_addr_compare("0::ffff:5.2.2.1", OP_LT,
+ "::ffff:6.0.0.0"); /* XXXX wrong. */
tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", 0, &t1, NULL, NULL, NULL);
tor_addr_parse_mask_ports("2.3.4.5", 0, &t2, NULL, NULL, NULL);
- test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
+ tt_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", 0, &t1, NULL, NULL, NULL);
tor_addr_parse_mask_ports("2.3.4.5", 0, &t2, NULL, NULL, NULL);
- test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
+ tt_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
/* test compare_masked */
- test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
- test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
- test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
- test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
+ test_addr_compare_masked("ffff::", OP_EQ, "ffff::0", 128);
+ test_addr_compare_masked("ffff::", OP_EQ, "ffff::0", 64);
+ test_addr_compare_masked("0::2:2:1", OP_LT, "0::8000:2:1", 81);
+ test_addr_compare_masked("0::2:2:1", OP_EQ, "0::8000:2:1", 80);
/* Test undecorated tor_addr_to_str */
- test_eq(AF_INET6, tor_addr_parse(&t1, "[123:45:6789::5005:11]"));
+ tt_int_op(AF_INET6,OP_EQ, tor_addr_parse(&t1, "[123:45:6789::5005:11]"));
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
- test_streq(p1, "123:45:6789::5005:11");
- test_eq(AF_INET, tor_addr_parse(&t1, "18.0.0.1"));
+ tt_str_op(p1,OP_EQ, "123:45:6789::5005:11");
+ tt_int_op(AF_INET,OP_EQ, tor_addr_parse(&t1, "18.0.0.1"));
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
- test_streq(p1, "18.0.0.1");
+ tt_str_op(p1,OP_EQ, "18.0.0.1");
/* Test decorated tor_addr_to_str */
- test_eq(AF_INET6, tor_addr_parse(&t1, "[123:45:6789::5005:11]"));
+ tt_int_op(AF_INET6,OP_EQ, tor_addr_parse(&t1, "[123:45:6789::5005:11]"));
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
- test_streq(p1, "[123:45:6789::5005:11]");
- test_eq(AF_INET, tor_addr_parse(&t1, "18.0.0.1"));
+ tt_str_op(p1,OP_EQ, "[123:45:6789::5005:11]");
+ tt_int_op(AF_INET,OP_EQ, tor_addr_parse(&t1, "18.0.0.1"));
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
- test_streq(p1, "18.0.0.1");
+ tt_str_op(p1,OP_EQ, "18.0.0.1");
/* Test buffer bounds checking of tor_addr_to_str */
- test_eq(AF_INET6, tor_addr_parse(&t1, "::")); /* 2 + \0 */
- test_eq_ptr(tor_addr_to_str(buf, &t1, 2, 0), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 3, 0), "::");
- test_eq_ptr(tor_addr_to_str(buf, &t1, 4, 1), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 5, 1), "[::]");
-
- test_eq(AF_INET6, tor_addr_parse(&t1, "2000::1337")); /* 10 + \0 */
- test_eq_ptr(tor_addr_to_str(buf, &t1, 10, 0), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 11, 0), "2000::1337");
- test_eq_ptr(tor_addr_to_str(buf, &t1, 12, 1), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 13, 1), "[2000::1337]");
-
- test_eq(AF_INET, tor_addr_parse(&t1, "1.2.3.4")); /* 7 + \0 */
- test_eq_ptr(tor_addr_to_str(buf, &t1, 7, 0), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 8, 0), "1.2.3.4");
-
- test_eq(AF_INET, tor_addr_parse(&t1, "255.255.255.255")); /* 15 + \0 */
- test_eq_ptr(tor_addr_to_str(buf, &t1, 15, 0), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 16, 0), "255.255.255.255");
- test_eq_ptr(tor_addr_to_str(buf, &t1, 15, 1), NULL); /* too short buf */
- test_streq(tor_addr_to_str(buf, &t1, 16, 1), "255.255.255.255");
+ tt_int_op(AF_INET6,OP_EQ, tor_addr_parse(&t1, "::")); /* 2 + \0 */
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 2, 0),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 3, 0),OP_EQ, "::");
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 4, 1),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 5, 1),OP_EQ, "[::]");
+
+ tt_int_op(AF_INET6,OP_EQ, tor_addr_parse(&t1, "2000::1337")); /* 10 + \0 */
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 10, 0),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 11, 0),OP_EQ, "2000::1337");
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 12, 1),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 13, 1),OP_EQ, "[2000::1337]");
+
+ tt_int_op(AF_INET,OP_EQ, tor_addr_parse(&t1, "1.2.3.4")); /* 7 + \0 */
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 7, 0),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 8, 0),OP_EQ, "1.2.3.4");
+
+ tt_int_op(AF_INET, OP_EQ,
+ tor_addr_parse(&t1, "255.255.255.255")); /* 15 + \0 */
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 15, 0),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 16, 0),OP_EQ, "255.255.255.255");
+ tt_ptr_op(tor_addr_to_str(buf, &t1, 15, 1),OP_EQ, NULL); /* too short buf */
+ tt_str_op(tor_addr_to_str(buf, &t1, 16, 1),OP_EQ, "255.255.255.255");
t1.family = AF_UNSPEC;
- test_eq_ptr(tor_addr_to_str(buf, &t1, sizeof(buf), 0), NULL);
+ tt_ptr_op(tor_addr_to_str(buf, &t1, sizeof(buf), 0),OP_EQ, NULL);
/* Test tor_addr_parse_PTR_name */
i = tor_addr_parse_PTR_name(&t1, "Foobar.baz", AF_UNSPEC, 0);
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
i = tor_addr_parse_PTR_name(&t1, "Foobar.baz", AF_UNSPEC, 1);
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
i = tor_addr_parse_PTR_name(&t1, "9999999999999999999999999999.in-addr.arpa",
AF_UNSPEC, 1);
- test_eq(-1, i);
+ tt_int_op(-1,OP_EQ, i);
i = tor_addr_parse_PTR_name(&t1, "1.0.168.192.in-addr.arpa",
AF_UNSPEC, 1);
- test_eq(1, i);
- test_eq(tor_addr_family(&t1), AF_INET);
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(tor_addr_family(&t1),OP_EQ, AF_INET);
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
- test_streq(p1, "192.168.0.1");
+ tt_str_op(p1,OP_EQ, "192.168.0.1");
i = tor_addr_parse_PTR_name(&t1, "192.168.0.99", AF_UNSPEC, 0);
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
i = tor_addr_parse_PTR_name(&t1, "192.168.0.99", AF_UNSPEC, 1);
- test_eq(1, i);
+ tt_int_op(1,OP_EQ, i);
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
- test_streq(p1, "192.168.0.99");
+ tt_str_op(p1,OP_EQ, "192.168.0.99");
memset(&t1, 0, sizeof(t1));
i = tor_addr_parse_PTR_name(&t1,
"0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
"f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
"ip6.ARPA",
AF_UNSPEC, 0);
- test_eq(1, i);
+ tt_int_op(1,OP_EQ, i);
p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
- test_streq(p1, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
+ tt_str_op(p1,OP_EQ, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
/* Failing cases. */
i = tor_addr_parse_PTR_name(&t1,
"6.7.8.9.a.b.c.d.e.f."
"f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
"ip6.ARPA",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1,
"6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
"f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
"ip6.ARPA",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1,
"6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
"f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
"ip6.ARPA",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1, "32.1.1.in-addr.arpa",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1, ".in-addr.arpa",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1, "1.2.3.4.5.in-addr.arpa",
AF_UNSPEC, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1, "1.2.3.4.5.in-addr.arpa",
AF_INET6, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
i = tor_addr_parse_PTR_name(&t1,
"6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
"f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
"ip6.ARPA",
AF_INET, 0);
- test_eq(i, -1);
+ tt_int_op(i,OP_EQ, -1);
/* === Test tor_addr_to_PTR_name */
@@ -553,19 +560,19 @@ test_addr_ip6_helpers(void)
tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin, NULL);
/* Check IPv4 PTR - too short buffer */
- test_eq(tor_addr_to_PTR_name(rbuf, 1, &t1), -1);
- test_eq(tor_addr_to_PTR_name(rbuf,
+ tt_int_op(tor_addr_to_PTR_name(rbuf, 1, &t1),OP_EQ, -1);
+ tt_int_op(tor_addr_to_PTR_name(rbuf,
strlen("3.2.1.127.in-addr.arpa") - 1,
- &t1), -1);
+ &t1),OP_EQ, -1);
/* Check IPv4 PTR - valid addr */
- test_eq(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1),
+ tt_int_op(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1),OP_EQ,
strlen("3.2.1.127.in-addr.arpa"));
- test_streq(rbuf, "3.2.1.127.in-addr.arpa");
+ tt_str_op(rbuf,OP_EQ, "3.2.1.127.in-addr.arpa");
/* Invalid addr family */
t1.family = AF_UNSPEC;
- test_eq(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1), -1);
+ tt_int_op(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1),OP_EQ, -1);
/* Stage IPv6 addr */
memset(&sa_storage, 0, sizeof(sa_storage));
@@ -582,153 +589,152 @@ test_addr_ip6_helpers(void)
"0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.ip6.arpa";
/* Check IPv6 PTR - too short buffer */
- test_eq(tor_addr_to_PTR_name(rbuf, 0, &t1), -1);
- test_eq(tor_addr_to_PTR_name(rbuf, strlen(addr_PTR) - 1, &t1), -1);
+ tt_int_op(tor_addr_to_PTR_name(rbuf, 0, &t1),OP_EQ, -1);
+ tt_int_op(tor_addr_to_PTR_name(rbuf, strlen(addr_PTR) - 1, &t1),OP_EQ, -1);
/* Check IPv6 PTR - valid addr */
- test_eq(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1),
+ tt_int_op(tor_addr_to_PTR_name(rbuf, sizeof(rbuf), &t1),OP_EQ,
strlen(addr_PTR));
- test_streq(rbuf, addr_PTR);
+ tt_str_op(rbuf,OP_EQ, addr_PTR);
}
/* XXXX turn this into a separate function; it's not all IPv6. */
/* test tor_addr_parse_mask_ports */
test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
0, 0, 0, 0x0000000f, 17, 47, 95);
- test_streq(p1, "::f");
+ tt_str_op(p1,OP_EQ, "::f");
//test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
//test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
- test_streq(p1, "::ffff:4.1.1.7");
+ tt_str_op(p1,OP_EQ, "::ffff:4.1.1.7");
test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
- test_streq(p1, "abcd:2::44a:0");
+ tt_str_op(p1,OP_EQ, "abcd:2::44a:0");
/* Try some long addresses. */
r=tor_addr_parse_mask_ports("[ffff:1111:1111:1111:1111:1111:1111:1111]",
0, &t1, NULL, NULL, NULL);
- test_assert(r == AF_INET6);
+ tt_assert(r == AF_INET6);
r=tor_addr_parse_mask_ports("[ffff:1111:1111:1111:1111:1111:1111:11111]",
0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[ffff:1111:1111:1111:1111:1111:1111:1111:1]",
0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports(
"[ffff:1111:1111:1111:1111:1111:1111:ffff:"
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:"
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:"
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]",
0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Try some failing cases. */
r=tor_addr_parse_mask_ports("[fefef::]/112", 0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[fefe::/112", 0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[fefe::", 0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[fefe::X]", 0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("efef::/112", 0, &t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]",0,&t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]",0,&t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]",0,&t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[f:f:f:f:f::]/fred",0,&t1,&mask, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("[f:f:f:f:f::]/255.255.0.0",
0,&t1, NULL, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* This one will get rejected because it isn't a pure prefix. */
r=tor_addr_parse_mask_ports("1.1.2.3/255.255.64.0",0,&t1, &mask,NULL,NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Test for V4-mapped address with mask < 96. (arguably not valid) */
r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]",0,&t1, &mask, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("1.1.2.2/33",0,&t1, &mask, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Try extended wildcard addresses with out TAPMP_EXTENDED_STAR*/
r=tor_addr_parse_mask_ports("*4",0,&t1, &mask, NULL, NULL);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r=tor_addr_parse_mask_ports("*6",0,&t1, &mask, NULL, NULL);
- test_assert(r == -1);
-#if 0
+ tt_int_op(r, OP_EQ, -1);
+ tt_assert(r == -1);
/* Try a mask with a wildcard. */
r=tor_addr_parse_mask_ports("*/16",0,&t1, &mask, NULL, NULL);
- test_assert(r == -1);
+ tt_assert(r == -1);
r=tor_addr_parse_mask_ports("*4/16",TAPMP_EXTENDED_STAR,
&t1, &mask, NULL, NULL);
- test_assert(r == -1);
+ tt_assert(r == -1);
r=tor_addr_parse_mask_ports("*6/30",TAPMP_EXTENDED_STAR,
&t1, &mask, NULL, NULL);
- test_assert(r == -1);
-#endif
+ tt_assert(r == -1);
/* Basic mask tests*/
r=tor_addr_parse_mask_ports("1.1.2.2/31",0,&t1, &mask, NULL, NULL);
- test_assert(r == AF_INET);
- tt_int_op(mask,==,31);
- tt_int_op(tor_addr_family(&t1),==,AF_INET);
- tt_int_op(tor_addr_to_ipv4h(&t1),==,0x01010202);
+ tt_assert(r == AF_INET);
+ tt_int_op(mask,OP_EQ,31);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ,0x01010202);
r=tor_addr_parse_mask_ports("3.4.16.032:1-2",0,&t1, &mask, &port1, &port2);
- test_assert(r == AF_INET);
- tt_int_op(mask,==,32);
- tt_int_op(tor_addr_family(&t1),==,AF_INET);
- tt_int_op(tor_addr_to_ipv4h(&t1),==,0x03041020);
- test_assert(port1 == 1);
- test_assert(port2 == 2);
+ tt_assert(r == AF_INET);
+ tt_int_op(mask,OP_EQ,32);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ,0x03041020);
+ tt_assert(port1 == 1);
+ tt_assert(port2 == 2);
r=tor_addr_parse_mask_ports("1.1.2.3/255.255.128.0",0,&t1, &mask,NULL,NULL);
- test_assert(r == AF_INET);
- tt_int_op(mask,==,17);
- tt_int_op(tor_addr_family(&t1),==,AF_INET);
- tt_int_op(tor_addr_to_ipv4h(&t1),==,0x01010203);
+ tt_assert(r == AF_INET);
+ tt_int_op(mask,OP_EQ,17);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ,0x01010203);
r=tor_addr_parse_mask_ports("[efef::]/112",0,&t1, &mask, &port1, &port2);
- test_assert(r == AF_INET6);
- test_assert(port1 == 1);
- test_assert(port2 == 65535);
+ tt_assert(r == AF_INET6);
+ tt_assert(port1 == 1);
+ tt_assert(port2 == 65535);
/* Try regular wildcard behavior without TAPMP_EXTENDED_STAR */
r=tor_addr_parse_mask_ports("*:80-443",0,&t1,&mask,&port1,&port2);
- tt_int_op(r,==,AF_INET); /* Old users of this always get inet */
- tt_int_op(tor_addr_family(&t1),==,AF_INET);
- tt_int_op(tor_addr_to_ipv4h(&t1),==,0);
- tt_int_op(mask,==,0);
- tt_int_op(port1,==,80);
- tt_int_op(port2,==,443);
+ tt_int_op(r,OP_EQ,AF_INET); /* Old users of this always get inet */
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ,0);
+ tt_int_op(mask,OP_EQ,0);
+ tt_int_op(port1,OP_EQ,80);
+ tt_int_op(port2,OP_EQ,443);
/* Now try wildcards *with* TAPMP_EXTENDED_STAR */
r=tor_addr_parse_mask_ports("*:8000-9000",TAPMP_EXTENDED_STAR,
&t1,&mask,&port1,&port2);
- tt_int_op(r,==,AF_UNSPEC);
- tt_int_op(tor_addr_family(&t1),==,AF_UNSPEC);
- tt_int_op(mask,==,0);
- tt_int_op(port1,==,8000);
- tt_int_op(port2,==,9000);
+ tt_int_op(r,OP_EQ,AF_UNSPEC);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_UNSPEC);
+ tt_int_op(mask,OP_EQ,0);
+ tt_int_op(port1,OP_EQ,8000);
+ tt_int_op(port2,OP_EQ,9000);
r=tor_addr_parse_mask_ports("*4:6667",TAPMP_EXTENDED_STAR,
&t1,&mask,&port1,&port2);
- tt_int_op(r,==,AF_INET);
- tt_int_op(tor_addr_family(&t1),==,AF_INET);
- tt_int_op(tor_addr_to_ipv4h(&t1),==,0);
- tt_int_op(mask,==,0);
- tt_int_op(port1,==,6667);
- tt_int_op(port2,==,6667);
+ tt_int_op(r,OP_EQ,AF_INET);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET);
+ tt_int_op(tor_addr_to_ipv4h(&t1),OP_EQ,0);
+ tt_int_op(mask,OP_EQ,0);
+ tt_int_op(port1,OP_EQ,6667);
+ tt_int_op(port2,OP_EQ,6667);
r=tor_addr_parse_mask_ports("*6",TAPMP_EXTENDED_STAR,
&t1,&mask,&port1,&port2);
- tt_int_op(r,==,AF_INET6);
- tt_int_op(tor_addr_family(&t1),==,AF_INET6);
+ tt_int_op(r,OP_EQ,AF_INET6);
+ tt_int_op(tor_addr_family(&t1),OP_EQ,AF_INET6);
tt_assert(tor_mem_is_zero((const char*)tor_addr_to_in6_addr32(&t1), 16));
- tt_int_op(mask,==,0);
- tt_int_op(port1,==,1);
- tt_int_op(port2,==,65535);
+ tt_int_op(mask,OP_EQ,0);
+ tt_int_op(port1,OP_EQ,1);
+ tt_int_op(port2,OP_EQ,65535);
/* make sure inet address lengths >= max */
- test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
- test_assert(TOR_ADDR_BUF_LEN >=
+ tt_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
+ tt_assert(TOR_ADDR_BUF_LEN >=
sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
- test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
+ tt_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
/* get interface addresses */
r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
@@ -745,7 +751,7 @@ test_addr_ip6_helpers(void)
/** Test tor_addr_port_parse(). */
static void
-test_addr_parse(void)
+test_addr_parse(void *arg)
{
int r;
tor_addr_t addr;
@@ -753,90 +759,91 @@ test_addr_parse(void)
uint16_t port = 0;
/* Correct call. */
+ (void)arg;
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.1:1234",
&addr, &port, -1);
- test_assert(r == 0);
+ tt_int_op(r, OP_EQ, 0);
tor_addr_to_str(buf, &addr, sizeof(buf), 0);
- test_streq(buf, "192.0.2.1");
- test_eq(port, 1234);
+ tt_str_op(buf,OP_EQ, "192.0.2.1");
+ tt_int_op(port,OP_EQ, 1234);
r= tor_addr_port_parse(LOG_DEBUG,
"[::1]:1234",
&addr, &port, -1);
- test_assert(r == 0);
+ tt_int_op(r, OP_EQ, 0);
tor_addr_to_str(buf, &addr, sizeof(buf), 0);
- test_streq(buf, "::1");
- test_eq(port, 1234);
+ tt_str_op(buf,OP_EQ, "::1");
+ tt_int_op(port,OP_EQ, 1234);
/* Domain name. */
r= tor_addr_port_parse(LOG_DEBUG,
"torproject.org:1234",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Only IP. */
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.2",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.2",
&addr, &port, 200);
- test_assert(r == 0);
- tt_int_op(port,==,200);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(port,OP_EQ,200);
r= tor_addr_port_parse(LOG_DEBUG,
"[::1]",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r= tor_addr_port_parse(LOG_DEBUG,
"[::1]",
&addr, &port, 400);
- test_assert(r == 0);
- tt_int_op(port,==,400);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(port,OP_EQ,400);
/* Bad port. */
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.2:66666",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.2:66666",
&addr, &port, 200);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Only domain name */
r= tor_addr_port_parse(LOG_DEBUG,
"torproject.org",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
r= tor_addr_port_parse(LOG_DEBUG,
"torproject.org",
&addr, &port, 200);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Bad IP address */
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2:1234",
&addr, &port, -1);
- test_assert(r == -1);
+ tt_int_op(r, OP_EQ, -1);
/* Make sure that the default port has lower priority than the real
one */
r= tor_addr_port_parse(LOG_DEBUG,
"192.0.2.2:1337",
&addr, &port, 200);
- test_assert(r == 0);
- tt_int_op(port,==,1337);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(port,OP_EQ,1337);
r= tor_addr_port_parse(LOG_DEBUG,
"[::1]:1369",
&addr, &port, 200);
- test_assert(r == 0);
- tt_int_op(port,==,1369);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(port,OP_EQ,1369);
done:
;
@@ -891,7 +898,7 @@ test_virtaddrmap(void *data)
get_random_virtual_addr(&cfg[ipv6], &a);
//printf("%s\n", fmt_addr(&a));
/* Make sure that the first b bits match the configured network */
- tt_int_op(0, ==, tor_addr_compare_masked(&a, &cfg[ipv6].addr,
+ tt_int_op(0, OP_EQ, tor_addr_compare_masked(&a, &cfg[ipv6].addr,
bits, CMP_EXACT));
/* And track which bits have been different between pairs of
@@ -935,7 +942,7 @@ test_addr_dup_ip(void *arg)
(void)arg;
#define CHECK(ip, s) do { \
v = tor_dup_ip(ip); \
- tt_str_op(v,==,(s)); \
+ tt_str_op(v,OP_EQ,(s)); \
tor_free(v); \
} while (0)
@@ -961,7 +968,7 @@ test_addr_sockaddr_to_str(void *arg)
#endif
#define CHECK(sa, s) do { \
v = tor_sockaddr_to_str((const struct sockaddr*) &(sa)); \
- tt_str_op(v,==,(s)); \
+ tt_str_op(v,OP_EQ,(s)); \
tor_free(v); \
} while (0)
(void)arg;
@@ -1018,12 +1025,13 @@ test_addr_is_loopback(void *data)
(void)data;
for (i=0; loopback_items[i].name; ++i) {
- tt_int_op(tor_addr_parse(&addr, loopback_items[i].name), >=, 0);
- tt_int_op(tor_addr_is_loopback(&addr), ==, loopback_items[i].is_loopback);
+ tt_int_op(tor_addr_parse(&addr, loopback_items[i].name), OP_GE, 0);
+ tt_int_op(tor_addr_is_loopback(&addr), OP_EQ,
+ loopback_items[i].is_loopback);
}
tor_addr_make_unspec(&addr);
- tt_int_op(tor_addr_is_loopback(&addr), ==, 0);
+ tt_int_op(tor_addr_is_loopback(&addr), OP_EQ, 0);
done:
;
@@ -1038,25 +1046,25 @@ test_addr_make_null(void *data)
(void) data;
/* Ensure that before tor_addr_make_null, addr != 0's */
memset(addr, 1, sizeof(*addr));
- tt_int_op(memcmp(addr, zeros, sizeof(*addr)), !=, 0);
+ tt_int_op(memcmp(addr, zeros, sizeof(*addr)), OP_NE, 0);
/* Test with AF == AF_INET */
zeros->family = AF_INET;
tor_addr_make_null(addr, AF_INET);
- tt_int_op(memcmp(addr, zeros, sizeof(*addr)), ==, 0);
- tt_str_op(tor_addr_to_str(buf, addr, sizeof(buf), 0), ==, "0.0.0.0");
+ tt_int_op(memcmp(addr, zeros, sizeof(*addr)), OP_EQ, 0);
+ tt_str_op(tor_addr_to_str(buf, addr, sizeof(buf), 0), OP_EQ, "0.0.0.0");
/* Test with AF == AF_INET6 */
memset(addr, 1, sizeof(*addr));
zeros->family = AF_INET6;
tor_addr_make_null(addr, AF_INET6);
- tt_int_op(memcmp(addr, zeros, sizeof(*addr)), ==, 0);
- tt_str_op(tor_addr_to_str(buf, addr, sizeof(buf), 0), ==, "::");
+ tt_int_op(memcmp(addr, zeros, sizeof(*addr)), OP_EQ, 0);
+ tt_str_op(tor_addr_to_str(buf, addr, sizeof(buf), 0), OP_EQ, "::");
done:
tor_free(addr);
tor_free(zeros);
}
#define ADDR_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_addr_ ## name }
+ { #name, test_addr_ ## name , 0, NULL, NULL }
struct testcase_t addr_tests[] = {
ADDR_LEGACY(basic),
diff --git a/src/test/test_address.c b/src/test/test_address.c
new file mode 100644
index 0000000000..3e5af56c52
--- /dev/null
+++ b/src/test/test_address.c
@@ -0,0 +1,1137 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define ADDRESS_PRIVATE
+
+#include "orconfig.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+/* For access to structs needed by GetAdaptersAddresses */
+#include <iphlpapi.h>
+#endif
+
+#ifdef HAVE_IFADDRS_TO_SMARTLIST
+#include <net/if.h>
+#include <ifaddrs.h>
+#endif
+
+#ifdef HAVE_IFCONF_TO_SMARTLIST
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#include <net/if.h>
+#endif
+
+#include "or.h"
+#include "address.h"
+#include "test.h"
+
+/** Return 1 iff <b>sockaddr1</b> and <b>sockaddr2</b> represent
+ * the same IP address and port combination. Otherwise, return 0.
+ */
+static uint8_t
+sockaddr_in_are_equal(struct sockaddr_in *sockaddr1,
+ struct sockaddr_in *sockaddr2)
+{
+ return ((sockaddr1->sin_family == sockaddr2->sin_family) &&
+ (sockaddr1->sin_port == sockaddr2->sin_port) &&
+ (sockaddr1->sin_addr.s_addr == sockaddr2->sin_addr.s_addr));
+}
+
+/** Return 1 iff <b>sockaddr1</b> and <b>sockaddr2</b> represent
+ * the same IP address and port combination. Otherwise, return 0.
+ */
+static uint8_t
+sockaddr_in6_are_equal(struct sockaddr_in6 *sockaddr1,
+ struct sockaddr_in6 *sockaddr2)
+{
+ return ((sockaddr1->sin6_family == sockaddr2->sin6_family) &&
+ (sockaddr1->sin6_port == sockaddr2->sin6_port) &&
+ (tor_memeq(sockaddr1->sin6_addr.s6_addr,
+ sockaddr2->sin6_addr.s6_addr,16)));
+}
+
+/** Create a sockaddr_in structure from IP address string <b>ip_str</b>.
+ *
+ * If <b>out</b> is not NULL, write the result
+ * to the memory address in <b>out</b>. Otherwise, allocate the memory
+ * for result. On success, return pointer to result. Otherwise, return
+ * NULL.
+ */
+static struct sockaddr_in *
+sockaddr_in_from_string(const char *ip_str, struct sockaddr_in *out)
+{
+ // [FIXME: add some error checking?]
+ if (!out)
+ out = tor_malloc_zero(sizeof(struct sockaddr_in));
+
+ out->sin_family = AF_INET;
+ out->sin_port = 0;
+ tor_inet_pton(AF_INET,ip_str,&(out->sin_addr));
+
+ return out;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is an IPv4 or IPv6 localhost address. Otherwise, return 0.
+ */
+static int
+smartlist_contains_localhost_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ if (tor_addr_is_loopback(tor_addr)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is an IPv4 or IPv6 multicast address. Otherwise, return 0.
+ */
+static int
+smartlist_contains_multicast_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ if (tor_addr_is_multicast(tor_addr)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is an IPv4 or IPv6 internal address. Otherwise, return 0.
+ */
+static int
+smartlist_contains_internal_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ if (tor_addr_is_internal(tor_addr, 0)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is NULL or the null tor_addr_t. Otherwise, return 0.
+ */
+static int
+smartlist_contains_null_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ if (tor_addr == NULL || tor_addr_is_null(tor_addr)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is an IPv4 address. Otherwise, return 0.
+ */
+static int
+smartlist_contains_ipv4_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ if (tor_addr_is_v4(tor_addr)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+/** Return 1 iff <b>smartlist</b> contains a tor_addr_t structure
+ * that is an IPv6 address. Otherwise, return 0.
+ */
+static int
+smartlist_contains_ipv6_tor_addr(smartlist_t *smartlist)
+{
+ SMARTLIST_FOREACH_BEGIN(smartlist, tor_addr_t *, tor_addr) {
+ /* Since there's no tor_addr_is_v6, assume all non-v4s are v6 */
+ if (!tor_addr_is_v4(tor_addr)) {
+ return 1;
+ }
+ } SMARTLIST_FOREACH_END(tor_addr);
+
+ return 0;
+}
+
+#ifdef HAVE_IFADDRS_TO_SMARTLIST
+static void
+test_address_ifaddrs_to_smartlist(void *arg)
+{
+ struct ifaddrs *ifa = NULL;
+ struct ifaddrs *ifa_ipv4 = NULL;
+ struct ifaddrs *ifa_ipv6 = NULL;
+ struct sockaddr_in *ipv4_sockaddr_local = NULL;
+ struct sockaddr_in *netmask_slash8 = NULL;
+ struct sockaddr_in *ipv4_sockaddr_remote = NULL;
+ struct sockaddr_in6 *ipv6_sockaddr = NULL;
+ smartlist_t *smartlist = NULL;
+ tor_addr_t *tor_addr = NULL;
+ struct sockaddr *sockaddr_to_check = NULL;
+ socklen_t addr_len;
+
+ (void)arg;
+
+ netmask_slash8 = sockaddr_in_from_string("255.0.0.0",NULL);
+ ipv4_sockaddr_local = sockaddr_in_from_string("127.0.0.1",NULL);
+ ipv4_sockaddr_remote = sockaddr_in_from_string("128.52.160.20",NULL);
+
+ ipv6_sockaddr = tor_malloc(sizeof(struct sockaddr_in6));
+ ipv6_sockaddr->sin6_family = AF_INET6;
+ ipv6_sockaddr->sin6_port = 0;
+ tor_inet_pton(AF_INET6, "2001:db8:8714:3a90::12",
+ &(ipv6_sockaddr->sin6_addr));
+
+ ifa = tor_malloc(sizeof(struct ifaddrs));
+ ifa_ipv4 = tor_malloc(sizeof(struct ifaddrs));
+ ifa_ipv6 = tor_malloc(sizeof(struct ifaddrs));
+
+ ifa->ifa_next = ifa_ipv4;
+ ifa->ifa_name = tor_strdup("eth0");
+ ifa->ifa_flags = IFF_UP | IFF_RUNNING;
+ ifa->ifa_addr = (struct sockaddr *)ipv4_sockaddr_local;
+ ifa->ifa_netmask = (struct sockaddr *)netmask_slash8;
+ ifa->ifa_dstaddr = NULL;
+ ifa->ifa_data = NULL;
+
+ ifa_ipv4->ifa_next = ifa_ipv6;
+ ifa_ipv4->ifa_name = tor_strdup("eth1");
+ ifa_ipv4->ifa_flags = IFF_UP | IFF_RUNNING;
+ ifa_ipv4->ifa_addr = (struct sockaddr *)ipv4_sockaddr_remote;
+ ifa_ipv4->ifa_netmask = (struct sockaddr *)netmask_slash8;
+ ifa_ipv4->ifa_dstaddr = NULL;
+ ifa_ipv4->ifa_data = NULL;
+
+ ifa_ipv6->ifa_next = NULL;
+ ifa_ipv6->ifa_name = tor_strdup("eth2");
+ ifa_ipv6->ifa_flags = IFF_UP | IFF_RUNNING;
+ ifa_ipv6->ifa_addr = (struct sockaddr *)ipv6_sockaddr;
+ ifa_ipv6->ifa_netmask = NULL;
+ ifa_ipv6->ifa_dstaddr = NULL;
+ ifa_ipv6->ifa_data = NULL;
+
+ smartlist = ifaddrs_to_smartlist(ifa, AF_UNSPEC);
+
+ tt_assert(smartlist);
+ tt_assert(smartlist_len(smartlist) == 3);
+
+ sockaddr_to_check = tor_malloc(sizeof(struct sockaddr_in6));
+
+ tor_addr = smartlist_get(smartlist,0);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in));
+ tt_assert(sockaddr_in_are_equal((struct sockaddr_in *)sockaddr_to_check,
+ ipv4_sockaddr_local));
+
+ tor_addr = smartlist_get(smartlist,1);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in));
+ tt_assert(sockaddr_in_are_equal((struct sockaddr_in *)sockaddr_to_check,
+ ipv4_sockaddr_remote));
+
+ tor_addr = smartlist_get(smartlist,2);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,sockaddr_to_check,
+ sizeof(struct sockaddr_in6));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in6));
+ tt_assert(sockaddr_in6_are_equal((struct sockaddr_in6*)sockaddr_to_check,
+ ipv6_sockaddr));
+
+ done:
+ tor_free(netmask_slash8);
+ tor_free(ipv4_sockaddr_local);
+ tor_free(ipv4_sockaddr_remote);
+ tor_free(ipv6_sockaddr);
+ tor_free(ifa->ifa_name);
+ tor_free(ifa_ipv4->ifa_name);
+ tor_free(ifa_ipv6->ifa_name);
+ tor_free(ifa);
+ tor_free(ifa_ipv4);
+ tor_free(ifa_ipv6);
+ tor_free(sockaddr_to_check);
+ if (smartlist) {
+ SMARTLIST_FOREACH(smartlist, tor_addr_t *, t, tor_free(t));
+ smartlist_free(smartlist);
+ }
+ return;
+}
+
+static void
+test_address_get_if_addrs_ifaddrs(void *arg)
+{
+
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_addresses_ifaddrs(LOG_ERR, AF_UNSPEC);
+
+ tt_assert(results);
+ /* Some FreeBSD jails don't have localhost IP address. Instead, they only
+ * have the address assigned to the jail (whatever that may be).
+ * And a jail without a network connection might not have any addresses at
+ * all. */
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* If there are addresses, they must be IPv4 or IPv6 */
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv4_tor_addr(results)
+ || smartlist_contains_ipv6_tor_addr(results));
+ }
+
+ done:
+ if (results) {
+ SMARTLIST_FOREACH(results, tor_addr_t *, t, tor_free(t));
+ }
+ smartlist_free(results);
+ return;
+}
+
+#endif
+
+#ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
+
+static void
+test_address_get_if_addrs_win32(void *arg)
+{
+
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_addresses_win32(LOG_ERR, AF_UNSPEC);
+
+ tt_int_op(smartlist_len(results),>=,1);
+ tt_assert(smartlist_contains_localhost_tor_addr(results));
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* If there are addresses, they must be IPv4 or IPv6 */
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv4_tor_addr(results)
+ || smartlist_contains_ipv6_tor_addr(results));
+ }
+
+ done:
+ SMARTLIST_FOREACH(results, tor_addr_t *, t, tor_free(t));
+ tor_free(results);
+ return;
+}
+
+static void
+test_address_ip_adapter_addresses_to_smartlist(void *arg)
+{
+
+ IP_ADAPTER_ADDRESSES *addrs1;
+ IP_ADAPTER_ADDRESSES *addrs2;
+
+ IP_ADAPTER_UNICAST_ADDRESS *unicast11;
+ IP_ADAPTER_UNICAST_ADDRESS *unicast12;
+ IP_ADAPTER_UNICAST_ADDRESS *unicast21;
+
+ smartlist_t *result = NULL;
+
+ struct sockaddr_in *sockaddr_test1;
+ struct sockaddr_in *sockaddr_test2;
+ struct sockaddr_in *sockaddr_localhost;
+ struct sockaddr_in *sockaddr_to_check;
+
+ tor_addr_t *tor_addr;
+
+ (void)arg;
+ (void)sockaddr_in6_are_equal;
+
+ sockaddr_to_check = tor_malloc_zero(sizeof(struct sockaddr_in));
+
+ addrs1 =
+ tor_malloc_zero(sizeof(IP_ADAPTER_ADDRESSES));
+
+ addrs1->FirstUnicastAddress =
+ unicast11 = tor_malloc_zero(sizeof(IP_ADAPTER_UNICAST_ADDRESS));
+ sockaddr_test1 = sockaddr_in_from_string("86.59.30.40",NULL);
+ unicast11->Address.lpSockaddr = (LPSOCKADDR)sockaddr_test1;
+
+ unicast11->Next = unicast12 =
+ tor_malloc_zero(sizeof(IP_ADAPTER_UNICAST_ADDRESS));
+ sockaddr_test2 = sockaddr_in_from_string("93.95.227.222", NULL);
+ unicast12->Address.lpSockaddr = (LPSOCKADDR)sockaddr_test2;
+
+ addrs1->Next = addrs2 =
+ tor_malloc_zero(sizeof(IP_ADAPTER_ADDRESSES));
+
+ addrs2->FirstUnicastAddress =
+ unicast21 = tor_malloc_zero(sizeof(IP_ADAPTER_UNICAST_ADDRESS));
+ sockaddr_localhost = sockaddr_in_from_string("127.0.0.1", NULL);
+ unicast21->Address.lpSockaddr = (LPSOCKADDR)sockaddr_localhost;
+
+ result = ip_adapter_addresses_to_smartlist(addrs1);
+
+ tt_assert(result);
+ tt_assert(smartlist_len(result) == 3);
+
+ tor_addr = smartlist_get(result,0);
+
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_assert(sockaddr_in_are_equal(sockaddr_test1,sockaddr_to_check));
+
+ tor_addr = smartlist_get(result,1);
+
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_assert(sockaddr_in_are_equal(sockaddr_test2,sockaddr_to_check));
+
+ tor_addr = smartlist_get(result,2);
+
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_assert(sockaddr_in_are_equal(sockaddr_localhost,sockaddr_to_check));
+
+ done:
+ SMARTLIST_FOREACH(result, tor_addr_t *, t, tor_free(t));
+ smartlist_free(result);
+ tor_free(addrs1);
+ tor_free(addrs2);
+ tor_free(unicast11->Address.lpSockaddr);
+ tor_free(unicast11);
+ tor_free(unicast12->Address.lpSockaddr);
+ tor_free(unicast12);
+ tor_free(unicast21->Address.lpSockaddr);
+ tor_free(unicast21);
+ tor_free(sockaddr_to_check);
+ return;
+}
+#endif
+
+#ifdef HAVE_IFCONF_TO_SMARTLIST
+
+static void
+test_address_ifreq_to_smartlist(void *arg)
+{
+ smartlist_t *results = NULL;
+ const tor_addr_t *tor_addr = NULL;
+ struct sockaddr_in *sockaddr = NULL;
+ struct sockaddr_in *sockaddr_eth1 = NULL;
+ struct sockaddr_in *sockaddr_to_check = NULL;
+
+ struct ifconf *ifc;
+ struct ifreq *ifr;
+ struct ifreq *ifr_next;
+
+ socklen_t addr_len;
+
+ (void)arg;
+
+ sockaddr_to_check = tor_malloc(sizeof(struct sockaddr_in));
+
+ ifr = tor_malloc(sizeof(struct ifreq));
+ memset(ifr,0,sizeof(struct ifreq));
+ strlcpy(ifr->ifr_name,"lo",3);
+ sockaddr = (struct sockaddr_in *) &(ifr->ifr_ifru.ifru_addr);
+ sockaddr_in_from_string("127.0.0.1",sockaddr);
+
+ ifc = tor_malloc(sizeof(struct ifconf));
+ memset(ifc,0,sizeof(struct ifconf));
+ ifc->ifc_len = sizeof(struct ifreq);
+ ifc->ifc_ifcu.ifcu_req = ifr;
+
+ results = ifreq_to_smartlist(ifc->ifc_buf,ifc->ifc_len);
+ tt_int_op(smartlist_len(results),==,1);
+
+ tor_addr = smartlist_get(results, 0);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in));
+ tt_assert(sockaddr_in_are_equal(sockaddr,sockaddr_to_check));
+
+ ifr = tor_realloc(ifr,2*sizeof(struct ifreq));
+ ifr_next = ifr+1;
+ strlcpy(ifr_next->ifr_name,"eth1",5);
+ ifc->ifc_len = 2*sizeof(struct ifreq);
+ ifc->ifc_ifcu.ifcu_req = ifr;
+ sockaddr = (struct sockaddr_in *) &(ifr->ifr_ifru.ifru_addr);
+
+ sockaddr_eth1 = (struct sockaddr_in *) &(ifr_next->ifr_ifru.ifru_addr);
+ sockaddr_in_from_string("192.168.10.55",sockaddr_eth1);
+ SMARTLIST_FOREACH(results, tor_addr_t *, t, tor_free(t));
+ smartlist_free(results);
+
+ results = ifreq_to_smartlist(ifc->ifc_buf,ifc->ifc_len);
+ tt_int_op(smartlist_len(results),==,2);
+
+ tor_addr = smartlist_get(results, 0);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in));
+ tt_assert(sockaddr_in_are_equal(sockaddr,sockaddr_to_check));
+
+ tor_addr = smartlist_get(results, 1);
+ addr_len =
+ tor_addr_to_sockaddr(tor_addr,0,(struct sockaddr *)sockaddr_to_check,
+ sizeof(struct sockaddr_in));
+
+ tt_int_op(addr_len,==,sizeof(struct sockaddr_in));
+ tt_assert(sockaddr_in_are_equal(sockaddr_eth1,sockaddr_to_check));
+
+ done:
+ tor_free(sockaddr_to_check);
+ SMARTLIST_FOREACH(results, tor_addr_t *, t, tor_free(t));
+ smartlist_free(results);
+ tor_free(ifc);
+ tor_free(ifr);
+ return;
+}
+
+static void
+test_address_get_if_addrs_ioctl(void *arg)
+{
+
+ smartlist_t *result = NULL;
+
+ (void)arg;
+
+ result = get_interface_addresses_ioctl(LOG_ERR, AF_INET);
+
+ /* On an IPv6-only system, this will fail and return NULL
+ tt_assert(result);
+ */
+
+ /* Some FreeBSD jails don't have localhost IP address. Instead, they only
+ * have the address assigned to the jail (whatever that may be).
+ * And a jail without a network connection might not have any addresses at
+ * all. */
+ if (result) {
+ tt_assert(!smartlist_contains_null_tor_addr(result));
+
+ /* If there are addresses, they must be IPv4 or IPv6.
+ * (AIX supports IPv6 from SIOCGIFCONF.) */
+ if (smartlist_len(result) > 0) {
+ tt_assert(smartlist_contains_ipv4_tor_addr(result)
+ || smartlist_contains_ipv6_tor_addr(result));
+ }
+ }
+
+ done:
+ if (result) {
+ SMARTLIST_FOREACH(result, tor_addr_t *, t, tor_free(t));
+ smartlist_free(result);
+ }
+ return;
+}
+
+#endif
+
+#define FAKE_SOCKET_FD (42)
+
+static tor_socket_t
+fake_open_socket(int domain, int type, int protocol)
+{
+ (void)domain;
+ (void)type;
+ (void)protocol;
+
+ return FAKE_SOCKET_FD;
+}
+
+static int last_connected_socket_fd = 0;
+
+static int connect_retval = 0;
+
+static tor_socket_t
+pretend_to_connect(tor_socket_t socket, const struct sockaddr *address,
+ socklen_t address_len)
+{
+ (void)address;
+ (void)address_len;
+
+ last_connected_socket_fd = socket;
+
+ return connect_retval;
+}
+
+static struct sockaddr *mock_addr = NULL;
+
+static int
+fake_getsockname(tor_socket_t socket, struct sockaddr *address,
+ socklen_t *address_len)
+{
+ socklen_t bytes_to_copy = 0;
+ (void) socket;
+
+ if (!mock_addr)
+ return -1;
+
+ if (mock_addr->sa_family == AF_INET) {
+ bytes_to_copy = sizeof(struct sockaddr_in);
+ } else if (mock_addr->sa_family == AF_INET6) {
+ bytes_to_copy = sizeof(struct sockaddr_in6);
+ } else {
+ return -1;
+ }
+
+ if (*address_len < bytes_to_copy) {
+ return -1;
+ }
+
+ memcpy(address,mock_addr,bytes_to_copy);
+ *address_len = bytes_to_copy;
+
+ return 0;
+}
+
+static void
+test_address_udp_socket_trick_whitebox(void *arg)
+{
+ int hack_retval;
+ tor_addr_t *addr_from_hack = tor_malloc_zero(sizeof(tor_addr_t));
+ struct sockaddr_in6 *mock_addr6;
+ struct sockaddr_in6 *ipv6_to_check =
+ tor_malloc_zero(sizeof(struct sockaddr_in6));
+
+ (void)arg;
+
+ MOCK(tor_open_socket,fake_open_socket);
+ MOCK(tor_connect_socket,pretend_to_connect);
+ MOCK(tor_getsockname,fake_getsockname);
+
+ mock_addr = tor_malloc_zero(sizeof(struct sockaddr_storage));
+ sockaddr_in_from_string("23.32.246.118",(struct sockaddr_in *)mock_addr);
+
+ hack_retval =
+ get_interface_address6_via_udp_socket_hack(LOG_DEBUG,
+ AF_INET, addr_from_hack);
+
+ tt_int_op(hack_retval,==,0);
+ tt_assert(tor_addr_eq_ipv4h(addr_from_hack, 0x1720f676));
+
+ /* Now, lets do an IPv6 case. */
+ memset(mock_addr,0,sizeof(struct sockaddr_storage));
+
+ mock_addr6 = (struct sockaddr_in6 *)mock_addr;
+ mock_addr6->sin6_family = AF_INET6;
+ mock_addr6->sin6_port = 0;
+ tor_inet_pton(AF_INET6,"2001:cdba::3257:9652",&(mock_addr6->sin6_addr));
+
+ hack_retval =
+ get_interface_address6_via_udp_socket_hack(LOG_DEBUG,
+ AF_INET6, addr_from_hack);
+
+ tt_int_op(hack_retval,==,0);
+
+ tor_addr_to_sockaddr(addr_from_hack,0,(struct sockaddr *)ipv6_to_check,
+ sizeof(struct sockaddr_in6));
+
+ tt_assert(sockaddr_in6_are_equal(mock_addr6,ipv6_to_check));
+
+ UNMOCK(tor_open_socket);
+ UNMOCK(tor_connect_socket);
+ UNMOCK(tor_getsockname);
+
+ done:
+ tor_free(ipv6_to_check);
+ tor_free(mock_addr);
+ tor_free(addr_from_hack);
+ return;
+}
+
+static void
+test_address_udp_socket_trick_blackbox(void *arg)
+{
+ /* We want get_interface_address6_via_udp_socket_hack() to yield
+ * the same valid address that get_interface_address6() returns.
+ * If the latter is unable to find a valid address, we want
+ * _hack() to fail and return-1.
+ *
+ * Furthermore, we want _hack() never to crash, even if
+ * get_interface_addresses_raw() is returning NULL.
+ */
+
+ tor_addr_t addr4;
+ tor_addr_t addr4_to_check;
+ tor_addr_t addr6;
+ tor_addr_t addr6_to_check;
+ int retval, retval_reference;
+
+ (void)arg;
+
+#if 0
+ retval_reference = get_interface_address6(LOG_DEBUG,AF_INET,&addr4);
+ retval = get_interface_address6_via_udp_socket_hack(LOG_DEBUG,
+ AF_INET,
+ &addr4_to_check);
+
+ tt_int_op(retval,==,retval_reference);
+ tt_assert( (retval == -1 && retval_reference == -1) ||
+ (tor_addr_compare(&addr4,&addr4_to_check,CMP_EXACT) == 0) );
+
+ retval_reference = get_interface_address6(LOG_DEBUG,AF_INET6,&addr6);
+ retval = get_interface_address6_via_udp_socket_hack(LOG_DEBUG,
+ AF_INET6,
+ &addr6_to_check);
+
+ tt_int_op(retval,==,retval_reference);
+ tt_assert( (retval == -1 && retval_reference == -1) ||
+ (tor_addr_compare(&addr6,&addr6_to_check,CMP_EXACT) == 0) );
+
+#else
+ /* Both of the blackbox test cases fail horribly if:
+ * * The host has no external addreses.
+ * * There are multiple interfaces with either AF_INET or AF_INET6.
+ * * The last address isn't the one associated with the default route.
+ *
+ * The tests SHOULD be re-enabled when #12377 is fixed correctly, but till
+ * then this fails a lot, in situations we expect failures due to knowing
+ * about the code being broken.
+ */
+
+ (void)addr4_to_check;
+ (void)addr6_to_check;
+ (void)addr6;
+ (void) retval_reference;
+#endif
+
+ /* When family is neither AF_INET nor AF_INET6, we want _hack to
+ * fail and return -1.
+ */
+
+ retval = get_interface_address6_via_udp_socket_hack(LOG_DEBUG,
+ AF_INET+AF_INET6,&addr4);
+
+ tt_assert(retval == -1);
+
+ done:
+ return;
+}
+
+static void
+test_address_get_if_addrs_list_internal(void *arg)
+{
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_address_list(LOG_ERR, 1);
+
+ tt_assert(results != NULL);
+ /* When the network is down, a system might not have any non-local
+ * non-multicast addresseses, not even internal ones.
+ * Unit tests shouldn't fail because of this. */
+ tt_int_op(smartlist_len(results),>=,0);
+
+ tt_assert(!smartlist_contains_localhost_tor_addr(results));
+ tt_assert(!smartlist_contains_multicast_tor_addr(results));
+ /* The list may or may not contain internal addresses */
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* if there are any addresses, they must be IPv4 */
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv4_tor_addr(results));
+ }
+ tt_assert(!smartlist_contains_ipv6_tor_addr(results));
+
+ done:
+ free_interface_address_list(results);
+ return;
+}
+
+static void
+test_address_get_if_addrs_list_no_internal(void *arg)
+{
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_address_list(LOG_ERR, 0);
+
+ tt_assert(results != NULL);
+ /* Work even on systems with only internal IPv4 addresses */
+ tt_int_op(smartlist_len(results),>=,0);
+
+ tt_assert(!smartlist_contains_localhost_tor_addr(results));
+ tt_assert(!smartlist_contains_multicast_tor_addr(results));
+ tt_assert(!smartlist_contains_internal_tor_addr(results));
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* if there are any addresses, they must be IPv4 */
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv4_tor_addr(results));
+ }
+ tt_assert(!smartlist_contains_ipv6_tor_addr(results));
+
+ done:
+ free_interface_address_list(results);
+ return;
+}
+
+static void
+test_address_get_if_addrs6_list_internal(void *arg)
+{
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_address6_list(LOG_ERR, AF_INET6, 1);
+
+ tt_assert(results != NULL);
+ /* Work even on systems without IPv6 interfaces */
+ tt_int_op(smartlist_len(results),>=,0);
+
+ tt_assert(!smartlist_contains_localhost_tor_addr(results));
+ tt_assert(!smartlist_contains_multicast_tor_addr(results));
+ /* The list may or may not contain internal addresses */
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* if there are any addresses, they must be IPv6 */
+ tt_assert(!smartlist_contains_ipv4_tor_addr(results));
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv6_tor_addr(results));
+ }
+
+ done:
+ free_interface_address6_list(results);
+ return;
+}
+
+static void
+test_address_get_if_addrs6_list_no_internal(void *arg)
+{
+ smartlist_t *results = NULL;
+
+ (void)arg;
+
+ results = get_interface_address6_list(LOG_ERR, AF_INET6, 0);
+
+ tt_assert(results != NULL);
+ /* Work even on systems without IPv6 interfaces */
+ tt_int_op(smartlist_len(results),>=,0);
+
+ tt_assert(!smartlist_contains_localhost_tor_addr(results));
+ tt_assert(!smartlist_contains_multicast_tor_addr(results));
+ tt_assert(!smartlist_contains_internal_tor_addr(results));
+ tt_assert(!smartlist_contains_null_tor_addr(results));
+
+ /* if there are any addresses, they must be IPv6 */
+ tt_assert(!smartlist_contains_ipv4_tor_addr(results));
+ if (smartlist_len(results) > 0) {
+ tt_assert(smartlist_contains_ipv6_tor_addr(results));
+ }
+
+ done:
+ free_interface_address6_list(results);
+ return;
+}
+
+static int called_get_interface_addresses_raw = 0;
+
+static smartlist_t *
+mock_get_interface_addresses_raw_fail(int severity, sa_family_t family)
+{
+ (void)severity;
+ (void)family;
+
+ called_get_interface_addresses_raw++;
+ return smartlist_new();
+}
+
+static int called_get_interface_address6_via_udp_socket_hack = 0;
+
+static int
+mock_get_interface_address6_via_udp_socket_hack_fail(int severity,
+ sa_family_t family,
+ tor_addr_t *addr)
+{
+ (void)severity;
+ (void)family;
+ (void)addr;
+
+ called_get_interface_address6_via_udp_socket_hack++;
+ return -1;
+}
+
+static void
+test_address_get_if_addrs_internal_fail(void *arg)
+{
+ smartlist_t *results1 = NULL, *results2 = NULL;
+ int rv = 0;
+ uint32_t ipv4h_addr = 0;
+ tor_addr_t ipv6_addr;
+
+ memset(&ipv6_addr, 0, sizeof(tor_addr_t));
+
+ (void)arg;
+
+ MOCK(get_interface_addresses_raw,
+ mock_get_interface_addresses_raw_fail);
+ MOCK(get_interface_address6_via_udp_socket_hack,
+ mock_get_interface_address6_via_udp_socket_hack_fail);
+
+ results1 = get_interface_address6_list(LOG_ERR, AF_INET6, 1);
+ tt_assert(results1 != NULL);
+ tt_int_op(smartlist_len(results1),==,0);
+
+ results2 = get_interface_address_list(LOG_ERR, 1);
+ tt_assert(results2 != NULL);
+ tt_int_op(smartlist_len(results2),==,0);
+
+ rv = get_interface_address6(LOG_ERR, AF_INET6, &ipv6_addr);
+ tt_assert(rv == -1);
+
+ rv = get_interface_address(LOG_ERR, &ipv4h_addr);
+ tt_assert(rv == -1);
+
+ done:
+ UNMOCK(get_interface_addresses_raw);
+ UNMOCK(get_interface_address6_via_udp_socket_hack);
+ free_interface_address6_list(results1);
+ free_interface_address6_list(results2);
+ return;
+}
+
+static void
+test_address_get_if_addrs_no_internal_fail(void *arg)
+{
+ smartlist_t *results1 = NULL, *results2 = NULL;
+
+ (void)arg;
+
+ MOCK(get_interface_addresses_raw,
+ mock_get_interface_addresses_raw_fail);
+ MOCK(get_interface_address6_via_udp_socket_hack,
+ mock_get_interface_address6_via_udp_socket_hack_fail);
+
+ results1 = get_interface_address6_list(LOG_ERR, AF_INET6, 0);
+ tt_assert(results1 != NULL);
+ tt_int_op(smartlist_len(results1),==,0);
+
+ results2 = get_interface_address_list(LOG_ERR, 0);
+ tt_assert(results2 != NULL);
+ tt_int_op(smartlist_len(results2),==,0);
+
+ done:
+ UNMOCK(get_interface_addresses_raw);
+ UNMOCK(get_interface_address6_via_udp_socket_hack);
+ free_interface_address6_list(results1);
+ free_interface_address6_list(results2);
+ return;
+}
+
+static void
+test_address_get_if_addrs(void *arg)
+{
+ int rv;
+ uint32_t addr_h = 0;
+ tor_addr_t tor_addr;
+
+ (void)arg;
+
+ rv = get_interface_address(LOG_ERR, &addr_h);
+
+ /* When the network is down, a system might not have any non-local
+ * non-multicast IPv4 addresses, not even internal ones.
+ * Unit tests shouldn't fail because of this. */
+ if (rv == 0) {
+ tor_addr_from_ipv4h(&tor_addr, addr_h);
+
+ tt_assert(!tor_addr_is_loopback(&tor_addr));
+ tt_assert(!tor_addr_is_multicast(&tor_addr));
+ /* The address may or may not be an internal address */
+
+ tt_assert(tor_addr_is_v4(&tor_addr));
+ }
+
+ done:
+ return;
+}
+
+static void
+test_address_get_if_addrs6(void *arg)
+{
+ int rv;
+ tor_addr_t tor_addr;
+
+ (void)arg;
+
+ rv = get_interface_address6(LOG_ERR, AF_INET6, &tor_addr);
+
+ /* Work even on systems without IPv6 interfaces */
+ if (rv == 0) {
+ tt_assert(!tor_addr_is_loopback(&tor_addr));
+ tt_assert(!tor_addr_is_multicast(&tor_addr));
+ /* The address may or may not be an internal address */
+
+ tt_assert(!tor_addr_is_v4(&tor_addr));
+ }
+
+ done:
+ return;
+}
+
+static void
+test_address_tor_addr_to_in6(void *ignored)
+{
+ (void)ignored;
+ tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
+ const struct in6_addr *res;
+ uint8_t expected[16] = {42, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15};
+
+ a->family = AF_INET;
+ res = tor_addr_to_in6(a);
+ tt_assert(!res);
+
+ a->family = AF_INET6;
+ memcpy(a->addr.in6_addr.s6_addr, expected, 16);
+ res = tor_addr_to_in6(a);
+ tt_assert(res);
+ tt_mem_op(res->s6_addr, OP_EQ, expected, 16);
+
+ done:
+ tor_free(a);
+}
+
+static void
+test_address_tor_addr_to_in(void *ignored)
+{
+ (void)ignored;
+ tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
+ const struct in_addr *res;
+
+ a->family = AF_INET6;
+ res = tor_addr_to_in(a);
+ tt_assert(!res);
+
+ a->family = AF_INET;
+ a->addr.in_addr.s_addr = 44;
+ res = tor_addr_to_in(a);
+ tt_assert(res);
+ tt_int_op(res->s_addr, OP_EQ, 44);
+
+ done:
+ tor_free(a);
+}
+
+static void
+test_address_tor_addr_to_ipv4n(void *ignored)
+{
+ (void)ignored;
+ tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
+ uint32_t res;
+
+ a->family = AF_INET6;
+ res = tor_addr_to_ipv4n(a);
+ tt_assert(!res);
+
+ a->family = AF_INET;
+ a->addr.in_addr.s_addr = 43;
+ res = tor_addr_to_ipv4n(a);
+ tt_assert(res);
+ tt_int_op(res, OP_EQ, 43);
+
+ done:
+ tor_free(a);
+}
+
+static void
+test_address_tor_addr_to_mapped_ipv4h(void *ignored)
+{
+ (void)ignored;
+ tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
+ uint32_t res;
+ uint8_t toset[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 42};
+
+ a->family = AF_INET;
+ res = tor_addr_to_mapped_ipv4h(a);
+ tt_assert(!res);
+
+ a->family = AF_INET6;
+
+ memcpy(a->addr.in6_addr.s6_addr, toset, 16);
+ res = tor_addr_to_mapped_ipv4h(a);
+ tt_assert(res);
+ tt_int_op(res, OP_EQ, 42);
+
+ done:
+ tor_free(a);
+}
+
+static void
+test_address_tor_addr_eq_ipv4h(void *ignored)
+{
+ (void)ignored;
+ tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
+ int res;
+
+ a->family = AF_INET6;
+ res = tor_addr_eq_ipv4h(a, 42);
+ tt_assert(!res);
+
+ a->family = AF_INET;
+ a->addr.in_addr.s_addr = 52;
+ res = tor_addr_eq_ipv4h(a, 42);
+ tt_assert(!res);
+
+ a->addr.in_addr.s_addr = 52;
+ res = tor_addr_eq_ipv4h(a, ntohl(52));
+ tt_assert(res);
+
+ done:
+ tor_free(a);
+}
+
+#define ADDRESS_TEST(name, flags) \
+ { #name, test_address_ ## name, flags, NULL, NULL }
+
+struct testcase_t address_tests[] = {
+ ADDRESS_TEST(udp_socket_trick_whitebox, TT_FORK),
+ ADDRESS_TEST(udp_socket_trick_blackbox, TT_FORK),
+ ADDRESS_TEST(get_if_addrs_list_internal, 0),
+ ADDRESS_TEST(get_if_addrs_list_no_internal, 0),
+ ADDRESS_TEST(get_if_addrs6_list_internal, 0),
+ ADDRESS_TEST(get_if_addrs6_list_no_internal, 0),
+ ADDRESS_TEST(get_if_addrs_internal_fail, 0),
+ ADDRESS_TEST(get_if_addrs_no_internal_fail, 0),
+ ADDRESS_TEST(get_if_addrs, 0),
+ ADDRESS_TEST(get_if_addrs6, 0),
+#ifdef HAVE_IFADDRS_TO_SMARTLIST
+ ADDRESS_TEST(get_if_addrs_ifaddrs, TT_FORK),
+ ADDRESS_TEST(ifaddrs_to_smartlist, 0),
+#endif
+#ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
+ ADDRESS_TEST(get_if_addrs_win32, TT_FORK),
+ ADDRESS_TEST(ip_adapter_addresses_to_smartlist, 0),
+#endif
+#ifdef HAVE_IFCONF_TO_SMARTLIST
+ ADDRESS_TEST(get_if_addrs_ioctl, TT_FORK),
+ ADDRESS_TEST(ifreq_to_smartlist, 0),
+#endif
+ ADDRESS_TEST(tor_addr_to_in6, 0),
+ ADDRESS_TEST(tor_addr_to_in, 0),
+ ADDRESS_TEST(tor_addr_to_ipv4n, 0),
+ ADDRESS_TEST(tor_addr_to_mapped_ipv4h, 0),
+ ADDRESS_TEST(tor_addr_eq_ipv4h, 0),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_bt.sh b/src/test/test_bt.sh
new file mode 100755
index 0000000000..033acac955
--- /dev/null
+++ b/src/test/test_bt.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Test backtrace functionality.
+
+exitcode=0
+
+"${builddir:-.}/src/test/test-bt-cl" backtraces || exit $?
+"${builddir:-.}/src/test/test-bt-cl" assert | "${PYTHON:-python}" "${abs_top_srcdir:-.}/src/test/bt_test.py" || exitcode="$?"
+"${builddir:-.}/src/test/test-bt-cl" crash | "${PYTHON:-python}" "${abs_top_srcdir:-.}/src/test/bt_test.py" || exitcode="$?"
+
+exit ${exitcode}
diff --git a/src/test/test_bt_cl.c b/src/test/test_bt_cl.c
index 45ae82fb85..2f5e50fbf5 100644
--- a/src/test/test_bt_cl.c
+++ b/src/test/test_bt_cl.c
@@ -1,10 +1,12 @@
-/* Copyright (c) 2012-2013, The Tor Project, Inc. */
+/* Copyright (c) 2012-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
#include <stdio.h>
#include <stdlib.h>
+/* To prevent 'assert' from going away. */
+#undef TOR_COVERAGE
#include "or.h"
#include "util.h"
#include "backtrace.h"
@@ -30,7 +32,12 @@ int
crash(int x)
{
if (crashtype == 0) {
+#if defined(__clang_analyzer__) || defined(__COVERITY__)
+ tor_assert(1 == 0); /* Avert your eyes, clangalyzer and coverity! You
+ * don't need to see us dereference NULL. */
+#else
*(volatile int *)0 = 0;
+#endif
} else if (crashtype == 1) {
tor_assert(1 == 0);
} else if (crashtype == -1) {
@@ -77,21 +84,30 @@ main(int argc, char **argv)
if (argc < 2) {
puts("I take an argument. It should be \"assert\" or \"crash\" or "
- "\"none\"");
+ "\"backtraces\" or \"none\"");
return 1;
}
+
+#if !(defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE) && \
+ defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_SIGACTION))
+ puts("Backtrace reporting is not supported on this platform");
+ return 77;
+#endif
+
if (!strcmp(argv[1], "assert")) {
crashtype = 1;
} else if (!strcmp(argv[1], "crash")) {
crashtype = 0;
} else if (!strcmp(argv[1], "none")) {
crashtype = -1;
+ } else if (!strcmp(argv[1], "backtraces")) {
+ return 0;
} else {
puts("Argument should be \"assert\" or \"crash\" or \"none\"");
return 1;
}
- init_logging();
+ init_logging(1);
set_log_severity_config(LOG_WARN, LOG_ERR, &severity);
add_stream_log(&severity, "stdout", STDOUT_FILENO);
tor_log_update_sigsafe_err_fds();
@@ -103,6 +119,7 @@ main(int argc, char **argv)
printf("%d\n", we_weave(2));
clean_up_backtrace_handler();
+ logs_free_all();
return 0;
}
diff --git a/src/test/test_buffers.c b/src/test/test_buffers.c
index f24b80f0b0..e5e56edf75 100644
--- a/src/test/test_buffers.c
+++ b/src/test/test_buffers.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define BUFFERS_PRIVATE
@@ -27,10 +27,10 @@ test_buffers_basic(void *arg)
* buf_new
****/
if (!(buf = buf_new()))
- test_fail();
+ TT_DIE(("Assertion failed."));
//test_eq(buf_capacity(buf), 4096);
- test_eq(buf_datalen(buf), 0);
+ tt_int_op(buf_datalen(buf),OP_EQ, 0);
/****
* General pointer frobbing
@@ -40,16 +40,16 @@ test_buffers_basic(void *arg)
}
write_to_buf(str, 256, buf);
write_to_buf(str, 256, buf);
- test_eq(buf_datalen(buf), 512);
+ tt_int_op(buf_datalen(buf),OP_EQ, 512);
fetch_from_buf(str2, 200, buf);
- test_memeq(str, str2, 200);
- test_eq(buf_datalen(buf), 312);
+ tt_mem_op(str,OP_EQ, str2, 200);
+ tt_int_op(buf_datalen(buf),OP_EQ, 312);
memset(str2, 0, sizeof(str2));
fetch_from_buf(str2, 256, buf);
- test_memeq(str+200, str2, 56);
- test_memeq(str, str2+56, 200);
- test_eq(buf_datalen(buf), 56);
+ tt_mem_op(str+200,OP_EQ, str2, 56);
+ tt_mem_op(str,OP_EQ, str2+56, 200);
+ tt_int_op(buf_datalen(buf),OP_EQ, 56);
memset(str2, 0, sizeof(str2));
/* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
* another 3584 bytes, we hit the end. */
@@ -57,16 +57,16 @@ test_buffers_basic(void *arg)
write_to_buf(str, 256, buf);
}
assert_buf_ok(buf);
- test_eq(buf_datalen(buf), 3896);
+ tt_int_op(buf_datalen(buf),OP_EQ, 3896);
fetch_from_buf(str2, 56, buf);
- test_eq(buf_datalen(buf), 3840);
- test_memeq(str+200, str2, 56);
+ tt_int_op(buf_datalen(buf),OP_EQ, 3840);
+ tt_mem_op(str+200,OP_EQ, str2, 56);
for (j=0;j<15;++j) {
memset(str2, 0, sizeof(str2));
fetch_from_buf(str2, 256, buf);
- test_memeq(str, str2, 256);
+ tt_mem_op(str,OP_EQ, str2, 256);
}
- test_eq(buf_datalen(buf), 0);
+ tt_int_op(buf_datalen(buf),OP_EQ, 0);
buf_free(buf);
buf = NULL;
@@ -76,7 +76,7 @@ test_buffers_basic(void *arg)
write_to_buf(str+1, 255, buf);
//test_eq(buf_capacity(buf), 256);
fetch_from_buf(str2, 254, buf);
- test_memeq(str+1, str2, 254);
+ tt_mem_op(str+1,OP_EQ, str2, 254);
//test_eq(buf_capacity(buf), 256);
assert_buf_ok(buf);
write_to_buf(str, 32, buf);
@@ -85,15 +85,15 @@ test_buffers_basic(void *arg)
write_to_buf(str, 256, buf);
assert_buf_ok(buf);
//test_eq(buf_capacity(buf), 512);
- test_eq(buf_datalen(buf), 33+256);
+ tt_int_op(buf_datalen(buf),OP_EQ, 33+256);
fetch_from_buf(str2, 33, buf);
- test_eq(*str2, str[255]);
+ tt_int_op(*str2,OP_EQ, str[255]);
- test_memeq(str2+1, str, 32);
+ tt_mem_op(str2+1,OP_EQ, str, 32);
//test_eq(buf_capacity(buf), 512);
- test_eq(buf_datalen(buf), 256);
+ tt_int_op(buf_datalen(buf),OP_EQ, 256);
fetch_from_buf(str2, 256, buf);
- test_memeq(str, str2, 256);
+ tt_mem_op(str,OP_EQ, str2, 256);
/* now try shrinking: case 1. */
buf_free(buf);
@@ -102,10 +102,10 @@ test_buffers_basic(void *arg)
write_to_buf(str,255, buf);
}
//test_eq(buf_capacity(buf), 33668);
- test_eq(buf_datalen(buf), 17085);
+ tt_int_op(buf_datalen(buf),OP_EQ, 17085);
for (j=0; j < 40; ++j) {
fetch_from_buf(str2, 255,buf);
- test_memeq(str2, str, 255);
+ tt_mem_op(str2,OP_EQ, str, 255);
}
/* now try shrinking: case 2. */
@@ -116,7 +116,7 @@ test_buffers_basic(void *arg)
}
for (j=0; j < 20; ++j) {
fetch_from_buf(str2, 255,buf);
- test_memeq(str2, str, 255);
+ tt_mem_op(str2,OP_EQ, str, 255);
}
for (j=0;j<80;++j) {
write_to_buf(str,255, buf);
@@ -124,7 +124,7 @@ test_buffers_basic(void *arg)
//test_eq(buf_capacity(buf),33668);
for (j=0; j < 120; ++j) {
fetch_from_buf(str2, 255,buf);
- test_memeq(str2, str, 255);
+ tt_mem_op(str2,OP_EQ, str, 255);
}
/* Move from buf to buf. */
@@ -133,27 +133,27 @@ test_buffers_basic(void *arg)
buf2 = buf_new_with_capacity(4096);
for (j=0;j<100;++j)
write_to_buf(str, 255, buf);
- test_eq(buf_datalen(buf), 25500);
+ tt_int_op(buf_datalen(buf),OP_EQ, 25500);
for (j=0;j<100;++j) {
r = 10;
move_buf_to_buf(buf2, buf, &r);
- test_eq(r, 0);
+ tt_int_op(r,OP_EQ, 0);
}
- test_eq(buf_datalen(buf), 24500);
- test_eq(buf_datalen(buf2), 1000);
+ tt_int_op(buf_datalen(buf),OP_EQ, 24500);
+ tt_int_op(buf_datalen(buf2),OP_EQ, 1000);
for (j=0;j<3;++j) {
fetch_from_buf(str2, 255, buf2);
- test_memeq(str2, str, 255);
+ tt_mem_op(str2,OP_EQ, str, 255);
}
r = 8192; /*big move*/
move_buf_to_buf(buf2, buf, &r);
- test_eq(r, 0);
+ tt_int_op(r,OP_EQ, 0);
r = 30000; /* incomplete move */
move_buf_to_buf(buf2, buf, &r);
- test_eq(r, 13692);
+ tt_int_op(r,OP_EQ, 13692);
for (j=0;j<97;++j) {
fetch_from_buf(str2, 255, buf2);
- test_memeq(str2, str, 255);
+ tt_mem_op(str2,OP_EQ, str, 255);
}
buf_free(buf);
buf_free(buf2);
@@ -163,16 +163,16 @@ test_buffers_basic(void *arg)
cp = "Testing. This is a moderately long Testing string.";
for (j = 0; cp[j]; j++)
write_to_buf(cp+j, 1, buf);
- test_eq(0, buf_find_string_offset(buf, "Testing", 7));
- test_eq(1, buf_find_string_offset(buf, "esting", 6));
- test_eq(1, buf_find_string_offset(buf, "est", 3));
- test_eq(39, buf_find_string_offset(buf, "ing str", 7));
- test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
- test_eq(32, buf_find_string_offset(buf, "ng ", 3));
- test_eq(43, buf_find_string_offset(buf, "string.", 7));
- test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
- test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
- test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
+ tt_int_op(0,OP_EQ, buf_find_string_offset(buf, "Testing", 7));
+ tt_int_op(1,OP_EQ, buf_find_string_offset(buf, "esting", 6));
+ tt_int_op(1,OP_EQ, buf_find_string_offset(buf, "est", 3));
+ tt_int_op(39,OP_EQ, buf_find_string_offset(buf, "ing str", 7));
+ tt_int_op(35,OP_EQ, buf_find_string_offset(buf, "Testing str", 11));
+ tt_int_op(32,OP_EQ, buf_find_string_offset(buf, "ng ", 3));
+ tt_int_op(43,OP_EQ, buf_find_string_offset(buf, "string.", 7));
+ tt_int_op(-1,OP_EQ, buf_find_string_offset(buf, "shrdlu", 6));
+ tt_int_op(-1,OP_EQ, buf_find_string_offset(buf, "Testing thing", 13));
+ tt_int_op(-1,OP_EQ, buf_find_string_offset(buf, "ngx", 3));
buf_free(buf);
buf = NULL;
@@ -183,7 +183,7 @@ test_buffers_basic(void *arg)
write_to_buf(cp, 65536, buf);
tor_free(cp);
- tt_int_op(buf_datalen(buf), ==, 65536);
+ tt_int_op(buf_datalen(buf), OP_EQ, 65536);
buf_free(buf);
buf = NULL;
}
@@ -193,7 +193,6 @@ test_buffers_basic(void *arg)
buf_free(buf);
if (buf2)
buf_free(buf2);
- buf_shrink_freelists(1);
}
static void
@@ -207,25 +206,22 @@ test_buffer_pullup(void *arg)
stuff = tor_malloc(16384);
tmp = tor_malloc(16384);
- /* Note: this test doesn't check the nulterminate argument to buf_pullup,
- since nothing actually uses it. We should remove it some time. */
-
buf = buf_new_with_capacity(3000); /* rounds up to next power of 2. */
tt_assert(buf);
- tt_int_op(buf_get_default_chunk_size(buf), ==, 4096);
+ tt_int_op(buf_get_default_chunk_size(buf), OP_EQ, 4096);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
/* There are a bunch of cases for pullup. One is the trivial case. Let's
mess around with an empty buffer. */
- buf_pullup(buf, 16, 1);
+ buf_pullup(buf, 16);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, ==, NULL);
- tt_uint_op(sz, ==, 0);
+ tt_ptr_op(cp, OP_EQ, NULL);
+ tt_uint_op(sz, OP_EQ, 0);
/* Let's make sure nothing got allocated */
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
/* Case 1: everything puts into the first chunk with some moving. */
@@ -234,22 +230,22 @@ test_buffer_pullup(void *arg)
write_to_buf(stuff, 3000, buf);
write_to_buf(stuff+3000, 3000, buf);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, !=, NULL);
- tt_int_op(sz, <=, 4096);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_int_op(sz, OP_LE, 4096);
/* Make room for 3000 bytes in the first chunk, so that the pullup-move code
* can get tested. */
- tt_int_op(fetch_from_buf(tmp, 3000, buf), ==, 3000);
- test_memeq(tmp, stuff, 3000);
- buf_pullup(buf, 2048, 0);
+ tt_int_op(fetch_from_buf(tmp, 3000, buf), OP_EQ, 3000);
+ tt_mem_op(tmp,OP_EQ, stuff, 3000);
+ buf_pullup(buf, 2048);
assert_buf_ok(buf);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, !=, NULL);
- tt_int_op(sz, >=, 2048);
- test_memeq(cp, stuff+3000, 2048);
- tt_int_op(3000, ==, buf_datalen(buf));
- tt_int_op(fetch_from_buf(tmp, 3000, buf), ==, 0);
- test_memeq(tmp, stuff+3000, 2048);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_int_op(sz, OP_GE, 2048);
+ tt_mem_op(cp,OP_EQ, stuff+3000, 2048);
+ tt_int_op(3000, OP_EQ, buf_datalen(buf));
+ tt_int_op(fetch_from_buf(tmp, 3000, buf), OP_EQ, 0);
+ tt_mem_op(tmp,OP_EQ, stuff+3000, 2048);
buf_free(buf);
@@ -259,26 +255,26 @@ test_buffer_pullup(void *arg)
write_to_buf(stuff+4000, 4000, buf);
write_to_buf(stuff+8000, 4000, buf);
write_to_buf(stuff+12000, 4000, buf);
- tt_int_op(buf_datalen(buf), ==, 16000);
+ tt_int_op(buf_datalen(buf), OP_EQ, 16000);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, !=, NULL);
- tt_int_op(sz, <=, 4096);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_int_op(sz, OP_LE, 4096);
- buf_pullup(buf, 12500, 0);
+ buf_pullup(buf, 12500);
assert_buf_ok(buf);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, !=, NULL);
- tt_int_op(sz, >=, 12500);
- test_memeq(cp, stuff, 12500);
- tt_int_op(buf_datalen(buf), ==, 16000);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_int_op(sz, OP_GE, 12500);
+ tt_mem_op(cp,OP_EQ, stuff, 12500);
+ tt_int_op(buf_datalen(buf), OP_EQ, 16000);
fetch_from_buf(tmp, 12400, buf);
- test_memeq(tmp, stuff, 12400);
- tt_int_op(buf_datalen(buf), ==, 3600);
+ tt_mem_op(tmp,OP_EQ, stuff, 12400);
+ tt_int_op(buf_datalen(buf), OP_EQ, 3600);
fetch_from_buf(tmp, 3500, buf);
- test_memeq(tmp, stuff+12400, 3500);
+ tt_mem_op(tmp,OP_EQ, stuff+12400, 3500);
fetch_from_buf(tmp, 100, buf);
- test_memeq(tmp, stuff+15900, 10);
+ tt_mem_op(tmp,OP_EQ, stuff+15900, 10);
buf_free(buf);
@@ -287,22 +283,19 @@ test_buffer_pullup(void *arg)
write_to_buf(stuff, 4000, buf);
write_to_buf(stuff+4000, 4000, buf);
fetch_from_buf(tmp, 100, buf); /* dump 100 bytes from first chunk */
- buf_pullup(buf, 16000, 0); /* Way too much. */
+ buf_pullup(buf, 16000); /* Way too much. */
assert_buf_ok(buf);
buf_get_first_chunk_data(buf, &cp, &sz);
- tt_ptr_op(cp, !=, NULL);
- tt_int_op(sz, ==, 7900);
- test_memeq(cp, stuff+100, 7900);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_int_op(sz, OP_EQ, 7900);
+ tt_mem_op(cp,OP_EQ, stuff+100, 7900);
buf_free(buf);
buf = NULL;
- buf_shrink_freelists(1);
-
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
done:
buf_free(buf);
- buf_shrink_freelists(1);
tor_free(stuff);
tor_free(tmp);
}
@@ -321,31 +314,31 @@ test_buffer_copy(void *arg)
tt_assert(buf);
/* Copy an empty buffer. */
- tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
+ tt_int_op(0, OP_EQ, generic_buffer_set_to_copy(&buf2, buf));
tt_assert(buf2);
- tt_int_op(0, ==, generic_buffer_len(buf2));
+ tt_int_op(0, OP_EQ, generic_buffer_len(buf2));
/* Now try with a short buffer. */
s = "And now comes an act of enormous enormance!";
len = strlen(s);
generic_buffer_add(buf, s, len);
- tt_int_op(len, ==, generic_buffer_len(buf));
+ tt_int_op(len, OP_EQ, generic_buffer_len(buf));
/* Add junk to buf2 so we can test replacing.*/
generic_buffer_add(buf2, "BLARG", 5);
- tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
- tt_int_op(len, ==, generic_buffer_len(buf2));
+ tt_int_op(0, OP_EQ, generic_buffer_set_to_copy(&buf2, buf));
+ tt_int_op(len, OP_EQ, generic_buffer_len(buf2));
generic_buffer_get(buf2, b, len);
- test_mem_op(b, ==, s, len);
+ tt_mem_op(b, OP_EQ, s, len);
/* Now free buf2 and retry so we can test allocating */
generic_buffer_free(buf2);
buf2 = NULL;
- tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
- tt_int_op(len, ==, generic_buffer_len(buf2));
+ tt_int_op(0, OP_EQ, generic_buffer_set_to_copy(&buf2, buf));
+ tt_int_op(len, OP_EQ, generic_buffer_len(buf2));
generic_buffer_get(buf2, b, len);
- test_mem_op(b, ==, s, len);
+ tt_mem_op(b, OP_EQ, s, len);
/* Clear buf for next test */
generic_buffer_get(buf, b, len);
- tt_int_op(generic_buffer_len(buf),==,0);
+ tt_int_op(generic_buffer_len(buf),OP_EQ,0);
/* Okay, now let's try a bigger buffer. */
s = "Quis autem vel eum iure reprehenderit qui in ea voluptate velit "
@@ -357,12 +350,12 @@ test_buffer_copy(void *arg)
generic_buffer_add(buf, b, 1);
generic_buffer_add(buf, s, len);
}
- tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
- tt_int_op(generic_buffer_len(buf2), ==, generic_buffer_len(buf));
+ tt_int_op(0, OP_EQ, generic_buffer_set_to_copy(&buf2, buf));
+ tt_int_op(generic_buffer_len(buf2), OP_EQ, generic_buffer_len(buf));
for (i = 0; i < 256; ++i) {
generic_buffer_get(buf2, b, len+1);
- tt_int_op((unsigned char)b[0],==,i);
- test_mem_op(b+1, ==, s, len);
+ tt_int_op((unsigned char)b[0],OP_EQ,i);
+ tt_mem_op(b+1, OP_EQ, s, len);
}
done:
@@ -370,7 +363,6 @@ test_buffer_copy(void *arg)
generic_buffer_free(buf);
if (buf2)
generic_buffer_free(buf2);
- buf_shrink_freelists(1);
}
static void
@@ -382,62 +374,62 @@ test_buffer_ext_or_cmd(void *arg)
(void) arg;
/* Empty -- should give "not there. */
- tt_int_op(0, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, ==, cmd);
+ tt_int_op(0, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_EQ, cmd);
/* Three bytes: shouldn't work. */
generic_buffer_add(buf, "\x00\x20\x00", 3);
- tt_int_op(0, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, ==, cmd);
- tt_int_op(3, ==, generic_buffer_len(buf));
+ tt_int_op(0, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_EQ, cmd);
+ tt_int_op(3, OP_EQ, generic_buffer_len(buf));
/* 0020 0000: That's a nil command. It should work. */
generic_buffer_add(buf, "\x00", 1);
- tt_int_op(1, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, !=, cmd);
- tt_int_op(0x20, ==, cmd->cmd);
- tt_int_op(0, ==, cmd->len);
- tt_int_op(0, ==, generic_buffer_len(buf));
+ tt_int_op(1, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_NE, cmd);
+ tt_int_op(0x20, OP_EQ, cmd->cmd);
+ tt_int_op(0, OP_EQ, cmd->len);
+ tt_int_op(0, OP_EQ, generic_buffer_len(buf));
ext_or_cmd_free(cmd);
cmd = NULL;
/* Now try a length-6 command with one byte missing. */
generic_buffer_add(buf, "\x10\x21\x00\x06""abcde", 9);
- tt_int_op(0, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, ==, cmd);
+ tt_int_op(0, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_EQ, cmd);
generic_buffer_add(buf, "f", 1);
- tt_int_op(1, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, !=, cmd);
- tt_int_op(0x1021, ==, cmd->cmd);
- tt_int_op(6, ==, cmd->len);
- test_mem_op("abcdef", ==, cmd->body, 6);
- tt_int_op(0, ==, generic_buffer_len(buf));
+ tt_int_op(1, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_NE, cmd);
+ tt_int_op(0x1021, OP_EQ, cmd->cmd);
+ tt_int_op(6, OP_EQ, cmd->len);
+ tt_mem_op("abcdef", OP_EQ, cmd->body, 6);
+ tt_int_op(0, OP_EQ, generic_buffer_len(buf));
ext_or_cmd_free(cmd);
cmd = NULL;
/* Now try a length-10 command with 4 extra bytes. */
generic_buffer_add(buf, "\xff\xff\x00\x0a"
"loremipsum\x10\x00\xff\xff", 18);
- tt_int_op(1, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, !=, cmd);
- tt_int_op(0xffff, ==, cmd->cmd);
- tt_int_op(10, ==, cmd->len);
- test_mem_op("loremipsum", ==, cmd->body, 10);
- tt_int_op(4, ==, generic_buffer_len(buf));
+ tt_int_op(1, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_NE, cmd);
+ tt_int_op(0xffff, OP_EQ, cmd->cmd);
+ tt_int_op(10, OP_EQ, cmd->len);
+ tt_mem_op("loremipsum", OP_EQ, cmd->body, 10);
+ tt_int_op(4, OP_EQ, generic_buffer_len(buf));
ext_or_cmd_free(cmd);
cmd = NULL;
/* Finally, let's try a maximum-length command. We already have the header
* waiting. */
- tt_int_op(0, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_int_op(0, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
tmp = tor_malloc_zero(65535);
generic_buffer_add(buf, tmp, 65535);
- tt_int_op(1, ==, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
- tt_ptr_op(NULL, !=, cmd);
- tt_int_op(0x1000, ==, cmd->cmd);
- tt_int_op(0xffff, ==, cmd->len);
- test_mem_op(tmp, ==, cmd->body, 65535);
- tt_int_op(0, ==, generic_buffer_len(buf));
+ tt_int_op(1, OP_EQ, generic_buffer_fetch_ext_or_cmd(buf, &cmd));
+ tt_ptr_op(NULL, OP_NE, cmd);
+ tt_int_op(0x1000, OP_EQ, cmd->cmd);
+ tt_int_op(0xffff, OP_EQ, cmd->len);
+ tt_mem_op(tmp, OP_EQ, cmd->body, 65535);
+ tt_int_op(0, OP_EQ, generic_buffer_len(buf));
ext_or_cmd_free(cmd);
cmd = NULL;
@@ -445,7 +437,6 @@ test_buffer_ext_or_cmd(void *arg)
ext_or_cmd_free(cmd);
generic_buffer_free(buf);
tor_free(tmp);
- buf_shrink_freelists(1);
}
static void
@@ -458,70 +449,61 @@ test_buffer_allocation_tracking(void *arg)
(void)arg;
crypto_rand(junk, 16384);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
buf1 = buf_new();
tt_assert(buf1);
buf2 = buf_new();
tt_assert(buf2);
- tt_int_op(buf_allocation(buf1), ==, 0);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_allocation(buf1), OP_EQ, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
write_to_buf(junk, 4000, buf1);
write_to_buf(junk, 4000, buf1);
write_to_buf(junk, 4000, buf1);
write_to_buf(junk, 4000, buf1);
- tt_int_op(buf_allocation(buf1), ==, 16384);
+ tt_int_op(buf_allocation(buf1), OP_EQ, 16384);
fetch_from_buf(junk, 100, buf1);
- tt_int_op(buf_allocation(buf1), ==, 16384); /* still 4 4k chunks */
+ tt_int_op(buf_allocation(buf1), OP_EQ, 16384); /* still 4 4k chunks */
- tt_int_op(buf_get_total_allocation(), ==, 16384);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 16384);
fetch_from_buf(junk, 4096, buf1); /* drop a 1k chunk... */
- tt_int_op(buf_allocation(buf1), ==, 3*4096); /* now 3 4k chunks */
+ tt_int_op(buf_allocation(buf1), OP_EQ, 3*4096); /* now 3 4k chunks */
-#ifdef ENABLE_BUF_FREELISTS
- tt_int_op(buf_get_total_allocation(), ==, 16384); /* that chunk went onto
- the freelist. */
-#else
- tt_int_op(buf_get_total_allocation(), ==, 12288); /* that chunk was really
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 12288); /* that chunk was really
freed. */
-#endif
write_to_buf(junk, 4000, buf2);
- tt_int_op(buf_allocation(buf2), ==, 4096); /* another 4k chunk. */
+ tt_int_op(buf_allocation(buf2), OP_EQ, 4096); /* another 4k chunk. */
/*
- * If we're using freelists, size stays at 16384 because we just pulled a
- * chunk from the freelist. If we aren't, we bounce back up to 16384 by
- * allocating a new chunk.
+ * We bounce back up to 16384 by allocating a new chunk.
*/
- tt_int_op(buf_get_total_allocation(), ==, 16384);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 16384);
write_to_buf(junk, 4000, buf2);
- tt_int_op(buf_allocation(buf2), ==, 8192); /* another 4k chunk. */
- tt_int_op(buf_get_total_allocation(), ==, 5*4096); /* that chunk was new. */
+ tt_int_op(buf_allocation(buf2), OP_EQ, 8192); /* another 4k chunk. */
+ tt_int_op(buf_get_total_allocation(),
+ OP_EQ, 5*4096); /* that chunk was new. */
/* Make a really huge buffer */
for (i = 0; i < 1000; ++i) {
write_to_buf(junk, 4000, buf2);
}
- tt_int_op(buf_allocation(buf2), >=, 4008000);
- tt_int_op(buf_get_total_allocation(), >=, 4008000);
+ tt_int_op(buf_allocation(buf2), OP_GE, 4008000);
+ tt_int_op(buf_get_total_allocation(), OP_GE, 4008000);
buf_free(buf2);
buf2 = NULL;
- tt_int_op(buf_get_total_allocation(), <, 4008000);
- buf_shrink_freelists(1);
- tt_int_op(buf_get_total_allocation(), ==, buf_allocation(buf1));
+ tt_int_op(buf_get_total_allocation(), OP_LT, 4008000);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, buf_allocation(buf1));
buf_free(buf1);
buf1 = NULL;
- buf_shrink_freelists(1);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
done:
buf_free(buf1);
buf_free(buf2);
- buf_shrink_freelists(1);
tor_free(junk);
}
@@ -545,37 +527,38 @@ test_buffer_time_tracking(void *arg)
tt_assert(buf);
/* Empty buffer means the timestamp is 0. */
- tt_int_op(0, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC));
- tt_int_op(0, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+1000));
+ tt_int_op(0, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC));
+ tt_int_op(0, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+1000));
tor_gettimeofday_cache_set(&tv0);
write_to_buf("ABCDEFG", 7, buf);
- tt_int_op(1000, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+1000));
+ tt_int_op(1000, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+1000));
buf2 = buf_copy(buf);
tt_assert(buf2);
- tt_int_op(1234, ==, buf_get_oldest_chunk_timestamp(buf2, START_MSEC+1234));
+ tt_int_op(1234, OP_EQ,
+ buf_get_oldest_chunk_timestamp(buf2, START_MSEC+1234));
/* Now add more bytes; enough to overflow the first chunk. */
tv0.tv_usec += 123 * 1000;
tor_gettimeofday_cache_set(&tv0);
for (i = 0; i < 600; ++i)
write_to_buf("ABCDEFG", 7, buf);
- tt_int_op(4207, ==, buf_datalen(buf));
+ tt_int_op(4207, OP_EQ, buf_datalen(buf));
/* The oldest bytes are still in the front. */
- tt_int_op(2000, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2000));
+ tt_int_op(2000, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2000));
/* Once those bytes are dropped, the chunk is still on the first
* timestamp. */
fetch_from_buf(tmp, 100, buf);
- tt_int_op(2000, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2000));
+ tt_int_op(2000, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2000));
/* But once we discard the whole first chunk, we get the data in the second
* chunk. */
fetch_from_buf(tmp, 4000, buf);
- tt_int_op(107, ==, buf_datalen(buf));
- tt_int_op(2000, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2123));
+ tt_int_op(107, OP_EQ, buf_datalen(buf));
+ tt_int_op(2000, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2123));
/* This time we'll be grabbing a chunk from the freelist, and making sure
its time gets updated */
@@ -584,13 +567,13 @@ test_buffer_time_tracking(void *arg)
tor_gettimeofday_cache_set(&tv0);
for (i = 0; i < 600; ++i)
write_to_buf("ABCDEFG", 7, buf);
- tt_int_op(4307, ==, buf_datalen(buf));
+ tt_int_op(4307, OP_EQ, buf_datalen(buf));
- tt_int_op(2000, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2123));
+ tt_int_op(2000, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+2123));
fetch_from_buf(tmp, 4000, buf);
fetch_from_buf(tmp, 306, buf);
- tt_int_op(0, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+5617));
- tt_int_op(383, ==, buf_get_oldest_chunk_timestamp(buf, START_MSEC+6000));
+ tt_int_op(0, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+5617));
+ tt_int_op(383, OP_EQ, buf_get_oldest_chunk_timestamp(buf, START_MSEC+6000));
done:
buf_free(buf);
@@ -609,35 +592,35 @@ test_buffers_zlib_impl(int finalize_with_nil)
int done;
buf = buf_new_with_capacity(128); /* will round up */
- zlib_state = tor_zlib_new(1, ZLIB_METHOD);
+ zlib_state = tor_zlib_new(1, ZLIB_METHOD, HIGH_COMPRESSION);
msg = tor_malloc(512);
crypto_rand(msg, 512);
- tt_int_op(write_to_buf_zlib(buf, zlib_state, msg, 128, 0), ==, 0);
- tt_int_op(write_to_buf_zlib(buf, zlib_state, msg+128, 128, 0), ==, 0);
- tt_int_op(write_to_buf_zlib(buf, zlib_state, msg+256, 256, 0), ==, 0);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, msg, 128, 0), OP_EQ, 0);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, msg+128, 128, 0), OP_EQ, 0);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, msg+256, 256, 0), OP_EQ, 0);
done = !finalize_with_nil;
- tt_int_op(write_to_buf_zlib(buf, zlib_state, "all done", 9, done), ==, 0);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, "all done", 9, done), OP_EQ, 0);
if (finalize_with_nil) {
- tt_int_op(write_to_buf_zlib(buf, zlib_state, "", 0, 1), ==, 0);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, "", 0, 1), OP_EQ, 0);
}
in_len = buf_datalen(buf);
contents = tor_malloc(in_len);
- tt_int_op(fetch_from_buf(contents, in_len, buf), ==, 0);
+ tt_int_op(fetch_from_buf(contents, in_len, buf), OP_EQ, 0);
- tt_int_op(0, ==, tor_gzip_uncompress(&expanded, &out_len,
+ tt_int_op(0, OP_EQ, tor_gzip_uncompress(&expanded, &out_len,
contents, in_len,
ZLIB_METHOD, 1,
LOG_WARN));
- tt_int_op(out_len, >=, 128);
- tt_mem_op(msg, ==, expanded, 128);
- tt_int_op(out_len, >=, 512);
- tt_mem_op(msg, ==, expanded, 512);
- tt_int_op(out_len, ==, 512+9);
- tt_mem_op("all done", ==, expanded+512, 9);
+ tt_int_op(out_len, OP_GE, 128);
+ tt_mem_op(msg, OP_EQ, expanded, 128);
+ tt_int_op(out_len, OP_GE, 512);
+ tt_mem_op(msg, OP_EQ, expanded, 512);
+ tt_int_op(out_len, OP_EQ, 512+9);
+ tt_mem_op("all done", OP_EQ, expanded+512, 9);
done:
buf_free(buf);
@@ -680,28 +663,28 @@ test_buffers_zlib_fin_at_chunk_end(void *arg)
tt_assert(buf->head);
/* Fill up the chunk so the zlib stuff won't fit in one chunk. */
- tt_uint_op(buf->head->memlen, <, sz);
+ tt_uint_op(buf->head->memlen, OP_LT, sz);
headerjunk = buf->head->memlen - 7;
write_to_buf(msg, headerjunk-1, buf);
- tt_uint_op(buf->head->datalen, ==, headerjunk);
- tt_uint_op(buf_datalen(buf), ==, headerjunk);
+ tt_uint_op(buf->head->datalen, OP_EQ, headerjunk);
+ tt_uint_op(buf_datalen(buf), OP_EQ, headerjunk);
/* Write an empty string, with finalization on. */
- zlib_state = tor_zlib_new(1, ZLIB_METHOD);
- tt_int_op(write_to_buf_zlib(buf, zlib_state, "", 0, 1), ==, 0);
+ zlib_state = tor_zlib_new(1, ZLIB_METHOD, HIGH_COMPRESSION);
+ tt_int_op(write_to_buf_zlib(buf, zlib_state, "", 0, 1), OP_EQ, 0);
in_len = buf_datalen(buf);
contents = tor_malloc(in_len);
- tt_int_op(fetch_from_buf(contents, in_len, buf), ==, 0);
+ tt_int_op(fetch_from_buf(contents, in_len, buf), OP_EQ, 0);
- tt_uint_op(in_len, >, headerjunk);
+ tt_uint_op(in_len, OP_GT, headerjunk);
- tt_int_op(0, ==, tor_gzip_uncompress(&expanded, &out_len,
+ tt_int_op(0, OP_EQ, tor_gzip_uncompress(&expanded, &out_len,
contents + headerjunk, in_len - headerjunk,
ZLIB_METHOD, 1,
LOG_WARN));
- tt_int_op(out_len, ==, 0);
+ tt_int_op(out_len, OP_EQ, 0);
tt_assert(expanded);
done:
@@ -712,6 +695,58 @@ test_buffers_zlib_fin_at_chunk_end(void *arg)
tor_free(msg);
}
+const uint8_t *tls_read_ptr;
+int n_remaining;
+int next_reply_val[16];
+
+static int
+mock_tls_read(tor_tls_t *tls, char *cp, size_t len)
+{
+ (void)tls;
+ int rv = next_reply_val[0];
+ if (rv > 0) {
+ int max = rv > (int)len ? (int)len : rv;
+ if (max > n_remaining)
+ max = n_remaining;
+ memcpy(cp, tls_read_ptr, max);
+ rv = max;
+ n_remaining -= max;
+ tls_read_ptr += max;
+ }
+
+ memmove(next_reply_val, next_reply_val + 1, 15*sizeof(int));
+ return rv;
+}
+
+static void
+test_buffers_tls_read_mocked(void *arg)
+{
+ uint8_t *mem;
+ buf_t *buf;
+ (void)arg;
+
+ mem = tor_malloc(64*1024);
+ crypto_rand((char*)mem, 64*1024);
+ tls_read_ptr = mem;
+ n_remaining = 64*1024;
+
+ MOCK(tor_tls_read, mock_tls_read);
+
+ buf = buf_new();
+
+ next_reply_val[0] = 1024;
+ tt_int_op(128, ==, read_to_buf_tls(NULL, 128, buf));
+
+ next_reply_val[0] = 5000;
+ next_reply_val[1] = 5000;
+ tt_int_op(6000, ==, read_to_buf_tls(NULL, 6000, buf));
+
+ done:
+ UNMOCK(tor_tls_read);
+ tor_free(mem);
+ buf_free(buf);
+}
+
struct testcase_t buffer_tests[] = {
{ "basic", test_buffers_basic, TT_FORK, NULL, NULL },
{ "copy", test_buffer_copy, TT_FORK, NULL, NULL },
@@ -724,6 +759,8 @@ struct testcase_t buffer_tests[] = {
{ "zlib_fin_with_nil", test_buffers_zlib_fin_with_nil, TT_FORK, NULL, NULL },
{ "zlib_fin_at_chunk_end", test_buffers_zlib_fin_at_chunk_end, TT_FORK,
NULL, NULL},
+ { "tls_read_mocked", test_buffers_tls_read_mocked, 0,
+ NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_cell_formats.c b/src/test/test_cell_formats.c
index d7f60680c2..499a637959 100644
--- a/src/test/test_cell_formats.c
+++ b/src/test/test_cell_formats.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -30,16 +30,16 @@ test_cfmt_relay_header(void *arg)
uint8_t hdr_out[RELAY_HEADER_SIZE];
(void)arg;
- tt_int_op(sizeof(hdr_1), ==, RELAY_HEADER_SIZE);
+ tt_int_op(sizeof(hdr_1), OP_EQ, RELAY_HEADER_SIZE);
relay_header_unpack(&rh, hdr_1);
- tt_int_op(rh.command, ==, 3);
- tt_int_op(rh.recognized, ==, 0);
- tt_int_op(rh.stream_id, ==, 0x2122);
- test_mem_op(rh.integrity, ==, "ABCD", 4);
- tt_int_op(rh.length, ==, 0x103);
+ tt_int_op(rh.command, OP_EQ, 3);
+ tt_int_op(rh.recognized, OP_EQ, 0);
+ tt_int_op(rh.stream_id, OP_EQ, 0x2122);
+ tt_mem_op(rh.integrity, OP_EQ, "ABCD", 4);
+ tt_int_op(rh.length, OP_EQ, 0x103);
relay_header_pack(hdr_out, &rh);
- test_mem_op(hdr_out, ==, hdr_1, RELAY_HEADER_SIZE);
+ tt_mem_op(hdr_out, OP_EQ, hdr_1, RELAY_HEADER_SIZE);
done:
;
@@ -74,32 +74,32 @@ test_cfmt_begin_cells(void *arg)
/* Try begindir. */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN_DIR, "", 0);
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_ptr_op(NULL, ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(0, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(1, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_ptr_op(NULL, OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(0, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(1, OP_EQ, bcell.is_begindir);
/* A Begindir with extra stuff. */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN_DIR, "12345", 5);
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_ptr_op(NULL, ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(0, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(1, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_ptr_op(NULL, OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(0, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(1, OP_EQ, bcell.is_begindir);
/* A short but valid begin cell */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b:9", 6);
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("a.b", ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(9, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("a.b", OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(9, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* A significantly loner begin cell */
@@ -108,35 +108,35 @@ test_cfmt_begin_cells(void *arg)
const char c[] = "here-is-a-nice-long.hostname.com:65535";
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, c, strlen(c)+1);
}
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("here-is-a-nice-long.hostname.com", ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(65535, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("here-is-a-nice-long.hostname.com", OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(65535, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* An IPv4 begin cell. */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "18.9.22.169:80", 15);
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("18.9.22.169", ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(80, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("18.9.22.169", OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(80, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* An IPv6 begin cell. Let's make sure we handle colons*/
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN,
"[2620::6b0:b:1a1a:0:26e5:480e]:80", 34);
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("[2620::6b0:b:1a1a:0:26e5:480e]", ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(80, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("[2620::6b0:b:1a1a:0:26e5:480e]", OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(80, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* a begin cell with extra junk but not enough for flags. */
@@ -145,12 +145,12 @@ test_cfmt_begin_cells(void *arg)
const char c[] = "another.example.com:80\x00\x01\x02";
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, c, sizeof(c)-1);
}
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("another.example.com", ==, bcell.address);
- tt_int_op(0, ==, bcell.flags);
- tt_int_op(80, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("another.example.com", OP_EQ, bcell.address);
+ tt_int_op(0, OP_EQ, bcell.flags);
+ tt_int_op(80, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* a begin cell with flags. */
@@ -159,12 +159,12 @@ test_cfmt_begin_cells(void *arg)
const char c[] = "another.example.com:443\x00\x01\x02\x03\x04";
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, c, sizeof(c)-1);
}
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("another.example.com", ==, bcell.address);
- tt_int_op(0x1020304, ==, bcell.flags);
- tt_int_op(443, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("another.example.com", OP_EQ, bcell.address);
+ tt_int_op(0x1020304, OP_EQ, bcell.flags);
+ tt_int_op(443, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* a begin cell with flags and even more cruft after that. */
@@ -173,12 +173,12 @@ test_cfmt_begin_cells(void *arg)
const char c[] = "a-further.example.com:22\x00\xee\xaa\x00\xffHi mom";
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, c, sizeof(c)-1);
}
- tt_int_op(0, ==, begin_cell_parse(&cell, &bcell, &end_reason));
- tt_str_op("a-further.example.com", ==, bcell.address);
- tt_int_op(0xeeaa00ff, ==, bcell.flags);
- tt_int_op(22, ==, bcell.port);
- tt_int_op(5, ==, bcell.stream_id);
- tt_int_op(0, ==, bcell.is_begindir);
+ tt_int_op(0, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_str_op("a-further.example.com", OP_EQ, bcell.address);
+ tt_int_op(0xeeaa00ff, OP_EQ, bcell.flags);
+ tt_int_op(22, OP_EQ, bcell.port);
+ tt_int_op(5, OP_EQ, bcell.stream_id);
+ tt_int_op(0, OP_EQ, bcell.is_begindir);
tor_free(bcell.address);
/* bad begin cell: impossible length. */
@@ -189,42 +189,42 @@ test_cfmt_begin_cells(void *arg)
{
relay_header_t rh;
relay_header_unpack(&rh, cell.payload);
- tt_int_op(rh.length, ==, 510);
+ tt_int_op(rh.length, OP_EQ, 510);
}
- tt_int_op(-2, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-2, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* Bad begin cell: no body. */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "", 0);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* bad begin cell: no body. */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "", 0);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* bad begin cell: no colon */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b", 4);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* bad begin cell: no ports */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b:", 5);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* bad begin cell: bad port */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b:xyz", 8);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b:100000", 11);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
/* bad begin cell: no nul */
memset(&bcell, 0x7f, sizeof(bcell));
make_relay_cell(&cell, RELAY_COMMAND_BEGIN, "a.b:80", 6);
- tt_int_op(-1, ==, begin_cell_parse(&cell, &bcell, &end_reason));
+ tt_int_op(-1, OP_EQ, begin_cell_parse(&cell, &bcell, &end_reason));
done:
tor_free(bcell.address);
@@ -244,47 +244,47 @@ test_cfmt_connected_cells(void *arg)
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED, "", 0);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_UNSPEC);
- tt_int_op(ttl, ==, -1);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_UNSPEC);
+ tt_int_op(ttl, OP_EQ, -1);
/* A slightly less oldschool one: only an IPv4 address */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED, "\x20\x30\x40\x50", 4);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET);
- tt_str_op(fmt_addr(&addr), ==, "32.48.64.80");
- tt_int_op(ttl, ==, -1);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "32.48.64.80");
+ tt_int_op(ttl, OP_EQ, -1);
/* Bogus but understandable: truncated TTL */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED, "\x11\x12\x13\x14\x15", 5);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET);
- tt_str_op(fmt_addr(&addr), ==, "17.18.19.20");
- tt_int_op(ttl, ==, -1);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "17.18.19.20");
+ tt_int_op(ttl, OP_EQ, -1);
/* Regular IPv4 one: address and TTL */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
"\x02\x03\x04\x05\x00\x00\x0e\x10", 8);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET);
- tt_str_op(fmt_addr(&addr), ==, "2.3.4.5");
- tt_int_op(ttl, ==, 3600);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "2.3.4.5");
+ tt_int_op(ttl, OP_EQ, 3600);
/* IPv4 with too-big TTL */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
"\x02\x03\x04\x05\xf0\x00\x00\x00", 8);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET);
- tt_str_op(fmt_addr(&addr), ==, "2.3.4.5");
- tt_int_op(ttl, ==, -1);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "2.3.4.5");
+ tt_int_op(ttl, OP_EQ, -1);
/* IPv6 (ttl is mandatory) */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
@@ -294,10 +294,10 @@ test_cfmt_connected_cells(void *arg)
"\x00\x00\x02\x58", 25);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET6);
- tt_str_op(fmt_addr(&addr), ==, "2607:f8b0:400c:c02::68");
- tt_int_op(ttl, ==, 600);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET6);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "2607:f8b0:400c:c02::68");
+ tt_int_op(ttl, OP_EQ, 600);
/* IPv6 (ttl too big) */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
@@ -307,17 +307,17 @@ test_cfmt_connected_cells(void *arg)
"\x90\x00\x02\x58", 25);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET6);
- tt_str_op(fmt_addr(&addr), ==, "2607:f8b0:400c:c02::68");
- tt_int_op(ttl, ==, -1);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET6);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "2607:f8b0:400c:c02::68");
+ tt_int_op(ttl, OP_EQ, -1);
/* Bogus size: 3. */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
"\x00\x01\x02", 3);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, -1);
+ tt_int_op(r, OP_EQ, -1);
/* Bogus family: 7. */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
@@ -327,7 +327,7 @@ test_cfmt_connected_cells(void *arg)
"\x90\x00\x02\x58", 25);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, -1);
+ tt_int_op(r, OP_EQ, -1);
/* Truncated IPv6. */
make_relay_cell(&cell, RELAY_COMMAND_CONNECTED,
@@ -337,7 +337,7 @@ test_cfmt_connected_cells(void *arg)
"\x00\x00\x02", 24);
relay_header_unpack(&rh, cell.payload);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, -1);
+ tt_int_op(r, OP_EQ, -1);
/* Now make sure we can generate connected cells correctly. */
/* Try an IPv4 address */
@@ -346,16 +346,16 @@ test_cfmt_connected_cells(void *arg)
tor_addr_parse(&addr, "30.40.50.60");
rh.length = connected_cell_format_payload(cell.payload+RELAY_HEADER_SIZE,
&addr, 128);
- tt_int_op(rh.length, ==, 8);
+ tt_int_op(rh.length, OP_EQ, 8);
test_memeq_hex(cell.payload+RELAY_HEADER_SIZE, "1e28323c" "00000080");
/* Try parsing it. */
tor_addr_make_unspec(&addr);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET);
- tt_str_op(fmt_addr(&addr), ==, "30.40.50.60");
- tt_int_op(ttl, ==, 128);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "30.40.50.60");
+ tt_int_op(ttl, OP_EQ, 128);
/* Try an IPv6 address */
memset(&rh, 0, sizeof(rh));
@@ -363,7 +363,7 @@ test_cfmt_connected_cells(void *arg)
tor_addr_parse(&addr, "2620::6b0:b:1a1a:0:26e5:480e");
rh.length = connected_cell_format_payload(cell.payload+RELAY_HEADER_SIZE,
&addr, 3600);
- tt_int_op(rh.length, ==, 25);
+ tt_int_op(rh.length, OP_EQ, 25);
test_memeq_hex(cell.payload + RELAY_HEADER_SIZE,
"00000000" "06"
"2620000006b0000b1a1a000026e5480e" "00000e10");
@@ -371,10 +371,10 @@ test_cfmt_connected_cells(void *arg)
/* Try parsing it. */
tor_addr_make_unspec(&addr);
r = connected_cell_parse(&rh, &cell, &addr, &ttl);
- tt_int_op(r, ==, 0);
- tt_int_op(tor_addr_family(&addr), ==, AF_INET6);
- tt_str_op(fmt_addr(&addr), ==, "2620:0:6b0:b:1a1a:0:26e5:480e");
- tt_int_op(ttl, ==, 3600);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(tor_addr_family(&addr), OP_EQ, AF_INET6);
+ tt_str_op(fmt_addr(&addr), OP_EQ, "2620:0:6b0:b:1a1a:0:26e5:480e");
+ tt_int_op(ttl, OP_EQ, 3600);
done:
tor_free(mem_op_hex_tmp);
@@ -398,14 +398,14 @@ test_cfmt_create_cells(void *arg)
crypto_rand((char*)b, TAP_ONIONSKIN_CHALLENGE_LEN);
cell.command = CELL_CREATE;
memcpy(cell.payload, b, TAP_ONIONSKIN_CHALLENGE_LEN);
- tt_int_op(0, ==, create_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATE, ==, cc.cell_type);
- tt_int_op(ONION_HANDSHAKE_TYPE_TAP, ==, cc.handshake_type);
- tt_int_op(TAP_ONIONSKIN_CHALLENGE_LEN, ==, cc.handshake_len);
- test_memeq(cc.onionskin, b, TAP_ONIONSKIN_CHALLENGE_LEN + 10);
- tt_int_op(0, ==, create_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, create_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATE, OP_EQ, cc.cell_type);
+ tt_int_op(ONION_HANDSHAKE_TYPE_TAP, OP_EQ, cc.handshake_type);
+ tt_int_op(TAP_ONIONSKIN_CHALLENGE_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.onionskin,OP_EQ, b, TAP_ONIONSKIN_CHALLENGE_LEN + 10);
+ tt_int_op(0, OP_EQ, create_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A valid create_fast cell. */
memset(&cell, 0, sizeof(cell));
@@ -413,14 +413,14 @@ test_cfmt_create_cells(void *arg)
crypto_rand((char*)b, CREATE_FAST_LEN);
cell.command = CELL_CREATE_FAST;
memcpy(cell.payload, b, CREATE_FAST_LEN);
- tt_int_op(0, ==, create_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATE_FAST, ==, cc.cell_type);
- tt_int_op(ONION_HANDSHAKE_TYPE_FAST, ==, cc.handshake_type);
- tt_int_op(CREATE_FAST_LEN, ==, cc.handshake_len);
- test_memeq(cc.onionskin, b, CREATE_FAST_LEN + 10);
- tt_int_op(0, ==, create_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, create_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATE_FAST, OP_EQ, cc.cell_type);
+ tt_int_op(ONION_HANDSHAKE_TYPE_FAST, OP_EQ, cc.handshake_type);
+ tt_int_op(CREATE_FAST_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.onionskin,OP_EQ, b, CREATE_FAST_LEN + 10);
+ tt_int_op(0, OP_EQ, create_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A valid create2 cell with a TAP payload */
memset(&cell, 0, sizeof(cell));
@@ -429,14 +429,14 @@ test_cfmt_create_cells(void *arg)
cell.command = CELL_CREATE2;
memcpy(cell.payload, "\x00\x00\x00\xBA", 4); /* TAP, 186 bytes long */
memcpy(cell.payload+4, b, TAP_ONIONSKIN_CHALLENGE_LEN);
- tt_int_op(0, ==, create_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATE2, ==, cc.cell_type);
- tt_int_op(ONION_HANDSHAKE_TYPE_TAP, ==, cc.handshake_type);
- tt_int_op(TAP_ONIONSKIN_CHALLENGE_LEN, ==, cc.handshake_len);
- test_memeq(cc.onionskin, b, TAP_ONIONSKIN_CHALLENGE_LEN + 10);
- tt_int_op(0, ==, create_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, create_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATE2, OP_EQ, cc.cell_type);
+ tt_int_op(ONION_HANDSHAKE_TYPE_TAP, OP_EQ, cc.handshake_type);
+ tt_int_op(TAP_ONIONSKIN_CHALLENGE_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.onionskin,OP_EQ, b, TAP_ONIONSKIN_CHALLENGE_LEN + 10);
+ tt_int_op(0, OP_EQ, create_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A valid create2 cell with an ntor payload */
memset(&cell, 0, sizeof(cell));
@@ -445,18 +445,14 @@ test_cfmt_create_cells(void *arg)
cell.command = CELL_CREATE2;
memcpy(cell.payload, "\x00\x02\x00\x54", 4); /* ntor, 84 bytes long */
memcpy(cell.payload+4, b, NTOR_ONIONSKIN_LEN);
-#ifdef CURVE25519_ENABLED
- tt_int_op(0, ==, create_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATE2, ==, cc.cell_type);
- tt_int_op(ONION_HANDSHAKE_TYPE_NTOR, ==, cc.handshake_type);
- tt_int_op(NTOR_ONIONSKIN_LEN, ==, cc.handshake_len);
- test_memeq(cc.onionskin, b, NTOR_ONIONSKIN_LEN + 10);
- tt_int_op(0, ==, create_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
-#else
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
-#endif
+ tt_int_op(0, OP_EQ, create_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATE2, OP_EQ, cc.cell_type);
+ tt_int_op(ONION_HANDSHAKE_TYPE_NTOR, OP_EQ, cc.handshake_type);
+ tt_int_op(NTOR_ONIONSKIN_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.onionskin,OP_EQ, b, NTOR_ONIONSKIN_LEN + 10);
+ tt_int_op(0, OP_EQ, create_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A valid create cell with an ntor payload, in legacy format. */
memset(&cell, 0, sizeof(cell));
@@ -465,42 +461,38 @@ test_cfmt_create_cells(void *arg)
cell.command = CELL_CREATE;
memcpy(cell.payload, "ntorNTORntorNTOR", 16);
memcpy(cell.payload+16, b, NTOR_ONIONSKIN_LEN);
-#ifdef CURVE25519_ENABLED
- tt_int_op(0, ==, create_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATE, ==, cc.cell_type);
- tt_int_op(ONION_HANDSHAKE_TYPE_NTOR, ==, cc.handshake_type);
- tt_int_op(NTOR_ONIONSKIN_LEN, ==, cc.handshake_len);
- test_memeq(cc.onionskin, b, NTOR_ONIONSKIN_LEN + 10);
- tt_int_op(0, ==, create_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
-#else
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
-#endif
+ tt_int_op(0, OP_EQ, create_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATE, OP_EQ, cc.cell_type);
+ tt_int_op(ONION_HANDSHAKE_TYPE_NTOR, OP_EQ, cc.handshake_type);
+ tt_int_op(NTOR_ONIONSKIN_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.onionskin,OP_EQ, b, NTOR_ONIONSKIN_LEN + 10);
+ tt_int_op(0, OP_EQ, create_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* == Okay, now let's try to parse some impossible stuff. */
/* It has to be some kind of a create cell! */
cell.command = CELL_CREATED;
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
+ tt_int_op(-1, OP_EQ, create_cell_parse(&cc, &cell));
/* You can't acutally make an unparseable CREATE or CREATE_FAST cell. */
/* Try some CREATE2 cells. First with a bad type. */
cell.command = CELL_CREATE2;
memcpy(cell.payload, "\x00\x50\x00\x99", 4); /* Type 0x50???? */
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
+ tt_int_op(-1, OP_EQ, create_cell_parse(&cc, &cell));
/* Now a good type with an incorrect length. */
memcpy(cell.payload, "\x00\x00\x00\xBC", 4); /* TAP, 187 bytes.*/
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
+ tt_int_op(-1, OP_EQ, create_cell_parse(&cc, &cell));
/* Now a good type with a ridiculous length. */
memcpy(cell.payload, "\x00\x00\x02\x00", 4); /* TAP, 512 bytes.*/
- tt_int_op(-1, ==, create_cell_parse(&cc, &cell));
+ tt_int_op(-1, OP_EQ, create_cell_parse(&cc, &cell));
/* == Time to try formatting bad cells. The important thing is that
we reject big lengths, so just check that for now. */
cc.handshake_len = 512;
- tt_int_op(-1, ==, create_cell_format(&cell2, &cc));
+ tt_int_op(-1, OP_EQ, create_cell_format(&cell2, &cc));
/* == Try formatting a create2 cell we don't understand. XXXX */
@@ -524,13 +516,13 @@ test_cfmt_created_cells(void *arg)
crypto_rand((char*)b, TAP_ONIONSKIN_REPLY_LEN);
cell.command = CELL_CREATED;
memcpy(cell.payload, b, TAP_ONIONSKIN_REPLY_LEN);
- tt_int_op(0, ==, created_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATED, ==, cc.cell_type);
- tt_int_op(TAP_ONIONSKIN_REPLY_LEN, ==, cc.handshake_len);
- test_memeq(cc.reply, b, TAP_ONIONSKIN_REPLY_LEN + 10);
- tt_int_op(0, ==, created_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, created_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATED, OP_EQ, cc.cell_type);
+ tt_int_op(TAP_ONIONSKIN_REPLY_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.reply,OP_EQ, b, TAP_ONIONSKIN_REPLY_LEN + 10);
+ tt_int_op(0, OP_EQ, created_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A good CREATED_FAST cell */
memset(&cell, 0, sizeof(cell));
@@ -538,13 +530,13 @@ test_cfmt_created_cells(void *arg)
crypto_rand((char*)b, CREATED_FAST_LEN);
cell.command = CELL_CREATED_FAST;
memcpy(cell.payload, b, CREATED_FAST_LEN);
- tt_int_op(0, ==, created_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATED_FAST, ==, cc.cell_type);
- tt_int_op(CREATED_FAST_LEN, ==, cc.handshake_len);
- test_memeq(cc.reply, b, CREATED_FAST_LEN + 10);
- tt_int_op(0, ==, created_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, created_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATED_FAST, OP_EQ, cc.cell_type);
+ tt_int_op(CREATED_FAST_LEN, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.reply,OP_EQ, b, CREATED_FAST_LEN + 10);
+ tt_int_op(0, OP_EQ, created_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A good CREATED2 cell with short reply */
memset(&cell, 0, sizeof(cell));
@@ -553,13 +545,13 @@ test_cfmt_created_cells(void *arg)
cell.command = CELL_CREATED2;
memcpy(cell.payload, "\x00\x40", 2);
memcpy(cell.payload+2, b, 64);
- tt_int_op(0, ==, created_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATED2, ==, cc.cell_type);
- tt_int_op(64, ==, cc.handshake_len);
- test_memeq(cc.reply, b, 80);
- tt_int_op(0, ==, created_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, created_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATED2, OP_EQ, cc.cell_type);
+ tt_int_op(64, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.reply,OP_EQ, b, 80);
+ tt_int_op(0, OP_EQ, created_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* A good CREATED2 cell with maximal reply */
memset(&cell, 0, sizeof(cell));
@@ -568,13 +560,13 @@ test_cfmt_created_cells(void *arg)
cell.command = CELL_CREATED2;
memcpy(cell.payload, "\x01\xF0", 2);
memcpy(cell.payload+2, b, 496);
- tt_int_op(0, ==, created_cell_parse(&cc, &cell));
- tt_int_op(CELL_CREATED2, ==, cc.cell_type);
- tt_int_op(496, ==, cc.handshake_len);
- test_memeq(cc.reply, b, 496);
- tt_int_op(0, ==, created_cell_format(&cell2, &cc));
- tt_int_op(cell.command, ==, cell2.command);
- test_memeq(cell.payload, cell2.payload, CELL_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, created_cell_parse(&cc, &cell));
+ tt_int_op(CELL_CREATED2, OP_EQ, cc.cell_type);
+ tt_int_op(496, OP_EQ, cc.handshake_len);
+ tt_mem_op(cc.reply,OP_EQ, b, 496);
+ tt_int_op(0, OP_EQ, created_cell_format(&cell2, &cc));
+ tt_int_op(cell.command, OP_EQ, cell2.command);
+ tt_mem_op(cell.payload,OP_EQ, cell2.payload, CELL_PAYLOAD_SIZE);
/* Bogus CREATED2 cell: too long! */
memset(&cell, 0, sizeof(cell));
@@ -582,11 +574,11 @@ test_cfmt_created_cells(void *arg)
crypto_rand((char*)b, 496);
cell.command = CELL_CREATED2;
memcpy(cell.payload, "\x01\xF1", 2);
- tt_int_op(-1, ==, created_cell_parse(&cc, &cell));
+ tt_int_op(-1, OP_EQ, created_cell_parse(&cc, &cell));
/* Unformattable CREATED2 cell: too long! */
cc.handshake_len = 497;
- tt_int_op(-1, ==, created_cell_format(&cell2, &cc));
+ tt_int_op(-1, OP_EQ, created_cell_format(&cell2, &cc));
done:
;
@@ -614,21 +606,21 @@ test_cfmt_extend_cells(void *arg)
memcpy(p, "\x12\xf4\x00\x01\x01\x02", 6); /* 18 244 0 1 : 258 */
memcpy(p+6,b,TAP_ONIONSKIN_CHALLENGE_LEN);
memcpy(p+6+TAP_ONIONSKIN_CHALLENGE_LEN, "electroencephalogram", 20);
- tt_int_op(0, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND,
+ tt_int_op(0, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND,
p, 26+TAP_ONIONSKIN_CHALLENGE_LEN));
- tt_int_op(RELAY_COMMAND_EXTEND, ==, ec.cell_type);
- tt_str_op("18.244.0.1", ==, fmt_addr(&ec.orport_ipv4.addr));
- tt_int_op(258, ==, ec.orport_ipv4.port);
- tt_int_op(AF_UNSPEC, ==, tor_addr_family(&ec.orport_ipv6.addr));
- test_memeq(ec.node_id, "electroencephalogram", 20);
- tt_int_op(cc->cell_type, ==, CELL_CREATE);
- tt_int_op(cc->handshake_type, ==, ONION_HANDSHAKE_TYPE_TAP);
- tt_int_op(cc->handshake_len, ==, TAP_ONIONSKIN_CHALLENGE_LEN);
- test_memeq(cc->onionskin, b, TAP_ONIONSKIN_CHALLENGE_LEN+20);
- tt_int_op(0, ==, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(p2_cmd, ==, RELAY_COMMAND_EXTEND);
- tt_int_op(p2_len, ==, 26+TAP_ONIONSKIN_CHALLENGE_LEN);
- test_memeq(p2, p, RELAY_PAYLOAD_SIZE);
+ tt_int_op(RELAY_COMMAND_EXTEND, OP_EQ, ec.cell_type);
+ tt_str_op("18.244.0.1", OP_EQ, fmt_addr(&ec.orport_ipv4.addr));
+ tt_int_op(258, OP_EQ, ec.orport_ipv4.port);
+ tt_int_op(AF_UNSPEC, OP_EQ, tor_addr_family(&ec.orport_ipv6.addr));
+ tt_mem_op(ec.node_id,OP_EQ, "electroencephalogram", 20);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATE);
+ tt_int_op(cc->handshake_type, OP_EQ, ONION_HANDSHAKE_TYPE_TAP);
+ tt_int_op(cc->handshake_len, OP_EQ, TAP_ONIONSKIN_CHALLENGE_LEN);
+ tt_mem_op(cc->onionskin,OP_EQ, b, TAP_ONIONSKIN_CHALLENGE_LEN+20);
+ tt_int_op(0, OP_EQ, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(p2_cmd, OP_EQ, RELAY_COMMAND_EXTEND);
+ tt_int_op(p2_len, OP_EQ, 26+TAP_ONIONSKIN_CHALLENGE_LEN);
+ tt_mem_op(p2,OP_EQ, p, RELAY_PAYLOAD_SIZE);
/* Let's do an ntor stuffed in a legacy EXTEND cell */
memset(p, 0, sizeof(p));
@@ -638,22 +630,22 @@ test_cfmt_extend_cells(void *arg)
memcpy(p+6,"ntorNTORntorNTOR", 16);
memcpy(p+22, b, NTOR_ONIONSKIN_LEN);
memcpy(p+6+TAP_ONIONSKIN_CHALLENGE_LEN, "electroencephalogram", 20);
- tt_int_op(0, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND,
+ tt_int_op(0, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND,
p, 26+TAP_ONIONSKIN_CHALLENGE_LEN));
- tt_int_op(RELAY_COMMAND_EXTEND, ==, ec.cell_type);
- tt_str_op("18.244.0.1", ==, fmt_addr(&ec.orport_ipv4.addr));
- tt_int_op(258, ==, ec.orport_ipv4.port);
- tt_int_op(AF_UNSPEC, ==, tor_addr_family(&ec.orport_ipv6.addr));
- test_memeq(ec.node_id, "electroencephalogram", 20);
- tt_int_op(cc->cell_type, ==, CELL_CREATE2);
- tt_int_op(cc->handshake_type, ==, ONION_HANDSHAKE_TYPE_NTOR);
- tt_int_op(cc->handshake_len, ==, NTOR_ONIONSKIN_LEN);
- test_memeq(cc->onionskin, b, NTOR_ONIONSKIN_LEN+20);
- tt_int_op(0, ==, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(p2_cmd, ==, RELAY_COMMAND_EXTEND);
- tt_int_op(p2_len, ==, 26+TAP_ONIONSKIN_CHALLENGE_LEN);
- test_memeq(p2, p, RELAY_PAYLOAD_SIZE);
- tt_int_op(0, ==, create_cell_format_relayed(&cell, cc));
+ tt_int_op(RELAY_COMMAND_EXTEND, OP_EQ, ec.cell_type);
+ tt_str_op("18.244.0.1", OP_EQ, fmt_addr(&ec.orport_ipv4.addr));
+ tt_int_op(258, OP_EQ, ec.orport_ipv4.port);
+ tt_int_op(AF_UNSPEC, OP_EQ, tor_addr_family(&ec.orport_ipv6.addr));
+ tt_mem_op(ec.node_id,OP_EQ, "electroencephalogram", 20);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATE2);
+ tt_int_op(cc->handshake_type, OP_EQ, ONION_HANDSHAKE_TYPE_NTOR);
+ tt_int_op(cc->handshake_len, OP_EQ, NTOR_ONIONSKIN_LEN);
+ tt_mem_op(cc->onionskin,OP_EQ, b, NTOR_ONIONSKIN_LEN+20);
+ tt_int_op(0, OP_EQ, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(p2_cmd, OP_EQ, RELAY_COMMAND_EXTEND);
+ tt_int_op(p2_len, OP_EQ, 26+TAP_ONIONSKIN_CHALLENGE_LEN);
+ tt_mem_op(p2,OP_EQ, p, RELAY_PAYLOAD_SIZE);
+ tt_int_op(0, OP_EQ, create_cell_format_relayed(&cell, cc));
/* Now let's do a minimal ntor EXTEND2 cell. */
memset(&ec, 0xff, sizeof(ec));
@@ -667,21 +659,21 @@ test_cfmt_extend_cells(void *arg)
/* Prep for the handshake: type and length */
memcpy(p+31, "\x00\x02\x00\x54", 4);
memcpy(p+35, b, NTOR_ONIONSKIN_LEN);
- tt_int_op(0, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(0, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, 35+NTOR_ONIONSKIN_LEN));
- tt_int_op(RELAY_COMMAND_EXTEND2, ==, ec.cell_type);
- tt_str_op("18.244.0.1", ==, fmt_addr(&ec.orport_ipv4.addr));
- tt_int_op(61681, ==, ec.orport_ipv4.port);
- tt_int_op(AF_UNSPEC, ==, tor_addr_family(&ec.orport_ipv6.addr));
- test_memeq(ec.node_id, "anarchoindividualist", 20);
- tt_int_op(cc->cell_type, ==, CELL_CREATE2);
- tt_int_op(cc->handshake_type, ==, ONION_HANDSHAKE_TYPE_NTOR);
- tt_int_op(cc->handshake_len, ==, NTOR_ONIONSKIN_LEN);
- test_memeq(cc->onionskin, b, NTOR_ONIONSKIN_LEN+20);
- tt_int_op(0, ==, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(p2_cmd, ==, RELAY_COMMAND_EXTEND2);
- tt_int_op(p2_len, ==, 35+NTOR_ONIONSKIN_LEN);
- test_memeq(p2, p, RELAY_PAYLOAD_SIZE);
+ tt_int_op(RELAY_COMMAND_EXTEND2, OP_EQ, ec.cell_type);
+ tt_str_op("18.244.0.1", OP_EQ, fmt_addr(&ec.orport_ipv4.addr));
+ tt_int_op(61681, OP_EQ, ec.orport_ipv4.port);
+ tt_int_op(AF_UNSPEC, OP_EQ, tor_addr_family(&ec.orport_ipv6.addr));
+ tt_mem_op(ec.node_id,OP_EQ, "anarchoindividualist", 20);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATE2);
+ tt_int_op(cc->handshake_type, OP_EQ, ONION_HANDSHAKE_TYPE_NTOR);
+ tt_int_op(cc->handshake_len, OP_EQ, NTOR_ONIONSKIN_LEN);
+ tt_mem_op(cc->onionskin,OP_EQ, b, NTOR_ONIONSKIN_LEN+20);
+ tt_int_op(0, OP_EQ, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(p2_cmd, OP_EQ, RELAY_COMMAND_EXTEND2);
+ tt_int_op(p2_len, OP_EQ, 35+NTOR_ONIONSKIN_LEN);
+ tt_mem_op(p2,OP_EQ, p, RELAY_PAYLOAD_SIZE);
/* Now let's do a fanciful EXTEND2 cell. */
memset(&ec, 0xff, sizeof(ec));
@@ -700,21 +692,21 @@ test_cfmt_extend_cells(void *arg)
/* Prep for the handshake: weird type and length */
memcpy(p+85, "\x01\x05\x00\x63", 4);
memcpy(p+89, b, 99);
- tt_int_op(0, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2, p, 89+99));
- tt_int_op(RELAY_COMMAND_EXTEND2, ==, ec.cell_type);
- tt_str_op("18.244.0.1", ==, fmt_addr(&ec.orport_ipv4.addr));
- tt_int_op(61681, ==, ec.orport_ipv4.port);
- tt_str_op("2002::f0:c51e", ==, fmt_addr(&ec.orport_ipv6.addr));
- tt_int_op(4370, ==, ec.orport_ipv6.port);
- test_memeq(ec.node_id, "anthropomorphization", 20);
- tt_int_op(cc->cell_type, ==, CELL_CREATE2);
- tt_int_op(cc->handshake_type, ==, 0x105);
- tt_int_op(cc->handshake_len, ==, 99);
- test_memeq(cc->onionskin, b, 99+20);
- tt_int_op(0, ==, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(p2_cmd, ==, RELAY_COMMAND_EXTEND2);
+ tt_int_op(0, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2, p, 89+99));
+ tt_int_op(RELAY_COMMAND_EXTEND2, OP_EQ, ec.cell_type);
+ tt_str_op("18.244.0.1", OP_EQ, fmt_addr(&ec.orport_ipv4.addr));
+ tt_int_op(61681, OP_EQ, ec.orport_ipv4.port);
+ tt_str_op("2002::f0:c51e", OP_EQ, fmt_addr(&ec.orport_ipv6.addr));
+ tt_int_op(4370, OP_EQ, ec.orport_ipv6.port);
+ tt_mem_op(ec.node_id,OP_EQ, "anthropomorphization", 20);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATE2);
+ tt_int_op(cc->handshake_type, OP_EQ, 0x105);
+ tt_int_op(cc->handshake_len, OP_EQ, 99);
+ tt_mem_op(cc->onionskin,OP_EQ, b, 99+20);
+ tt_int_op(0, OP_EQ, extend_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(p2_cmd, OP_EQ, RELAY_COMMAND_EXTEND2);
/* We'll generate it minus the IPv6 address and minus the konami code */
- tt_int_op(p2_len, ==, 89+99-34-20);
+ tt_int_op(p2_len, OP_EQ, 89+99-34-20);
test_memeq_hex(p2,
/* Two items: one that same darn IP address. */
"02000612F40001F0F1"
@@ -722,8 +714,8 @@ test_cfmt_extend_cells(void *arg)
"0214616e7468726f706f6d6f727068697a6174696f6e"
/* Now the handshake prologue */
"01050063");
- test_memeq(p2+1+8+22+4, b, 99+20);
- tt_int_op(0, ==, create_cell_format_relayed(&cell, cc));
+ tt_mem_op(p2+1+8+22+4,OP_EQ, b, 99+20);
+ tt_int_op(0, OP_EQ, create_cell_format_relayed(&cell, cc));
/* == Now try parsing some junk */
@@ -732,7 +724,7 @@ test_cfmt_extend_cells(void *arg)
memcpy(p, "\x02\x00\x06\x12\xf4\x00\x01\xf0\xf1", 9);
memcpy(p+9, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+31, "\xff\xff\x01\xd0", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* Try two identities. */
@@ -741,14 +733,14 @@ test_cfmt_extend_cells(void *arg)
memcpy(p+9, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+31, "\x02\x14" "autodepolymerization", 22);
memcpy(p+53, "\xff\xff\x00\x10", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* No identities. */
memset(p, 0, sizeof(p));
memcpy(p, "\x01\x00\x06\x12\xf4\x00\x01\xf0\xf1", 9);
memcpy(p+53, "\xff\xff\x00\x10", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* Try a bad IPv4 address (too long, too short)*/
@@ -756,13 +748,13 @@ test_cfmt_extend_cells(void *arg)
memcpy(p, "\x02\x00\x07\x12\xf4\x00\x01\xf0\xf1\xff", 10);
memcpy(p+10, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+32, "\xff\xff\x00\x10", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
memset(p, 0, sizeof(p));
memcpy(p, "\x02\x00\x05\x12\xf4\x00\x01\xf0", 8);
memcpy(p+8, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+30, "\xff\xff\x00\x10", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* IPv6 address (too long, too short, no IPv4)*/
@@ -771,28 +763,28 @@ test_cfmt_extend_cells(void *arg)
memcpy(p+9, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+31, "\x01\x13" "xxxxxxxxxxxxxxxxYYZ", 19);
memcpy(p+50, "\xff\xff\x00\x20", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
memset(p, 0, sizeof(p));
memcpy(p, "\x03\x00\x06\x12\xf4\x00\x01\xf0\xf1", 9);
memcpy(p+9, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+31, "\x01\x11" "xxxxxxxxxxxxxxxxY", 17);
memcpy(p+48, "\xff\xff\x00\x20", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
memset(p, 0, sizeof(p));
memcpy(p, "\x02", 1);
memcpy(p+1, "\x02\x14" "anarchoindividualist", 22);
memcpy(p+23, "\x01\x12" "xxxxxxxxxxxxxxxxYY", 18);
memcpy(p+41, "\xff\xff\x00\x20", 4);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* Running out of space in specifiers */
memset(p,0,sizeof(p));
memcpy(p, "\x05\x0a\xff", 3);
memcpy(p+3+255, "\x0a\xff", 2);
- tt_int_op(-1, ==, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
+ tt_int_op(-1, OP_EQ, extend_cell_parse(&ec, RELAY_COMMAND_EXTEND2,
p, sizeof(p)));
/* Fuzz, because why not. */
@@ -831,16 +823,16 @@ test_cfmt_extended_cells(void *arg)
memset(b, 0, sizeof(b));
crypto_rand((char*)b, TAP_ONIONSKIN_REPLY_LEN);
memcpy(p,b,TAP_ONIONSKIN_REPLY_LEN);
- tt_int_op(0, ==, extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED, p,
+ tt_int_op(0, OP_EQ, extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED, p,
TAP_ONIONSKIN_REPLY_LEN));
- tt_int_op(RELAY_COMMAND_EXTENDED, ==, ec.cell_type);
- tt_int_op(cc->cell_type, ==, CELL_CREATED);
- tt_int_op(cc->handshake_len, ==, TAP_ONIONSKIN_REPLY_LEN);
- test_memeq(cc->reply, b, TAP_ONIONSKIN_REPLY_LEN);
- tt_int_op(0, ==, extended_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(RELAY_COMMAND_EXTENDED, ==, p2_cmd);
- tt_int_op(TAP_ONIONSKIN_REPLY_LEN, ==, p2_len);
- test_memeq(p2, p, sizeof(p2));
+ tt_int_op(RELAY_COMMAND_EXTENDED, OP_EQ, ec.cell_type);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATED);
+ tt_int_op(cc->handshake_len, OP_EQ, TAP_ONIONSKIN_REPLY_LEN);
+ tt_mem_op(cc->reply,OP_EQ, b, TAP_ONIONSKIN_REPLY_LEN);
+ tt_int_op(0, OP_EQ, extended_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(RELAY_COMMAND_EXTENDED, OP_EQ, p2_cmd);
+ tt_int_op(TAP_ONIONSKIN_REPLY_LEN, OP_EQ, p2_len);
+ tt_mem_op(p2,OP_EQ, p, sizeof(p2));
/* Try an EXTENDED2 cell */
memset(&ec, 0xff, sizeof(ec));
@@ -849,25 +841,26 @@ test_cfmt_extended_cells(void *arg)
crypto_rand((char*)b, 42);
memcpy(p,"\x00\x2a",2);
memcpy(p+2,b,42);
- tt_int_op(0, ==, extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED2, p, 2+42));
- tt_int_op(RELAY_COMMAND_EXTENDED2, ==, ec.cell_type);
- tt_int_op(cc->cell_type, ==, CELL_CREATED2);
- tt_int_op(cc->handshake_len, ==, 42);
- test_memeq(cc->reply, b, 42+10);
- tt_int_op(0, ==, extended_cell_format(&p2_cmd, &p2_len, p2, &ec));
- tt_int_op(RELAY_COMMAND_EXTENDED2, ==, p2_cmd);
- tt_int_op(2+42, ==, p2_len);
- test_memeq(p2, p, sizeof(p2));
+ tt_int_op(0, OP_EQ,
+ extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED2, p, 2+42));
+ tt_int_op(RELAY_COMMAND_EXTENDED2, OP_EQ, ec.cell_type);
+ tt_int_op(cc->cell_type, OP_EQ, CELL_CREATED2);
+ tt_int_op(cc->handshake_len, OP_EQ, 42);
+ tt_mem_op(cc->reply,OP_EQ, b, 42+10);
+ tt_int_op(0, OP_EQ, extended_cell_format(&p2_cmd, &p2_len, p2, &ec));
+ tt_int_op(RELAY_COMMAND_EXTENDED2, OP_EQ, p2_cmd);
+ tt_int_op(2+42, OP_EQ, p2_len);
+ tt_mem_op(p2,OP_EQ, p, sizeof(p2));
/* Try an almost-too-long EXTENDED2 cell */
memcpy(p, "\x01\xf0", 2);
- tt_int_op(0, ==,
+ tt_int_op(0, OP_EQ,
extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED2, p, sizeof(p)));
/* Now try a too-long extended2 cell. That's the only misparse I can think
* of. */
memcpy(p, "\x01\xf1", 2);
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
extended_cell_parse(&ec, RELAY_COMMAND_EXTENDED2, p, sizeof(p)));
done:
@@ -911,22 +904,22 @@ test_cfmt_resolved_cells(void *arg)
/* Let's try an empty cell */
SET_CELL("");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
CLEAR_ADDRS(); /* redundant but let's be consistent */
/* Cell with one ipv4 addr */
SET_CELL("\x04\x04" "\x7f\x00\x02\x0a" "\x00\00\x01\x00");
- tt_int_op(rh.length, ==, 10);
+ tt_int_op(rh.length, OP_EQ, 10);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 1);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 1);
a = smartlist_get(addrs, 0);
- tt_str_op(fmt_addr(&a->addr), ==, "127.0.2.10");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 256);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "127.0.2.10");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 256);
CLEAR_ADDRS();
/* Cell with one ipv6 addr */
@@ -934,30 +927,30 @@ test_cfmt_resolved_cells(void *arg)
"\x20\x02\x90\x90\x00\x00\x00\x00"
"\x00\x00\x00\x00\xf0\xf0\xab\xcd"
"\x02\00\x00\x01");
- tt_int_op(rh.length, ==, 22);
+ tt_int_op(rh.length, OP_EQ, 22);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 1);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 1);
a = smartlist_get(addrs, 0);
- tt_str_op(fmt_addr(&a->addr), ==, "2002:9090::f0f0:abcd");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 0x2000001);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "2002:9090::f0f0:abcd");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 0x2000001);
CLEAR_ADDRS();
/* Cell with one hostname */
SET_CELL("\x00\x11"
"motherbrain.zebes"
"\x00\00\x00\x00");
- tt_int_op(rh.length, ==, 23);
+ tt_int_op(rh.length, OP_EQ, 23);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 1);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 1);
a = smartlist_get(addrs, 0);
tt_assert(tor_addr_is_null(&a->addr));
- tt_str_op(a->hostname, ==, "motherbrain.zebes");
- tt_int_op(a->ttl, ==, 0);
+ tt_str_op(a->hostname, OP_EQ, "motherbrain.zebes");
+ tt_int_op(a->ttl, OP_EQ, 0);
CLEAR_ADDRS();
#define LONG_NAME \
@@ -966,51 +959,51 @@ test_cfmt_resolved_cells(void *arg)
"function-is-already-very-full.of-copy-and-pasted-stuff.having-this-app" \
"ear-more-than-once-would-bother-me-somehow.is"
- tt_int_op(strlen(LONG_NAME), ==, 255);
+ tt_int_op(strlen(LONG_NAME), OP_EQ, 255);
SET_CELL("\x00\xff"
LONG_NAME
"\x00\01\x00\x00");
- tt_int_op(rh.length, ==, 261);
+ tt_int_op(rh.length, OP_EQ, 261);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 1);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 1);
a = smartlist_get(addrs, 0);
tt_assert(tor_addr_is_null(&a->addr));
- tt_str_op(a->hostname, ==, LONG_NAME);
- tt_int_op(a->ttl, ==, 65536);
+ tt_str_op(a->hostname, OP_EQ, LONG_NAME);
+ tt_int_op(a->ttl, OP_EQ, 65536);
CLEAR_ADDRS();
/* Cells with an error */
SET_CELL("\xf0\x2b"
"I'm sorry, Dave. I'm afraid I can't do that"
"\x00\x11\x22\x33");
- tt_int_op(rh.length, ==, 49);
+ tt_int_op(rh.length, OP_EQ, 49);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, RESOLVED_TYPE_ERROR_TRANSIENT);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, RESOLVED_TYPE_ERROR_TRANSIENT);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
CLEAR_ADDRS();
SET_CELL("\xf1\x40"
"This hostname is too important for me to allow you to resolve it"
"\x00\x00\x00\x00");
- tt_int_op(rh.length, ==, 70);
+ tt_int_op(rh.length, OP_EQ, 70);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, RESOLVED_TYPE_ERROR);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, RESOLVED_TYPE_ERROR);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
CLEAR_ADDRS();
/* Cell with an unrecognized type */
SET_CELL("\xee\x16"
"fault in the AE35 unit"
"\x09\x09\x01\x01");
- tt_int_op(rh.length, ==, 28);
+ tt_int_op(rh.length, OP_EQ, 28);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
CLEAR_ADDRS();
/* Cell with one of each */
@@ -1035,21 +1028,21 @@ test_cfmt_resolved_cells(void *arg)
"\x00\00\x00\x00"
);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0); /* no error reported; we got answers */
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 3);
+ tt_int_op(errcode, OP_EQ, 0); /* no error reported; we got answers */
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 3);
a = smartlist_get(addrs, 0);
- tt_str_op(fmt_addr(&a->addr), ==, "2002:9090::f0f0:abcd");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 0x2000001);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "2002:9090::f0f0:abcd");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 0x2000001);
a = smartlist_get(addrs, 1);
- tt_str_op(fmt_addr(&a->addr), ==, "127.0.2.10");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 256);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "127.0.2.10");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 256);
a = smartlist_get(addrs, 2);
tt_assert(tor_addr_is_null(&a->addr));
- tt_str_op(a->hostname, ==, "motherbrain.zebes");
- tt_int_op(a->ttl, ==, 0);
+ tt_str_op(a->hostname, OP_EQ, "motherbrain.zebes");
+ tt_int_op(a->ttl, OP_EQ, 0);
CLEAR_ADDRS();
/* Cell with several of similar type */
@@ -1067,29 +1060,29 @@ test_cfmt_resolved_cells(void *arg)
"\x00\x00\x00\x00\x00\xfa\xca\xde"
"\x00\00\x00\x03");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 5);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 5);
a = smartlist_get(addrs, 0);
- tt_str_op(fmt_addr(&a->addr), ==, "127.0.2.10");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 256);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "127.0.2.10");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 256);
a = smartlist_get(addrs, 1);
- tt_str_op(fmt_addr(&a->addr), ==, "8.8.8.8");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 261);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "8.8.8.8");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 261);
a = smartlist_get(addrs, 2);
- tt_str_op(fmt_addr(&a->addr), ==, "127.176.2.176");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 131071);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "127.176.2.176");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 131071);
a = smartlist_get(addrs, 3);
- tt_str_op(fmt_addr(&a->addr), ==, "2002:9000::cafe:f00d");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 1);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "2002:9000::cafe:f00d");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 1);
a = smartlist_get(addrs, 4);
- tt_str_op(fmt_addr(&a->addr), ==, "2002:9001::fa:cade");
- tt_ptr_op(a->hostname, ==, NULL);
- tt_int_op(a->ttl, ==, 3);
+ tt_str_op(fmt_addr(&a->addr), OP_EQ, "2002:9001::fa:cade");
+ tt_ptr_op(a->hostname, OP_EQ, NULL);
+ tt_int_op(a->ttl, OP_EQ, 3);
CLEAR_ADDRS();
/* Full cell */
@@ -1099,22 +1092,22 @@ test_cfmt_resolved_cells(void *arg)
"g-case.to-avoid-off-by-one-errors.where-full-things-are-misreported-as" \
".overflowing-by-one.z"
- tt_int_op(strlen(LONG_NAME2), ==, 231);
+ tt_int_op(strlen(LONG_NAME2), OP_EQ, 231);
SET_CELL("\x00\xff"
LONG_NAME
"\x00\01\x00\x00"
"\x00\xe7"
LONG_NAME2
"\x00\01\x00\x00");
- tt_int_op(rh.length, ==, RELAY_PAYLOAD_SIZE);
+ tt_int_op(rh.length, OP_EQ, RELAY_PAYLOAD_SIZE);
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, 0);
- tt_int_op(smartlist_len(addrs), ==, 2);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 2);
a = smartlist_get(addrs, 0);
- tt_str_op(a->hostname, ==, LONG_NAME);
+ tt_str_op(a->hostname, OP_EQ, LONG_NAME);
a = smartlist_get(addrs, 1);
- tt_str_op(a->hostname, ==, LONG_NAME2);
+ tt_str_op(a->hostname, OP_EQ, LONG_NAME2);
CLEAR_ADDRS();
/* BAD CELLS */
@@ -1122,49 +1115,49 @@ test_cfmt_resolved_cells(void *arg)
/* Invalid length on an IPv4 */
SET_CELL("\x04\x03zzz1234");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\x04\x04" "\x7f\x00\x02\x0a" "\x00\00\x01\x00"
"\x04\x05zzzzz1234");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
/* Invalid length on an IPv6 */
SET_CELL("\x06\x03zzz1234");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\x04\x04" "\x7f\x00\x02\x0a" "\x00\00\x01\x00"
"\x06\x17wwwwwwwwwwwwwwwww1234");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\x04\x04" "\x7f\x00\x02\x0a" "\x00\00\x01\x00"
"\x06\x10xxxx");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
/* Empty hostname */
SET_CELL("\x00\x00xxxx");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
/* rh.length out of range */
CLEAR_CELL();
rh.length = 499;
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(errcode, ==, 0);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(errcode, OP_EQ, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
/* Item length extends beyond rh.length */
CLEAR_CELL();
@@ -1173,18 +1166,18 @@ test_cfmt_resolved_cells(void *arg)
"\x00\01\x00\x00");
rh.length -= 1;
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
rh.length -= 5;
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\x04\x04" "\x7f\x00\x02\x0a" "\x00\00\x01\x00");
rh.length -= 1;
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\xee\x10"
"\x20\x02\x90\x01\x00\x00\x00\x00"
@@ -1192,19 +1185,19 @@ test_cfmt_resolved_cells(void *arg)
"\x00\00\x00\x03");
rh.length -= 1;
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
/* Truncated item after first character */
SET_CELL("\x04");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
SET_CELL("\xee");
r = resolved_cell_parse(&cell, &rh, addrs, &errcode);
- tt_int_op(r, ==, -1);
- tt_int_op(smartlist_len(addrs), ==, 0);
+ tt_int_op(r, OP_EQ, -1);
+ tt_int_op(smartlist_len(addrs), OP_EQ, 0);
done:
CLEAR_ADDRS();
@@ -1232,19 +1225,19 @@ test_cfmt_is_destroy(void *arg)
cell_pack(&packed, &cell, 0);
chan->wide_circ_ids = 0;
tt_assert(! packed_cell_is_destroy(chan, &packed, &circid));
- tt_int_op(circid, ==, 0);
+ tt_int_op(circid, OP_EQ, 0);
cell_pack(&packed, &cell, 1);
chan->wide_circ_ids = 1;
tt_assert(! packed_cell_is_destroy(chan, &packed, &circid));
- tt_int_op(circid, ==, 0);
+ tt_int_op(circid, OP_EQ, 0);
cell.command = CELL_DESTROY;
cell_pack(&packed, &cell, 0);
chan->wide_circ_ids = 0;
tt_assert(packed_cell_is_destroy(chan, &packed, &circid));
- tt_int_op(circid, ==, 3003);
+ tt_int_op(circid, OP_EQ, 3003);
circid = 0;
cell_pack(&packed, &cell, 1);
diff --git a/src/test/test_cell_queue.c b/src/test/test_cell_queue.c
index 92629823ec..93ac9854d8 100644
--- a/src/test/test_cell_queue.c
+++ b/src/test/test_cell_queue.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define CIRCUITLIST_PRIVATE
@@ -16,12 +16,8 @@ test_cq_manip(void *arg)
cell_t cell;
(void) arg;
-#ifdef ENABLE_MEMPOOLS
- init_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
-
cell_queue_init(&cq);
- tt_int_op(cq.n, ==, 0);
+ tt_int_op(cq.n, OP_EQ, 0);
pc1 = packed_cell_new();
pc2 = packed_cell_new();
@@ -29,26 +25,26 @@ test_cq_manip(void *arg)
pc4 = packed_cell_new();
tt_assert(pc1 && pc2 && pc3 && pc4);
- tt_ptr_op(NULL, ==, cell_queue_pop(&cq));
+ tt_ptr_op(NULL, OP_EQ, cell_queue_pop(&cq));
/* Add and remove a singleton. */
cell_queue_append(&cq, pc1);
- tt_int_op(cq.n, ==, 1);
- tt_ptr_op(pc1, ==, cell_queue_pop(&cq));
- tt_int_op(cq.n, ==, 0);
+ tt_int_op(cq.n, OP_EQ, 1);
+ tt_ptr_op(pc1, OP_EQ, cell_queue_pop(&cq));
+ tt_int_op(cq.n, OP_EQ, 0);
/* Add and remove four items */
cell_queue_append(&cq, pc4);
cell_queue_append(&cq, pc3);
cell_queue_append(&cq, pc2);
cell_queue_append(&cq, pc1);
- tt_int_op(cq.n, ==, 4);
- tt_ptr_op(pc4, ==, cell_queue_pop(&cq));
- tt_ptr_op(pc3, ==, cell_queue_pop(&cq));
- tt_ptr_op(pc2, ==, cell_queue_pop(&cq));
- tt_ptr_op(pc1, ==, cell_queue_pop(&cq));
- tt_int_op(cq.n, ==, 0);
- tt_ptr_op(NULL, ==, cell_queue_pop(&cq));
+ tt_int_op(cq.n, OP_EQ, 4);
+ tt_ptr_op(pc4, OP_EQ, cell_queue_pop(&cq));
+ tt_ptr_op(pc3, OP_EQ, cell_queue_pop(&cq));
+ tt_ptr_op(pc2, OP_EQ, cell_queue_pop(&cq));
+ tt_ptr_op(pc1, OP_EQ, cell_queue_pop(&cq));
+ tt_int_op(cq.n, OP_EQ, 0);
+ tt_ptr_op(NULL, OP_EQ, cell_queue_pop(&cq));
/* Try a packed copy (wide, then narrow, which is a bit of a cheat, since a
* real cell queue has only one type.) */
@@ -64,32 +60,32 @@ test_cq_manip(void *arg)
cell.circ_id = 0x2013;
cell_queue_append_packed_copy(NULL /*circ*/, &cq, 0 /*exitward*/, &cell,
0 /*wide*/, 0 /*stats*/);
- tt_int_op(cq.n, ==, 2);
+ tt_int_op(cq.n, OP_EQ, 2);
pc_tmp = cell_queue_pop(&cq);
- tt_int_op(cq.n, ==, 1);
- tt_ptr_op(pc_tmp, !=, NULL);
- test_mem_op(pc_tmp->body, ==, "\x12\x34\x56\x78\x0a", 5);
- test_mem_op(pc_tmp->body+5, ==, cell.payload, sizeof(cell.payload));
+ tt_int_op(cq.n, OP_EQ, 1);
+ tt_ptr_op(pc_tmp, OP_NE, NULL);
+ tt_mem_op(pc_tmp->body, OP_EQ, "\x12\x34\x56\x78\x0a", 5);
+ tt_mem_op(pc_tmp->body+5, OP_EQ, cell.payload, sizeof(cell.payload));
packed_cell_free(pc_tmp);
pc_tmp = cell_queue_pop(&cq);
- tt_int_op(cq.n, ==, 0);
- tt_ptr_op(pc_tmp, !=, NULL);
- test_mem_op(pc_tmp->body, ==, "\x20\x13\x0a", 3);
- test_mem_op(pc_tmp->body+3, ==, cell.payload, sizeof(cell.payload));
+ tt_int_op(cq.n, OP_EQ, 0);
+ tt_ptr_op(pc_tmp, OP_NE, NULL);
+ tt_mem_op(pc_tmp->body, OP_EQ, "\x20\x13\x0a", 3);
+ tt_mem_op(pc_tmp->body+3, OP_EQ, cell.payload, sizeof(cell.payload));
packed_cell_free(pc_tmp);
pc_tmp = NULL;
- tt_ptr_op(NULL, ==, cell_queue_pop(&cq));
+ tt_ptr_op(NULL, OP_EQ, cell_queue_pop(&cq));
/* Now make sure cell_queue_clear works. */
cell_queue_append(&cq, pc2);
cell_queue_append(&cq, pc1);
- tt_int_op(cq.n, ==, 2);
+ tt_int_op(cq.n, OP_EQ, 2);
cell_queue_clear(&cq);
pc2 = pc1 = NULL; /* prevent double-free */
- tt_int_op(cq.n, ==, 0);
+ tt_int_op(cq.n, OP_EQ, 0);
done:
packed_cell_free(pc1);
@@ -99,10 +95,6 @@ test_cq_manip(void *arg)
packed_cell_free(pc_tmp);
cell_queue_clear(&cq);
-
-#ifdef ENABLE_MEMPOOLS
- free_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
}
static void
@@ -114,10 +106,6 @@ test_circuit_n_cells(void *arg)
(void)arg;
-#ifdef ENABLE_MEMPOOLS
- init_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
-
pc1 = packed_cell_new();
pc2 = packed_cell_new();
pc3 = packed_cell_new();
@@ -129,25 +117,21 @@ test_circuit_n_cells(void *arg)
origin_c = origin_circuit_new();
origin_c->base_.purpose = CIRCUIT_PURPOSE_C_GENERAL;
- tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), ==, 0);
+ tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), OP_EQ, 0);
cell_queue_append(&or_c->p_chan_cells, pc1);
- tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), ==, 1);
+ tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), OP_EQ, 1);
cell_queue_append(&or_c->base_.n_chan_cells, pc2);
cell_queue_append(&or_c->base_.n_chan_cells, pc3);
- tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), ==, 3);
+ tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(or_c)), OP_EQ, 3);
- tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(origin_c)), ==, 0);
+ tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(origin_c)), OP_EQ, 0);
cell_queue_append(&origin_c->base_.n_chan_cells, pc4);
cell_queue_append(&origin_c->base_.n_chan_cells, pc5);
- tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(origin_c)), ==, 2);
+ tt_int_op(n_cells_in_circ_queues(TO_CIRCUIT(origin_c)), OP_EQ, 2);
done:
circuit_free(TO_CIRCUIT(or_c));
circuit_free(TO_CIRCUIT(origin_c));
-
-#ifdef ENABLE_MEMPOOLS
- free_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
}
struct testcase_t cell_queue_tests[] = {
diff --git a/src/test/test_channel.c b/src/test/test_channel.c
new file mode 100644
index 0000000000..846e419fea
--- /dev/null
+++ b/src/test/test_channel.c
@@ -0,0 +1,1784 @@
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define TOR_CHANNEL_INTERNAL_
+#define CHANNEL_PRIVATE_
+#include "or.h"
+#include "channel.h"
+/* For channel_note_destroy_not_pending */
+#include "circuitlist.h"
+#include "circuitmux.h"
+/* For var_cell_free */
+#include "connection_or.h"
+/* For packed_cell stuff */
+#define RELAY_PRIVATE
+#include "relay.h"
+/* For init/free stuff */
+#include "scheduler.h"
+
+/* Test suite stuff */
+#include "test.h"
+#include "fakechans.h"
+
+/* This comes from channel.c */
+extern uint64_t estimated_total_queue_size;
+
+static int test_chan_accept_cells = 0;
+static int test_chan_fixed_cells_recved = 0;
+static cell_t * test_chan_last_seen_fixed_cell_ptr = NULL;
+static int test_chan_var_cells_recved = 0;
+static var_cell_t * test_chan_last_seen_var_cell_ptr = NULL;
+static int test_cells_written = 0;
+static int test_destroy_not_pending_calls = 0;
+static int test_doesnt_want_writes_count = 0;
+static int test_dumpstats_calls = 0;
+static int test_has_waiting_cells_count = 0;
+static double test_overhead_estimate = 1.0f;
+static int test_releases_count = 0;
+static circuitmux_t *test_target_cmux = NULL;
+static unsigned int test_cmux_cells = 0;
+static channel_t *dump_statistics_mock_target = NULL;
+static int dump_statistics_mock_matches = 0;
+
+static void chan_test_channel_dump_statistics_mock(
+ channel_t *chan, int severity);
+static int chan_test_channel_flush_from_first_active_circuit_mock(
+ channel_t *chan, int max);
+static unsigned int chan_test_circuitmux_num_cells_mock(circuitmux_t *cmux);
+static void channel_note_destroy_not_pending_mock(channel_t *ch,
+ circid_t circid);
+static void chan_test_cell_handler(channel_t *ch,
+ cell_t *cell);
+static const char * chan_test_describe_transport(channel_t *ch);
+static void chan_test_dumpstats(channel_t *ch, int severity);
+static void chan_test_var_cell_handler(channel_t *ch,
+ var_cell_t *var_cell);
+static void chan_test_close(channel_t *ch);
+static void chan_test_error(channel_t *ch);
+static void chan_test_finish_close(channel_t *ch);
+static const char * chan_test_get_remote_descr(channel_t *ch, int flags);
+static int chan_test_is_canonical(channel_t *ch, int req);
+static size_t chan_test_num_bytes_queued(channel_t *ch);
+static int chan_test_num_cells_writeable(channel_t *ch);
+static int chan_test_write_cell(channel_t *ch, cell_t *cell);
+static int chan_test_write_packed_cell(channel_t *ch,
+ packed_cell_t *packed_cell);
+static int chan_test_write_var_cell(channel_t *ch, var_cell_t *var_cell);
+static void scheduler_channel_doesnt_want_writes_mock(channel_t *ch);
+
+static void test_channel_dumpstats(void *arg);
+static void test_channel_flush(void *arg);
+static void test_channel_flushmux(void *arg);
+static void test_channel_incoming(void *arg);
+static void test_channel_lifecycle(void *arg);
+static void test_channel_multi(void *arg);
+static void test_channel_queue_incoming(void *arg);
+static void test_channel_queue_size(void *arg);
+static void test_channel_write(void *arg);
+
+static void
+channel_note_destroy_not_pending_mock(channel_t *ch,
+ circid_t circid)
+{
+ (void)ch;
+ (void)circid;
+
+ ++test_destroy_not_pending_calls;
+}
+
+static const char *
+chan_test_describe_transport(channel_t *ch)
+{
+ tt_assert(ch != NULL);
+
+ done:
+ return "Fake channel for unit tests";
+}
+
+/**
+ * Mock for channel_dump_statistics(); if the channel matches the
+ * target, bump a counter - otherwise ignore.
+ */
+
+static void
+chan_test_channel_dump_statistics_mock(channel_t *chan, int severity)
+{
+ tt_assert(chan != NULL);
+
+ (void)severity;
+
+ if (chan != NULL && chan == dump_statistics_mock_target) {
+ ++dump_statistics_mock_matches;
+ }
+
+ done:
+ return;
+}
+
+/**
+ * If the target cmux is the cmux for chan, make fake cells up to the
+ * target number of cells and write them to chan. Otherwise, invoke
+ * the real channel_flush_from_first_active_circuit().
+ */
+
+static int
+chan_test_channel_flush_from_first_active_circuit_mock(channel_t *chan,
+ int max)
+{
+ int result = 0, c = 0;
+ packed_cell_t *cell = NULL;
+
+ tt_assert(chan != NULL);
+ if (test_target_cmux != NULL &&
+ test_target_cmux == chan->cmux) {
+ while (c <= max && test_cmux_cells > 0) {
+ cell = packed_cell_new();
+ channel_write_packed_cell(chan, cell);
+ ++c;
+ --test_cmux_cells;
+ }
+ result = c;
+ } else {
+ result = channel_flush_from_first_active_circuit__real(chan, max);
+ }
+
+ done:
+ return result;
+}
+
+/**
+ * If we have a target cmux set and this matches it, lie about how
+ * many cells we have according to the number indicated; otherwise
+ * pass to the real circuitmux_num_cells().
+ */
+
+static unsigned int
+chan_test_circuitmux_num_cells_mock(circuitmux_t *cmux)
+{
+ unsigned int result = 0;
+
+ tt_assert(cmux != NULL);
+ if (cmux != NULL) {
+ if (cmux == test_target_cmux) {
+ result = test_cmux_cells;
+ } else {
+ result = circuitmux_num_cells__real(cmux);
+ }
+ }
+
+ done:
+
+ return result;
+}
+
+/*
+ * Handle an incoming fixed-size cell for unit tests
+ */
+
+static void
+chan_test_cell_handler(channel_t *ch,
+ cell_t *cell)
+{
+ tt_assert(ch);
+ tt_assert(cell);
+
+ test_chan_last_seen_fixed_cell_ptr = cell;
+ ++test_chan_fixed_cells_recved;
+
+ done:
+ return;
+}
+
+/*
+ * Fake transport-specific stats call
+ */
+
+static void
+chan_test_dumpstats(channel_t *ch, int severity)
+{
+ tt_assert(ch != NULL);
+
+ (void)severity;
+
+ ++test_dumpstats_calls;
+
+ done:
+ return;
+}
+
+/*
+ * Handle an incoming variable-size cell for unit tests
+ */
+
+static void
+chan_test_var_cell_handler(channel_t *ch,
+ var_cell_t *var_cell)
+{
+ tt_assert(ch);
+ tt_assert(var_cell);
+
+ test_chan_last_seen_var_cell_ptr = var_cell;
+ ++test_chan_var_cells_recved;
+
+ done:
+ return;
+}
+
+static void
+chan_test_close(channel_t *ch)
+{
+ tt_assert(ch);
+
+ done:
+ return;
+}
+
+/*
+ * Close a channel through the error path
+ */
+
+static void
+chan_test_error(channel_t *ch)
+{
+ tt_assert(ch);
+ tt_assert(!(ch->state == CHANNEL_STATE_CLOSING ||
+ ch->state == CHANNEL_STATE_ERROR ||
+ ch->state == CHANNEL_STATE_CLOSED));
+
+ channel_close_for_error(ch);
+
+ done:
+ return;
+}
+
+/*
+ * Finish closing a channel from CHANNEL_STATE_CLOSING
+ */
+
+static void
+chan_test_finish_close(channel_t *ch)
+{
+ tt_assert(ch);
+ tt_assert(ch->state == CHANNEL_STATE_CLOSING);
+
+ channel_closed(ch);
+
+ done:
+ return;
+}
+
+static const char *
+chan_test_get_remote_descr(channel_t *ch, int flags)
+{
+ tt_assert(ch);
+ tt_int_op(flags & ~(GRD_FLAG_ORIGINAL | GRD_FLAG_ADDR_ONLY), ==, 0);
+
+ done:
+ return "Fake channel for unit tests; no real endpoint";
+}
+
+static double
+chan_test_get_overhead_estimate(channel_t *ch)
+{
+ tt_assert(ch);
+
+ done:
+ return test_overhead_estimate;
+}
+
+static int
+chan_test_is_canonical(channel_t *ch, int req)
+{
+ tt_assert(ch != NULL);
+ tt_assert(req == 0 || req == 1);
+
+ done:
+ /* Fake channels are always canonical */
+ return 1;
+}
+
+static size_t
+chan_test_num_bytes_queued(channel_t *ch)
+{
+ tt_assert(ch);
+
+ done:
+ return 0;
+}
+
+static int
+chan_test_num_cells_writeable(channel_t *ch)
+{
+ tt_assert(ch);
+
+ done:
+ return 32;
+}
+
+static int
+chan_test_write_cell(channel_t *ch, cell_t *cell)
+{
+ int rv = 0;
+
+ tt_assert(ch);
+ tt_assert(cell);
+
+ if (test_chan_accept_cells) {
+ /* Free the cell and bump the counter */
+ tor_free(cell);
+ ++test_cells_written;
+ rv = 1;
+ }
+ /* else return 0, we didn't accept it */
+
+ done:
+ return rv;
+}
+
+static int
+chan_test_write_packed_cell(channel_t *ch,
+ packed_cell_t *packed_cell)
+{
+ int rv = 0;
+
+ tt_assert(ch);
+ tt_assert(packed_cell);
+
+ if (test_chan_accept_cells) {
+ /* Free the cell and bump the counter */
+ packed_cell_free(packed_cell);
+ ++test_cells_written;
+ rv = 1;
+ }
+ /* else return 0, we didn't accept it */
+
+ done:
+ return rv;
+}
+
+static int
+chan_test_write_var_cell(channel_t *ch, var_cell_t *var_cell)
+{
+ int rv = 0;
+
+ tt_assert(ch);
+ tt_assert(var_cell);
+
+ if (test_chan_accept_cells) {
+ /* Free the cell and bump the counter */
+ var_cell_free(var_cell);
+ ++test_cells_written;
+ rv = 1;
+ }
+ /* else return 0, we didn't accept it */
+
+ done:
+ return rv;
+}
+
+/**
+ * Fill out c with a new fake cell for test suite use
+ */
+
+void
+make_fake_cell(cell_t *c)
+{
+ tt_assert(c != NULL);
+
+ c->circ_id = 1;
+ c->command = CELL_RELAY;
+ memset(c->payload, 0, CELL_PAYLOAD_SIZE);
+
+ done:
+ return;
+}
+
+/**
+ * Fill out c with a new fake var_cell for test suite use
+ */
+
+void
+make_fake_var_cell(var_cell_t *c)
+{
+ tt_assert(c != NULL);
+
+ c->circ_id = 1;
+ c->command = CELL_VERSIONS;
+ c->payload_len = CELL_PAYLOAD_SIZE / 2;
+ memset(c->payload, 0, c->payload_len);
+
+ done:
+ return;
+}
+
+/**
+ * Set up a new fake channel for the test suite
+ */
+
+channel_t *
+new_fake_channel(void)
+{
+ channel_t *chan = tor_malloc_zero(sizeof(channel_t));
+ channel_init(chan);
+
+ chan->close = chan_test_close;
+ chan->get_overhead_estimate = chan_test_get_overhead_estimate;
+ chan->get_remote_descr = chan_test_get_remote_descr;
+ chan->num_bytes_queued = chan_test_num_bytes_queued;
+ chan->num_cells_writeable = chan_test_num_cells_writeable;
+ chan->write_cell = chan_test_write_cell;
+ chan->write_packed_cell = chan_test_write_packed_cell;
+ chan->write_var_cell = chan_test_write_var_cell;
+ chan->state = CHANNEL_STATE_OPEN;
+
+ return chan;
+}
+
+void
+free_fake_channel(channel_t *chan)
+{
+ cell_queue_entry_t *cell, *cell_tmp;
+
+ if (! chan)
+ return;
+
+ if (chan->cmux)
+ circuitmux_free(chan->cmux);
+
+ TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
+ cell_queue_entry_free(cell, 0);
+ }
+ TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
+ cell_queue_entry_free(cell, 0);
+ }
+
+ tor_free(chan);
+}
+
+/**
+ * Counter query for scheduler_channel_has_waiting_cells_mock()
+ */
+
+int
+get_mock_scheduler_has_waiting_cells_count(void)
+{
+ return test_has_waiting_cells_count;
+}
+
+/**
+ * Mock for scheduler_channel_has_waiting_cells()
+ */
+
+void
+scheduler_channel_has_waiting_cells_mock(channel_t *ch)
+{
+ (void)ch;
+
+ /* Increment counter */
+ ++test_has_waiting_cells_count;
+
+ return;
+}
+
+static void
+scheduler_channel_doesnt_want_writes_mock(channel_t *ch)
+{
+ (void)ch;
+
+ /* Increment counter */
+ ++test_doesnt_want_writes_count;
+
+ return;
+}
+
+/**
+ * Counter query for scheduler_release_channel_mock()
+ */
+
+int
+get_mock_scheduler_release_channel_count(void)
+{
+ return test_releases_count;
+}
+
+/**
+ * Mock for scheduler_release_channel()
+ */
+
+void
+scheduler_release_channel_mock(channel_t *ch)
+{
+ (void)ch;
+
+ /* Increment counter */
+ ++test_releases_count;
+
+ return;
+}
+
+/**
+ * Test for channel_dumpstats() and limited test for
+ * channel_dump_statistics()
+ */
+
+static void
+test_channel_dumpstats(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ int old_count;
+
+ (void)arg;
+
+ /* Mock these for duration of the test */
+ MOCK(scheduler_channel_doesnt_want_writes,
+ scheduler_channel_doesnt_want_writes_mock);
+ MOCK(scheduler_release_channel,
+ scheduler_release_channel_mock);
+
+ /* Set up a new fake channel */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->cmux = circuitmux_alloc();
+
+ /* Try to register it */
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Set up mock */
+ dump_statistics_mock_target = ch;
+ dump_statistics_mock_matches = 0;
+ MOCK(channel_dump_statistics,
+ chan_test_channel_dump_statistics_mock);
+
+ /* Call channel_dumpstats() */
+ channel_dumpstats(LOG_DEBUG);
+
+ /* Assert that we hit the mock */
+ tt_int_op(dump_statistics_mock_matches, ==, 1);
+
+ /* Close the channel */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+
+ /* Try again and hit the finished channel */
+ channel_dumpstats(LOG_DEBUG);
+ tt_int_op(dump_statistics_mock_matches, ==, 2);
+
+ channel_run_cleanup();
+ ch = NULL;
+
+ /* Now we should hit nothing */
+ channel_dumpstats(LOG_DEBUG);
+ tt_int_op(dump_statistics_mock_matches, ==, 2);
+
+ /* Unmock */
+ UNMOCK(channel_dump_statistics);
+ dump_statistics_mock_target = NULL;
+ dump_statistics_mock_matches = 0;
+
+ /* Now make another channel */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->cmux = circuitmux_alloc();
+ channel_register(ch);
+ tt_assert(ch->registered);
+ /* Lie about its age so dumpstats gets coverage for rate calculations */
+ ch->timestamp_created = time(NULL) - 30;
+ tt_assert(ch->timestamp_created > 0);
+ tt_assert(time(NULL) > ch->timestamp_created);
+
+ /* Put cells through it both ways to make the counters non-zero */
+ cell = tor_malloc_zero(sizeof(*cell));
+ make_fake_cell(cell);
+ test_chan_accept_cells = 1;
+ old_count = test_cells_written;
+ channel_write_cell(ch, cell);
+ cell = NULL;
+ tt_int_op(test_cells_written, ==, old_count + 1);
+ tt_assert(ch->n_bytes_xmitted > 0);
+ tt_assert(ch->n_cells_xmitted > 0);
+
+ /* Receive path */
+ channel_set_cell_handlers(ch,
+ chan_test_cell_handler,
+ chan_test_var_cell_handler);
+ tt_ptr_op(channel_get_cell_handler(ch), ==, chan_test_cell_handler);
+ tt_ptr_op(channel_get_var_cell_handler(ch), ==, chan_test_var_cell_handler);
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ old_count = test_chan_fixed_cells_recved;
+ channel_queue_cell(ch, cell);
+ tor_free(cell);
+ tt_int_op(test_chan_fixed_cells_recved, ==, old_count + 1);
+ tt_assert(ch->n_bytes_recved > 0);
+ tt_assert(ch->n_cells_recved > 0);
+
+ /* Test channel_dump_statistics */
+ ch->describe_transport = chan_test_describe_transport;
+ ch->dumpstats = chan_test_dumpstats;
+ ch->is_canonical = chan_test_is_canonical;
+ old_count = test_dumpstats_calls;
+ channel_dump_statistics(ch, LOG_DEBUG);
+ tt_int_op(test_dumpstats_calls, ==, old_count + 1);
+
+ /* Close the channel */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ done:
+ tor_free(cell);
+ free_fake_channel(ch);
+
+ UNMOCK(scheduler_channel_doesnt_want_writes);
+ UNMOCK(scheduler_release_channel);
+
+ return;
+}
+
+static void
+test_channel_flush(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ packed_cell_t *p_cell = NULL;
+ var_cell_t *v_cell = NULL;
+ int init_count;
+
+ (void)arg;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+
+ /* Cache the original count */
+ init_count = test_cells_written;
+
+ /* Stop accepting so we can queue some */
+ test_chan_accept_cells = 0;
+
+ /* Queue a regular cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch, cell);
+ /* It should be queued, so assert that we didn't write it */
+ tt_int_op(test_cells_written, ==, init_count);
+
+ /* Queue a var cell */
+ v_cell = tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ make_fake_var_cell(v_cell);
+ channel_write_var_cell(ch, v_cell);
+ /* It should be queued, so assert that we didn't write it */
+ tt_int_op(test_cells_written, ==, init_count);
+
+ /* Try a packed cell now */
+ p_cell = packed_cell_new();
+ tt_assert(p_cell);
+ channel_write_packed_cell(ch, p_cell);
+ /* It should be queued, so assert that we didn't write it */
+ tt_int_op(test_cells_written, ==, init_count);
+
+ /* Now allow writes through again */
+ test_chan_accept_cells = 1;
+
+ /* ...and flush */
+ channel_flush_cells(ch);
+
+ /* All three should have gone through */
+ tt_int_op(test_cells_written, ==, init_count + 3);
+
+ done:
+ tor_free(ch);
+
+ return;
+}
+
+/**
+ * Channel flush tests that require cmux mocking
+ */
+
+static void
+test_channel_flushmux(void *arg)
+{
+ channel_t *ch = NULL;
+ int old_count, q_len_before, q_len_after;
+ ssize_t result;
+
+ (void)arg;
+
+ /* Install mocks we need for this test */
+ MOCK(channel_flush_from_first_active_circuit,
+ chan_test_channel_flush_from_first_active_circuit_mock);
+ MOCK(circuitmux_num_cells,
+ chan_test_circuitmux_num_cells_mock);
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->cmux = circuitmux_alloc();
+
+ old_count = test_cells_written;
+
+ test_target_cmux = ch->cmux;
+ test_cmux_cells = 1;
+
+ /* Enable cell acceptance */
+ test_chan_accept_cells = 1;
+
+ result = channel_flush_some_cells(ch, 1);
+
+ tt_int_op(result, ==, 1);
+ tt_int_op(test_cells_written, ==, old_count + 1);
+ tt_int_op(test_cmux_cells, ==, 0);
+
+ /* Now try it without accepting to force them into the queue */
+ test_chan_accept_cells = 0;
+ test_cmux_cells = 1;
+ q_len_before = chan_cell_queue_len(&(ch->outgoing_queue));
+
+ result = channel_flush_some_cells(ch, 1);
+
+ /* We should not have actually flushed any */
+ tt_int_op(result, ==, 0);
+ tt_int_op(test_cells_written, ==, old_count + 1);
+ /* But we should have gotten to the fake cellgen loop */
+ tt_int_op(test_cmux_cells, ==, 0);
+ /* ...and we should have a queued cell */
+ q_len_after = chan_cell_queue_len(&(ch->outgoing_queue));
+ tt_int_op(q_len_after, ==, q_len_before + 1);
+
+ /* Now accept cells again and drain the queue */
+ test_chan_accept_cells = 1;
+ channel_flush_cells(ch);
+ tt_int_op(test_cells_written, ==, old_count + 2);
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ test_target_cmux = NULL;
+ test_cmux_cells = 0;
+
+ done:
+ if (ch)
+ circuitmux_free(ch->cmux);
+ tor_free(ch);
+
+ UNMOCK(channel_flush_from_first_active_circuit);
+ UNMOCK(circuitmux_num_cells);
+
+ test_chan_accept_cells = 0;
+
+ return;
+}
+
+static void
+test_channel_incoming(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ var_cell_t *var_cell = NULL;
+ int old_count;
+
+ (void)arg;
+
+ /* Mock these for duration of the test */
+ MOCK(scheduler_channel_doesnt_want_writes,
+ scheduler_channel_doesnt_want_writes_mock);
+ MOCK(scheduler_release_channel,
+ scheduler_release_channel_mock);
+
+ /* Accept cells to lower layer */
+ test_chan_accept_cells = 1;
+ /* Use default overhead factor */
+ test_overhead_estimate = 1.0f;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+ /* Start it off in OPENING */
+ ch->state = CHANNEL_STATE_OPENING;
+ /* We'll need a cmux */
+ ch->cmux = circuitmux_alloc();
+
+ /* Install incoming cell handlers */
+ channel_set_cell_handlers(ch,
+ chan_test_cell_handler,
+ chan_test_var_cell_handler);
+ /* Test cell handler getters */
+ tt_ptr_op(channel_get_cell_handler(ch), ==, chan_test_cell_handler);
+ tt_ptr_op(channel_get_var_cell_handler(ch), ==, chan_test_var_cell_handler);
+
+ /* Try to register it */
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Open it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_OPEN);
+
+ /* Receive a fixed cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ old_count = test_chan_fixed_cells_recved;
+ channel_queue_cell(ch, cell);
+ tor_free(cell);
+ tt_int_op(test_chan_fixed_cells_recved, ==, old_count + 1);
+
+ /* Receive a variable-size cell */
+ var_cell = tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ make_fake_var_cell(var_cell);
+ old_count = test_chan_var_cells_recved;
+ channel_queue_var_cell(ch, var_cell);
+ tor_free(cell);
+ tt_int_op(test_chan_var_cells_recved, ==, old_count + 1);
+
+ /* Close it */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ done:
+ free_fake_channel(ch);
+ tor_free(cell);
+ tor_free(var_cell);
+
+ UNMOCK(scheduler_channel_doesnt_want_writes);
+ UNMOCK(scheduler_release_channel);
+
+ return;
+}
+
+/**
+ * Normal channel lifecycle test:
+ *
+ * OPENING->OPEN->MAINT->OPEN->CLOSING->CLOSED
+ */
+
+static void
+test_channel_lifecycle(void *arg)
+{
+ channel_t *ch1 = NULL, *ch2 = NULL;
+ cell_t *cell = NULL;
+ int old_count, init_doesnt_want_writes_count;
+ int init_releases_count;
+
+ (void)arg;
+
+ /* Mock these for the whole lifecycle test */
+ MOCK(scheduler_channel_doesnt_want_writes,
+ scheduler_channel_doesnt_want_writes_mock);
+ MOCK(scheduler_release_channel,
+ scheduler_release_channel_mock);
+
+ /* Cache some initial counter values */
+ init_doesnt_want_writes_count = test_doesnt_want_writes_count;
+ init_releases_count = test_releases_count;
+
+ /* Accept cells to lower layer */
+ test_chan_accept_cells = 1;
+ /* Use default overhead factor */
+ test_overhead_estimate = 1.0f;
+
+ ch1 = new_fake_channel();
+ tt_assert(ch1);
+ /* Start it off in OPENING */
+ ch1->state = CHANNEL_STATE_OPENING;
+ /* We'll need a cmux */
+ ch1->cmux = circuitmux_alloc();
+
+ /* Try to register it */
+ channel_register(ch1);
+ tt_assert(ch1->registered);
+
+ /* Try to write a cell through (should queue) */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ old_count = test_cells_written;
+ channel_write_cell(ch1, cell);
+ tt_int_op(old_count, ==, test_cells_written);
+
+ /* Move it to OPEN and flush */
+ channel_change_state(ch1, CHANNEL_STATE_OPEN);
+
+ /* Queue should drain */
+ tt_int_op(old_count + 1, ==, test_cells_written);
+
+ /* Get another one */
+ ch2 = new_fake_channel();
+ tt_assert(ch2);
+ ch2->state = CHANNEL_STATE_OPENING;
+ ch2->cmux = circuitmux_alloc();
+
+ /* Register */
+ channel_register(ch2);
+ tt_assert(ch2->registered);
+
+ /* Check counters */
+ tt_int_op(test_doesnt_want_writes_count, ==, init_doesnt_want_writes_count);
+ tt_int_op(test_releases_count, ==, init_releases_count);
+
+ /* Move ch1 to MAINT */
+ channel_change_state(ch1, CHANNEL_STATE_MAINT);
+ tt_int_op(test_doesnt_want_writes_count, ==,
+ init_doesnt_want_writes_count + 1);
+ tt_int_op(test_releases_count, ==, init_releases_count);
+
+ /* Move ch2 to OPEN */
+ channel_change_state(ch2, CHANNEL_STATE_OPEN);
+ tt_int_op(test_doesnt_want_writes_count, ==,
+ init_doesnt_want_writes_count + 1);
+ tt_int_op(test_releases_count, ==, init_releases_count);
+
+ /* Move ch1 back to OPEN */
+ channel_change_state(ch1, CHANNEL_STATE_OPEN);
+ tt_int_op(test_doesnt_want_writes_count, ==,
+ init_doesnt_want_writes_count + 1);
+ tt_int_op(test_releases_count, ==, init_releases_count);
+
+ /* Mark ch2 for close */
+ channel_mark_for_close(ch2);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_CLOSING);
+ tt_int_op(test_doesnt_want_writes_count, ==,
+ init_doesnt_want_writes_count + 1);
+ tt_int_op(test_releases_count, ==, init_releases_count + 1);
+
+ /* Shut down channels */
+ channel_free_all();
+ ch1 = ch2 = NULL;
+ tt_int_op(test_doesnt_want_writes_count, ==,
+ init_doesnt_want_writes_count + 1);
+ /* channel_free() calls scheduler_release_channel() */
+ tt_int_op(test_releases_count, ==, init_releases_count + 4);
+
+ done:
+ free_fake_channel(ch1);
+ free_fake_channel(ch2);
+
+ UNMOCK(scheduler_channel_doesnt_want_writes);
+ UNMOCK(scheduler_release_channel);
+
+ return;
+}
+
+/**
+ * Weird channel lifecycle test:
+ *
+ * OPENING->CLOSING->CLOSED
+ * OPENING->OPEN->CLOSING->ERROR
+ * OPENING->OPEN->MAINT->CLOSING->CLOSED
+ * OPENING->OPEN->MAINT->CLOSING->ERROR
+ */
+
+static void
+test_channel_lifecycle_2(void *arg)
+{
+ channel_t *ch = NULL;
+
+ (void)arg;
+
+ /* Mock these for the whole lifecycle test */
+ MOCK(scheduler_channel_doesnt_want_writes,
+ scheduler_channel_doesnt_want_writes_mock);
+ MOCK(scheduler_release_channel,
+ scheduler_release_channel_mock);
+
+ /* Accept cells to lower layer */
+ test_chan_accept_cells = 1;
+ /* Use default overhead factor */
+ test_overhead_estimate = 1.0f;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+ /* Start it off in OPENING */
+ ch->state = CHANNEL_STATE_OPENING;
+ /* The full lifecycle test needs a cmux */
+ ch->cmux = circuitmux_alloc();
+
+ /* Try to register it */
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Try to close it */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+
+ /* Finish closing it */
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ /* Now try OPENING->OPEN->CLOSING->ERROR */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->state = CHANNEL_STATE_OPENING;
+ ch->cmux = circuitmux_alloc();
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Finish opening it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+
+ /* Error exit from lower layer */
+ chan_test_error(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_ERROR);
+ channel_run_cleanup();
+ ch = NULL;
+
+ /* OPENING->OPEN->MAINT->CLOSING->CLOSED close from maintenance state */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->state = CHANNEL_STATE_OPENING;
+ ch->cmux = circuitmux_alloc();
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Finish opening it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_OPEN);
+
+ /* Go to maintenance state */
+ channel_change_state(ch, CHANNEL_STATE_MAINT);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_MAINT);
+
+ /* Lower layer close */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+
+ /* Finish */
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ /*
+ * OPENING->OPEN->MAINT->CLOSING->CLOSED lower-layer close during
+ * maintenance state
+ */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->state = CHANNEL_STATE_OPENING;
+ ch->cmux = circuitmux_alloc();
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Finish opening it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_OPEN);
+
+ /* Go to maintenance state */
+ channel_change_state(ch, CHANNEL_STATE_MAINT);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_MAINT);
+
+ /* Lower layer close */
+ channel_close_from_lower_layer(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+
+ /* Finish */
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ /* OPENING->OPEN->MAINT->CLOSING->ERROR */
+ ch = new_fake_channel();
+ tt_assert(ch);
+ ch->state = CHANNEL_STATE_OPENING;
+ ch->cmux = circuitmux_alloc();
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Finish opening it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_OPEN);
+
+ /* Go to maintenance state */
+ channel_change_state(ch, CHANNEL_STATE_MAINT);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_MAINT);
+
+ /* Lower layer close */
+ chan_test_error(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+
+ /* Finish */
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_ERROR);
+ channel_run_cleanup();
+ ch = NULL;
+
+ /* Shut down channels */
+ channel_free_all();
+
+ done:
+ tor_free(ch);
+
+ UNMOCK(scheduler_channel_doesnt_want_writes);
+ UNMOCK(scheduler_release_channel);
+
+ return;
+}
+
+static void
+test_channel_multi(void *arg)
+{
+ channel_t *ch1 = NULL, *ch2 = NULL;
+ uint64_t global_queue_estimate;
+ cell_t *cell = NULL;
+
+ (void)arg;
+
+ /* Accept cells to lower layer */
+ test_chan_accept_cells = 1;
+ /* Use default overhead factor */
+ test_overhead_estimate = 1.0f;
+
+ ch1 = new_fake_channel();
+ tt_assert(ch1);
+ ch2 = new_fake_channel();
+ tt_assert(ch2);
+
+ /* Initial queue size update */
+ channel_update_xmit_queue_size(ch1);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 0);
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Queue some cells, check queue estimates */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch1, cell);
+
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch2, cell);
+
+ channel_update_xmit_queue_size(ch1);
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 0);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Stop accepting cells at lower layer */
+ test_chan_accept_cells = 0;
+
+ /* Queue some cells and check queue estimates */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch1, cell);
+
+ channel_update_xmit_queue_size(ch1);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 512);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 512);
+
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch2, cell);
+
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 512);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 1024);
+
+ /* Allow cells through again */
+ test_chan_accept_cells = 1;
+
+ /* Flush chan 2 */
+ channel_flush_cells(ch2);
+
+ /* Update and check queue sizes */
+ channel_update_xmit_queue_size(ch1);
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 512);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 512);
+
+ /* Flush chan 1 */
+ channel_flush_cells(ch1);
+
+ /* Update and check queue sizes */
+ channel_update_xmit_queue_size(ch1);
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 0);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Now block again */
+ test_chan_accept_cells = 0;
+
+ /* Queue some cells */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch1, cell);
+
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch2, cell);
+ cell = NULL;
+
+ /* Check the estimates */
+ channel_update_xmit_queue_size(ch1);
+ channel_update_xmit_queue_size(ch2);
+ tt_u64_op(ch1->bytes_queued_for_xmit, ==, 512);
+ tt_u64_op(ch2->bytes_queued_for_xmit, ==, 512);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 1024);
+
+ /* Now close channel 2; it should be subtracted from the global queue */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_mark_for_close(ch2);
+ UNMOCK(scheduler_release_channel);
+
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 512);
+
+ /*
+ * Since the fake channels aren't registered, channel_free_all() can't
+ * see them properly.
+ */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_mark_for_close(ch1);
+ UNMOCK(scheduler_release_channel);
+
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Now free everything */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_free_all();
+ UNMOCK(scheduler_release_channel);
+
+ done:
+ free_fake_channel(ch1);
+ free_fake_channel(ch2);
+
+ return;
+}
+
+/**
+ * Check some hopefully-impossible edge cases in the channel queue we
+ * can only trigger by doing evil things to the queue directly.
+ */
+
+static void
+test_channel_queue_impossible(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ packed_cell_t *packed_cell = NULL;
+ var_cell_t *var_cell = NULL;
+ int old_count;
+ cell_queue_entry_t *q = NULL;
+ uint64_t global_queue_estimate;
+ uintptr_t cellintptr;
+
+ /* Cache the global queue size (see below) */
+ global_queue_estimate = channel_get_global_queue_estimate();
+
+ (void)arg;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+
+ /* We test queueing here; tell it not to accept cells */
+ test_chan_accept_cells = 0;
+ /* ...and keep it from trying to flush the queue */
+ ch->state = CHANNEL_STATE_MAINT;
+
+ /* Cache the cell written count */
+ old_count = test_cells_written;
+
+ /* Assert that the queue is initially empty */
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ /* Get a fresh cell and write it to the channel*/
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ cellintptr = (uintptr_t)(void*)cell;
+ channel_write_cell(ch, cell);
+
+ /* Now it should be queued */
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 1);
+ q = TOR_SIMPLEQ_FIRST(&(ch->outgoing_queue));
+ tt_assert(q);
+ if (q) {
+ tt_int_op(q->type, ==, CELL_QUEUE_FIXED);
+ tt_assert((uintptr_t)q->u.fixed.cell == cellintptr);
+ }
+ /* Do perverse things to it */
+ tor_free(q->u.fixed.cell);
+ q->u.fixed.cell = NULL;
+
+ /*
+ * Now change back to open with channel_change_state() and assert that it
+ * gets thrown away properly.
+ */
+ test_chan_accept_cells = 1;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_assert(test_cells_written == old_count);
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ /* Same thing but for a var_cell */
+
+ test_chan_accept_cells = 0;
+ ch->state = CHANNEL_STATE_MAINT;
+ var_cell = tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ make_fake_var_cell(var_cell);
+ cellintptr = (uintptr_t)(void*)var_cell;
+ channel_write_var_cell(ch, var_cell);
+
+ /* Check that it's queued */
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 1);
+ q = TOR_SIMPLEQ_FIRST(&(ch->outgoing_queue));
+ tt_assert(q);
+ if (q) {
+ tt_int_op(q->type, ==, CELL_QUEUE_VAR);
+ tt_assert((uintptr_t)q->u.var.var_cell == cellintptr);
+ }
+
+ /* Remove the cell from the queue entry */
+ tor_free(q->u.var.var_cell);
+ q->u.var.var_cell = NULL;
+
+ /* Let it drain and check that the bad entry is discarded */
+ test_chan_accept_cells = 1;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_assert(test_cells_written == old_count);
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ /* Same thing with a packed_cell */
+
+ test_chan_accept_cells = 0;
+ ch->state = CHANNEL_STATE_MAINT;
+ packed_cell = packed_cell_new();
+ tt_assert(packed_cell);
+ cellintptr = (uintptr_t)(void*)packed_cell;
+ channel_write_packed_cell(ch, packed_cell);
+
+ /* Check that it's queued */
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 1);
+ q = TOR_SIMPLEQ_FIRST(&(ch->outgoing_queue));
+ tt_assert(q);
+ if (q) {
+ tt_int_op(q->type, ==, CELL_QUEUE_PACKED);
+ tt_assert((uintptr_t)q->u.packed.packed_cell == cellintptr);
+ }
+
+ /* Remove the cell from the queue entry */
+ packed_cell_free(q->u.packed.packed_cell);
+ q->u.packed.packed_cell = NULL;
+
+ /* Let it drain and check that the bad entry is discarded */
+ test_chan_accept_cells = 1;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_assert(test_cells_written == old_count);
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ /* Unknown cell type case */
+ test_chan_accept_cells = 0;
+ ch->state = CHANNEL_STATE_MAINT;
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ cellintptr = (uintptr_t)(void*)cell;
+ channel_write_cell(ch, cell);
+
+ /* Check that it's queued */
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 1);
+ q = TOR_SIMPLEQ_FIRST(&(ch->outgoing_queue));
+ tt_assert(q);
+ if (q) {
+ tt_int_op(q->type, ==, CELL_QUEUE_FIXED);
+ tt_assert((uintptr_t)q->u.fixed.cell == cellintptr);
+ }
+ /* Clobber it, including the queue entry type */
+ tor_free(q->u.fixed.cell);
+ q->u.fixed.cell = NULL;
+ q->type = CELL_QUEUE_PACKED + 1;
+
+ /* Let it drain and check that the bad entry is discarded */
+ test_chan_accept_cells = 1;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_assert(test_cells_written == old_count);
+ tt_int_op(chan_cell_queue_len(&(ch->outgoing_queue)), ==, 0);
+
+ done:
+ free_fake_channel(ch);
+
+ /*
+ * Doing that meant that we couldn't correctly adjust the queue size
+ * for the var cell, so manually reset the global queue size estimate
+ * so the next test doesn't break if we run with --no-fork.
+ */
+ estimated_total_queue_size = global_queue_estimate;
+
+ return;
+}
+
+static void
+test_channel_queue_incoming(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ var_cell_t *var_cell = NULL;
+ int old_fixed_count, old_var_count;
+
+ (void)arg;
+
+ /* Mock these for duration of the test */
+ MOCK(scheduler_channel_doesnt_want_writes,
+ scheduler_channel_doesnt_want_writes_mock);
+ MOCK(scheduler_release_channel,
+ scheduler_release_channel_mock);
+
+ /* Accept cells to lower layer */
+ test_chan_accept_cells = 1;
+ /* Use default overhead factor */
+ test_overhead_estimate = 1.0f;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+ /* Start it off in OPENING */
+ ch->state = CHANNEL_STATE_OPENING;
+ /* We'll need a cmux */
+ ch->cmux = circuitmux_alloc();
+
+ /* Test cell handler getters */
+ tt_ptr_op(channel_get_cell_handler(ch), ==, NULL);
+ tt_ptr_op(channel_get_var_cell_handler(ch), ==, NULL);
+
+ /* Try to register it */
+ channel_register(ch);
+ tt_assert(ch->registered);
+
+ /* Open it */
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_OPEN);
+
+ /* Assert that the incoming queue is empty */
+ tt_assert(TOR_SIMPLEQ_EMPTY(&(ch->incoming_queue)));
+
+ /* Queue an incoming fixed-length cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_queue_cell(ch, cell);
+
+ /* Assert that the incoming queue has one entry */
+ tt_int_op(chan_cell_queue_len(&(ch->incoming_queue)), ==, 1);
+
+ /* Queue an incoming var cell */
+ var_cell = tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ make_fake_var_cell(var_cell);
+ channel_queue_var_cell(ch, var_cell);
+
+ /* Assert that the incoming queue has two entries */
+ tt_int_op(chan_cell_queue_len(&(ch->incoming_queue)), ==, 2);
+
+ /*
+ * Install cell handlers; this will drain the queue, so save the old
+ * cell counters first
+ */
+ old_fixed_count = test_chan_fixed_cells_recved;
+ old_var_count = test_chan_var_cells_recved;
+ channel_set_cell_handlers(ch,
+ chan_test_cell_handler,
+ chan_test_var_cell_handler);
+ tt_ptr_op(channel_get_cell_handler(ch), ==, chan_test_cell_handler);
+ tt_ptr_op(channel_get_var_cell_handler(ch), ==, chan_test_var_cell_handler);
+
+ /* Assert cells were received */
+ tt_int_op(test_chan_fixed_cells_recved, ==, old_fixed_count + 1);
+ tt_int_op(test_chan_var_cells_recved, ==, old_var_count + 1);
+
+ /*
+ * Assert that the pointers are different from the cells we allocated;
+ * when queueing cells with no incoming cell handlers installed, the
+ * channel layer should copy them to a new buffer, and free them after
+ * delivery. These pointers will have already been freed by the time
+ * we get here, so don't dereference them.
+ */
+ tt_ptr_op(test_chan_last_seen_fixed_cell_ptr, !=, cell);
+ tt_ptr_op(test_chan_last_seen_var_cell_ptr, !=, var_cell);
+
+ /* Assert queue is now empty */
+ tt_assert(TOR_SIMPLEQ_EMPTY(&(ch->incoming_queue)));
+
+ /* Close it; this contains an assertion that the incoming queue is empty */
+ channel_mark_for_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSING);
+ chan_test_finish_close(ch);
+ tt_int_op(ch->state, ==, CHANNEL_STATE_CLOSED);
+ channel_run_cleanup();
+ ch = NULL;
+
+ done:
+ free_fake_channel(ch);
+ tor_free(cell);
+ tor_free(var_cell);
+
+ UNMOCK(scheduler_channel_doesnt_want_writes);
+ UNMOCK(scheduler_release_channel);
+
+ return;
+}
+
+static void
+test_channel_queue_size(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = NULL;
+ int n, old_count;
+ uint64_t global_queue_estimate;
+
+ (void)arg;
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+
+ /* Initial queue size update */
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Test the call-through to our fake lower layer */
+ n = channel_num_cells_writeable(ch);
+ /* chan_test_num_cells_writeable() always returns 32 */
+ tt_int_op(n, ==, 32);
+
+ /*
+ * Now we queue some cells and check that channel_num_cells_writeable()
+ * adjusts properly
+ */
+
+ /* tell it not to accept cells */
+ test_chan_accept_cells = 0;
+ /* ...and keep it from trying to flush the queue */
+ ch->state = CHANNEL_STATE_MAINT;
+
+ /* Get a fresh cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+
+ old_count = test_cells_written;
+ channel_write_cell(ch, cell);
+ /* Assert that it got queued, not written through, correctly */
+ tt_int_op(test_cells_written, ==, old_count);
+
+ /* Now check chan_test_num_cells_writeable() again */
+ n = channel_num_cells_writeable(ch);
+ tt_int_op(n, ==, 0); /* Should return 0 since we're in CHANNEL_STATE_MAINT */
+
+ /* Update queue size estimates */
+ channel_update_xmit_queue_size(ch);
+ /* One cell, times an overhead factor of 1.0 */
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 512);
+ /* Try a different overhead factor */
+ test_overhead_estimate = 0.5f;
+ /* This one should be ignored since it's below 1.0 */
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 512);
+ /* Now try a larger one */
+ test_overhead_estimate = 2.0f;
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 1024);
+ /* Go back to 1.0 */
+ test_overhead_estimate = 1.0f;
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 512);
+ /* Check the global estimate too */
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 512);
+
+ /* Go to open */
+ old_count = test_cells_written;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+
+ /*
+ * It should try to write, but we aren't accepting cells right now, so
+ * it'll requeue
+ */
+ tt_int_op(test_cells_written, ==, old_count);
+
+ /* Check the queue size again */
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 512);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 512);
+
+ /*
+ * Now the cell is in the queue, and we're open, so we should get 31
+ * writeable cells.
+ */
+ n = channel_num_cells_writeable(ch);
+ tt_int_op(n, ==, 31);
+
+ /* Accept cells again */
+ test_chan_accept_cells = 1;
+ /* ...and re-process the queue */
+ old_count = test_cells_written;
+ channel_flush_cells(ch);
+ tt_int_op(test_cells_written, ==, old_count + 1);
+
+ /* Should have 32 writeable now */
+ n = channel_num_cells_writeable(ch);
+ tt_int_op(n, ==, 32);
+
+ /* Should have queue size estimate of zero */
+ channel_update_xmit_queue_size(ch);
+ tt_u64_op(ch->bytes_queued_for_xmit, ==, 0);
+ global_queue_estimate = channel_get_global_queue_estimate();
+ tt_u64_op(global_queue_estimate, ==, 0);
+
+ /* Okay, now we're done with this one */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_mark_for_close(ch);
+ UNMOCK(scheduler_release_channel);
+
+ done:
+ free_fake_channel(ch);
+
+ return;
+}
+
+static void
+test_channel_write(void *arg)
+{
+ channel_t *ch = NULL;
+ cell_t *cell = tor_malloc_zero(sizeof(cell_t));
+ packed_cell_t *packed_cell = NULL;
+ var_cell_t *var_cell =
+ tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ int old_count;
+
+ (void)arg;
+
+ packed_cell = packed_cell_new();
+ tt_assert(packed_cell);
+
+ ch = new_fake_channel();
+ tt_assert(ch);
+ make_fake_cell(cell);
+ make_fake_var_cell(var_cell);
+
+ /* Tell it to accept cells */
+ test_chan_accept_cells = 1;
+
+ old_count = test_cells_written;
+ channel_write_cell(ch, cell);
+ cell = NULL;
+ tt_assert(test_cells_written == old_count + 1);
+
+ channel_write_var_cell(ch, var_cell);
+ var_cell = NULL;
+ tt_assert(test_cells_written == old_count + 2);
+
+ channel_write_packed_cell(ch, packed_cell);
+ packed_cell = NULL;
+ tt_assert(test_cells_written == old_count + 3);
+
+ /* Now we test queueing; tell it not to accept cells */
+ test_chan_accept_cells = 0;
+ /* ...and keep it from trying to flush the queue */
+ ch->state = CHANNEL_STATE_MAINT;
+
+ /* Get a fresh cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+
+ old_count = test_cells_written;
+ channel_write_cell(ch, cell);
+ tt_assert(test_cells_written == old_count);
+
+ /*
+ * Now change back to open with channel_change_state() and assert that it
+ * gets drained from the queue.
+ */
+ test_chan_accept_cells = 1;
+ channel_change_state(ch, CHANNEL_STATE_OPEN);
+ tt_assert(test_cells_written == old_count + 1);
+
+ /*
+ * Check the note destroy case
+ */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ cell->command = CELL_DESTROY;
+
+ /* Set up the mock */
+ MOCK(channel_note_destroy_not_pending,
+ channel_note_destroy_not_pending_mock);
+
+ old_count = test_destroy_not_pending_calls;
+ channel_write_cell(ch, cell);
+ tt_assert(test_destroy_not_pending_calls == old_count + 1);
+
+ /* Now send a non-destroy and check we don't call it */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch, cell);
+ tt_assert(test_destroy_not_pending_calls == old_count + 1);
+
+ UNMOCK(channel_note_destroy_not_pending);
+
+ /*
+ * Now switch it to CLOSING so we can test the discard-cells case
+ * in the channel_write_*() functions.
+ */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_mark_for_close(ch);
+ UNMOCK(scheduler_release_channel);
+
+ /* Send cells that will drop in the closing state */
+ old_count = test_cells_written;
+
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+ channel_write_cell(ch, cell);
+ cell = NULL;
+ tt_assert(test_cells_written == old_count);
+
+ var_cell = tor_malloc_zero(sizeof(var_cell_t) + CELL_PAYLOAD_SIZE);
+ make_fake_var_cell(var_cell);
+ channel_write_var_cell(ch, var_cell);
+ var_cell = NULL;
+ tt_assert(test_cells_written == old_count);
+
+ packed_cell = packed_cell_new();
+ channel_write_packed_cell(ch, packed_cell);
+ packed_cell = NULL;
+ tt_assert(test_cells_written == old_count);
+
+ done:
+ free_fake_channel(ch);
+ tor_free(var_cell);
+ tor_free(cell);
+ packed_cell_free(packed_cell);
+ return;
+}
+
+struct testcase_t channel_tests[] = {
+ { "dumpstats", test_channel_dumpstats, TT_FORK, NULL, NULL },
+ { "flush", test_channel_flush, TT_FORK, NULL, NULL },
+ { "flushmux", test_channel_flushmux, TT_FORK, NULL, NULL },
+ { "incoming", test_channel_incoming, TT_FORK, NULL, NULL },
+ { "lifecycle", test_channel_lifecycle, TT_FORK, NULL, NULL },
+ { "lifecycle_2", test_channel_lifecycle_2, TT_FORK, NULL, NULL },
+ { "multi", test_channel_multi, TT_FORK, NULL, NULL },
+ { "queue_impossible", test_channel_queue_impossible, TT_FORK, NULL, NULL },
+ { "queue_incoming", test_channel_queue_incoming, TT_FORK, NULL, NULL },
+ { "queue_size", test_channel_queue_size, TT_FORK, NULL, NULL },
+ { "write", test_channel_write, TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_channeltls.c b/src/test/test_channeltls.c
new file mode 100644
index 0000000000..04ae9a6da7
--- /dev/null
+++ b/src/test/test_channeltls.c
@@ -0,0 +1,333 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include <math.h>
+
+#define TOR_CHANNEL_INTERNAL_
+#include "or.h"
+#include "address.h"
+#include "buffers.h"
+#include "channel.h"
+#include "channeltls.h"
+#include "connection_or.h"
+#include "config.h"
+/* For init/free stuff */
+#include "scheduler.h"
+#include "tortls.h"
+
+/* Test suite stuff */
+#include "test.h"
+#include "fakechans.h"
+
+/* The channeltls unit tests */
+static void test_channeltls_create(void *arg);
+static void test_channeltls_num_bytes_queued(void *arg);
+static void test_channeltls_overhead_estimate(void *arg);
+
+/* Mocks used by channeltls unit tests */
+static size_t tlschan_buf_datalen_mock(const buf_t *buf);
+static or_connection_t * tlschan_connection_or_connect_mock(
+ const tor_addr_t *addr,
+ uint16_t port,
+ const char *digest,
+ channel_tls_t *tlschan);
+static int tlschan_is_local_addr_mock(const tor_addr_t *addr);
+
+/* Fake close method */
+static void tlschan_fake_close_method(channel_t *chan);
+
+/* Flags controlling behavior of channeltls unit test mocks */
+static int tlschan_local = 0;
+static const buf_t * tlschan_buf_datalen_mock_target = NULL;
+static size_t tlschan_buf_datalen_mock_size = 0;
+
+/* Thing to cast to fake tor_tls_t * to appease assert_connection_ok() */
+static int fake_tortls = 0; /* Bleh... */
+
+static void
+test_channeltls_create(void *arg)
+{
+ tor_addr_t test_addr;
+ channel_t *ch = NULL;
+ const char test_digest[DIGEST_LEN] = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14 };
+
+ (void)arg;
+
+ /* Set up a fake address to fake-connect to */
+ test_addr.family = AF_INET;
+ test_addr.addr.in_addr.s_addr = htonl(0x01020304);
+
+ /* For this test we always want the address to be treated as non-local */
+ tlschan_local = 0;
+ /* Install is_local_addr() mock */
+ MOCK(is_local_addr, tlschan_is_local_addr_mock);
+
+ /* Install mock for connection_or_connect() */
+ MOCK(connection_or_connect, tlschan_connection_or_connect_mock);
+
+ /* Try connecting */
+ ch = channel_tls_connect(&test_addr, 567, test_digest);
+ tt_assert(ch != NULL);
+
+ done:
+ if (ch) {
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ /*
+ * Use fake close method that doesn't try to do too much to fake
+ * orconn
+ */
+ ch->close = tlschan_fake_close_method;
+ channel_mark_for_close(ch);
+ free_fake_channel(ch);
+ UNMOCK(scheduler_release_channel);
+ }
+
+ UNMOCK(connection_or_connect);
+ UNMOCK(is_local_addr);
+
+ return;
+}
+
+static void
+test_channeltls_num_bytes_queued(void *arg)
+{
+ tor_addr_t test_addr;
+ channel_t *ch = NULL;
+ const char test_digest[DIGEST_LEN] = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14 };
+ channel_tls_t *tlschan = NULL;
+ size_t len;
+ int fake_outbuf = 0, n;
+
+ (void)arg;
+
+ /* Set up a fake address to fake-connect to */
+ test_addr.family = AF_INET;
+ test_addr.addr.in_addr.s_addr = htonl(0x01020304);
+
+ /* For this test we always want the address to be treated as non-local */
+ tlschan_local = 0;
+ /* Install is_local_addr() mock */
+ MOCK(is_local_addr, tlschan_is_local_addr_mock);
+
+ /* Install mock for connection_or_connect() */
+ MOCK(connection_or_connect, tlschan_connection_or_connect_mock);
+
+ /* Try connecting */
+ ch = channel_tls_connect(&test_addr, 567, test_digest);
+ tt_assert(ch != NULL);
+
+ /*
+ * Next, we have to test ch->num_bytes_queued, which is
+ * channel_tls_num_bytes_queued_method. We can't mock
+ * connection_get_outbuf_len() directly because it's static inline
+ * in connection.h, but we can mock buf_datalen(). Note that
+ * if bufferevents ever work, this will break with them enabled.
+ */
+
+ tt_assert(ch->num_bytes_queued != NULL);
+ tlschan = BASE_CHAN_TO_TLS(ch);
+ tt_assert(tlschan != NULL);
+ if (TO_CONN(tlschan->conn)->outbuf == NULL) {
+ /* We need an outbuf to make sure buf_datalen() gets called */
+ fake_outbuf = 1;
+ TO_CONN(tlschan->conn)->outbuf = buf_new();
+ }
+ tlschan_buf_datalen_mock_target = TO_CONN(tlschan->conn)->outbuf;
+ tlschan_buf_datalen_mock_size = 1024;
+ MOCK(buf_datalen, tlschan_buf_datalen_mock);
+ len = ch->num_bytes_queued(ch);
+ tt_int_op(len, ==, tlschan_buf_datalen_mock_size);
+ /*
+ * We also cover num_cells_writeable here; since wide_circ_ids = 0 on
+ * the fake tlschans, cell_network_size returns 512, and so with
+ * tlschan_buf_datalen_mock_size == 1024, we should be able to write
+ * ceil((OR_CONN_HIGHWATER - 1024) / 512) = ceil(OR_CONN_HIGHWATER / 512)
+ * - 2 cells.
+ */
+ n = ch->num_cells_writeable(ch);
+ tt_int_op(n, ==, CEIL_DIV(OR_CONN_HIGHWATER, 512) - 2);
+ UNMOCK(buf_datalen);
+ tlschan_buf_datalen_mock_target = NULL;
+ tlschan_buf_datalen_mock_size = 0;
+ if (fake_outbuf) {
+ buf_free(TO_CONN(tlschan->conn)->outbuf);
+ TO_CONN(tlschan->conn)->outbuf = NULL;
+ }
+
+ done:
+ if (ch) {
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ /*
+ * Use fake close method that doesn't try to do too much to fake
+ * orconn
+ */
+ ch->close = tlschan_fake_close_method;
+ channel_mark_for_close(ch);
+ free_fake_channel(ch);
+ UNMOCK(scheduler_release_channel);
+ }
+
+ UNMOCK(connection_or_connect);
+ UNMOCK(is_local_addr);
+
+ return;
+}
+
+static void
+test_channeltls_overhead_estimate(void *arg)
+{
+ tor_addr_t test_addr;
+ channel_t *ch = NULL;
+ const char test_digest[DIGEST_LEN] = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14 };
+ float r;
+ channel_tls_t *tlschan = NULL;
+
+ (void)arg;
+
+ /* Set up a fake address to fake-connect to */
+ test_addr.family = AF_INET;
+ test_addr.addr.in_addr.s_addr = htonl(0x01020304);
+
+ /* For this test we always want the address to be treated as non-local */
+ tlschan_local = 0;
+ /* Install is_local_addr() mock */
+ MOCK(is_local_addr, tlschan_is_local_addr_mock);
+
+ /* Install mock for connection_or_connect() */
+ MOCK(connection_or_connect, tlschan_connection_or_connect_mock);
+
+ /* Try connecting */
+ ch = channel_tls_connect(&test_addr, 567, test_digest);
+ tt_assert(ch != NULL);
+
+ /* First case: silly low ratios should get clamped to 1.0f */
+ tlschan = BASE_CHAN_TO_TLS(ch);
+ tt_assert(tlschan != NULL);
+ tlschan->conn->bytes_xmitted = 128;
+ tlschan->conn->bytes_xmitted_by_tls = 64;
+ r = ch->get_overhead_estimate(ch);
+ tt_assert(fabsf(r - 1.0f) < 1E-12);
+
+ tlschan->conn->bytes_xmitted_by_tls = 127;
+ r = ch->get_overhead_estimate(ch);
+ tt_assert(fabsf(r - 1.0f) < 1E-12);
+
+ /* Now middle of the range */
+ tlschan->conn->bytes_xmitted_by_tls = 192;
+ r = ch->get_overhead_estimate(ch);
+ tt_assert(fabsf(r - 1.5f) < 1E-12);
+
+ /* Now above the 2.0f clamp */
+ tlschan->conn->bytes_xmitted_by_tls = 257;
+ r = ch->get_overhead_estimate(ch);
+ tt_assert(fabsf(r - 2.0f) < 1E-12);
+
+ tlschan->conn->bytes_xmitted_by_tls = 512;
+ r = ch->get_overhead_estimate(ch);
+ tt_assert(fabsf(r - 2.0f) < 1E-12);
+
+ done:
+ if (ch) {
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ /*
+ * Use fake close method that doesn't try to do too much to fake
+ * orconn
+ */
+ ch->close = tlschan_fake_close_method;
+ channel_mark_for_close(ch);
+ free_fake_channel(ch);
+ UNMOCK(scheduler_release_channel);
+ }
+
+ UNMOCK(connection_or_connect);
+ UNMOCK(is_local_addr);
+
+ return;
+}
+
+static size_t
+tlschan_buf_datalen_mock(const buf_t *buf)
+{
+ if (buf != NULL && buf == tlschan_buf_datalen_mock_target) {
+ return tlschan_buf_datalen_mock_size;
+ } else {
+ return buf_datalen__real(buf);
+ }
+}
+
+static or_connection_t *
+tlschan_connection_or_connect_mock(const tor_addr_t *addr,
+ uint16_t port,
+ const char *digest,
+ channel_tls_t *tlschan)
+{
+ or_connection_t *result = NULL;
+
+ tt_assert(addr != NULL);
+ tt_assert(port != 0);
+ tt_assert(digest != NULL);
+ tt_assert(tlschan != NULL);
+
+ /* Make a fake orconn */
+ result = tor_malloc_zero(sizeof(*result));
+ result->base_.magic = OR_CONNECTION_MAGIC;
+ result->base_.state = OR_CONN_STATE_OPEN;
+ result->base_.type = CONN_TYPE_OR;
+ result->base_.socket_family = addr->family;
+ result->base_.address = tor_strdup("<fake>");
+ memcpy(&(result->base_.addr), addr, sizeof(tor_addr_t));
+ result->base_.port = port;
+ memcpy(result->identity_digest, digest, DIGEST_LEN);
+ result->chan = tlschan;
+ memcpy(&(result->real_addr), addr, sizeof(tor_addr_t));
+ result->tls = (tor_tls_t *)((void *)(&fake_tortls));
+
+ done:
+ return result;
+}
+
+static void
+tlschan_fake_close_method(channel_t *chan)
+{
+ channel_tls_t *tlschan = NULL;
+
+ tt_assert(chan != NULL);
+ tt_int_op(chan->magic, ==, TLS_CHAN_MAGIC);
+
+ tlschan = BASE_CHAN_TO_TLS(chan);
+ tt_assert(tlschan != NULL);
+
+ /* Just free the fake orconn */
+ tor_free(tlschan->conn->base_.address);
+ tor_free(tlschan->conn);
+
+ channel_closed(chan);
+
+ done:
+ return;
+}
+
+static int
+tlschan_is_local_addr_mock(const tor_addr_t *addr)
+{
+ tt_assert(addr != NULL);
+
+ done:
+ return tlschan_local;
+}
+
+struct testcase_t channeltls_tests[] = {
+ { "create", test_channeltls_create, TT_FORK, NULL, NULL },
+ { "num_bytes_queued", test_channeltls_num_bytes_queued,
+ TT_FORK, NULL, NULL },
+ { "overhead_estimate", test_channeltls_overhead_estimate,
+ TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_checkdir.c b/src/test/test_checkdir.c
new file mode 100644
index 0000000000..fbb33f87f6
--- /dev/null
+++ b/src/test/test_checkdir.c
@@ -0,0 +1,149 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#include "or.h"
+
+#ifdef _WIN32
+#include <direct.h>
+#else
+#include <dirent.h>
+#endif
+
+#include "config.h"
+#include "test.h"
+#include "util.h"
+
+#ifdef _WIN32
+#define mkdir(a,b) mkdir(a)
+#define tt_int_op_nowin(a,op,b) do { (void)(a); (void)(b); } while (0)
+#define umask(mask) ((void)0)
+#else
+#define tt_int_op_nowin(a,op,b) tt_int_op((a),op,(b))
+#endif
+
+/** Run unit tests for private dir permission enforcement logic. */
+static void
+test_checkdir_perms(void *testdata)
+{
+ (void)testdata;
+ or_options_t *options = get_options_mutable();
+ const char *subdir = "test_checkdir";
+ char *testdir = NULL;
+ cpd_check_t cpd_chkopts;
+ cpd_check_t unix_create_opts;
+ cpd_check_t unix_verify_optsmask;
+ struct stat st;
+
+ umask(022);
+
+ /* setup data directory before tests. */
+ tor_free(options->DataDirectory);
+ options->DataDirectory = tor_strdup(get_fname(subdir));
+ tt_int_op(mkdir(options->DataDirectory, 0750), OP_EQ, 0);
+
+ /* test: create new dir, no flags. */
+ testdir = get_datadir_fname("checkdir_new_none");
+ cpd_chkopts = CPD_CREATE;
+ unix_verify_optsmask = 0077;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: create new dir, CPD_GROUP_OK option set. */
+ testdir = get_datadir_fname("checkdir_new_groupok");
+ cpd_chkopts = CPD_CREATE|CPD_GROUP_OK;
+ unix_verify_optsmask = 0077;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: should get an error on existing dir with
+ wrong perms */
+ testdir = get_datadir_fname("checkdir_new_groupok_err");
+ tt_int_op(0, OP_EQ, mkdir(testdir, 027));
+ cpd_chkopts = CPD_CHECK_MODE_ONLY|CPD_CREATE|CPD_GROUP_OK;
+ tt_int_op_nowin(-1, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tor_free(testdir);
+
+ /* test: create new dir, CPD_GROUP_READ option set. */
+ testdir = get_datadir_fname("checkdir_new_groupread");
+ cpd_chkopts = CPD_CREATE|CPD_GROUP_READ;
+ unix_verify_optsmask = 0027;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: check existing dir created with defaults,
+ and verify with CPD_CREATE only. */
+ testdir = get_datadir_fname("checkdir_exists_none");
+ cpd_chkopts = CPD_CREATE;
+ unix_create_opts = 0700;
+ (void)unix_create_opts;
+ unix_verify_optsmask = 0077;
+ tt_int_op(0, OP_EQ, mkdir(testdir, unix_create_opts));
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: check existing dir created with defaults,
+ and verify with CPD_GROUP_OK option set. */
+ testdir = get_datadir_fname("checkdir_exists_groupok");
+ cpd_chkopts = CPD_CREATE;
+ unix_verify_optsmask = 0077;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ cpd_chkopts = CPD_GROUP_OK;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: check existing dir created with defaults,
+ and verify with CPD_GROUP_READ option set. */
+ testdir = get_datadir_fname("checkdir_exists_groupread");
+ cpd_chkopts = CPD_CREATE;
+ unix_verify_optsmask = 0027;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ cpd_chkopts = CPD_GROUP_READ;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: check existing dir created with CPD_GROUP_READ,
+ and verify with CPD_GROUP_OK option set. */
+ testdir = get_datadir_fname("checkdir_existsread_groupok");
+ cpd_chkopts = CPD_CREATE|CPD_GROUP_READ;
+ unix_verify_optsmask = 0027;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ cpd_chkopts = CPD_GROUP_OK;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+ tor_free(testdir);
+
+ /* test: check existing dir created with CPD_GROUP_READ,
+ and verify with CPD_GROUP_READ option set. */
+ testdir = get_datadir_fname("checkdir_existsread_groupread");
+ cpd_chkopts = CPD_CREATE|CPD_GROUP_READ;
+ unix_verify_optsmask = 0027;
+ tt_int_op(0, OP_EQ, check_private_dir(testdir, cpd_chkopts, NULL));
+ tt_int_op(0, OP_EQ, stat(testdir, &st));
+ tt_int_op_nowin(0, OP_EQ, (st.st_mode & unix_verify_optsmask));
+
+ done:
+ tor_free(testdir);
+}
+
+#define CHECKDIR(name,flags) \
+ { #name, test_checkdir_##name, (flags), NULL, NULL }
+
+struct testcase_t checkdir_tests[] = {
+ CHECKDIR(perms, TT_FORK),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_circuitlist.c b/src/test/test_circuitlist.c
index b19edd1fd4..1e640b5709 100644
--- a/src/test/test_circuitlist.c
+++ b/src/test/test_circuitlist.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define TOR_CHANNEL_INTERNAL_
@@ -50,17 +50,17 @@ circuitmux_detach_mock(circuitmux_t *cmux, circuit_t *circ)
}
#define GOT_CMUX_ATTACH(mux_, circ_, dir_) do { \
- tt_int_op(cam.ncalls, ==, 1); \
- tt_ptr_op(cam.cmux, ==, (mux_)); \
- tt_ptr_op(cam.circ, ==, (circ_)); \
- tt_int_op(cam.dir, ==, (dir_)); \
+ tt_int_op(cam.ncalls, OP_EQ, 1); \
+ tt_ptr_op(cam.cmux, OP_EQ, (mux_)); \
+ tt_ptr_op(cam.circ, OP_EQ, (circ_)); \
+ tt_int_op(cam.dir, OP_EQ, (dir_)); \
memset(&cam, 0, sizeof(cam)); \
} while (0)
#define GOT_CMUX_DETACH(mux_, circ_) do { \
- tt_int_op(cdm.ncalls, ==, 1); \
- tt_ptr_op(cdm.cmux, ==, (mux_)); \
- tt_ptr_op(cdm.circ, ==, (circ_)); \
+ tt_int_op(cdm.ncalls, OP_EQ, 1); \
+ tt_ptr_op(cdm.cmux, OP_EQ, (mux_)); \
+ tt_ptr_op(cdm.circ, OP_EQ, (circ_)); \
memset(&cdm, 0, sizeof(cdm)); \
} while (0)
@@ -79,21 +79,25 @@ test_clist_maps(void *arg)
memset(&cam, 0, sizeof(cam));
memset(&cdm, 0, sizeof(cdm));
- ch1->cmux = (void*)0x1001;
- ch2->cmux = (void*)0x1002;
- ch3->cmux = (void*)0x1003;
+ tt_assert(ch1);
+ tt_assert(ch2);
+ tt_assert(ch3);
+
+ ch1->cmux = tor_malloc(1);
+ ch2->cmux = tor_malloc(1);
+ ch3->cmux = tor_malloc(1);
or_c1 = or_circuit_new(100, ch2);
tt_assert(or_c1);
GOT_CMUX_ATTACH(ch2->cmux, or_c1, CELL_DIRECTION_IN);
- tt_int_op(or_c1->p_circ_id, ==, 100);
- tt_ptr_op(or_c1->p_chan, ==, ch2);
+ tt_int_op(or_c1->p_circ_id, OP_EQ, 100);
+ tt_ptr_op(or_c1->p_chan, OP_EQ, ch2);
or_c2 = or_circuit_new(100, ch1);
tt_assert(or_c2);
GOT_CMUX_ATTACH(ch1->cmux, or_c2, CELL_DIRECTION_IN);
- tt_int_op(or_c2->p_circ_id, ==, 100);
- tt_ptr_op(or_c2->p_chan, ==, ch1);
+ tt_int_op(or_c2->p_circ_id, OP_EQ, 100);
+ tt_ptr_op(or_c2->p_chan, OP_EQ, ch1);
circuit_set_n_circid_chan(TO_CIRCUIT(or_c1), 200, ch1);
GOT_CMUX_ATTACH(ch1->cmux, or_c1, CELL_DIRECTION_OUT);
@@ -101,11 +105,11 @@ test_clist_maps(void *arg)
circuit_set_n_circid_chan(TO_CIRCUIT(or_c2), 200, ch2);
GOT_CMUX_ATTACH(ch2->cmux, or_c2, CELL_DIRECTION_OUT);
- tt_ptr_op(circuit_get_by_circid_channel(200, ch1), ==, TO_CIRCUIT(or_c1));
- tt_ptr_op(circuit_get_by_circid_channel(200, ch2), ==, TO_CIRCUIT(or_c2));
- tt_ptr_op(circuit_get_by_circid_channel(100, ch2), ==, TO_CIRCUIT(or_c1));
+ tt_ptr_op(circuit_get_by_circid_channel(200, ch1), OP_EQ, TO_CIRCUIT(or_c1));
+ tt_ptr_op(circuit_get_by_circid_channel(200, ch2), OP_EQ, TO_CIRCUIT(or_c2));
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch2), OP_EQ, TO_CIRCUIT(or_c1));
/* Try the same thing again, to test the "fast" path. */
- tt_ptr_op(circuit_get_by_circid_channel(100, ch2), ==, TO_CIRCUIT(or_c1));
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch2), OP_EQ, TO_CIRCUIT(or_c1));
tt_assert(circuit_id_in_use_on_channel(100, ch2));
tt_assert(! circuit_id_in_use_on_channel(101, ch2));
@@ -113,9 +117,9 @@ test_clist_maps(void *arg)
circuit_set_p_circid_chan(or_c1, 500, ch3);
GOT_CMUX_DETACH(ch2->cmux, TO_CIRCUIT(or_c1));
GOT_CMUX_ATTACH(ch3->cmux, TO_CIRCUIT(or_c1), CELL_DIRECTION_IN);
- tt_ptr_op(circuit_get_by_circid_channel(100, ch2), ==, NULL);
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch2), OP_EQ, NULL);
tt_assert(! circuit_id_in_use_on_channel(100, ch2));
- tt_ptr_op(circuit_get_by_circid_channel(500, ch3), ==, TO_CIRCUIT(or_c1));
+ tt_ptr_op(circuit_get_by_circid_channel(500, ch3), OP_EQ, TO_CIRCUIT(or_c1));
/* Now let's see about destroy handling. */
tt_assert(! circuit_id_in_use_on_channel(205, ch2));
@@ -128,26 +132,26 @@ test_clist_maps(void *arg)
tt_assert(circuit_id_in_use_on_channel(100, ch1));
tt_assert(TO_CIRCUIT(or_c2)->n_delete_pending != 0);
- tt_ptr_op(circuit_get_by_circid_channel(200, ch2), ==, TO_CIRCUIT(or_c2));
- tt_ptr_op(circuit_get_by_circid_channel(100, ch1), ==, TO_CIRCUIT(or_c2));
+ tt_ptr_op(circuit_get_by_circid_channel(200, ch2), OP_EQ, TO_CIRCUIT(or_c2));
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch1), OP_EQ, TO_CIRCUIT(or_c2));
/* Okay, now free ch2 and make sure that the circuit ID is STILL not
* usable, because we haven't declared the destroy to be nonpending */
- tt_int_op(cdm.ncalls, ==, 0);
+ tt_int_op(cdm.ncalls, OP_EQ, 0);
circuit_free(TO_CIRCUIT(or_c2));
or_c2 = NULL; /* prevent free */
- tt_int_op(cdm.ncalls, ==, 2);
+ tt_int_op(cdm.ncalls, OP_EQ, 2);
memset(&cdm, 0, sizeof(cdm));
tt_assert(circuit_id_in_use_on_channel(200, ch2));
tt_assert(circuit_id_in_use_on_channel(100, ch1));
- tt_ptr_op(circuit_get_by_circid_channel(200, ch2), ==, NULL);
- tt_ptr_op(circuit_get_by_circid_channel(100, ch1), ==, NULL);
+ tt_ptr_op(circuit_get_by_circid_channel(200, ch2), OP_EQ, NULL);
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch1), OP_EQ, NULL);
/* Now say that the destroy is nonpending */
channel_note_destroy_not_pending(ch2, 200);
- tt_ptr_op(circuit_get_by_circid_channel(200, ch2), ==, NULL);
+ tt_ptr_op(circuit_get_by_circid_channel(200, ch2), OP_EQ, NULL);
channel_note_destroy_not_pending(ch1, 100);
- tt_ptr_op(circuit_get_by_circid_channel(100, ch1), ==, NULL);
+ tt_ptr_op(circuit_get_by_circid_channel(100, ch1), OP_EQ, NULL);
tt_assert(! circuit_id_in_use_on_channel(200, ch2));
tt_assert(! circuit_id_in_use_on_channel(100, ch1));
@@ -156,6 +160,12 @@ test_clist_maps(void *arg)
circuit_free(TO_CIRCUIT(or_c1));
if (or_c2)
circuit_free(TO_CIRCUIT(or_c2));
+ if (ch1)
+ tor_free(ch1->cmux);
+ if (ch2)
+ tor_free(ch2->cmux);
+ if (ch3)
+ tor_free(ch3->cmux);
tor_free(ch1);
tor_free(ch2);
tor_free(ch3);
@@ -180,73 +190,73 @@ test_rend_token_maps(void *arg)
c4 = or_circuit_new(0, NULL);
/* Make sure we really filled up the tok* variables */
- tt_int_op(tok1[REND_TOKEN_LEN-1], ==, 'y');
- tt_int_op(tok2[REND_TOKEN_LEN-1], ==, ' ');
- tt_int_op(tok3[REND_TOKEN_LEN-1], ==, '.');
+ tt_int_op(tok1[REND_TOKEN_LEN-1], OP_EQ, 'y');
+ tt_int_op(tok2[REND_TOKEN_LEN-1], OP_EQ, ' ');
+ tt_int_op(tok3[REND_TOKEN_LEN-1], OP_EQ, '.');
/* No maps; nothing there. */
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok1));
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok1));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok1));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok1));
circuit_set_rendezvous_cookie(c1, tok1);
circuit_set_intro_point_digest(c2, tok2);
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok3));
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok3));
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok2));
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok1));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok3));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok3));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok2));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok1));
/* Without purpose set, we don't get the circuits */
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok1));
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok2));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok1));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok2));
c1->base_.purpose = CIRCUIT_PURPOSE_REND_POINT_WAITING;
c2->base_.purpose = CIRCUIT_PURPOSE_INTRO_POINT;
/* Okay, make sure they show up now. */
- tt_ptr_op(c1, ==, circuit_get_rendezvous(tok1));
- tt_ptr_op(c2, ==, circuit_get_intro_point(tok2));
+ tt_ptr_op(c1, OP_EQ, circuit_get_rendezvous(tok1));
+ tt_ptr_op(c2, OP_EQ, circuit_get_intro_point(tok2));
/* Two items at the same place with the same token. */
c3->base_.purpose = CIRCUIT_PURPOSE_REND_POINT_WAITING;
circuit_set_rendezvous_cookie(c3, tok2);
- tt_ptr_op(c2, ==, circuit_get_intro_point(tok2));
- tt_ptr_op(c3, ==, circuit_get_rendezvous(tok2));
+ tt_ptr_op(c2, OP_EQ, circuit_get_intro_point(tok2));
+ tt_ptr_op(c3, OP_EQ, circuit_get_rendezvous(tok2));
/* Marking a circuit makes it not get returned any more */
circuit_mark_for_close(TO_CIRCUIT(c1), END_CIRC_REASON_FINISHED);
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok1));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok1));
circuit_free(TO_CIRCUIT(c1));
c1 = NULL;
/* Freeing a circuit makes it not get returned any more. */
circuit_free(TO_CIRCUIT(c2));
c2 = NULL;
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok2));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok2));
/* c3 -- are you still there? */
- tt_ptr_op(c3, ==, circuit_get_rendezvous(tok2));
+ tt_ptr_op(c3, OP_EQ, circuit_get_rendezvous(tok2));
/* Change its cookie. This never happens in Tor per se, but hey. */
c3->base_.purpose = CIRCUIT_PURPOSE_INTRO_POINT;
circuit_set_intro_point_digest(c3, tok3);
- tt_ptr_op(NULL, ==, circuit_get_rendezvous(tok2));
- tt_ptr_op(c3, ==, circuit_get_intro_point(tok3));
+ tt_ptr_op(NULL, OP_EQ, circuit_get_rendezvous(tok2));
+ tt_ptr_op(c3, OP_EQ, circuit_get_intro_point(tok3));
/* Now replace c3 with c4. */
c4->base_.purpose = CIRCUIT_PURPOSE_INTRO_POINT;
circuit_set_intro_point_digest(c4, tok3);
- tt_ptr_op(c4, ==, circuit_get_intro_point(tok3));
+ tt_ptr_op(c4, OP_EQ, circuit_get_intro_point(tok3));
- tt_ptr_op(c3->rendinfo, ==, NULL);
- tt_ptr_op(c4->rendinfo, !=, NULL);
- test_mem_op(c4->rendinfo, ==, tok3, REND_TOKEN_LEN);
+ tt_ptr_op(c3->rendinfo, OP_EQ, NULL);
+ tt_ptr_op(c4->rendinfo, OP_NE, NULL);
+ tt_mem_op(c4->rendinfo, OP_EQ, tok3, REND_TOKEN_LEN);
/* Now clear c4's cookie. */
circuit_set_intro_point_digest(c4, NULL);
- tt_ptr_op(c4->rendinfo, ==, NULL);
- tt_ptr_op(NULL, ==, circuit_get_intro_point(tok3));
+ tt_ptr_op(c4->rendinfo, OP_EQ, NULL);
+ tt_ptr_op(NULL, OP_EQ, circuit_get_intro_point(tok3));
done:
if (c1)
@@ -273,32 +283,32 @@ test_pick_circid(void *arg)
chan2->wide_circ_ids = 1;
chan1->circ_id_type = CIRC_ID_TYPE_NEITHER;
- tt_int_op(0, ==, get_unique_circ_id_by_chan(chan1));
+ tt_int_op(0, OP_EQ, get_unique_circ_id_by_chan(chan1));
/* Basic tests, with no collisions */
chan1->circ_id_type = CIRC_ID_TYPE_LOWER;
for (i = 0; i < 50; ++i) {
circid = get_unique_circ_id_by_chan(chan1);
- tt_uint_op(0, <, circid);
- tt_uint_op(circid, <, (1<<15));
+ tt_uint_op(0, OP_LT, circid);
+ tt_uint_op(circid, OP_LT, (1<<15));
}
chan1->circ_id_type = CIRC_ID_TYPE_HIGHER;
for (i = 0; i < 50; ++i) {
circid = get_unique_circ_id_by_chan(chan1);
- tt_uint_op((1<<15), <, circid);
- tt_uint_op(circid, <, (1<<16));
+ tt_uint_op((1<<15), OP_LT, circid);
+ tt_uint_op(circid, OP_LT, (1<<16));
}
chan2->circ_id_type = CIRC_ID_TYPE_LOWER;
for (i = 0; i < 50; ++i) {
circid = get_unique_circ_id_by_chan(chan2);
- tt_uint_op(0, <, circid);
- tt_uint_op(circid, <, (1u<<31));
+ tt_uint_op(0, OP_LT, circid);
+ tt_uint_op(circid, OP_LT, (1u<<31));
}
chan2->circ_id_type = CIRC_ID_TYPE_HIGHER;
for (i = 0; i < 50; ++i) {
circid = get_unique_circ_id_by_chan(chan2);
- tt_uint_op((1u<<31), <, circid);
+ tt_uint_op((1u<<31), OP_LT, circid);
}
/* Now make sure that we can behave well when we are full up on circuits */
@@ -309,20 +319,20 @@ test_pick_circid(void *arg)
for (i = 0; i < (1<<15); ++i) {
circid = get_unique_circ_id_by_chan(chan1);
if (circid == 0) {
- tt_int_op(i, >, (1<<14));
+ tt_int_op(i, OP_GT, (1<<14));
break;
}
- tt_uint_op(circid, <, (1<<15));
+ tt_uint_op(circid, OP_LT, (1<<15));
tt_assert(! bitarray_is_set(ba, circid));
bitarray_set(ba, circid);
channel_mark_circid_unusable(chan1, circid);
}
- tt_int_op(i, <, (1<<15));
+ tt_int_op(i, OP_LT, (1<<15));
/* Make sure that being full on chan1 does not interfere with chan2 */
for (i = 0; i < 100; ++i) {
circid = get_unique_circ_id_by_chan(chan2);
- tt_uint_op(circid, >, 0);
- tt_uint_op(circid, <, (1<<15));
+ tt_uint_op(circid, OP_GT, 0);
+ tt_uint_op(circid, OP_LT, (1<<15));
channel_mark_circid_unusable(chan2, circid);
}
diff --git a/src/test/test_circuitmux.c b/src/test/test_circuitmux.c
index b9c0436ebf..9e8fb54964 100644
--- a/src/test/test_circuitmux.c
+++ b/src/test/test_circuitmux.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define TOR_CHANNEL_INTERNAL_
@@ -8,6 +8,7 @@
#include "channel.h"
#include "circuitmux.h"
#include "relay.h"
+#include "scheduler.h"
#include "test.h"
/* XXXX duplicated function from test_circuitlist.c */
@@ -36,9 +37,8 @@ test_cmux_destroy_cell_queue(void *arg)
cell_queue_t *cq = NULL;
packed_cell_t *pc = NULL;
-#ifdef ENABLE_MEMPOOLS
- init_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
+ scheduler_init();
+
(void) arg;
cmux = circuitmux_alloc();
@@ -55,30 +55,26 @@ test_cmux_destroy_cell_queue(void *arg)
circuitmux_append_destroy_cell(ch, cmux, 190, 6);
circuitmux_append_destroy_cell(ch, cmux, 30, 1);
- tt_int_op(circuitmux_num_cells(cmux), ==, 3);
+ tt_int_op(circuitmux_num_cells(cmux), OP_EQ, 3);
circ = circuitmux_get_first_active_circuit(cmux, &cq);
tt_assert(!circ);
tt_assert(cq);
- tt_int_op(cq->n, ==, 3);
+ tt_int_op(cq->n, OP_EQ, 3);
pc = cell_queue_pop(cq);
tt_assert(pc);
- test_mem_op(pc->body, ==, "\x00\x00\x00\x64\x04\x0a\x00\x00\x00", 9);
+ tt_mem_op(pc->body, OP_EQ, "\x00\x00\x00\x64\x04\x0a\x00\x00\x00", 9);
packed_cell_free(pc);
pc = NULL;
- tt_int_op(circuitmux_num_cells(cmux), ==, 2);
+ tt_int_op(circuitmux_num_cells(cmux), OP_EQ, 2);
done:
circuitmux_free(cmux);
channel_free(ch);
packed_cell_free(pc);
-
-#ifdef ENABLE_MEMPOOLS
- free_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
}
struct testcase_t circuitmux_tests[] = {
diff --git a/src/test/test_cmdline_args.py b/src/test/test_cmdline_args.py
deleted file mode 100755
index 55d1cdb805..0000000000
--- a/src/test/test_cmdline_args.py
+++ /dev/null
@@ -1,292 +0,0 @@
-#!/usr/bin/python
-
-import binascii
-import hashlib
-import os
-import re
-import shutil
-import subprocess
-import sys
-import tempfile
-import unittest
-
-TOR = "./src/or/tor"
-TOP_SRCDIR = "."
-
-if len(sys.argv) > 1:
- TOR = sys.argv[1]
- del sys.argv[1]
-
-if len(sys.argv) > 1:
- TOP_SRCDIR = sys.argv[1]
- del sys.argv[1]
-
-class UnexpectedSuccess(Exception):
- pass
-
-class UnexpectedFailure(Exception):
- pass
-
-if sys.version < '3':
- def b2s(b):
- return b
- def s2b(s):
- return s
- def NamedTemporaryFile():
- return tempfile.NamedTemporaryFile(delete=False)
-else:
- def b2s(b):
- return str(b, 'ascii')
- def s2b(s):
- return s.encode('ascii')
- def NamedTemporaryFile():
- return tempfile.NamedTemporaryFile(mode="w",delete=False,encoding="ascii")
-
-def contents(fn):
- f = open(fn)
- try:
- return f.read()
- finally:
- f.close()
-
-def run_tor(args, failure=False):
- p = subprocess.Popen([TOR] + args, stdout=subprocess.PIPE)
- output, _ = p.communicate()
- result = p.poll()
- if result and not failure:
- raise UnexpectedFailure()
- elif not result and failure:
- raise UnexpectedSuccess()
- return b2s(output)
-
-def spaceify_fp(fp):
- for i in range(0, len(fp), 4):
- yield fp[i:i+4]
-
-def lines(s):
- out = s.split("\n")
- if out and out[-1] == '':
- del out[-1]
- return out
-
-def strip_log_junk(line):
- m = re.match(r'([^\[]+\[[a-z]*\] *)(.*)', line)
- if not m:
- return ""+line
- return m.group(2).strip()
-
-def randstring(entropy_bytes):
- s = os.urandom(entropy_bytes)
- return b2s(binascii.b2a_hex(s))
-
-def findLineContaining(lines, s):
- for ln in lines:
- if s in ln:
- return True
- return False
-
-class CmdlineTests(unittest.TestCase):
-
- def test_version(self):
- out = run_tor(["--version"])
- self.assertTrue(out.startswith("Tor version "))
- self.assertEqual(len(lines(out)), 1)
-
- def test_quiet(self):
- out = run_tor(["--quiet", "--quumblebluffin", "1"], failure=True)
- self.assertEqual(out, "")
-
- def test_help(self):
- out = run_tor(["--help"], failure=False)
- out2 = run_tor(["-h"], failure=False)
- self.assertTrue(out.startswith("Copyright (c) 2001"))
- self.assertTrue(out.endswith(
- "tor -f <torrc> [args]\n"
- "See man page for options, or https://www.torproject.org/ for documentation.\n"))
- self.assertTrue(out == out2)
-
- def test_hush(self):
- torrc = NamedTemporaryFile()
- torrc.close()
- try:
- out = run_tor(["--hush", "-f", torrc.name,
- "--quumblebluffin", "1"], failure=True)
- finally:
- os.unlink(torrc.name)
- self.assertEqual(len(lines(out)), 2)
- ln = [ strip_log_junk(l) for l in lines(out) ]
- self.assertEqual(ln[0], "Failed to parse/validate config: Unknown option 'quumblebluffin'. Failing.")
- self.assertEqual(ln[1], "Reading config failed--see warnings above.")
-
- def test_missing_argument(self):
- out = run_tor(["--hush", "--hash-password"], failure=True)
- self.assertEqual(len(lines(out)), 2)
- ln = [ strip_log_junk(l) for l in lines(out) ]
- self.assertEqual(ln[0], "Command-line option '--hash-password' with no value. Failing.")
-
- def test_hash_password(self):
- out = run_tor(["--hash-password", "woodwose"])
- result = lines(out)[-1]
- self.assertEqual(result[:3], "16:")
- self.assertEqual(len(result), 61)
- r = binascii.a2b_hex(result[3:])
- self.assertEqual(len(r), 29)
-
- salt, how, hashed = r[:8], r[8], r[9:]
- self.assertEqual(len(hashed), 20)
- if type(how) == type("A"):
- how = ord(how)
-
- count = (16 + (how & 15)) << ((how >> 4) + 6)
- stuff = salt + s2b("woodwose")
- repetitions = count // len(stuff) + 1
- inp = stuff * repetitions
- inp = inp[:count]
-
- self.assertEqual(hashlib.sha1(inp).digest(), hashed)
-
- def test_digests(self):
- main_c = os.path.join(TOP_SRCDIR, "src", "or", "main.c")
-
- if os.stat(TOR).st_mtime < os.stat(main_c).st_mtime:
- self.skipTest(TOR+" not up to date")
- out = run_tor(["--digests"])
- main_line = [ l for l in lines(out) if l.endswith("/main.c") ]
- digest, name = main_line[0].split()
- f = open(main_c, 'rb')
- actual = hashlib.sha1(f.read()).hexdigest()
- f.close()
- self.assertEqual(digest, actual)
-
- def test_dump_options(self):
- default_torrc = NamedTemporaryFile()
- torrc = NamedTemporaryFile()
- torrc.write("SocksPort 9999")
- torrc.close()
- default_torrc.write("SafeLogging 0")
- default_torrc.close()
- out_sh = out_nb = out_fl = None
- opts = [ "-f", torrc.name,
- "--defaults-torrc", default_torrc.name ]
- try:
- out_sh = run_tor(["--dump-config", "short"]+opts)
- out_nb = run_tor(["--dump-config", "non-builtin"]+opts)
- out_fl = run_tor(["--dump-config", "full"]+opts)
- out_nr = run_tor(["--dump-config", "bliznert"]+opts,
- failure=True)
-
- out_verif = run_tor(["--verify-config"]+opts)
- finally:
- os.unlink(torrc.name)
- os.unlink(default_torrc.name)
-
- self.assertEqual(len(lines(out_sh)), 2)
- self.assertTrue(lines(out_sh)[0].startswith("DataDirectory "))
- self.assertEqual(lines(out_sh)[1:],
- [ "SocksPort 9999" ])
-
- self.assertEqual(len(lines(out_nb)), 2)
- self.assertEqual(lines(out_nb),
- [ "SafeLogging 0",
- "SocksPort 9999" ])
-
- out_fl = lines(out_fl)
- self.assertTrue(len(out_fl) > 100)
- self.assertTrue("SocksPort 9999" in out_fl)
- self.assertTrue("SafeLogging 0" in out_fl)
- self.assertTrue("ClientOnly 0" in out_fl)
-
- self.assertTrue(out_verif.endswith("Configuration was valid\n"))
-
- def test_list_fingerprint(self):
- tmpdir = tempfile.mkdtemp(prefix='ttca_')
- torrc = NamedTemporaryFile()
- torrc.write("ORPort 9999\n")
- torrc.write("DataDirectory %s\n"%tmpdir)
- torrc.write("Nickname tippi")
- torrc.close()
- opts = ["-f", torrc.name]
- try:
- out = run_tor(["--list-fingerprint"]+opts)
- fp = contents(os.path.join(tmpdir, "fingerprint"))
- finally:
- os.unlink(torrc.name)
- shutil.rmtree(tmpdir)
-
- out = lines(out)
- lastlog = strip_log_junk(out[-2])
- lastline = out[-1]
- fp = fp.strip()
- nn_fp = fp.split()[0]
- space_fp = " ".join(spaceify_fp(fp.split()[1]))
- self.assertEqual(lastlog,
- "Your Tor server's identity key fingerprint is '%s'"%fp)
- self.assertEqual(lastline, "tippi %s"%space_fp)
- self.assertEqual(nn_fp, "tippi")
-
- def test_list_options(self):
- out = lines(run_tor(["--list-torrc-options"]))
- self.assertTrue(len(out)>100)
- self.assertTrue(out[0] <= 'AccountingMax')
- self.assertTrue("UseBridges" in out)
- self.assertTrue("SocksPort" in out)
-
- def test_cmdline_args(self):
- default_torrc = NamedTemporaryFile()
- torrc = NamedTemporaryFile()
- torrc.write("SocksPort 9999\n")
- torrc.write("SocksPort 9998\n")
- torrc.write("ORPort 9000\n")
- torrc.write("ORPort 9001\n")
- torrc.write("Nickname eleventeen\n")
- torrc.write("ControlPort 9500\n")
- torrc.close()
- default_torrc.write("")
- default_torrc.close()
- out_sh = out_nb = out_fl = None
- opts = [ "-f", torrc.name,
- "--defaults-torrc", default_torrc.name,
- "--dump-config", "short" ]
- try:
- out_1 = run_tor(opts)
- out_2 = run_tor(opts+["+ORPort", "9003",
- "SocksPort", "9090",
- "/ControlPort",
- "/TransPort",
- "+ExtORPort", "9005"])
- finally:
- os.unlink(torrc.name)
- os.unlink(default_torrc.name)
-
- out_1 = [ l for l in lines(out_1) if not l.startswith("DataDir") ]
- out_2 = [ l for l in lines(out_2) if not l.startswith("DataDir") ]
-
- self.assertEqual(out_1,
- ["ControlPort 9500",
- "Nickname eleventeen",
- "ORPort 9000",
- "ORPort 9001",
- "SocksPort 9999",
- "SocksPort 9998"])
- self.assertEqual(out_2,
- ["ExtORPort 9005",
- "Nickname eleventeen",
- "ORPort 9000",
- "ORPort 9001",
- "ORPort 9003",
- "SocksPort 9090"])
-
- def test_missing_torrc(self):
- fname = "nonexistent_file_"+randstring(8)
- out = run_tor(["-f", fname, "--verify-config"], failure=True)
- ln = [ strip_log_junk(l) for l in lines(out) ]
- self.assertTrue("Unable to open configuration file" in ln[-2])
- self.assertTrue("Reading config failed" in ln[-1])
-
- out = run_tor(["-f", fname, "--verify-config", "--ignore-missing-torrc"])
- ln = [ strip_log_junk(l) for l in lines(out) ]
- self.assertTrue(findLineContaining(ln, ", using reasonable defaults"))
- self.assertTrue("Configuration was valid" in ln[-1])
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/src/test/test_compat_libevent.c b/src/test/test_compat_libevent.c
new file mode 100644
index 0000000000..266ebbcf3b
--- /dev/null
+++ b/src/test/test_compat_libevent.c
@@ -0,0 +1,224 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define COMPAT_LIBEVENT_PRIVATE
+#include "orconfig.h"
+#include "or.h"
+
+#include "test.h"
+
+#include "compat_libevent.h"
+
+#ifdef HAVE_EVENT2_EVENT_H
+#include <event2/event.h>
+#include <event2/thread.h>
+#ifdef USE_BUFFEREVENTS
+#include <event2/bufferevent.h>
+#endif
+#else
+#include <event.h>
+#endif
+
+#include "log_test_helpers.h"
+
+#define NS_MODULE compat_libevent
+
+static void
+test_compat_libevent_logging_callback(void *ignored)
+{
+ (void)ignored;
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+
+ libevent_logging_callback(_EVENT_LOG_DEBUG, "hello world");
+ expect_log_msg("Message from libevent: hello world\n");
+ expect_log_severity(LOG_DEBUG);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_MSG, "hello world another time");
+ expect_log_msg("Message from libevent: hello world another time\n");
+ expect_log_severity(LOG_INFO);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_WARN, "hello world a third time");
+ expect_log_msg("Warning from libevent: hello world a third time\n");
+ expect_log_severity(LOG_WARN);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_ERR, "hello world a fourth time");
+ expect_log_msg("Error from libevent: hello world a fourth time\n");
+ expect_log_severity(LOG_ERR);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(42, "hello world a fifth time");
+ expect_log_msg("Message [42] from libevent: hello world a fifth time\n");
+ expect_log_severity(LOG_WARN);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_DEBUG,
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ );
+ expect_log_msg("Message from libevent: "
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789"
+ "012345678901234567890123456789\n");
+ expect_log_severity(LOG_DEBUG);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(42, "xxx\n");
+ expect_log_msg("Message [42] from libevent: xxx\n");
+ expect_log_severity(LOG_WARN);
+
+ suppress_libevent_log_msg("something");
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_MSG, "hello there");
+ expect_log_msg("Message from libevent: hello there\n");
+ expect_log_severity(LOG_INFO);
+
+ mock_clean_saved_logs();
+ libevent_logging_callback(_EVENT_LOG_MSG, "hello there something else");
+ expect_no_log_msg("hello there something else");
+
+ // No way of verifying the result of this, it seems =/
+ configure_libevent_logging();
+
+ done:
+ suppress_libevent_log_msg(NULL);
+ teardown_capture_of_logs(previous_log);
+}
+
+static void
+test_compat_libevent_le_versions_compatibility(void *ignored)
+{
+ (void)ignored;
+ int res;
+
+ res = le_versions_compatibility(LE_OTHER);
+ tt_int_op(res, OP_EQ, 0);
+
+ res = le_versions_compatibility(V_OLD(0,9,'c'));
+ tt_int_op(res, OP_EQ, 1);
+
+ res = le_versions_compatibility(V(1,3,98));
+ tt_int_op(res, OP_EQ, 2);
+
+ res = le_versions_compatibility(V(1,4,98));
+ tt_int_op(res, OP_EQ, 3);
+
+ res = le_versions_compatibility(V(1,5,0));
+ tt_int_op(res, OP_EQ, 4);
+
+ res = le_versions_compatibility(V(2,0,0));
+ tt_int_op(res, OP_EQ, 4);
+
+ res = le_versions_compatibility(V(2,0,2));
+ tt_int_op(res, OP_EQ, 5);
+
+ done:
+ (void)0;
+}
+
+static void
+test_compat_libevent_tor_decode_libevent_version(void *ignored)
+{
+ (void)ignored;
+ le_version_t res;
+
+ res = tor_decode_libevent_version("SOMETHING WRONG");
+ tt_int_op(res, OP_EQ, LE_OTHER);
+
+ res = tor_decode_libevent_version("1.4.11");
+ tt_int_op(res, OP_EQ, V(1,4,11));
+
+ res = tor_decode_libevent_version("1.4.12b-stable");
+ tt_int_op(res, OP_EQ, V(1,4,12));
+
+ res = tor_decode_libevent_version("1.4.17b_stable");
+ tt_int_op(res, OP_EQ, V(1,4,17));
+
+ res = tor_decode_libevent_version("1.4.12!stable");
+ tt_int_op(res, OP_EQ, LE_OTHER);
+
+ res = tor_decode_libevent_version("1.4.12b!stable");
+ tt_int_op(res, OP_EQ, LE_OTHER);
+
+ res = tor_decode_libevent_version("1.4.13-");
+ tt_int_op(res, OP_EQ, V(1,4,13));
+
+ res = tor_decode_libevent_version("1.4.14_");
+ tt_int_op(res, OP_EQ, V(1,4,14));
+
+ res = tor_decode_libevent_version("1.4.15c-");
+ tt_int_op(res, OP_EQ, V(1,4,15));
+
+ res = tor_decode_libevent_version("1.4.16c_");
+ tt_int_op(res, OP_EQ, V(1,4,16));
+
+ res = tor_decode_libevent_version("1.4.17-s");
+ tt_int_op(res, OP_EQ, V(1,4,17));
+
+ res = tor_decode_libevent_version("1.5");
+ tt_int_op(res, OP_EQ, V(1,5,0));
+
+ res = tor_decode_libevent_version("1.2");
+ tt_int_op(res, OP_EQ, V(1,2,0));
+
+ res = tor_decode_libevent_version("1.2-");
+ tt_int_op(res, OP_EQ, LE_OTHER);
+
+ res = tor_decode_libevent_version("1.6e");
+ tt_int_op(res, OP_EQ, V_OLD(1,6,'e'));
+
+ done:
+ (void)0;
+}
+
+#if defined(LIBEVENT_VERSION)
+#define HEADER_VERSION LIBEVENT_VERSION
+#elif defined(_EVENT_VERSION)
+#define HEADER_VERSION _EVENT_VERSION
+#endif
+
+static void
+test_compat_libevent_header_version(void *ignored)
+{
+ (void)ignored;
+ const char *res;
+
+ res = tor_libevent_get_header_version_str();
+ tt_str_op(res, OP_EQ, HEADER_VERSION);
+
+ done:
+ (void)0;
+}
+
+struct testcase_t compat_libevent_tests[] = {
+ { "logging_callback", test_compat_libevent_logging_callback,
+ TT_FORK, NULL, NULL },
+ { "le_versions_compatibility",
+ test_compat_libevent_le_versions_compatibility, 0, NULL, NULL },
+ { "tor_decode_libevent_version",
+ test_compat_libevent_tor_decode_libevent_version, 0, NULL, NULL },
+ { "header_version", test_compat_libevent_header_version, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_config.c b/src/test/test_config.c
index 94ac4dca13..90ea4da87d 100644
--- a/src/test/test_config.c
+++ b/src/test/test_config.c
@@ -1,19 +1,49 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
#define CONFIG_PRIVATE
+#define PT_PRIVATE
+#define ROUTERSET_PRIVATE
#include "or.h"
+#include "address.h"
#include "addressmap.h"
+#include "circuitmux_ewma.h"
+#include "circuitbuild.h"
#include "config.h"
#include "confparse.h"
+#include "connection.h"
#include "connection_edge.h"
#include "test.h"
#include "util.h"
#include "address.h"
+#include "connection_or.h"
+#include "control.h"
+#include "cpuworker.h"
+#include "dirserv.h"
+#include "dirvote.h"
+#include "dns.h"
+#include "entrynodes.h"
+#include "transports.h"
+#include "ext_orport.h"
+#include "geoip.h"
+#include "hibernate.h"
+#include "main.h"
+#include "networkstatus.h"
+#include "nodelist.h"
+#include "policies.h"
+#include "rendclient.h"
+#include "rendservice.h"
+#include "router.h"
+#include "routerlist.h"
+#include "routerset.h"
+#include "statefile.h"
+#include "test.h"
+#include "transports.h"
+#include "util.h"
static void
test_config_addressmap(void *arg)
@@ -48,62 +78,61 @@ test_config_addressmap(void *arg)
/* Use old interface for now, so we don't need to rewrite the unit tests */
#define addressmap_rewrite(a,s,eo,ao) \
- addressmap_rewrite((a),(s),AMR_FLAG_USE_IPV4_DNS|AMR_FLAG_USE_IPV6_DNS, \
- (eo),(ao))
+ addressmap_rewrite((a),(s), ~0, (eo),(ao))
/* MapAddress .invalidwildcard.com .torserver.exit - no match */
strlcpy(address, "www.invalidwildcard.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
/* MapAddress *invalidasterisk.com .torserver.exit - no match */
strlcpy(address, "www.invalidasterisk.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
/* Where no mapping for FQDN match on top-level domain */
/* MapAddress .google.com .torserver.exit */
strlcpy(address, "reader.google.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "reader.torserver.exit");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "reader.torserver.exit");
/* MapAddress *.yahoo.com *.google.com.torserver.exit */
strlcpy(address, "reader.yahoo.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "reader.google.com.torserver.exit");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "reader.google.com.torserver.exit");
/*MapAddress *.cnn.com www.cnn.com */
strlcpy(address, "cnn.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "www.cnn.com");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "www.cnn.com");
/* MapAddress .cn.com www.cnn.com */
strlcpy(address, "www.cn.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "www.cnn.com");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "www.cnn.com");
/* MapAddress ex.com www.cnn.com - no match */
strlcpy(address, "www.ex.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
/* MapAddress ey.com *.cnn.com - invalid expression */
strlcpy(address, "ey.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
/* Where mapping for FQDN match on FQDN */
strlcpy(address, "www.google.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "3.3.3.3");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "3.3.3.3");
strlcpy(address, "www.torproject.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "1.1.1.1");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "1.1.1.1");
strlcpy(address, "other.torproject.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "this.torproject.org.otherserver.exit");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "this.torproject.org.otherserver.exit");
strlcpy(address, "test.torproject.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "2.2.2.2");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "2.2.2.2");
/* Test a chain of address mappings and the order in which they were added:
"MapAddress www.example.org 4.4.4.4"
@@ -111,17 +140,17 @@ test_config_addressmap(void *arg)
"MapAddress 4.4.4.4 5.5.5.5"
*/
strlcpy(address, "www.example.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "5.5.5.5");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "5.5.5.5");
/* Test infinite address mapping results in no change */
strlcpy(address, "www.infiniteloop.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "www.infiniteloop.org");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "www.infiniteloop.org");
/* Test we don't find false positives */
strlcpy(address, "www.example.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
/* Test top-level-domain matching a bit harder */
config_free_lines(get_options_mutable()->AddressMap);
@@ -134,24 +163,24 @@ test_config_addressmap(void *arg)
config_register_addressmaps(get_options());
strlcpy(address, "www.abc.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "www.abc.torserver.exit");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "www.abc.torserver.exit");
strlcpy(address, "www.def.com", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "www.def.torserver.exit");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "www.def.torserver.exit");
strlcpy(address, "www.torproject.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "1.1.1.1");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "1.1.1.1");
strlcpy(address, "test.torproject.org", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "1.1.1.1");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "1.1.1.1");
strlcpy(address, "torproject.net", sizeof(address));
- test_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
- test_streq(address, "2.2.2.2");
+ tt_assert(addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_str_op(address,OP_EQ, "2.2.2.2");
/* We don't support '*' as a mapping directive */
config_free_lines(get_options_mutable()->AddressMap);
@@ -161,19 +190,20 @@ test_config_addressmap(void *arg)
config_register_addressmaps(get_options());
strlcpy(address, "www.abc.com", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
strlcpy(address, "www.def.net", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
strlcpy(address, "www.torproject.org", sizeof(address));
- test_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
+ tt_assert(!addressmap_rewrite(address, sizeof(address), &expires, NULL));
#undef addressmap_rewrite
done:
config_free_lines(get_options_mutable()->AddressMap);
get_options_mutable()->AddressMap = NULL;
+ addressmap_free_all();
}
static int
@@ -184,7 +214,7 @@ is_private_dir(const char* path)
if (r) {
return 0;
}
-#if !defined (_WIN32) || defined (WINCE)
+#if !defined (_WIN32)
if ((st.st_mode & (S_IFDIR | 0777)) != (S_IFDIR | 0700)) {
return 0;
}
@@ -201,7 +231,7 @@ test_config_check_or_create_data_subdir(void *arg)
char *subpath;
struct stat st;
int r;
-#if !defined (_WIN32) || defined (WINCE)
+#if !defined (_WIN32)
unsigned group_permission;
#endif
(void)arg;
@@ -210,30 +240,30 @@ test_config_check_or_create_data_subdir(void *arg)
datadir = options->DataDirectory = tor_strdup(get_fname("datadir-0"));
subpath = get_datadir_fname(subdir);
-#if defined (_WIN32) && !defined (WINCE)
- tt_int_op(mkdir(options->DataDirectory), ==, 0);
+#if defined (_WIN32)
+ tt_int_op(mkdir(options->DataDirectory), OP_EQ, 0);
#else
- tt_int_op(mkdir(options->DataDirectory, 0700), ==, 0);
+ tt_int_op(mkdir(options->DataDirectory, 0700), OP_EQ, 0);
#endif
r = stat(subpath, &st);
// The subdirectory shouldn't exist yet,
// but should be created by the call to check_or_create_data_subdir.
- test_assert(r && (errno == ENOENT));
- test_assert(!check_or_create_data_subdir(subdir));
- test_assert(is_private_dir(subpath));
+ tt_assert(r && (errno == ENOENT));
+ tt_assert(!check_or_create_data_subdir(subdir));
+ tt_assert(is_private_dir(subpath));
// The check should return 0, if the directory already exists
// and is private to the user.
- test_assert(!check_or_create_data_subdir(subdir));
+ tt_assert(!check_or_create_data_subdir(subdir));
r = stat(subpath, &st);
if (r) {
tt_abort_perror("stat");
}
-#if !defined (_WIN32) || defined (WINCE)
+#if !defined (_WIN32)
group_permission = st.st_mode | 0070;
r = chmod(subpath, group_permission);
@@ -243,9 +273,9 @@ test_config_check_or_create_data_subdir(void *arg)
// If the directory exists, but its mode is too permissive
// a call to check_or_create_data_subdir should reset the mode.
- test_assert(!is_private_dir(subpath));
- test_assert(!check_or_create_data_subdir(subdir));
- test_assert(is_private_dir(subpath));
+ tt_assert(!is_private_dir(subpath));
+ tt_assert(!check_or_create_data_subdir(subdir));
+ tt_assert(is_private_dir(subpath));
#endif
done:
@@ -284,27 +314,27 @@ test_config_write_to_data_subdir(void *arg)
datadir = options->DataDirectory = tor_strdup(get_fname("datadir-1"));
filepath = get_datadir_fname2(subdir, fname);
-#if defined (_WIN32) && !defined (WINCE)
- tt_int_op(mkdir(options->DataDirectory), ==, 0);
+#if defined (_WIN32)
+ tt_int_op(mkdir(options->DataDirectory), OP_EQ, 0);
#else
- tt_int_op(mkdir(options->DataDirectory, 0700), ==, 0);
+ tt_int_op(mkdir(options->DataDirectory, 0700), OP_EQ, 0);
#endif
// Write attempt shoudl fail, if subdirectory doesn't exist.
- test_assert(write_to_data_subdir(subdir, fname, str, NULL));
- test_assert(! check_or_create_data_subdir(subdir));
+ tt_assert(write_to_data_subdir(subdir, fname, str, NULL));
+ tt_assert(! check_or_create_data_subdir(subdir));
// Content of file after write attempt should be
// equal to the original string.
- test_assert(!write_to_data_subdir(subdir, fname, str, NULL));
+ tt_assert(!write_to_data_subdir(subdir, fname, str, NULL));
cp = read_file_to_str(filepath, 0, NULL);
- test_streq(cp, str);
+ tt_str_op(cp,OP_EQ, str);
tor_free(cp);
// A second write operation should overwrite the old content.
- test_assert(!write_to_data_subdir(subdir, fname, str, NULL));
+ tt_assert(!write_to_data_subdir(subdir, fname, str, NULL));
cp = read_file_to_str(filepath, 0, NULL);
- test_streq(cp, str);
+ tt_str_op(cp,OP_EQ, str);
tor_free(cp);
done:
@@ -325,48 +355,48 @@ good_bridge_line_test(const char *string, const char *test_addrport,
{
char *tmp = NULL;
bridge_line_t *bridge_line = parse_bridge_line(string);
- test_assert(bridge_line);
+ tt_assert(bridge_line);
/* test addrport */
tmp = tor_strdup(fmt_addrport(&bridge_line->addr, bridge_line->port));
- test_streq(test_addrport, tmp);
+ tt_str_op(test_addrport,OP_EQ, tmp);
tor_free(tmp);
/* If we were asked to validate a digest, but we did not get a
digest after parsing, we failed. */
if (test_digest && tor_digest_is_zero(bridge_line->digest))
- test_assert(0);
+ tt_assert(0);
/* If we were not asked to validate a digest, and we got a digest
after parsing, we failed again. */
if (!test_digest && !tor_digest_is_zero(bridge_line->digest))
- test_assert(0);
+ tt_assert(0);
/* If we were asked to validate a digest, and we got a digest after
parsing, make sure it's correct. */
if (test_digest) {
tmp = tor_strdup(hex_str(bridge_line->digest, DIGEST_LEN));
tor_strlower(tmp);
- test_streq(test_digest, tmp);
+ tt_str_op(test_digest,OP_EQ, tmp);
tor_free(tmp);
}
/* If we were asked to validate a transport name, make sure tha it
matches with the transport name that was parsed. */
if (test_transport && !bridge_line->transport_name)
- test_assert(0);
+ tt_assert(0);
if (!test_transport && bridge_line->transport_name)
- test_assert(0);
+ tt_assert(0);
if (test_transport)
- test_streq(test_transport, bridge_line->transport_name);
+ tt_str_op(test_transport,OP_EQ, bridge_line->transport_name);
/* Validate the SOCKS argument smartlist. */
if (test_socks_args && !bridge_line->socks_args)
- test_assert(0);
+ tt_assert(0);
if (!test_socks_args && bridge_line->socks_args)
- test_assert(0);
+ tt_assert(0);
if (test_socks_args)
- test_assert(smartlist_strings_eq(test_socks_args,
+ tt_assert(smartlist_strings_eq(test_socks_args,
bridge_line->socks_args));
done:
@@ -382,7 +412,7 @@ bad_bridge_line_test(const char *string)
bridge_line_t *bridge_line = parse_bridge_line(string);
if (bridge_line)
TT_FAIL(("%s was supposed to fail, but it didn't.", string));
- test_assert(!bridge_line);
+ tt_assert(!bridge_line);
done:
bridge_line_free(bridge_line);
@@ -490,18 +520,18 @@ test_config_parse_transport_options_line(void *arg)
{ /* too small line */
options_sl = get_options_from_transport_options_line("valley", NULL);
- test_assert(!options_sl);
+ tt_assert(!options_sl);
}
{ /* no k=v values */
options_sl = get_options_from_transport_options_line("hit it!", NULL);
- test_assert(!options_sl);
+ tt_assert(!options_sl);
}
{ /* correct line, but wrong transport specified */
options_sl =
get_options_from_transport_options_line("trebuchet k=v", "rook");
- test_assert(!options_sl);
+ tt_assert(!options_sl);
}
{ /* correct -- no transport specified */
@@ -512,8 +542,8 @@ test_config_parse_transport_options_line(void *arg)
options_sl =
get_options_from_transport_options_line("rook ladi=dadi weliketo=party",
NULL);
- test_assert(options_sl);
- test_assert(smartlist_strings_eq(options_sl, sl_tmp));
+ tt_assert(options_sl);
+ tt_assert(smartlist_strings_eq(options_sl, sl_tmp));
SMARTLIST_FOREACH(sl_tmp, char *, s, tor_free(s));
smartlist_free(sl_tmp);
@@ -531,8 +561,8 @@ test_config_parse_transport_options_line(void *arg)
options_sl =
get_options_from_transport_options_line("rook ladi=dadi weliketo=party",
"rook");
- test_assert(options_sl);
- test_assert(smartlist_strings_eq(options_sl, sl_tmp));
+ tt_assert(options_sl);
+ tt_assert(smartlist_strings_eq(options_sl, sl_tmp));
SMARTLIST_FOREACH(sl_tmp, char *, s, tor_free(s));
smartlist_free(sl_tmp);
sl_tmp = NULL;
@@ -552,6 +582,269 @@ test_config_parse_transport_options_line(void *arg)
}
}
+/* Mocks needed for the transport plugin line test */
+
+static void pt_kickstart_proxy_mock(const smartlist_t *transport_list,
+ char **proxy_argv, int is_server);
+static int transport_add_from_config_mock(const tor_addr_t *addr,
+ uint16_t port, const char *name,
+ int socks_ver);
+static int transport_is_needed_mock(const char *transport_name);
+
+static int pt_kickstart_proxy_mock_call_count = 0;
+static int transport_add_from_config_mock_call_count = 0;
+static int transport_is_needed_mock_call_count = 0;
+static int transport_is_needed_mock_return = 0;
+
+static void
+pt_kickstart_proxy_mock(const smartlist_t *transport_list,
+ char **proxy_argv, int is_server)
+{
+ (void) transport_list;
+ (void) proxy_argv;
+ (void) is_server;
+ /* XXXX check that args are as expected. */
+
+ ++pt_kickstart_proxy_mock_call_count;
+
+ free_execve_args(proxy_argv);
+}
+
+static int
+transport_add_from_config_mock(const tor_addr_t *addr,
+ uint16_t port, const char *name,
+ int socks_ver)
+{
+ (void) addr;
+ (void) port;
+ (void) name;
+ (void) socks_ver;
+ /* XXXX check that args are as expected. */
+
+ ++transport_add_from_config_mock_call_count;
+
+ return 0;
+}
+
+static int
+transport_is_needed_mock(const char *transport_name)
+{
+ (void) transport_name;
+ /* XXXX check that arg is as expected. */
+
+ ++transport_is_needed_mock_call_count;
+
+ return transport_is_needed_mock_return;
+}
+
+/**
+ * Test parsing for the ClientTransportPlugin and ServerTransportPlugin config
+ * options.
+ */
+
+static void
+test_config_parse_transport_plugin_line(void *arg)
+{
+ (void)arg;
+
+ or_options_t *options = get_options_mutable();
+ int r, tmp;
+ int old_pt_kickstart_proxy_mock_call_count;
+ int old_transport_add_from_config_mock_call_count;
+ int old_transport_is_needed_mock_call_count;
+
+ /* Bad transport lines - too short */
+ r = parse_transport_line(options, "bad", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options, "bad", 1, 1);
+ tt_assert(r < 0);
+ r = parse_transport_line(options, "bad bad", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options, "bad bad", 1, 1);
+ tt_assert(r < 0);
+
+ /* Test transport list parsing */
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 1, 0);
+ tt_assert(r == 0);
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 1, 1);
+ tt_assert(r == 0);
+ r = parse_transport_line(options,
+ "transport_1,transport_2 exec /usr/bin/fake-transport", 1, 0);
+ tt_assert(r == 0);
+ r = parse_transport_line(options,
+ "transport_1,transport_2 exec /usr/bin/fake-transport", 1, 1);
+ tt_assert(r == 0);
+ /* Bad transport identifiers */
+ r = parse_transport_line(options,
+ "transport_* exec /usr/bin/fake-transport", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_* exec /usr/bin/fake-transport", 1, 1);
+ tt_assert(r < 0);
+
+ /* Check SOCKS cases for client transport */
+ r = parse_transport_line(options,
+ "transport_1 socks4 1.2.3.4:567", 1, 0);
+ tt_assert(r == 0);
+ r = parse_transport_line(options,
+ "transport_1 socks5 1.2.3.4:567", 1, 0);
+ tt_assert(r == 0);
+ /* Proxy case for server transport */
+ r = parse_transport_line(options,
+ "transport_1 proxy 1.2.3.4:567", 1, 1);
+ tt_assert(r == 0);
+ /* Multiple-transport error exit */
+ r = parse_transport_line(options,
+ "transport_1,transport_2 socks5 1.2.3.4:567", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_1,transport_2 proxy 1.2.3.4:567", 1, 1);
+ /* No port error exit */
+ r = parse_transport_line(options,
+ "transport_1 socks5 1.2.3.4", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_1 proxy 1.2.3.4", 1, 1);
+ tt_assert(r < 0);
+ /* Unparsable address error exit */
+ r = parse_transport_line(options,
+ "transport_1 socks5 1.2.3:6x7", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_1 proxy 1.2.3:6x7", 1, 1);
+ tt_assert(r < 0);
+
+ /* "Strange {Client|Server}TransportPlugin field" error exit */
+ r = parse_transport_line(options,
+ "transport_1 foo bar", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_1 foo bar", 1, 1);
+ tt_assert(r < 0);
+
+ /* No sandbox mode error exit */
+ tmp = options->Sandbox;
+ options->Sandbox = 1;
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 1, 0);
+ tt_assert(r < 0);
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 1, 1);
+ tt_assert(r < 0);
+ options->Sandbox = tmp;
+
+ /*
+ * These final test cases cover code paths that only activate without
+ * validate_only, so they need mocks in place.
+ */
+ MOCK(pt_kickstart_proxy, pt_kickstart_proxy_mock);
+ old_pt_kickstart_proxy_mock_call_count =
+ pt_kickstart_proxy_mock_call_count;
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 0, 1);
+ tt_assert(r == 0);
+ tt_assert(pt_kickstart_proxy_mock_call_count ==
+ old_pt_kickstart_proxy_mock_call_count + 1);
+ UNMOCK(pt_kickstart_proxy);
+
+ /* This one hits a log line in the !validate_only case only */
+ r = parse_transport_line(options,
+ "transport_1 proxy 1.2.3.4:567", 0, 1);
+ tt_assert(r == 0);
+
+ /* Check mocked client transport cases */
+ MOCK(pt_kickstart_proxy, pt_kickstart_proxy_mock);
+ MOCK(transport_add_from_config, transport_add_from_config_mock);
+ MOCK(transport_is_needed, transport_is_needed_mock);
+
+ /* Unnecessary transport case */
+ transport_is_needed_mock_return = 0;
+ old_pt_kickstart_proxy_mock_call_count =
+ pt_kickstart_proxy_mock_call_count;
+ old_transport_add_from_config_mock_call_count =
+ transport_add_from_config_mock_call_count;
+ old_transport_is_needed_mock_call_count =
+ transport_is_needed_mock_call_count;
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 0, 0);
+ /* Should have succeeded */
+ tt_assert(r == 0);
+ /* transport_is_needed() should have been called */
+ tt_assert(transport_is_needed_mock_call_count ==
+ old_transport_is_needed_mock_call_count + 1);
+ /*
+ * pt_kickstart_proxy() and transport_add_from_config() should
+ * not have been called.
+ */
+ tt_assert(pt_kickstart_proxy_mock_call_count ==
+ old_pt_kickstart_proxy_mock_call_count);
+ tt_assert(transport_add_from_config_mock_call_count ==
+ old_transport_add_from_config_mock_call_count);
+
+ /* Necessary transport case */
+ transport_is_needed_mock_return = 1;
+ old_pt_kickstart_proxy_mock_call_count =
+ pt_kickstart_proxy_mock_call_count;
+ old_transport_add_from_config_mock_call_count =
+ transport_add_from_config_mock_call_count;
+ old_transport_is_needed_mock_call_count =
+ transport_is_needed_mock_call_count;
+ r = parse_transport_line(options,
+ "transport_1 exec /usr/bin/fake-transport", 0, 0);
+ /* Should have succeeded */
+ tt_assert(r == 0);
+ /*
+ * transport_is_needed() and pt_kickstart_proxy() should have been
+ * called.
+ */
+ tt_assert(pt_kickstart_proxy_mock_call_count ==
+ old_pt_kickstart_proxy_mock_call_count + 1);
+ tt_assert(transport_is_needed_mock_call_count ==
+ old_transport_is_needed_mock_call_count + 1);
+ /* transport_add_from_config() should not have been called. */
+ tt_assert(transport_add_from_config_mock_call_count ==
+ old_transport_add_from_config_mock_call_count);
+
+ /* proxy case */
+ transport_is_needed_mock_return = 1;
+ old_pt_kickstart_proxy_mock_call_count =
+ pt_kickstart_proxy_mock_call_count;
+ old_transport_add_from_config_mock_call_count =
+ transport_add_from_config_mock_call_count;
+ old_transport_is_needed_mock_call_count =
+ transport_is_needed_mock_call_count;
+ r = parse_transport_line(options,
+ "transport_1 socks5 1.2.3.4:567", 0, 0);
+ /* Should have succeeded */
+ tt_assert(r == 0);
+ /*
+ * transport_is_needed() and transport_add_from_config() should have
+ * been called.
+ */
+ tt_assert(transport_add_from_config_mock_call_count ==
+ old_transport_add_from_config_mock_call_count + 1);
+ tt_assert(transport_is_needed_mock_call_count ==
+ old_transport_is_needed_mock_call_count + 1);
+ /* pt_kickstart_proxy() should not have been called. */
+ tt_assert(pt_kickstart_proxy_mock_call_count ==
+ old_pt_kickstart_proxy_mock_call_count);
+
+ /* Done with mocked client transport cases */
+ UNMOCK(transport_is_needed);
+ UNMOCK(transport_add_from_config);
+ UNMOCK(pt_kickstart_proxy);
+
+ done:
+ /* Make sure we undo all mocks */
+ UNMOCK(pt_kickstart_proxy);
+ UNMOCK(transport_add_from_config);
+ UNMOCK(transport_is_needed);
+
+ return;
+}
+
// Tests if an options with MyFamily fingerprints missing '$' normalises
// them correctly and also ensure it also works with multiple fingerprints
static void
@@ -576,7 +869,8 @@ test_config_fix_my_family(void *arg)
TT_FAIL(("options_validate failed: %s", err));
}
- test_streq(options->MyFamily, "$1111111111111111111111111111111111111111, "
+ tt_str_op(options->MyFamily,OP_EQ,
+ "$1111111111111111111111111111111111111111, "
"$1111111111111111111111111111111111111112, "
"$1111111111111111111111111111111111111113");
@@ -589,16 +883,3760 @@ test_config_fix_my_family(void *arg)
or_options_free(defaults);
}
+static int n_hostname_01010101 = 0;
+
+/** This mock function is meant to replace tor_lookup_hostname().
+ * It answers with 1.1.1.1 as IP adddress that resulted from lookup.
+ * This function increments <b>n_hostname_01010101</b> counter by one
+ * every time it is called.
+ */
+static int
+tor_lookup_hostname_01010101(const char *name, uint32_t *addr)
+{
+ n_hostname_01010101++;
+
+ if (name && addr) {
+ *addr = ntohl(0x01010101);
+ }
+
+ return 0;
+}
+
+static int n_hostname_localhost = 0;
+
+/** This mock function is meant to replace tor_lookup_hostname().
+ * It answers with 127.0.0.1 as IP adddress that resulted from lookup.
+ * This function increments <b>n_hostname_localhost</b> counter by one
+ * every time it is called.
+ */
+static int
+tor_lookup_hostname_localhost(const char *name, uint32_t *addr)
+{
+ n_hostname_localhost++;
+
+ if (name && addr) {
+ *addr = 0x7f000001;
+ }
+
+ return 0;
+}
+
+static int n_hostname_failure = 0;
+
+/** This mock function is meant to replace tor_lookup_hostname().
+ * It pretends to fail by returning -1 to caller. Also, this function
+ * increments <b>n_hostname_failure</b> every time it is called.
+ */
+static int
+tor_lookup_hostname_failure(const char *name, uint32_t *addr)
+{
+ (void)name;
+ (void)addr;
+
+ n_hostname_failure++;
+
+ return -1;
+}
+
+static int n_gethostname_replacement = 0;
+
+/** This mock function is meant to replace tor_gethostname(). It
+ * responds with string "onionrouter!" as hostname. This function
+ * increments <b>n_gethostname_replacement</b> by one every time
+ * it is called.
+ */
+static int
+tor_gethostname_replacement(char *name, size_t namelen)
+{
+ n_gethostname_replacement++;
+
+ if (name && namelen) {
+ strlcpy(name,"onionrouter!",namelen);
+ }
+
+ return 0;
+}
+
+static int n_gethostname_localhost = 0;
+
+/** This mock function is meant to replace tor_gethostname(). It
+ * responds with string "127.0.0.1" as hostname. This function
+ * increments <b>n_gethostname_localhost</b> by one every time
+ * it is called.
+ */
+static int
+tor_gethostname_localhost(char *name, size_t namelen)
+{
+ n_gethostname_localhost++;
+
+ if (name && namelen) {
+ strlcpy(name,"127.0.0.1",namelen);
+ }
+
+ return 0;
+}
+
+static int n_gethostname_failure = 0;
+
+/** This mock function is meant to replace tor_gethostname.
+ * It pretends to fail by returning -1. This function increments
+ * <b>n_gethostname_failure</b> by one every time it is called.
+ */
+static int
+tor_gethostname_failure(char *name, size_t namelen)
+{
+ (void)name;
+ (void)namelen;
+ n_gethostname_failure++;
+
+ return -1;
+}
+
+static int n_get_interface_address = 0;
+
+/** This mock function is meant to replace get_interface_address().
+ * It answers with address 8.8.8.8. This function increments
+ * <b>n_get_interface_address</b> by one every time it is called.
+ */
+static int
+get_interface_address_08080808(int severity, uint32_t *addr)
+{
+ (void)severity;
+
+ n_get_interface_address++;
+
+ if (addr) {
+ *addr = ntohl(0x08080808);
+ }
+
+ return 0;
+}
+
+static int n_get_interface_address6 = 0;
+static sa_family_t last_address6_family;
+
+/** This mock function is meant to replace get_interface_address6().
+ * It answers with IP address 9.9.9.9 iff both of the following are true:
+ * - <b>family</b> is AF_INET
+ * - <b>addr</b> pointer is not NULL.
+ * This function increments <b>n_get_interface_address6</b> by one every
+ * time it is called.
+ */
+static int
+get_interface_address6_replacement(int severity, sa_family_t family,
+ tor_addr_t *addr)
+{
+ (void)severity;
+
+ last_address6_family = family;
+ n_get_interface_address6++;
+
+ if ((family != AF_INET) || !addr) {
+ return -1;
+ }
+
+ tor_addr_from_ipv4h(addr,0x09090909);
+
+ return 0;
+}
+
+static int n_get_interface_address_failure = 0;
+
+/**
+ * This mock function is meant to replace get_interface_address().
+ * It pretends to fail getting interface address by returning -1.
+ * <b>n_get_interface_address_failure</b> is incremented by one
+ * every time this function is called.
+ */
+static int
+get_interface_address_failure(int severity, uint32_t *addr)
+{
+ (void)severity;
+ (void)addr;
+
+ n_get_interface_address_failure++;
+
+ return -1;
+}
+
+static int n_get_interface_address6_failure = 0;
+
+/**
+ * This mock function is meant to replace get_interface_addres6().
+ * It will pretend to fail by return -1.
+ * <b>n_get_interface_address6_failure</b> is incremented by one
+ * every time this function is called and <b>last_address6_family</b>
+ * is assigned the value of <b>family</b> argument.
+ */
+static int
+get_interface_address6_failure(int severity, sa_family_t family,
+ tor_addr_t *addr)
+{
+ (void)severity;
+ (void)addr;
+ n_get_interface_address6_failure++;
+ last_address6_family = family;
+
+ return -1;
+}
+
+static void
+test_config_resolve_my_address(void *arg)
+{
+ or_options_t *options;
+ uint32_t resolved_addr;
+ const char *method_used;
+ char *hostname_out = NULL;
+ int retval;
+ int prev_n_hostname_01010101;
+ int prev_n_hostname_localhost;
+ int prev_n_hostname_failure;
+ int prev_n_gethostname_replacement;
+ int prev_n_gethostname_failure;
+ int prev_n_gethostname_localhost;
+ int prev_n_get_interface_address;
+ int prev_n_get_interface_address_failure;
+ int prev_n_get_interface_address6;
+ int prev_n_get_interface_address6_failure;
+
+ (void)arg;
+
+ options = options_new();
+
+ options_init(options);
+
+ /*
+ * CASE 1:
+ * If options->Address is a valid IPv4 address string, we want
+ * the corresponding address to be parsed and returned.
+ */
+
+ options->Address = tor_strdup("128.52.128.105");
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(retval == 0);
+ tt_want_str_op(method_used,==,"CONFIGURED");
+ tt_want(hostname_out == NULL);
+ tt_assert(resolved_addr == 0x80348069);
+
+ tor_free(options->Address);
+
+/*
+ * CASE 2:
+ * If options->Address is a valid DNS address, we want resolve_my_address()
+ * function to ask tor_lookup_hostname() for help with resolving it
+ * and return the address that was resolved (in host order).
+ */
+
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_01010101);
+
+ tor_free(options->Address);
+ options->Address = tor_strdup("www.torproject.org");
+
+ prev_n_hostname_01010101 = n_hostname_01010101;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(retval == 0);
+ tt_want(n_hostname_01010101 == prev_n_hostname_01010101 + 1);
+ tt_want_str_op(method_used,==,"RESOLVED");
+ tt_want_str_op(hostname_out,==,"www.torproject.org");
+ tt_assert(resolved_addr == 0x01010101);
+
+ UNMOCK(tor_lookup_hostname);
+
+ tor_free(options->Address);
+ tor_free(hostname_out);
+
+/*
+ * CASE 3:
+ * Given that options->Address is NULL, we want resolve_my_address()
+ * to try and use tor_gethostname() to get hostname AND use
+ * tor_lookup_hostname() to get IP address.
+ */
+
+ resolved_addr = 0;
+ tor_free(options->Address);
+ options->Address = NULL;
+
+ MOCK(tor_gethostname,tor_gethostname_replacement);
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_01010101);
+
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+ prev_n_hostname_01010101 = n_hostname_01010101;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(retval == 0);
+ tt_want(n_gethostname_replacement == prev_n_gethostname_replacement + 1);
+ tt_want(n_hostname_01010101 == prev_n_hostname_01010101 + 1);
+ tt_want_str_op(method_used,==,"GETHOSTNAME");
+ tt_want_str_op(hostname_out,==,"onionrouter!");
+ tt_assert(resolved_addr == 0x01010101);
+
+ UNMOCK(tor_gethostname);
+ UNMOCK(tor_lookup_hostname);
+
+ tor_free(hostname_out);
+
+/*
+ * CASE 4:
+ * Given that options->Address is a local host address, we want
+ * resolve_my_address() function to fail.
+ */
+
+ resolved_addr = 0;
+ tor_free(options->Address);
+ options->Address = tor_strdup("127.0.0.1");
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(resolved_addr == 0);
+ tt_assert(retval == -1);
+
+ tor_free(options->Address);
+ tor_free(hostname_out);
+
+/*
+ * CASE 5:
+ * We want resolve_my_address() to fail if DNS address in options->Address
+ * cannot be resolved.
+ */
+
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_failure);
+
+ prev_n_hostname_failure = n_hostname_failure;
+
+ tor_free(options->Address);
+ options->Address = tor_strdup("www.tor-project.org");
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_hostname_failure == prev_n_hostname_failure + 1);
+ tt_assert(retval == -1);
+
+ UNMOCK(tor_lookup_hostname);
+
+ tor_free(options->Address);
+ tor_free(hostname_out);
+
+/*
+ * CASE 6:
+ * If options->Address is NULL AND gettting local hostname fails, we want
+ * resolve_my_address() to fail as well.
+ */
+
+ MOCK(tor_gethostname,tor_gethostname_failure);
+
+ prev_n_gethostname_failure = n_gethostname_failure;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_gethostname_failure == prev_n_gethostname_failure + 1);
+ tt_assert(retval == -1);
+
+ UNMOCK(tor_gethostname);
+ tor_free(hostname_out);
+
+/*
+ * CASE 7:
+ * We want resolve_my_address() to try and get network interface address via
+ * get_interface_address() if hostname returned by tor_gethostname() cannot be
+ * resolved into IP address.
+ */
+
+ MOCK(tor_gethostname,tor_gethostname_replacement);
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_failure);
+ MOCK(get_interface_address,get_interface_address_08080808);
+
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+ prev_n_get_interface_address = n_get_interface_address;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(retval == 0);
+ tt_want_int_op(n_gethostname_replacement, ==,
+ prev_n_gethostname_replacement + 1);
+ tt_want_int_op(n_get_interface_address, ==,
+ prev_n_get_interface_address + 1);
+ tt_want_str_op(method_used,==,"INTERFACE");
+ tt_want(hostname_out == NULL);
+ tt_assert(resolved_addr == 0x08080808);
+
+ UNMOCK(get_interface_address);
+ tor_free(hostname_out);
+
+/*
+ * CASE 8:
+ * Suppose options->Address is NULL AND hostname returned by tor_gethostname()
+ * is unresolvable. We want resolve_my_address to fail if
+ * get_interface_address() fails.
+ */
+
+ MOCK(get_interface_address,get_interface_address_failure);
+
+ prev_n_get_interface_address_failure = n_get_interface_address_failure;
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_get_interface_address_failure ==
+ prev_n_get_interface_address_failure + 1);
+ tt_want(n_gethostname_replacement ==
+ prev_n_gethostname_replacement + 1);
+ tt_assert(retval == -1);
+
+ UNMOCK(get_interface_address);
+ tor_free(hostname_out);
+
+/*
+ * CASE 9:
+ * Given that options->Address is NULL AND tor_lookup_hostname()
+ * fails AND hostname returned by gethostname() resolves
+ * to local IP address, we want resolve_my_address() function to
+ * call get_interface_address6(.,AF_INET,.) and return IP address
+ * the latter function has found.
+ */
+
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_failure);
+ MOCK(tor_gethostname,tor_gethostname_replacement);
+ MOCK(get_interface_address6,get_interface_address6_replacement);
+
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+ prev_n_hostname_failure = n_hostname_failure;
+ prev_n_get_interface_address6 = n_get_interface_address6;
+
+ retval = resolve_my_address(LOG_NOTICE,options,&resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(last_address6_family == AF_INET);
+ tt_want(n_get_interface_address6 == prev_n_get_interface_address6 + 1);
+ tt_want(n_hostname_failure == prev_n_hostname_failure + 1);
+ tt_want(n_gethostname_replacement == prev_n_gethostname_replacement + 1);
+ tt_want(retval == 0);
+ tt_want_str_op(method_used,==,"INTERFACE");
+ tt_assert(resolved_addr == 0x09090909);
+
+ UNMOCK(tor_lookup_hostname);
+ UNMOCK(tor_gethostname);
+ UNMOCK(get_interface_address6);
+
+ tor_free(hostname_out);
+
+ /*
+ * CASE 10: We want resolve_my_address() to fail if all of the following
+ * are true:
+ * 1. options->Address is not NULL
+ * 2. ... but it cannot be converted to struct in_addr by
+ * tor_inet_aton()
+ * 3. ... and tor_lookup_hostname() fails to resolve the
+ * options->Address
+ */
+
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_failure);
+
+ prev_n_hostname_failure = n_hostname_failure;
+
+ tor_free(options->Address);
+ options->Address = tor_strdup("some_hostname");
+
+ retval = resolve_my_address(LOG_NOTICE, options, &resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_hostname_failure == prev_n_hostname_failure + 1);
+ tt_assert(retval == -1);
+
+ UNMOCK(tor_gethostname);
+ UNMOCK(tor_lookup_hostname);
+
+ tor_free(hostname_out);
+
+ /*
+ * CASE 11:
+ * Suppose the following sequence of events:
+ * 1. options->Address is NULL
+ * 2. tor_gethostname() succeeds to get hostname of machine Tor
+ * if running on.
+ * 3. Hostname from previous step cannot be converted to
+ * address by using tor_inet_aton() function.
+ * 4. However, tor_lookup_hostname() succeds in resolving the
+ * hostname from step 2.
+ * 5. Unfortunately, tor_addr_is_internal() deems this address
+ * to be internal.
+ * 6. get_interface_address6(.,AF_INET,.) returns non-internal
+ * IPv4
+ *
+ * We want resolve_my_addr() to succeed with method "INTERFACE"
+ * and address from step 6.
+ */
+
+ tor_free(options->Address);
+ options->Address = NULL;
+
+ MOCK(tor_gethostname,tor_gethostname_replacement);
+ MOCK(tor_lookup_hostname,tor_lookup_hostname_localhost);
+ MOCK(get_interface_address6,get_interface_address6_replacement);
+
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+ prev_n_hostname_localhost = n_hostname_localhost;
+ prev_n_get_interface_address6 = n_get_interface_address6;
+
+ retval = resolve_my_address(LOG_DEBUG, options, &resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_gethostname_replacement == prev_n_gethostname_replacement + 1);
+ tt_want(n_hostname_localhost == prev_n_hostname_localhost + 1);
+ tt_want(n_get_interface_address6 == prev_n_get_interface_address6 + 1);
+
+ tt_str_op(method_used,==,"INTERFACE");
+ tt_assert(!hostname_out);
+ tt_assert(retval == 0);
+
+ /*
+ * CASE 11b:
+ * 1-5 as above.
+ * 6. get_interface_address6() fails.
+ *
+ * In this subcase, we want resolve_my_address() to fail.
+ */
+
+ UNMOCK(get_interface_address6);
+ MOCK(get_interface_address6,get_interface_address6_failure);
+
+ prev_n_gethostname_replacement = n_gethostname_replacement;
+ prev_n_hostname_localhost = n_hostname_localhost;
+ prev_n_get_interface_address6_failure = n_get_interface_address6_failure;
+
+ retval = resolve_my_address(LOG_DEBUG, options, &resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_gethostname_replacement == prev_n_gethostname_replacement + 1);
+ tt_want(n_hostname_localhost == prev_n_hostname_localhost + 1);
+ tt_want(n_get_interface_address6_failure ==
+ prev_n_get_interface_address6_failure + 1);
+
+ tt_assert(retval == -1);
+
+ UNMOCK(tor_gethostname);
+ UNMOCK(tor_lookup_hostname);
+ UNMOCK(get_interface_address6);
+
+ /* CASE 12:
+ * Suppose the following happens:
+ * 1. options->Address is NULL AND options->DirAuthorities is non-NULL
+ * 2. tor_gethostname() succeeds in getting hostname of a machine ...
+ * 3. ... which is successfully parsed by tor_inet_aton() ...
+ * 4. into IPv4 address that tor_addr_is_inernal() considers to be
+ * internal.
+ *
+ * In this case, we want resolve_my_address() to fail.
+ */
+
+ tor_free(options->Address);
+ options->Address = NULL;
+ options->DirAuthorities = tor_malloc_zero(sizeof(config_line_t));
+
+ MOCK(tor_gethostname,tor_gethostname_localhost);
+
+ prev_n_gethostname_localhost = n_gethostname_localhost;
+
+ retval = resolve_my_address(LOG_DEBUG, options, &resolved_addr,
+ &method_used,&hostname_out);
+
+ tt_want(n_gethostname_localhost == prev_n_gethostname_localhost + 1);
+ tt_assert(retval == -1);
+
+ UNMOCK(tor_gethostname);
+
+ done:
+ tor_free(options->Address);
+ tor_free(options->DirAuthorities);
+ or_options_free(options);
+ tor_free(hostname_out);
+
+ UNMOCK(tor_gethostname);
+ UNMOCK(tor_lookup_hostname);
+ UNMOCK(get_interface_address);
+ UNMOCK(get_interface_address6);
+ UNMOCK(tor_gethostname);
+}
+
+static void
+test_config_adding_trusted_dir_server(void *arg)
+{
+ (void)arg;
+
+ const char digest[DIGEST_LEN] = "";
+ dir_server_t *ds = NULL;
+ tor_addr_port_t ipv6;
+ int rv = -1;
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* create a trusted ds without an IPv6 address and port */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+ tt_assert(get_n_authorities(V3_DIRINFO) == 1);
+ tt_assert(smartlist_len(router_get_fallback_dir_servers()) == 1);
+
+ /* create a trusted ds with an IPv6 address and port */
+ rv = tor_addr_port_parse(LOG_WARN, "[::1]:9061", &ipv6.addr, &ipv6.port, -1);
+ tt_assert(rv == 0);
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, &ipv6, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+ tt_assert(get_n_authorities(V3_DIRINFO) == 2);
+ tt_assert(smartlist_len(router_get_fallback_dir_servers()) == 2);
+
+ done:
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static void
+test_config_adding_fallback_dir_server(void *arg)
+{
+ (void)arg;
+
+ const char digest[DIGEST_LEN] = "";
+ dir_server_t *ds = NULL;
+ tor_addr_t ipv4;
+ tor_addr_port_t ipv6;
+ int rv = -1;
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ rv = tor_addr_parse(&ipv4, "127.0.0.1");
+ tt_assert(rv == AF_INET);
+
+ /* create a trusted ds without an IPv6 address and port */
+ ds = fallback_dir_server_new(&ipv4, 9059, 9060, NULL, digest, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+ tt_assert(smartlist_len(router_get_fallback_dir_servers()) == 1);
+
+ /* create a trusted ds with an IPv6 address and port */
+ rv = tor_addr_port_parse(LOG_WARN, "[::1]:9061", &ipv6.addr, &ipv6.port, -1);
+ tt_assert(rv == 0);
+ ds = fallback_dir_server_new(&ipv4, 9059, 9060, &ipv6, digest, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+ tt_assert(smartlist_len(router_get_fallback_dir_servers()) == 2);
+
+ done:
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+/* No secrets here:
+ * v3ident is `echo "onion" | shasum | cut -d" " -f1 | tr "a-f" "A-F"`
+ * fingerprint is `echo "unionem" | shasum | cut -d" " -f1 | tr "a-f" "A-F"`
+ * with added spaces
+ */
+#define TEST_DIR_AUTH_LINE_START \
+ "foobar orport=12345 " \
+ "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
+#define TEST_DIR_AUTH_LINE_END \
+ "1.2.3.4:54321 " \
+ "FDB2 FBD2 AAA5 25FA 2999 E617 5091 5A32 C777 3B17"
+#define TEST_DIR_AUTH_IPV6_FLAG \
+ "ipv6=[feed::beef]:9 "
+
+static void
+test_config_parsing_trusted_dir_server(void *arg)
+{
+ (void)arg;
+ int rv = -1;
+
+ /* parse a trusted dir server without an IPv6 address and port */
+ rv = parse_dir_authority_line(TEST_DIR_AUTH_LINE_START
+ TEST_DIR_AUTH_LINE_END,
+ V3_DIRINFO, 1);
+ tt_assert(rv == 0);
+
+ /* parse a trusted dir server with an IPv6 address and port */
+ rv = parse_dir_authority_line(TEST_DIR_AUTH_LINE_START
+ TEST_DIR_AUTH_IPV6_FLAG
+ TEST_DIR_AUTH_LINE_END,
+ V3_DIRINFO, 1);
+ tt_assert(rv == 0);
+
+ /* Since we are only validating, there is no cleanup. */
+ done:
+ ;
+}
+
+#undef TEST_DIR_AUTH_LINE_START
+#undef TEST_DIR_AUTH_LINE_END
+#undef TEST_DIR_AUTH_IPV6_FLAG
+
+/* No secrets here:
+ * id is `echo "syn-propanethial-S-oxide" | shasum | cut -d" " -f1`
+ */
+#define TEST_DIR_FALLBACK_LINE \
+ "1.2.3.4:54321 orport=12345 " \
+ "id=50e643986f31ea1235bcc1af17a1c5c5cfc0ee54 "
+#define TEST_DIR_FALLBACK_IPV6_FLAG \
+ "ipv6=[2015:c0de::deed]:9"
+
+static void
+test_config_parsing_fallback_dir_server(void *arg)
+{
+ (void)arg;
+ int rv = -1;
+
+ /* parse a trusted dir server without an IPv6 address and port */
+ rv = parse_dir_fallback_line(TEST_DIR_FALLBACK_LINE, 1);
+ tt_assert(rv == 0);
+
+ /* parse a trusted dir server with an IPv6 address and port */
+ rv = parse_dir_fallback_line(TEST_DIR_FALLBACK_LINE
+ TEST_DIR_FALLBACK_IPV6_FLAG,
+ 1);
+ tt_assert(rv == 0);
+
+ /* Since we are only validating, there is no cleanup. */
+ done:
+ ;
+}
+
+#undef TEST_DIR_FALLBACK_LINE
+#undef TEST_DIR_FALLBACK_IPV6_FLAG
+
+static void
+test_config_adding_default_trusted_dir_servers(void *arg)
+{
+ (void)arg;
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* Assume we only have one bridge authority */
+ add_default_trusted_dir_authorities(BRIDGE_DIRINFO);
+ tt_assert(get_n_authorities(BRIDGE_DIRINFO) == 1);
+ tt_assert(smartlist_len(router_get_fallback_dir_servers()) == 1);
+
+ /* Assume we have eight V3 authorities */
+ add_default_trusted_dir_authorities(V3_DIRINFO);
+ tt_int_op(get_n_authorities(V3_DIRINFO), OP_EQ, 8);
+ tt_int_op(smartlist_len(router_get_fallback_dir_servers()), OP_EQ, 9);
+
+ done:
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static int n_add_default_fallback_dir_servers_known_default = 0;
+
+/**
+ * This mock function is meant to replace add_default_fallback_dir_servers().
+ * It will parse and add one known default fallback dir server,
+ * which has a dir_port of 99.
+ * <b>n_add_default_fallback_dir_servers_known_default</b> is incremented by
+ * one every time this function is called.
+ */
+static void
+add_default_fallback_dir_servers_known_default(void)
+{
+ int i;
+ const char *fallback[] = {
+ "127.0.0.1:60099 orport=9009 "
+ "id=0923456789012345678901234567890123456789",
+ NULL
+ };
+ for (i=0; fallback[i]; i++) {
+ if (parse_dir_fallback_line(fallback[i], 0)<0) {
+ log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
+ fallback[i]);
+ }
+ }
+ n_add_default_fallback_dir_servers_known_default++;
+}
+
+/* Test all the different combinations of adding dir servers */
+static void
+test_config_adding_dir_servers(void *arg)
+{
+ (void)arg;
+
+ /* allocate options */
+ or_options_t *options = tor_malloc_zero(sizeof(or_options_t));
+
+ /* Allocate and populate configuration lines:
+ *
+ * Use the same format as the hard-coded directories in
+ * add_default_trusted_dir_authorities().
+ * Zeroing the structure has the same effect as initialising to:
+ * { NULL, NULL, NULL, CONFIG_LINE_NORMAL, 0};
+ */
+ config_line_t *test_dir_authority = tor_malloc_zero(sizeof(config_line_t));
+ test_dir_authority->key = tor_strdup("DirAuthority");
+ test_dir_authority->value = tor_strdup(
+ "D0 orport=9000 "
+ "v3ident=0023456789012345678901234567890123456789 "
+ "127.0.0.1:60090 0123 4567 8901 2345 6789 0123 4567 8901 2345 6789"
+ );
+
+ config_line_t *test_alt_bridge_authority = tor_malloc_zero(
+ sizeof(config_line_t));
+ test_alt_bridge_authority->key = tor_strdup("AlternateBridgeAuthority");
+ test_alt_bridge_authority->value = tor_strdup(
+ "B1 orport=9001 bridge "
+ "127.0.0.1:60091 1123 4567 8901 2345 6789 0123 4567 8901 2345 6789"
+ );
+
+ config_line_t *test_alt_dir_authority = tor_malloc_zero(
+ sizeof(config_line_t));
+ test_alt_dir_authority->key = tor_strdup("AlternateDirAuthority");
+ test_alt_dir_authority->value = tor_strdup(
+ "A2 orport=9002 "
+ "v3ident=0223456789012345678901234567890123456789 "
+ "127.0.0.1:60092 2123 4567 8901 2345 6789 0123 4567 8901 2345 6789"
+ );
+
+ /* Use the format specified in the manual page */
+ config_line_t *test_fallback_directory = tor_malloc_zero(
+ sizeof(config_line_t));
+ test_fallback_directory->key = tor_strdup("FallbackDir");
+ test_fallback_directory->value = tor_strdup(
+ "127.0.0.1:60093 orport=9003 id=0323456789012345678901234567890123456789"
+ );
+
+ /* We need to know if add_default_fallback_dir_servers is called,
+ * whatever the size of the list in fallback_dirs.inc,
+ * so we use a version of add_default_fallback_dir_servers that adds
+ * one known default fallback directory. */
+ MOCK(add_default_fallback_dir_servers,
+ add_default_fallback_dir_servers_known_default);
+
+ /* There are 16 different cases, covering each combination of set/NULL for:
+ * DirAuthorities, AlternateBridgeAuthority, AlternateDirAuthority &
+ * FallbackDir. (We always set UseDefaultFallbackDirs to 1.)
+ * But validate_dir_servers() ensures that:
+ * "You cannot set both DirAuthority and Alternate*Authority."
+ * This reduces the number of cases to 10.
+ *
+ * Let's count these cases using binary, with 1 meaning set & 0 meaning NULL
+ * So 1001 or case 9 is:
+ * DirAuthorities set,
+ * AlternateBridgeAuthority NULL,
+ * AlternateDirAuthority NULL
+ * FallbackDir set
+ * The valid cases are cases 0-9 counting using this method, as every case
+ * greater than or equal to 10 = 1010 is invalid.
+ *
+ * 1. Outcome: Use Set Directory Authorities
+ * - No Default Authorities
+ * - Use AlternateBridgeAuthority, AlternateDirAuthority, and FallbackDir
+ * if they are set
+ * Cases expected to yield this outcome:
+ * 8 & 9 (the 2 valid cases where DirAuthorities is set)
+ * 6 & 7 (the 2 cases where DirAuthorities is NULL, and
+ * AlternateBridgeAuthority and AlternateDirAuthority are both set)
+ *
+ * 2. Outcome: Use Set Bridge Authority
+ * - Use Default Non-Bridge Directory Authorities
+ * - Use FallbackDir if it is set, otherwise use default FallbackDir
+ * Cases expected to yield this outcome:
+ * 4 & 5 (the 2 cases where DirAuthorities is NULL,
+ * AlternateBridgeAuthority is set, and
+ * AlternateDirAuthority is NULL)
+ *
+ * 3. Outcome: Use Set Alternate Directory Authority
+ * - Use Default Bridge Authorities
+ * - Use FallbackDir if it is set, otherwise No Default Fallback Directories
+ * Cases expected to yield this outcome:
+ * 2 & 3 (the 2 cases where DirAuthorities and AlternateBridgeAuthority
+ * are both NULL, but AlternateDirAuthority is set)
+ *
+ * 4. Outcome: Use Set Custom Fallback Directory
+ * - Use Default Bridge & Directory Authorities
+ * Cases expected to yield this outcome:
+ * 1 (DirAuthorities, AlternateBridgeAuthority and AlternateDirAuthority
+ * are all NULL, but FallbackDir is set)
+ *
+ * 5. Outcome: Use All Defaults
+ * - Use Default Bridge & Directory Authorities, and
+ * Default Fallback Directories
+ * Cases expected to yield this outcome:
+ * 0 (DirAuthorities, AlternateBridgeAuthority, AlternateDirAuthority
+ * and FallbackDir are all NULL)
+ */
+
+ /*
+ * Find out how many default Bridge, Non-Bridge and Fallback Directories
+ * are hard-coded into this build.
+ * This code makes some assumptions about the implementation.
+ * If they are wrong, one or more of cases 0-5 could fail.
+ */
+ int n_default_alt_bridge_authority = 0;
+ int n_default_alt_dir_authority = 0;
+ int n_default_fallback_dir = 0;
+#define n_default_authorities ((n_default_alt_bridge_authority) \
+ + (n_default_alt_dir_authority))
+
+ /* Pre-Count Number of Authorities of Each Type
+ * Use 0000: No Directory Authorities or Fallback Directories Set
+ */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0000 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 1);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+
+ /* Count Bridge Authorities */
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if it's a bridge auth */
+ n_default_alt_bridge_authority +=
+ ((ds->is_authority && (ds->type & BRIDGE_DIRINFO)) ?
+ 1 : 0)
+ );
+ /* If we have no default bridge authority, something has gone wrong */
+ tt_assert(n_default_alt_bridge_authority >= 1);
+
+ /* Count v3 Authorities */
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment found counter if it's a v3 auth */
+ n_default_alt_dir_authority +=
+ ((ds->is_authority && (ds->type & V3_DIRINFO)) ?
+ 1 : 0)
+ );
+ /* If we have no default authorities, something has gone really wrong */
+ tt_assert(n_default_alt_dir_authority >= 1);
+
+ /* Calculate Fallback Directory Count */
+ n_default_fallback_dir = (smartlist_len(fallback_servers) -
+ n_default_alt_bridge_authority -
+ n_default_alt_dir_authority);
+ /* If we have a negative count, something has gone really wrong,
+ * or some authorities aren't being added as fallback directories.
+ * (networkstatus_consensus_can_use_extra_fallbacks depends on all
+ * authorities being fallback directories.) */
+ tt_assert(n_default_fallback_dir >= 0);
+ }
+ }
+
+ /*
+ * 1. Outcome: Use Set Directory Authorities
+ * - No Default Authorities
+ * - Use AlternateBridgeAuthority, AlternateDirAuthority, and FallbackDir
+ * if they are set
+ * Cases expected to yield this outcome:
+ * 8 & 9 (the 2 valid cases where DirAuthorities is set)
+ * 6 & 7 (the 2 cases where DirAuthorities is NULL, and
+ * AlternateBridgeAuthority and AlternateDirAuthority are both set)
+ */
+
+ /* Case 9: 1001 - DirAuthorities Set, AlternateBridgeAuthority Not Set,
+ AlternateDirAuthority Not Set, FallbackDir Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 1001 */
+ options->DirAuthorities = test_dir_authority;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = test_fallback_directory;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* D0, (No B1), (No A2) */
+ tt_assert(smartlist_len(dir_servers) == 1);
+
+ /* DirAuthority - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 1);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* D0, (No B1), (No A2), Custom Fallback */
+ tt_assert(smartlist_len(fallback_servers) == 2);
+
+ /* DirAuthority - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 1);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 1);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+ }
+ }
+
+ /* Case 8: 1000 - DirAuthorities Set, Others Not Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 1000 */
+ options->DirAuthorities = test_dir_authority;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we just have the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 0);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* D0, (No B1), (No A2) */
+ tt_assert(smartlist_len(dir_servers) == 1);
+
+ /* DirAuthority - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 1);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* D0, (No B1), (No A2), (No Fallback) */
+ tt_assert(smartlist_len(fallback_servers) == 1);
+
+ /* DirAuthority - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 1);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* (No Custom FallbackDir) - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 0);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+ }
+ }
+
+ /* Case 7: 0111 - DirAuthorities Not Set, Others Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0111 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = test_alt_bridge_authority;
+ options->AlternateDirAuthority = test_alt_dir_authority;
+ options->FallbackDir = test_fallback_directory;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), B1, A2 */
+ tt_assert(smartlist_len(dir_servers) == 2);
+
+ /* (No DirAuthority) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), B1, A2, Custom Fallback */
+ tt_assert(smartlist_len(fallback_servers) == 3);
+
+ /* (No DirAuthority) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 1);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+ }
+ }
+
+ /* Case 6: 0110 - DirAuthorities Not Set, AlternateBridgeAuthority &
+ AlternateDirAuthority Set, FallbackDir Not Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0110 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = test_alt_bridge_authority;
+ options->AlternateDirAuthority = test_alt_dir_authority;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 0);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), B1, A2 */
+ tt_assert(smartlist_len(dir_servers) == 2);
+
+ /* (No DirAuthority) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), B1, A2, (No Fallback) */
+ tt_assert(smartlist_len(fallback_servers) == 2);
+
+ /* (No DirAuthority) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* (No Custom FallbackDir) - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 0);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+ }
+ }
+
+ /*
+ 2. Outcome: Use Set Bridge Authority
+ - Use Default Non-Bridge Directory Authorities
+ - Use FallbackDir if it is set, otherwise use default FallbackDir
+ Cases expected to yield this outcome:
+ 4 & 5 (the 2 cases where DirAuthorities is NULL,
+ AlternateBridgeAuthority is set, and
+ AlternateDirAuthority is NULL)
+ */
+
+ /* Case 5: 0101 - DirAuthorities Not Set, AlternateBridgeAuthority Set,
+ AlternateDirAuthority Not Set, FallbackDir Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0101 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = test_alt_bridge_authority;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = test_fallback_directory;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), B1, (No A2), Default v3 Non-Bridge Authorities */
+ tt_assert(smartlist_len(dir_servers) == 1 + n_default_alt_dir_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default v3 non-Bridge directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), B1, (No A2), Default v3 Non-Bridge Authorities,
+ * Custom Fallback */
+ tt_assert(smartlist_len(fallback_servers) ==
+ 2 + n_default_alt_dir_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 1);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default v3 non-Bridge directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+ }
+
+ /* Case 4: 0100 - DirAuthorities Not Set, AlternateBridgeAuthority Set,
+ AlternateDirAuthority & FallbackDir Not Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0100 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = test_alt_bridge_authority;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 1);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), B1, (No A2), Default v3 Non-Bridge Authorities */
+ tt_assert(smartlist_len(dir_servers) == 1 + n_default_alt_dir_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default v3 non-Bridge directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), B1, (No A2), Default v3 Non-Bridge Authorities,
+ * Default Fallback */
+ tt_assert(smartlist_len(fallback_servers) ==
+ 2 + n_default_alt_dir_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* AlternateBridgeAuthority - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 1);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* (No Custom FallbackDir) - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 0);
+
+ /* Default FallbackDir - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 1);
+
+ /* There's no easy way of checking that we have included all the
+ * default v3 non-Bridge directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+ }
+
+ /*
+ 3. Outcome: Use Set Alternate Directory Authority
+ - Use Default Bridge Authorities
+ - Use FallbackDir if it is set, otherwise No Default Fallback Directories
+ Cases expected to yield this outcome:
+ 2 & 3 (the 2 cases where DirAuthorities and AlternateBridgeAuthority
+ are both NULL, but AlternateDirAuthority is set)
+ */
+
+ /* Case 3: 0011 - DirAuthorities & AlternateBridgeAuthority Not Set,
+ AlternateDirAuthority & FallbackDir Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0011 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = test_alt_dir_authority;
+ options->FallbackDir = test_fallback_directory;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities, A2 */
+ tt_assert(smartlist_len(dir_servers) ==
+ 1 + n_default_alt_bridge_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge authorities (except for hard-coding tonga's details),
+ * so let's assume that if the total count above is correct,
+ * we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities, A2,
+ * Custom Fallback Directory, (No Default Fallback Directories) */
+ tt_assert(smartlist_len(fallback_servers) ==
+ 2 + n_default_alt_bridge_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 1);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge authorities (except for hard-coding tonga's details),
+ * so let's assume that if the total count above is correct,
+ * we have the right ones.
+ */
+ }
+ }
+
+ /* Case 2: 0010 - DirAuthorities & AlternateBridgeAuthority Not Set,
+ AlternateDirAuthority Set, FallbackDir Not Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0010 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = test_alt_dir_authority;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we just have the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 0);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities, A2,
+ * No Default or Custom Fallback Directories */
+ tt_assert(smartlist_len(dir_servers) ==
+ 1 + n_default_alt_bridge_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge authorities (except for hard-coding tonga's details),
+ * so let's assume that if the total count above is correct,
+ * we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities, A2,
+ * No Custom or Default Fallback Directories */
+ tt_assert(smartlist_len(fallback_servers) ==
+ 1 + n_default_alt_bridge_authority);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* AlternateDirAuthority - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 1);
+
+ /* (No Custom FallbackDir) - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 0);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge authorities (except for hard-coding tonga's details),
+ * so let's assume that if the total count above is correct,
+ * we have the right ones.
+ */
+ }
+ }
+
+ /*
+ 4. Outcome: Use Set Custom Fallback Directory
+ - Use Default Bridge & Directory Authorities
+ Cases expected to yield this outcome:
+ 1 (DirAuthorities, AlternateBridgeAuthority and AlternateDirAuthority
+ are all NULL, but FallbackDir is set)
+ */
+
+ /* Case 1: 0001 - DirAuthorities, AlternateBridgeAuthority
+ & AlternateDirAuthority Not Set, FallbackDir Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0001 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = test_fallback_directory;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must not have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 0);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities,
+ * (No A2), Default v3 Directory Authorities */
+ tt_assert(smartlist_len(dir_servers) == n_default_authorities);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge & V3 Directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities,
+ * (No A2), Default v3 Directory Authorities,
+ * Custom Fallback Directory, (No Default Fallback Directories) */
+ tt_assert(smartlist_len(fallback_servers) ==
+ 1 + n_default_authorities);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 1);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge & V3 Directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+ }
+
+ /*
+ 5. Outcome: Use All Defaults
+ - Use Default Bridge & Directory Authorities, Default Fallback Directories
+ Cases expected to yield this outcome:
+ 0 (DirAuthorities, AlternateBridgeAuthority, AlternateDirAuthority
+ and FallbackDir are all NULL)
+ */
+
+ /* Case 0: 0000 - All Not Set */
+ {
+ /* clear fallback dirs counter */
+ n_add_default_fallback_dir_servers_known_default = 0;
+
+ /* clear options*/
+ memset(options, 0, sizeof(or_options_t));
+
+ /* clear any previous dir servers:
+ consider_adding_dir_servers() should do this anyway */
+ clear_dir_servers();
+
+ /* assign options: 0001 */
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = NULL;
+ options->UseDefaultFallbackDirs = 1;
+
+ /* parse options - ensure we always update by passing NULL old_options */
+ consider_adding_dir_servers(options, NULL);
+
+ /* check outcome */
+
+ /* we must have added the default fallback dirs */
+ tt_assert(n_add_default_fallback_dir_servers_known_default == 1);
+
+ /* we have more fallbacks than just the authorities */
+ tt_assert(networkstatus_consensus_can_use_extra_fallbacks(options) == 1);
+
+ {
+ /* trusted_dir_servers */
+ const smartlist_t *dir_servers = router_get_trusted_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities,
+ * (No A2), Default v3 Directory Authorities */
+ tt_assert(smartlist_len(dir_servers) == n_default_authorities);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(dir_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge & V3 Directory authorities, so let's assume that
+ * if the total count above is correct, we have the right ones.
+ */
+ }
+
+ {
+ /* fallback_dir_servers */
+ const smartlist_t *fallback_servers = router_get_fallback_dir_servers();
+ /* (No D0), (No B1), Default Bridge Authorities,
+ * (No A2), Default v3 Directory Authorities,
+ * (No Custom Fallback Directory), Default Fallback Directories */
+ tt_assert(smartlist_len(fallback_servers) ==
+ n_default_authorities + n_default_fallback_dir);
+
+ /* (No DirAuthorities) - D0 - dir_port: 60090 */
+ int found_D0 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_D0 +=
+ (ds->dir_port == 60090 ?
+ 1 : 0)
+ );
+ tt_assert(found_D0 == 0);
+
+ /* (No AlternateBridgeAuthority) - B1 - dir_port: 60091 */
+ int found_B1 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_B1 +=
+ (ds->dir_port == 60091 ?
+ 1 : 0)
+ );
+ tt_assert(found_B1 == 0);
+
+ /* (No AlternateDirAuthority) - A2 - dir_port: 60092 */
+ int found_A2 = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_A2 +=
+ (ds->dir_port == 60092 ?
+ 1 : 0)
+ );
+ tt_assert(found_A2 == 0);
+
+ /* Custom FallbackDir - No Nickname - dir_port: 60093 */
+ int found_non_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_non_default_fallback +=
+ (ds->dir_port == 60093 ?
+ 1 : 0)
+ );
+ tt_assert(found_non_default_fallback == 0);
+
+ /* (No Default FallbackDir) - No Nickname - dir_port: 60099 */
+ int found_default_fallback = 0;
+ SMARTLIST_FOREACH(fallback_servers,
+ dir_server_t *,
+ ds,
+ /* increment the found counter if dir_port matches */
+ found_default_fallback +=
+ (ds->dir_port == 60099 ?
+ 1 : 0)
+ );
+ tt_assert(found_default_fallback == 1);
+
+ /* There's no easy way of checking that we have included all the
+ * default Bridge & V3 Directory authorities, and the default
+ * Fallback Directories, so let's assume that if the total count
+ * above is correct, we have the right ones.
+ */
+ }
+ }
+
+ done:
+ clear_dir_servers();
+
+ tor_free(test_dir_authority->key);
+ tor_free(test_dir_authority->value);
+ tor_free(test_dir_authority);
+
+ tor_free(test_alt_dir_authority->key);
+ tor_free(test_alt_dir_authority->value);
+ tor_free(test_alt_dir_authority);
+
+ tor_free(test_alt_bridge_authority->key);
+ tor_free(test_alt_bridge_authority->value);
+ tor_free(test_alt_bridge_authority);
+
+ tor_free(test_fallback_directory->key);
+ tor_free(test_fallback_directory->value);
+ tor_free(test_fallback_directory);
+
+ options->DirAuthorities = NULL;
+ options->AlternateBridgeAuthority = NULL;
+ options->AlternateDirAuthority = NULL;
+ options->FallbackDir = NULL;
+ or_options_free(options);
+
+ UNMOCK(add_default_fallback_dir_servers);
+}
+
+static void
+test_config_default_dir_servers(void *arg)
+{
+ or_options_t *opts = NULL;
+ (void)arg;
+ int trusted_count = 0;
+ int fallback_count = 0;
+
+ /* new set of options should stop fallback parsing */
+ opts = tor_malloc_zero(sizeof(or_options_t));
+ opts->UseDefaultFallbackDirs = 0;
+ /* set old_options to NULL to force dir update */
+ consider_adding_dir_servers(opts, NULL);
+ trusted_count = smartlist_len(router_get_trusted_dir_servers());
+ fallback_count = smartlist_len(router_get_fallback_dir_servers());
+ or_options_free(opts);
+ opts = NULL;
+
+ /* assume a release will never go out with less than 7 authorities */
+ tt_assert(trusted_count >= 7);
+ /* if we disable the default fallbacks, there must not be any extra */
+ tt_assert(fallback_count == trusted_count);
+
+ opts = tor_malloc_zero(sizeof(or_options_t));
+ opts->UseDefaultFallbackDirs = 1;
+ consider_adding_dir_servers(opts, opts);
+ trusted_count = smartlist_len(router_get_trusted_dir_servers());
+ fallback_count = smartlist_len(router_get_fallback_dir_servers());
+ or_options_free(opts);
+ opts = NULL;
+
+ /* assume a release will never go out with less than 7 authorities */
+ tt_assert(trusted_count >= 7);
+ /* XX/teor - allow for default fallbacks to be added without breaking
+ * the unit tests. Set a minimum fallback count once the list is stable. */
+ tt_assert(fallback_count >= trusted_count);
+
+ done:
+ or_options_free(opts);
+}
+
+static int mock_router_pick_published_address_result = 0;
+
+static int
+mock_router_pick_published_address(const or_options_t *options, uint32_t *addr)
+{
+ (void)options;
+ (void)addr;
+ return mock_router_pick_published_address_result;
+}
+
+static int mock_router_my_exit_policy_is_reject_star_result = 0;
+
+static int
+mock_router_my_exit_policy_is_reject_star(void)
+{
+ return mock_router_my_exit_policy_is_reject_star_result;
+}
+
+static int mock_advertised_server_mode_result = 0;
+
+static int
+mock_advertised_server_mode(void)
+{
+ return mock_advertised_server_mode_result;
+}
+
+static routerinfo_t *mock_router_get_my_routerinfo_result = NULL;
+
+static const routerinfo_t *
+mock_router_get_my_routerinfo(void)
+{
+ return mock_router_get_my_routerinfo_result;
+}
+
+static void
+test_config_directory_fetch(void *arg)
+{
+ (void)arg;
+
+ /* Test Setup */
+ or_options_t *options = tor_malloc_zero(sizeof(or_options_t));
+ routerinfo_t routerinfo;
+ memset(&routerinfo, 0, sizeof(routerinfo));
+ mock_router_pick_published_address_result = -1;
+ mock_router_my_exit_policy_is_reject_star_result = 1;
+ mock_advertised_server_mode_result = 0;
+ mock_router_get_my_routerinfo_result = NULL;
+ MOCK(router_pick_published_address, mock_router_pick_published_address);
+ MOCK(router_my_exit_policy_is_reject_star,
+ mock_router_my_exit_policy_is_reject_star);
+ MOCK(advertised_server_mode, mock_advertised_server_mode);
+ MOCK(router_get_my_routerinfo, mock_router_get_my_routerinfo);
+
+ /* Clients can use multiple directory mirrors for bootstrap */
+ memset(options, 0, sizeof(or_options_t));
+ options->ClientOnly = 1;
+ tt_assert(server_mode(options) == 0);
+ tt_assert(public_server_mode(options) == 0);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 1);
+
+ /* Bridge Clients can use multiple directory mirrors for bootstrap */
+ memset(options, 0, sizeof(or_options_t));
+ options->UseBridges = 1;
+ tt_assert(server_mode(options) == 0);
+ tt_assert(public_server_mode(options) == 0);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 1);
+
+ /* Bridge Relays (Bridges) must act like clients, and use multiple
+ * directory mirrors for bootstrap */
+ memset(options, 0, sizeof(or_options_t));
+ options->BridgeRelay = 1;
+ options->ORPort_set = 1;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 0);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 1);
+
+ /* Clients set to FetchDirInfoEarly must fetch it from the authorities,
+ * but can use multiple authorities for bootstrap */
+ memset(options, 0, sizeof(or_options_t));
+ options->FetchDirInfoEarly = 1;
+ tt_assert(server_mode(options) == 0);
+ tt_assert(public_server_mode(options) == 0);
+ tt_assert(directory_fetches_from_authorities(options) == 1);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 1);
+
+ /* OR servers only fetch the consensus from the authorities when they don't
+ * know their own address, but never use multiple directories for bootstrap
+ */
+ memset(options, 0, sizeof(or_options_t));
+ options->ORPort_set = 1;
+
+ mock_router_pick_published_address_result = -1;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 1);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ mock_router_pick_published_address_result = 0;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ /* Exit OR servers only fetch the consensus from the authorities when they
+ * refuse unknown exits, but never use multiple directories for bootstrap
+ */
+ memset(options, 0, sizeof(or_options_t));
+ options->ORPort_set = 1;
+ options->ExitRelay = 1;
+ mock_router_pick_published_address_result = 0;
+ mock_router_my_exit_policy_is_reject_star_result = 0;
+ mock_advertised_server_mode_result = 1;
+ mock_router_get_my_routerinfo_result = &routerinfo;
+
+ routerinfo.supports_tunnelled_dir_requests = 1;
+
+ options->RefuseUnknownExits = 1;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 1);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ options->RefuseUnknownExits = 0;
+ mock_router_pick_published_address_result = 0;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ /* Dir servers fetch the consensus from the authorities, unless they are not
+ * advertising themselves (hibernating) or have no routerinfo or are not
+ * advertising their dirport, and never use multiple directories for
+ * bootstrap. This only applies if they are also OR servers.
+ * (We don't care much about the behaviour of non-OR directory servers.) */
+ memset(options, 0, sizeof(or_options_t));
+ options->DirPort_set = 1;
+ options->ORPort_set = 1;
+ options->DirCache = 1;
+ mock_router_pick_published_address_result = 0;
+ mock_router_my_exit_policy_is_reject_star_result = 1;
+
+ mock_advertised_server_mode_result = 1;
+ routerinfo.dir_port = 1;
+ mock_router_get_my_routerinfo_result = &routerinfo;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 1);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ mock_advertised_server_mode_result = 0;
+ routerinfo.dir_port = 1;
+ mock_router_get_my_routerinfo_result = &routerinfo;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ mock_advertised_server_mode_result = 1;
+ mock_router_get_my_routerinfo_result = NULL;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ mock_advertised_server_mode_result = 1;
+ routerinfo.dir_port = 0;
+ routerinfo.supports_tunnelled_dir_requests = 0;
+ mock_router_get_my_routerinfo_result = &routerinfo;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 0);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ mock_advertised_server_mode_result = 1;
+ routerinfo.dir_port = 1;
+ routerinfo.supports_tunnelled_dir_requests = 1;
+ mock_router_get_my_routerinfo_result = &routerinfo;
+ tt_assert(server_mode(options) == 1);
+ tt_assert(public_server_mode(options) == 1);
+ tt_assert(directory_fetches_from_authorities(options) == 1);
+ tt_assert(networkstatus_consensus_can_use_multiple_directories(options)
+ == 0);
+
+ done:
+ tor_free(options);
+ UNMOCK(router_pick_published_address);
+ UNMOCK(router_get_my_routerinfo);
+ UNMOCK(advertised_server_mode);
+ UNMOCK(router_my_exit_policy_is_reject_star);
+}
+
+static void
+test_config_default_fallback_dirs(void *arg)
+{
+ const char *fallback[] = {
+#include "../or/fallback_dirs.inc"
+ NULL
+ };
+
+ int n_included_fallback_dirs = 0;
+ int n_added_fallback_dirs = 0;
+
+ (void)arg;
+ clear_dir_servers();
+
+ while (fallback[n_included_fallback_dirs])
+ n_included_fallback_dirs++;
+
+ add_default_fallback_dir_servers();
+
+ n_added_fallback_dirs = smartlist_len(router_get_fallback_dir_servers());
+
+ tt_assert(n_included_fallback_dirs == n_added_fallback_dirs);
+
+ done:
+ clear_dir_servers();
+}
+
+static config_line_t *
+mock_config_line(const char *key, const char *val)
+{
+ config_line_t *config_line = tor_malloc(sizeof(config_line_t));
+ memset(config_line, 0, sizeof(config_line_t));
+ config_line->key = tor_strdup(key);
+ config_line->value = tor_strdup(val);
+ return config_line;
+}
+
+static void
+test_config_parse_port_config__listenaddress(void *data)
+{
+ (void)data;
+ int ret;
+ config_line_t *config_listen_address = NULL, *config_listen_address2 = NULL,
+ *config_listen_address3 = NULL;
+ config_line_t *config_port1 = NULL, *config_port2 = NULL,
+ *config_port3 = NULL, *config_port4 = NULL, *config_port5 = NULL;
+ smartlist_t *slout = NULL;
+ port_cfg_t *port_cfg = NULL;
+
+ // Test basic invocation with no arguments
+ ret = parse_port_config(NULL, NULL, NULL, NULL, 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Setup some test data
+ config_listen_address = mock_config_line("DNSListenAddress", "127.0.0.1");
+ config_listen_address2 = mock_config_line("DNSListenAddress", "x$$$:::345");
+ config_listen_address3 = mock_config_line("DNSListenAddress",
+ "127.0.0.1:1442");
+ config_port1 = mock_config_line("DNSPort", "42");
+ config_port2 = mock_config_line("DNSPort", "43");
+ config_port1->next = config_port2;
+ config_port3 = mock_config_line("DNSPort", "auto");
+ config_port4 = mock_config_line("DNSPort", "55542");
+ config_port5 = mock_config_line("DNSPort", "666777");
+
+ // Test failure when we have a ListenAddress line and several
+ // Port lines for the same portname
+ ret = parse_port_config(NULL, config_port1, config_listen_address, "DNS", 0,
+ NULL, 0, 0);
+
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test case when we have a listen address, no default port and allow
+ // spurious listen address lines
+ ret = parse_port_config(NULL, NULL, config_listen_address, "DNS", 0, NULL,
+ 0, CL_PORT_ALLOW_EXTRA_LISTENADDR);
+ tt_int_op(ret, OP_EQ, 1);
+
+ // Test case when we have a listen address, no default port but doesn't
+ // allow spurious listen address lines
+ ret = parse_port_config(NULL, NULL, config_listen_address, "DNS", 0, NULL,
+ 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test case when we have a listen address, and a port that points to auto,
+ // should use the AUTO port
+ slout = smartlist_new();
+ ret = parse_port_config(slout, config_port3, config_listen_address, "DNS",
+ 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, CFG_AUTO_PORT);
+
+ // Test when we have a listen address and a custom port
+ ret = parse_port_config(slout, config_port4, config_listen_address, "DNS",
+ 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 2);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 1);
+ tt_int_op(port_cfg->port, OP_EQ, 55542);
+
+ // Test when we have a listen address and an invalid custom port
+ ret = parse_port_config(slout, config_port5, config_listen_address, "DNS",
+ 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test we get a server port configuration when asked for it
+ ret = parse_port_config(slout, NULL, config_listen_address, "DNS", 0, NULL,
+ 123, CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 4);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 2);
+ tt_int_op(port_cfg->port, OP_EQ, 123);
+ tt_int_op(port_cfg->server_cfg.no_listen, OP_EQ, 1);
+ tt_int_op(port_cfg->server_cfg.bind_ipv4_only, OP_EQ, 1);
+
+ // Test an invalid ListenAddress configuration
+ ret = parse_port_config(NULL, NULL, config_listen_address2, "DNS", 0, NULL,
+ 222, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test default to the port in the listen address if available
+ ret = parse_port_config(slout, config_port2, config_listen_address3, "DNS",
+ 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 5);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 4);
+ tt_int_op(port_cfg->port, OP_EQ, 1442);
+
+ // Test we work correctly without an out, but with a listen address
+ // and a port
+ ret = parse_port_config(NULL, config_port2, config_listen_address, "DNS",
+ 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test warning nonlocal control
+ ret = parse_port_config(slout, config_port2, config_listen_address, "DNS",
+ CONN_TYPE_CONTROL_LISTENER, NULL, 0,
+ CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test warning nonlocal ext or listener
+ ret = parse_port_config(slout, config_port2, config_listen_address, "DNS",
+ CONN_TYPE_EXT_OR_LISTENER, NULL, 0,
+ CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test warning nonlocal other
+ ret = parse_port_config(slout, config_port2, config_listen_address, "DNS",
+ 0, NULL, 0, CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test warning nonlocal control without an out
+ ret = parse_port_config(NULL, config_port2, config_listen_address, "DNS",
+ CONN_TYPE_CONTROL_LISTENER, NULL, 0,
+ CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ config_free_lines(config_listen_address);
+ config_free_lines(config_listen_address2);
+ config_free_lines(config_listen_address3);
+ config_free_lines(config_port1);
+ /* 2 was linked from 1. */
+ config_free_lines(config_port3);
+ config_free_lines(config_port4);
+ config_free_lines(config_port5);
+ if (slout)
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_free(slout);
+}
+
+static void
+test_config_parse_port_config__ports__no_ports_given(void *data)
+{
+ (void)data;
+ int ret;
+ smartlist_t *slout = NULL;
+ port_cfg_t *port_cfg = NULL;
+
+ slout = smartlist_new();
+
+ // Test no defaultport, no defaultaddress and no out
+ ret = parse_port_config(NULL, NULL, NULL, "DNS", 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test with defaultport, no defaultaddress and no out
+ ret = parse_port_config(NULL, NULL, NULL, "DNS", 0, NULL, 42, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test no defaultport, with defaultaddress and no out
+ ret = parse_port_config(NULL, NULL, NULL, "DNS", 0, "127.0.0.2", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test with defaultport, with defaultaddress and no out
+ ret = parse_port_config(NULL, NULL, NULL, "DNS", 0, "127.0.0.2", 42, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test no defaultport, no defaultaddress and with out
+ ret = parse_port_config(slout, NULL, NULL, "DNS", 0, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 0);
+
+ // Test with defaultport, no defaultaddress and with out
+ ret = parse_port_config(slout, NULL, NULL, "DNS", 0, NULL, 42, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 0);
+
+ // Test no defaultport, with defaultaddress and with out
+ ret = parse_port_config(slout, NULL, NULL, "DNS", 0, "127.0.0.2", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 0);
+
+ // Test with defaultport, with defaultaddress and out, adds a new port cfg
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, NULL, NULL, "DNS", 0, "127.0.0.2", 42, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, 42);
+ tt_int_op(port_cfg->is_unix_addr, OP_EQ, 0);
+
+ // Test with defaultport, with defaultaddress and out, adds a new port cfg
+ // for a unix address
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, NULL, NULL, "DNS", 0, "/foo/bar/unixdomain",
+ 42, CL_PORT_IS_UNIXSOCKET);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, 0);
+ tt_int_op(port_cfg->is_unix_addr, OP_EQ, 1);
+ tt_str_op(port_cfg->unix_addr, OP_EQ, "/foo/bar/unixdomain");
+
+ done:
+ if (slout)
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_free(slout);
+}
+
+static void
+test_config_parse_port_config__ports__ports_given(void *data)
+{
+ (void)data;
+ int ret;
+ smartlist_t *slout = NULL;
+ port_cfg_t *port_cfg = NULL;
+ config_line_t *config_port_invalid = NULL, *config_port_valid = NULL;
+ tor_addr_t addr;
+
+ slout = smartlist_new();
+
+ // Test error when encounters an invalid Port specification
+ config_port_invalid = mock_config_line("DNSPort", "");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test error when encounters an empty unix domain specification
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort", "unix:");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test error when encounters a unix domain specification but the listener
+ // doesnt support domain sockets
+ config_port_valid = mock_config_line("DNSPort", "unix:/tmp/foo/bar");
+ ret = parse_port_config(NULL, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_DNS_LISTENER, NULL, 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test valid unix domain
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, NULL, 0, 0);
+#ifdef _WIN32
+ tt_int_op(ret, OP_EQ, -1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, 0);
+ tt_int_op(port_cfg->is_unix_addr, OP_EQ, 1);
+ tt_str_op(port_cfg->unix_addr, OP_EQ, "/tmp/foo/bar");
+#endif
+
+ // Test failure if we have no ipv4 and no ipv6 (for unix domain sockets,
+ // this makes no sense - it should be fixed)
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort",
+ "unix:/tmp/foo/bar NoIPv4Traffic");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, NULL, 0,
+ CL_PORT_TAKES_HOSTNAMES);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with no ipv4 but take ipv6 (for unix domain sockets, this
+ // makes no sense - it should be fixed)
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "unix:/tmp/foo/bar "
+ "NoIPv4Traffic IPv6Traffic");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, NULL, 0,
+ CL_PORT_TAKES_HOSTNAMES);
+#ifdef _WIN32
+ tt_int_op(ret, OP_EQ, -1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.ipv4_traffic, OP_EQ, 0);
+ tt_int_op(port_cfg->entry_cfg.ipv6_traffic, OP_EQ, 1);
+#endif
+
+ // Test success with both ipv4 and ipv6 (for unix domain sockets,
+ // this makes no sense - it should be fixed)
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "unix:/tmp/foo/bar "
+ "IPv4Traffic IPv6Traffic");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, NULL, 0,
+ CL_PORT_TAKES_HOSTNAMES);
+#ifdef _WIN32
+ tt_int_op(ret, OP_EQ, -1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.ipv4_traffic, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.ipv6_traffic, OP_EQ, 1);
+#endif
+
+ // Test failure if we specify world writable for an IP Port
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort", "42 WorldWritable");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test failure if we specify group writable for an IP Port
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort", "42 GroupWritable");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test failure if we specify group writable for an IP Port
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort", "42 RelaxDirModeCheck");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with only a port (this will fail without a default address)
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ config_port_valid = mock_config_line("DNSPort", "42");
+ ret = parse_port_config(NULL, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with only a port and isolate destination port
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IsolateDestPort");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT | ISO_DESTPORT);
+
+ // Test success with a negative isolate destination port, and plural
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 NoIsolateDestPorts");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT & ~ISO_DESTPORT);
+
+ // Test success with isolate destination address
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IsolateDestAddr");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT | ISO_DESTADDR);
+
+ // Test success with isolate socks AUTH
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IsolateSOCKSAuth");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT | ISO_SOCKSAUTH);
+
+ // Test success with isolate client protocol
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IsolateClientProtocol");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT | ISO_CLIENTPROTO);
+
+ // Test success with isolate client address
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IsolateClientAddr");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.isolation_flags, OP_EQ,
+ ISO_DEFAULT | ISO_CLIENTADDR);
+
+ // Test success with ignored unknown options
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ config_port_valid = mock_config_line("DNSPort", "42 ThisOptionDoesntExist");
+ ret = parse_port_config(NULL, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with no isolate socks AUTH
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 NoIsolateSOCKSAuth");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.3", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.socks_prefer_no_auth, OP_EQ, 1);
+
+ // Test success with prefer ipv6
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IPv6Traffic PreferIPv6");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, "127.0.0.42", 0,
+ CL_PORT_TAKES_HOSTNAMES);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.prefer_ipv6, OP_EQ, 1);
+
+ // Test success with cache ipv4 DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 CacheIPv4DNS");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv4_answers, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv6_answers, OP_EQ, 0);
+
+ // Test success with cache ipv6 DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 CacheIPv6DNS");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv4_answers, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv6_answers, OP_EQ, 1);
+
+ // Test success with no cache ipv4 DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 NoCacheIPv4DNS");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv4_answers, OP_EQ, 0);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv6_answers, OP_EQ, 0);
+
+ // Test success with cache DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 CacheDNS");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, CL_PORT_TAKES_HOSTNAMES);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv4_answers, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.cache_ipv6_answers, OP_EQ, 1);
+
+ // Test success with use cached ipv4 DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 UseIPv4Cache");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv4_answers, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv6_answers, OP_EQ, 0);
+
+ // Test success with use cached ipv6 DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 UseIPv6Cache");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv4_answers, OP_EQ, 0);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv6_answers, OP_EQ, 1);
+
+ // Test success with use cached DNS
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 UseDNSCache");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv4_answers, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.use_cached_ipv6_answers, OP_EQ, 1);
+
+ // Test success with not preferring ipv6 automap
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 NoPreferIPv6Automap");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.prefer_ipv6_virtaddr, OP_EQ, 0);
+
+ // Test success with prefer SOCKS no auth
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 PreferSOCKSNoAuth");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.socks_prefer_no_auth, OP_EQ, 1);
+
+ // Test failure with both a zero port and a non-zero port
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "0");
+ config_port_valid = mock_config_line("DNSPort", "42");
+ config_port_invalid->next = config_port_valid;
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.42", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with warn non-local control
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_CONTROL_LISTENER, "127.0.0.42", 0,
+ CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with warn non-local listener
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_EXT_OR_LISTENER, "127.0.0.42", 0,
+ CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with warn non-local other
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with warn non-local other without out
+ ret = parse_port_config(NULL, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.42", 0, CL_PORT_WARN_NONLOCAL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test success with both ipv4 and ipv6 but without stream options
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 IPv4Traffic "
+ "IPv6Traffic");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.44", 0,
+ CL_PORT_TAKES_HOSTNAMES |
+ CL_PORT_NO_STREAM_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.ipv4_traffic, OP_EQ, 1);
+ tt_int_op(port_cfg->entry_cfg.ipv6_traffic, OP_EQ, 0);
+
+ // Test failure for a SessionGroup argument with invalid value
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "42 SessionGroup=invalid");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.44", 0, CL_PORT_NO_STREAM_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // TODO: this seems wrong. Shouldn't it be the other way around?
+ // Potential bug.
+ // Test failure for a SessionGroup argument with valid value but with stream
+ // options allowed
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "42 SessionGroup=123");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.44", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test failure for more than one SessionGroup argument
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "42 SessionGroup=123 "
+ "SessionGroup=321");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.44", 0, CL_PORT_NO_STREAM_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with a sessiongroup options
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "42 SessionGroup=1111122");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.44", 0, CL_PORT_NO_STREAM_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->entry_cfg.session_group, OP_EQ, 1111122);
+
+ // Test success with a zero unix domain socket, and doesnt add it to out
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "0");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.45", 0, CL_PORT_IS_UNIXSOCKET);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 0);
+
+ // Test success with a one unix domain socket, and doesnt add it to out
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "something");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.45", 0, CL_PORT_IS_UNIXSOCKET);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->is_unix_addr, OP_EQ, 1);
+ tt_str_op(port_cfg->unix_addr, OP_EQ, "something");
+
+ // Test success with a port of auto - it uses the default address
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "auto");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, CFG_AUTO_PORT);
+ tor_addr_parse(&addr, "127.0.0.46");
+ tt_assert(tor_addr_eq(&port_cfg->addr, &addr))
+
+ // Test success with parsing both an address and an auto port
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "127.0.0.122:auto");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, CFG_AUTO_PORT);
+ tor_addr_parse(&addr, "127.0.0.122");
+ tt_assert(tor_addr_eq(&port_cfg->addr, &addr))
+
+ // Test failure when asked to parse an invalid address followed by auto
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_port_invalid = mock_config_line("DNSPort", "invalidstuff!!:auto");
+ ret = parse_port_config(NULL, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with parsing both an address and a real port
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "127.0.0.123:656");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->port, OP_EQ, 656);
+ tor_addr_parse(&addr, "127.0.0.123");
+ tt_assert(tor_addr_eq(&port_cfg->addr, &addr))
+
+ // Test failure if we can't parse anything at all
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "something wrong");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test failure if we find both an address, a port and an auto
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "127.0.1.0:123:auto");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0,
+ "127.0.0.46", 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test that default to group writeable default sets group writeable for
+ // domain socket
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "unix:/tmp/somewhere");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS",
+ CONN_TYPE_AP_LISTENER, "127.0.0.46", 0,
+ CL_PORT_DFLT_GROUP_WRITABLE);
+#ifdef _WIN32
+ tt_int_op(ret, OP_EQ, -1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->is_group_writable, OP_EQ, 1);
+#endif
+
+ done:
+ if (slout)
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_free(slout);
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+}
+
+static void
+test_config_parse_port_config__ports__server_options(void *data)
+{
+ (void)data;
+ int ret;
+ smartlist_t *slout = NULL;
+ port_cfg_t *port_cfg = NULL;
+ config_line_t *config_port_invalid = NULL, *config_port_valid = NULL;
+
+ slout = smartlist_new();
+
+ // Test success with NoAdvertise option
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ config_port_valid = mock_config_line("DNSPort",
+ "127.0.0.124:656 NoAdvertise");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0, NULL, 0,
+ CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->server_cfg.no_advertise, OP_EQ, 1);
+ tt_int_op(port_cfg->server_cfg.no_listen, OP_EQ, 0);
+
+ // Test success with NoListen option
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "127.0.0.124:656 NoListen");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0, NULL, 0,
+ CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->server_cfg.no_advertise, OP_EQ, 0);
+ tt_int_op(port_cfg->server_cfg.no_listen, OP_EQ, 1);
+
+ // Test failure with both NoAdvertise and NoListen option
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "127.0.0.124:656 NoListen "
+ "NoAdvertise");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with IPv4Only
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "127.0.0.124:656 IPv4Only");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0, NULL, 0,
+ CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->server_cfg.bind_ipv4_only, OP_EQ, 1);
+ tt_int_op(port_cfg->server_cfg.bind_ipv6_only, OP_EQ, 0);
+
+ // Test success with IPv6Only
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "[::1]:656 IPv6Only");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0, NULL, 0,
+ CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+ port_cfg = (port_cfg_t *)smartlist_get(slout, 0);
+ tt_int_op(port_cfg->server_cfg.bind_ipv4_only, OP_EQ, 0);
+ tt_int_op(port_cfg->server_cfg.bind_ipv6_only, OP_EQ, 1);
+
+ // Test failure with both IPv4Only and IPv6Only
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "127.0.0.124:656 IPv6Only "
+ "IPv4Only");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test success with invalid parameter
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_valid = mock_config_line("DNSPort", "127.0.0.124:656 unknown");
+ ret = parse_port_config(slout, config_port_valid, NULL, "DNS", 0, NULL, 0,
+ CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(smartlist_len(slout), OP_EQ, 1);
+
+ // Test failure when asked to bind only to ipv6 but gets an ipv4 address
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort",
+ "127.0.0.124:656 IPv6Only");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test failure when asked to bind only to ipv4 but gets an ipv6 address
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_clear(slout);
+ config_port_invalid = mock_config_line("DNSPort", "[::1]:656 IPv4Only");
+ ret = parse_port_config(slout, config_port_invalid, NULL, "DNS", 0, NULL,
+ 0, CL_PORT_SERVER_OPTIONS);
+ tt_int_op(ret, OP_EQ, -1);
+
+ done:
+ if (slout)
+ SMARTLIST_FOREACH(slout,port_cfg_t *,pf,port_cfg_free(pf));
+ smartlist_free(slout);
+ config_free_lines(config_port_invalid); config_port_invalid = NULL;
+ config_free_lines(config_port_valid); config_port_valid = NULL;
+}
+
#define CONFIG_TEST(name, flags) \
{ #name, test_config_ ## name, flags, NULL, NULL }
struct testcase_t config_tests[] = {
+ CONFIG_TEST(adding_trusted_dir_server, TT_FORK),
+ CONFIG_TEST(adding_fallback_dir_server, TT_FORK),
+ CONFIG_TEST(parsing_trusted_dir_server, 0),
+ CONFIG_TEST(parsing_fallback_dir_server, 0),
+ CONFIG_TEST(adding_default_trusted_dir_servers, TT_FORK),
+ CONFIG_TEST(adding_dir_servers, TT_FORK),
+ CONFIG_TEST(default_dir_servers, TT_FORK),
+ CONFIG_TEST(default_fallback_dirs, 0),
+ CONFIG_TEST(resolve_my_address, TT_FORK),
CONFIG_TEST(addressmap, 0),
CONFIG_TEST(parse_bridge_line, 0),
CONFIG_TEST(parse_transport_options_line, 0),
+ CONFIG_TEST(parse_transport_plugin_line, TT_FORK),
CONFIG_TEST(check_or_create_data_subdir, TT_FORK),
CONFIG_TEST(write_to_data_subdir, TT_FORK),
CONFIG_TEST(fix_my_family, 0),
+ CONFIG_TEST(directory_fetch, 0),
+ CONFIG_TEST(parse_port_config__listenaddress, 0),
+ CONFIG_TEST(parse_port_config__ports__no_ports_given, 0),
+ CONFIG_TEST(parse_port_config__ports__server_options, 0),
+ CONFIG_TEST(parse_port_config__ports__ports_given, 0),
END_OF_TESTCASES
};
diff --git a/src/test/test_connection.c b/src/test/test_connection.c
new file mode 100644
index 0000000000..bf95b0b59f
--- /dev/null
+++ b/src/test/test_connection.c
@@ -0,0 +1,858 @@
+/* Copyright (c) 2015-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+
+#define CONNECTION_PRIVATE
+#define MAIN_PRIVATE
+
+#include "or.h"
+#include "test.h"
+
+#include "connection.h"
+#include "main.h"
+#include "microdesc.h"
+#include "networkstatus.h"
+#include "rendcache.h"
+#include "directory.h"
+
+static void test_conn_lookup_addr_helper(const char *address,
+ int family,
+ tor_addr_t *addr);
+
+static void * test_conn_get_basic_setup(const struct testcase_t *tc);
+static int test_conn_get_basic_teardown(const struct testcase_t *tc,
+ void *arg);
+
+static void * test_conn_get_rend_setup(const struct testcase_t *tc);
+static int test_conn_get_rend_teardown(const struct testcase_t *tc,
+ void *arg);
+
+static void * test_conn_get_rsrc_setup(const struct testcase_t *tc);
+static int test_conn_get_rsrc_teardown(const struct testcase_t *tc,
+ void *arg);
+
+/* Arbitrary choice - IPv4 Directory Connection to localhost */
+#define TEST_CONN_TYPE (CONN_TYPE_DIR)
+/* We assume every machine has IPv4 localhost, is that ok? */
+#define TEST_CONN_ADDRESS "127.0.0.1"
+#define TEST_CONN_PORT (12345)
+#define TEST_CONN_ADDRESS_PORT "127.0.0.1:12345"
+#define TEST_CONN_FAMILY (AF_INET)
+#define TEST_CONN_STATE (DIR_CONN_STATE_MIN_)
+#define TEST_CONN_ADDRESS_2 "127.0.0.2"
+
+#define TEST_CONN_BASIC_PURPOSE (DIR_PURPOSE_MIN_)
+
+#define TEST_CONN_REND_ADDR "cfs3rltphxxvabci"
+#define TEST_CONN_REND_PURPOSE (DIR_PURPOSE_FETCH_RENDDESC_V2)
+#define TEST_CONN_REND_PURPOSE_SUCCESSFUL (DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2)
+#define TEST_CONN_REND_TYPE_2 (CONN_TYPE_AP)
+#define TEST_CONN_REND_ADDR_2 "icbavxxhptlr3sfc"
+
+#define TEST_CONN_RSRC (networkstatus_get_flavor_name(FLAV_MICRODESC))
+#define TEST_CONN_RSRC_PURPOSE (DIR_PURPOSE_FETCH_CONSENSUS)
+#define TEST_CONN_RSRC_STATE_SUCCESSFUL (DIR_CONN_STATE_CLIENT_FINISHED)
+#define TEST_CONN_RSRC_2 (networkstatus_get_flavor_name(FLAV_NS))
+
+#define TEST_CONN_DL_STATE (DIR_CONN_STATE_CLIENT_READING)
+
+/* see AP_CONN_STATE_IS_UNATTACHED() */
+#define TEST_CONN_UNATTACHED_STATE (AP_CONN_STATE_CIRCUIT_WAIT)
+#define TEST_CONN_ATTACHED_STATE (AP_CONN_STATE_CONNECT_WAIT)
+
+#define TEST_CONN_FD_INIT 50
+static int mock_connection_connect_sockaddr_called = 0;
+static int fake_socket_number = TEST_CONN_FD_INIT;
+
+static int
+mock_connection_connect_sockaddr(connection_t *conn,
+ const struct sockaddr *sa,
+ socklen_t sa_len,
+ const struct sockaddr *bindaddr,
+ socklen_t bindaddr_len,
+ int *socket_error)
+{
+ (void)sa_len;
+ (void)bindaddr;
+ (void)bindaddr_len;
+
+ tor_assert(conn);
+ tor_assert(sa);
+ tor_assert(socket_error);
+
+ mock_connection_connect_sockaddr_called++;
+
+ conn->s = fake_socket_number++;
+ tt_assert(SOCKET_OK(conn->s));
+ /* We really should call tor_libevent_initialize() here. Because we don't,
+ * we are relying on other parts of the code not checking if the_event_base
+ * (and therefore event->ev_base) is NULL. */
+ tt_assert(connection_add_connecting(conn) == 0);
+
+ done:
+ /* Fake "connected" status */
+ return 1;
+}
+
+static void
+test_conn_lookup_addr_helper(const char *address, int family, tor_addr_t *addr)
+{
+ int rv = 0;
+
+ tt_assert(addr);
+
+ rv = tor_addr_lookup(address, family, addr);
+ /* XXXX - should we retry on transient failure? */
+ tt_assert(rv == 0);
+ tt_assert(tor_addr_is_loopback(addr));
+ tt_assert(tor_addr_is_v4(addr));
+
+ return;
+
+ done:
+ tor_addr_make_null(addr, TEST_CONN_FAMILY);
+}
+
+static connection_t *
+test_conn_get_connection(uint8_t state, uint8_t type, uint8_t purpose)
+{
+ connection_t *conn = NULL;
+ tor_addr_t addr;
+ int socket_err = 0;
+ int in_progress = 0;
+
+ MOCK(connection_connect_sockaddr,
+ mock_connection_connect_sockaddr);
+
+ init_connection_lists();
+
+ conn = connection_new(type, TEST_CONN_FAMILY);
+ tt_assert(conn);
+
+ test_conn_lookup_addr_helper(TEST_CONN_ADDRESS, TEST_CONN_FAMILY, &addr);
+ tt_assert(!tor_addr_is_null(&addr));
+
+ tor_addr_copy_tight(&conn->addr, &addr);
+ conn->port = TEST_CONN_PORT;
+ mock_connection_connect_sockaddr_called = 0;
+ in_progress = connection_connect(conn, TEST_CONN_ADDRESS_PORT, &addr,
+ TEST_CONN_PORT, &socket_err);
+ tt_assert(mock_connection_connect_sockaddr_called == 1);
+ tt_assert(!socket_err);
+ tt_assert(in_progress == 0 || in_progress == 1);
+
+ /* fake some of the attributes so the connection looks OK */
+ conn->state = state;
+ conn->purpose = purpose;
+ assert_connection_ok(conn, time(NULL));
+
+ UNMOCK(connection_connect_sockaddr);
+
+ return conn;
+
+ /* On failure */
+ done:
+ UNMOCK(connection_connect_sockaddr);
+ return NULL;
+}
+
+static void *
+test_conn_get_basic_setup(const struct testcase_t *tc)
+{
+ (void)tc;
+ return test_conn_get_connection(TEST_CONN_STATE, TEST_CONN_TYPE,
+ TEST_CONN_BASIC_PURPOSE);
+}
+
+static int
+test_conn_get_basic_teardown(const struct testcase_t *tc, void *arg)
+{
+ (void)tc;
+ connection_t *conn = arg;
+
+ tt_assert(conn);
+ assert_connection_ok(conn, time(NULL));
+
+ /* teardown the connection as fast as possible */
+ if (conn->linked_conn) {
+ assert_connection_ok(conn->linked_conn, time(NULL));
+
+ /* We didn't call tor_libevent_initialize(), so event_base was NULL,
+ * so we can't rely on connection_unregister_events() use of event_del().
+ */
+ if (conn->linked_conn->read_event) {
+ tor_free(conn->linked_conn->read_event);
+ conn->linked_conn->read_event = NULL;
+ }
+ if (conn->linked_conn->write_event) {
+ tor_free(conn->linked_conn->write_event);
+ conn->linked_conn->write_event = NULL;
+ }
+
+ if (!conn->linked_conn->marked_for_close) {
+ connection_close_immediate(conn->linked_conn);
+ connection_mark_for_close(conn->linked_conn);
+ }
+
+ close_closeable_connections();
+ }
+
+ /* We didn't set the events up properly, so we can't use event_del() in
+ * close_closeable_connections() > connection_free()
+ * > connection_unregister_events() */
+ if (conn->read_event) {
+ tor_free(conn->read_event);
+ conn->read_event = NULL;
+ }
+ if (conn->write_event) {
+ tor_free(conn->write_event);
+ conn->write_event = NULL;
+ }
+
+ if (!conn->marked_for_close) {
+ connection_close_immediate(conn);
+ connection_mark_for_close(conn);
+ }
+
+ close_closeable_connections();
+
+ /* The unit test will fail if we return 0 */
+ return 1;
+
+ /* When conn == NULL, we can't cleanup anything */
+ done:
+ return 0;
+}
+
+static void *
+test_conn_get_rend_setup(const struct testcase_t *tc)
+{
+ dir_connection_t *conn = DOWNCAST(dir_connection_t,
+ test_conn_get_connection(
+ TEST_CONN_STATE,
+ TEST_CONN_TYPE,
+ TEST_CONN_REND_PURPOSE));
+ tt_assert(conn);
+ assert_connection_ok(&conn->base_, time(NULL));
+
+ rend_cache_init();
+
+ /* TODO: use directory_initiate_command_rend() to do this - maybe? */
+ conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
+ tor_assert(strlen(TEST_CONN_REND_ADDR) == REND_SERVICE_ID_LEN_BASE32);
+ memcpy(conn->rend_data->onion_address,
+ TEST_CONN_REND_ADDR,
+ REND_SERVICE_ID_LEN_BASE32+1);
+ conn->rend_data->hsdirs_fp = smartlist_new();
+
+ assert_connection_ok(&conn->base_, time(NULL));
+ return conn;
+
+ /* On failure */
+ done:
+ test_conn_get_rend_teardown(tc, conn);
+ /* Returning NULL causes the unit test to fail */
+ return NULL;
+}
+
+static int
+test_conn_get_rend_teardown(const struct testcase_t *tc, void *arg)
+{
+ dir_connection_t *conn = DOWNCAST(dir_connection_t, arg);
+ int rv = 0;
+
+ tt_assert(conn);
+ assert_connection_ok(&conn->base_, time(NULL));
+
+ /* avoid a last-ditch attempt to refetch the descriptor */
+ conn->base_.purpose = TEST_CONN_REND_PURPOSE_SUCCESSFUL;
+
+ /* connection_free_() cleans up rend_data */
+ rv = test_conn_get_basic_teardown(tc, arg);
+ done:
+ rend_cache_free_all();
+ return rv;
+}
+
+static dir_connection_t *
+test_conn_download_status_add_a_connection(const char *resource)
+{
+ dir_connection_t *conn = DOWNCAST(dir_connection_t,
+ test_conn_get_connection(
+ TEST_CONN_STATE,
+ TEST_CONN_TYPE,
+ TEST_CONN_RSRC_PURPOSE));
+
+ tt_assert(conn);
+ assert_connection_ok(&conn->base_, time(NULL));
+
+ /* Replace the existing resource with the one we want */
+ if (resource) {
+ if (conn->requested_resource) {
+ tor_free(conn->requested_resource);
+ }
+ conn->requested_resource = tor_strdup(resource);
+ assert_connection_ok(&conn->base_, time(NULL));
+ }
+
+ return conn;
+
+ done:
+ test_conn_get_rsrc_teardown(NULL, conn);
+ return NULL;
+}
+
+static void *
+test_conn_get_rsrc_setup(const struct testcase_t *tc)
+{
+ (void)tc;
+ return test_conn_download_status_add_a_connection(TEST_CONN_RSRC);
+}
+
+static int
+test_conn_get_rsrc_teardown(const struct testcase_t *tc, void *arg)
+{
+ int rv = 0;
+
+ connection_t *conn = (connection_t *)arg;
+ tt_assert(conn);
+ assert_connection_ok(conn, time(NULL));
+
+ if (conn->type == CONN_TYPE_DIR) {
+ dir_connection_t *dir_conn = DOWNCAST(dir_connection_t, arg);
+
+ tt_assert(dir_conn);
+ assert_connection_ok(&dir_conn->base_, time(NULL));
+
+ /* avoid a last-ditch attempt to refetch the consensus */
+ dir_conn->base_.state = TEST_CONN_RSRC_STATE_SUCCESSFUL;
+ assert_connection_ok(&dir_conn->base_, time(NULL));
+ }
+
+ /* connection_free_() cleans up requested_resource */
+ rv = test_conn_get_basic_teardown(tc, conn);
+
+ done:
+ return rv;
+}
+
+static void *
+test_conn_download_status_setup(const struct testcase_t *tc)
+{
+ (void)tc;
+
+ /* Don't return NULL, that causes the test to fail */
+ return (void*)"ok";
+}
+
+static int
+test_conn_download_status_teardown(const struct testcase_t *tc, void *arg)
+{
+ (void)arg;
+ int rv = 0;
+
+ /* Ignore arg, and just loop through the connection array */
+ SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
+ if (conn) {
+ assert_connection_ok(conn, time(NULL));
+
+ /* connection_free_() cleans up requested_resource */
+ rv = test_conn_get_rsrc_teardown(tc, conn);
+ tt_assert(rv == 1);
+ }
+ } SMARTLIST_FOREACH_END(conn);
+
+ done:
+ return rv;
+}
+
+/* Like connection_ap_make_link(), but does much less */
+static connection_t *
+test_conn_get_linked_connection(connection_t *l_conn, uint8_t state)
+{
+ tt_assert(l_conn);
+ assert_connection_ok(l_conn, time(NULL));
+
+ /* AP connections don't seem to have purposes */
+ connection_t *conn = test_conn_get_connection(state, CONN_TYPE_AP,
+ 0);
+
+ tt_assert(conn);
+ assert_connection_ok(conn, time(NULL));
+
+ conn->linked = 1;
+ l_conn->linked = 1;
+ conn->linked_conn = l_conn;
+ l_conn->linked_conn = conn;
+ /* we never opened a real socket, so we can just overwrite it */
+ conn->s = TOR_INVALID_SOCKET;
+ l_conn->s = TOR_INVALID_SOCKET;
+
+ assert_connection_ok(conn, time(NULL));
+ assert_connection_ok(l_conn, time(NULL));
+
+ return conn;
+
+ done:
+ test_conn_download_status_teardown(NULL, NULL);
+ return NULL;
+}
+
+static struct testcase_setup_t test_conn_get_basic_st = {
+ test_conn_get_basic_setup, test_conn_get_basic_teardown
+};
+
+static struct testcase_setup_t test_conn_get_rend_st = {
+ test_conn_get_rend_setup, test_conn_get_rend_teardown
+};
+
+static struct testcase_setup_t test_conn_get_rsrc_st = {
+ test_conn_get_rsrc_setup, test_conn_get_rsrc_teardown
+};
+
+static struct testcase_setup_t test_conn_download_status_st = {
+ test_conn_download_status_setup, test_conn_download_status_teardown
+};
+
+static void
+test_conn_get_basic(void *arg)
+{
+ connection_t *conn = (connection_t*)arg;
+ tor_addr_t addr, addr2;
+
+ tt_assert(conn);
+ assert_connection_ok(conn, time(NULL));
+
+ test_conn_lookup_addr_helper(TEST_CONN_ADDRESS, TEST_CONN_FAMILY, &addr);
+ tt_assert(!tor_addr_is_null(&addr));
+ test_conn_lookup_addr_helper(TEST_CONN_ADDRESS_2, TEST_CONN_FAMILY, &addr2);
+ tt_assert(!tor_addr_is_null(&addr2));
+
+ /* Check that we get this connection back when we search for it by
+ * its attributes, but get NULL when we supply a different value. */
+
+ tt_assert(connection_get_by_global_id(conn->global_identifier) == conn);
+ tt_assert(connection_get_by_global_id(!conn->global_identifier) == NULL);
+
+ tt_assert(connection_get_by_type(conn->type) == conn);
+ tt_assert(connection_get_by_type(TEST_CONN_TYPE) == conn);
+ tt_assert(connection_get_by_type(!conn->type) == NULL);
+ tt_assert(connection_get_by_type(!TEST_CONN_TYPE) == NULL);
+
+ tt_assert(connection_get_by_type_state(conn->type, conn->state)
+ == conn);
+ tt_assert(connection_get_by_type_state(TEST_CONN_TYPE, TEST_CONN_STATE)
+ == conn);
+ tt_assert(connection_get_by_type_state(!conn->type, !conn->state)
+ == NULL);
+ tt_assert(connection_get_by_type_state(!TEST_CONN_TYPE, !TEST_CONN_STATE)
+ == NULL);
+
+ /* Match on the connection fields themselves */
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &conn->addr,
+ conn->port,
+ conn->purpose)
+ == conn);
+ /* Match on the original inputs to the connection */
+ tt_assert(connection_get_by_type_addr_port_purpose(TEST_CONN_TYPE,
+ &conn->addr,
+ conn->port,
+ conn->purpose)
+ == conn);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &addr,
+ conn->port,
+ conn->purpose)
+ == conn);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &conn->addr,
+ TEST_CONN_PORT,
+ conn->purpose)
+ == conn);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &conn->addr,
+ conn->port,
+ TEST_CONN_BASIC_PURPOSE)
+ == conn);
+ tt_assert(connection_get_by_type_addr_port_purpose(TEST_CONN_TYPE,
+ &addr,
+ TEST_CONN_PORT,
+ TEST_CONN_BASIC_PURPOSE)
+ == conn);
+ /* Then try each of the not-matching combinations */
+ tt_assert(connection_get_by_type_addr_port_purpose(!conn->type,
+ &conn->addr,
+ conn->port,
+ conn->purpose)
+ == NULL);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &addr2,
+ conn->port,
+ conn->purpose)
+ == NULL);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &conn->addr,
+ !conn->port,
+ conn->purpose)
+ == NULL);
+ tt_assert(connection_get_by_type_addr_port_purpose(conn->type,
+ &conn->addr,
+ conn->port,
+ !conn->purpose)
+ == NULL);
+ /* Then try everything not-matching */
+ tt_assert(connection_get_by_type_addr_port_purpose(!conn->type,
+ &addr2,
+ !conn->port,
+ !conn->purpose)
+ == NULL);
+ tt_assert(connection_get_by_type_addr_port_purpose(!TEST_CONN_TYPE,
+ &addr2,
+ !TEST_CONN_PORT,
+ !TEST_CONN_BASIC_PURPOSE)
+ == NULL);
+
+ done:
+ ;
+}
+
+static void
+test_conn_get_rend(void *arg)
+{
+ dir_connection_t *conn = DOWNCAST(dir_connection_t, arg);
+ tt_assert(conn);
+ assert_connection_ok(&conn->base_, time(NULL));
+
+ tt_assert(connection_get_by_type_state_rendquery(
+ conn->base_.type,
+ conn->base_.state,
+ conn->rend_data->onion_address)
+ == TO_CONN(conn));
+ tt_assert(connection_get_by_type_state_rendquery(
+ TEST_CONN_TYPE,
+ TEST_CONN_STATE,
+ TEST_CONN_REND_ADDR)
+ == TO_CONN(conn));
+ tt_assert(connection_get_by_type_state_rendquery(TEST_CONN_REND_TYPE_2,
+ !conn->base_.state,
+ "")
+ == NULL);
+ tt_assert(connection_get_by_type_state_rendquery(TEST_CONN_REND_TYPE_2,
+ !TEST_CONN_STATE,
+ TEST_CONN_REND_ADDR_2)
+ == NULL);
+
+ done:
+ ;
+}
+
+#define sl_is_conn_assert(sl_input, conn) \
+ do { \
+ the_sl = (sl_input); \
+ tt_assert(smartlist_len((the_sl)) == 1); \
+ tt_assert(smartlist_get((the_sl), 0) == (conn)); \
+ smartlist_free(the_sl); the_sl = NULL; \
+ } while (0)
+
+#define sl_no_conn_assert(sl_input) \
+ do { \
+ the_sl = (sl_input); \
+ tt_assert(smartlist_len((the_sl)) == 0); \
+ smartlist_free(the_sl); the_sl = NULL; \
+ } while (0)
+
+static void
+test_conn_get_rsrc(void *arg)
+{
+ dir_connection_t *conn = DOWNCAST(dir_connection_t, arg);
+ smartlist_t *the_sl = NULL;
+ tt_assert(conn);
+ assert_connection_ok(&conn->base_, time(NULL));
+
+ sl_is_conn_assert(connection_dir_list_by_purpose_and_resource(
+ conn->base_.purpose,
+ conn->requested_resource),
+ conn);
+ sl_is_conn_assert(connection_dir_list_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC),
+ conn);
+ sl_no_conn_assert(connection_dir_list_by_purpose_and_resource(
+ !conn->base_.purpose,
+ ""));
+ sl_no_conn_assert(connection_dir_list_by_purpose_and_resource(
+ !TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC_2));
+
+ sl_is_conn_assert(connection_dir_list_by_purpose_resource_and_state(
+ conn->base_.purpose,
+ conn->requested_resource,
+ conn->base_.state),
+ conn);
+ sl_is_conn_assert(connection_dir_list_by_purpose_resource_and_state(
+ TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC,
+ TEST_CONN_STATE),
+ conn);
+ sl_no_conn_assert(connection_dir_list_by_purpose_resource_and_state(
+ !conn->base_.purpose,
+ "",
+ !conn->base_.state));
+ sl_no_conn_assert(connection_dir_list_by_purpose_resource_and_state(
+ !TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC_2,
+ !TEST_CONN_STATE));
+
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ conn->base_.purpose,
+ conn->requested_resource)
+ == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC)
+ == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ !conn->base_.purpose,
+ "")
+ == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ !TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC_2)
+ == 0);
+
+ tt_assert(connection_dir_count_by_purpose_resource_and_state(
+ conn->base_.purpose,
+ conn->requested_resource,
+ conn->base_.state)
+ == 1);
+ tt_assert(connection_dir_count_by_purpose_resource_and_state(
+ TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC,
+ TEST_CONN_STATE)
+ == 1);
+ tt_assert(connection_dir_count_by_purpose_resource_and_state(
+ !conn->base_.purpose,
+ "",
+ !conn->base_.state)
+ == 0);
+ tt_assert(connection_dir_count_by_purpose_resource_and_state(
+ !TEST_CONN_RSRC_PURPOSE,
+ TEST_CONN_RSRC_2,
+ !TEST_CONN_STATE)
+ == 0);
+
+ done:
+ smartlist_free(the_sl);
+}
+
+static void
+test_conn_download_status(void *arg)
+{
+ dir_connection_t *conn = NULL;
+ dir_connection_t *conn2 = NULL;
+ dir_connection_t *conn4 = NULL;
+ connection_t *ap_conn = NULL;
+
+ consensus_flavor_t usable_flavor = (consensus_flavor_t)arg;
+
+ /* The "other flavor" trick only works if there are two flavors */
+ tor_assert(N_CONSENSUS_FLAVORS == 2);
+ consensus_flavor_t other_flavor = ((usable_flavor == FLAV_NS)
+ ? FLAV_MICRODESC
+ : FLAV_NS);
+ const char *res = networkstatus_get_flavor_name(usable_flavor);
+ const char *other_res = networkstatus_get_flavor_name(other_flavor);
+
+ /* no connections */
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* one connection, not downloading */
+ conn = test_conn_download_status_add_a_connection(res);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* one connection, downloading but not linked (not possible on a client,
+ * but possible on a relay) */
+ conn->base_.state = TEST_CONN_DL_STATE;
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* one connection, downloading and linked, but not yet attached */
+ ap_conn = test_conn_get_linked_connection(TO_CONN(conn),
+ TEST_CONN_UNATTACHED_STATE);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* one connection, downloading and linked and attached */
+ ap_conn->state = TEST_CONN_ATTACHED_STATE;
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* one connection, linked and attached but not downloading */
+ conn->base_.state = TEST_CONN_STATE;
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* two connections, both not downloading */
+ conn2 = test_conn_download_status_add_a_connection(res);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 2);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* two connections, one downloading */
+ conn->base_.state = TEST_CONN_DL_STATE;
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 2);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+ conn->base_.state = TEST_CONN_STATE;
+
+ /* more connections, all not downloading */
+ /* ignore the return value, it's free'd using the connection list */
+ (void)test_conn_download_status_add_a_connection(res);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 0);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* more connections, one downloading */
+ conn->base_.state = TEST_CONN_DL_STATE;
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* more connections, two downloading (should never happen, but needs
+ * to be tested for completeness) */
+ conn2->base_.state = TEST_CONN_DL_STATE;
+ /* ignore the return value, it's free'd using the connection list */
+ (void)test_conn_get_linked_connection(TO_CONN(conn2),
+ TEST_CONN_ATTACHED_STATE);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+ conn->base_.state = TEST_CONN_STATE;
+
+ /* more connections, a different one downloading */
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 0);
+
+ /* a connection for the other flavor (could happen if a client is set to
+ * cache directory documents), one preferred flavor downloading
+ */
+ conn4 = test_conn_download_status_add_a_connection(other_res);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 0);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 1);
+
+ /* a connection for the other flavor (could happen if a client is set to
+ * cache directory documents), both flavors downloading
+ */
+ conn4->base_.state = TEST_CONN_DL_STATE;
+ /* ignore the return value, it's free'd using the connection list */
+ (void)test_conn_get_linked_connection(TO_CONN(conn4),
+ TEST_CONN_ATTACHED_STATE);
+ tt_assert(networkstatus_consensus_is_already_downloading(res) == 1);
+ tt_assert(networkstatus_consensus_is_already_downloading(other_res) == 1);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ res) == 3);
+ tt_assert(connection_dir_count_by_purpose_and_resource(
+ TEST_CONN_RSRC_PURPOSE,
+ other_res) == 1);
+
+ done:
+ /* the teardown function removes all the connections in the global list*/;
+}
+
+#define CONNECTION_TESTCASE(name, fork, setup) \
+ { #name, test_conn_##name, fork, &setup, NULL }
+
+/* where arg is an expression (constant, varaible, compound expression) */
+#define CONNECTION_TESTCASE_ARG(name, fork, setup, arg) \
+ { #name "_" #arg, test_conn_##name, fork, &setup, (void *)arg }
+
+struct testcase_t connection_tests[] = {
+ CONNECTION_TESTCASE(get_basic, TT_FORK, test_conn_get_basic_st),
+ CONNECTION_TESTCASE(get_rend, TT_FORK, test_conn_get_rend_st),
+ CONNECTION_TESTCASE(get_rsrc, TT_FORK, test_conn_get_rsrc_st),
+ CONNECTION_TESTCASE_ARG(download_status, TT_FORK,
+ test_conn_download_status_st, FLAV_MICRODESC),
+ CONNECTION_TESTCASE_ARG(download_status, TT_FORK,
+ test_conn_download_status_st, FLAV_NS),
+//CONNECTION_TESTCASE(func_suffix, TT_FORK, setup_func_pair),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_containers.c b/src/test/test_containers.c
index 067c4c1907..fd896760c0 100644
--- a/src/test/test_containers.c
+++ b/src/test/test_containers.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -29,7 +29,7 @@ compare_strs_for_bsearch_(const void *a, const void **b)
/** Helper: return a tristate based on comparing the strings in *<b>a</b> and
* *<b>b</b>, excluding a's first character, and ignoring case. */
static int
-compare_without_first_ch_(const void *a, const void **b)
+cmp_without_first_(const void *a, const void **b)
{
const char *s1 = a, *s2 = *b;
return strcasecmp(s1+1, s2);
@@ -37,237 +37,259 @@ compare_without_first_ch_(const void *a, const void **b)
/** Run unit tests for basic dynamic-sized array functionality. */
static void
-test_container_smartlist_basic(void)
+test_container_smartlist_basic(void *arg)
{
smartlist_t *sl;
+ char *v0 = tor_strdup("v0");
+ char *v1 = tor_strdup("v1");
+ char *v2 = tor_strdup("v2");
+ char *v3 = tor_strdup("v3");
+ char *v4 = tor_strdup("v4");
+ char *v22 = tor_strdup("v22");
+ char *v99 = tor_strdup("v99");
+ char *v555 = tor_strdup("v555");
/* XXXX test sort_digests, uniq_strings, uniq_digests */
/* Test smartlist add, del_keeporder, insert, get. */
+ (void)arg;
sl = smartlist_new();
- smartlist_add(sl, (void*)1);
- smartlist_add(sl, (void*)2);
- smartlist_add(sl, (void*)3);
- smartlist_add(sl, (void*)4);
+ smartlist_add(sl, v1);
+ smartlist_add(sl, v2);
+ smartlist_add(sl, v3);
+ smartlist_add(sl, v4);
smartlist_del_keeporder(sl, 1);
- smartlist_insert(sl, 1, (void*)22);
- smartlist_insert(sl, 0, (void*)0);
- smartlist_insert(sl, 5, (void*)555);
- test_eq_ptr((void*)0, smartlist_get(sl,0));
- test_eq_ptr((void*)1, smartlist_get(sl,1));
- test_eq_ptr((void*)22, smartlist_get(sl,2));
- test_eq_ptr((void*)3, smartlist_get(sl,3));
- test_eq_ptr((void*)4, smartlist_get(sl,4));
- test_eq_ptr((void*)555, smartlist_get(sl,5));
+ smartlist_insert(sl, 1, v22);
+ smartlist_insert(sl, 0, v0);
+ smartlist_insert(sl, 5, v555);
+ tt_ptr_op(v0,OP_EQ, smartlist_get(sl,0));
+ tt_ptr_op(v1,OP_EQ, smartlist_get(sl,1));
+ tt_ptr_op(v22,OP_EQ, smartlist_get(sl,2));
+ tt_ptr_op(v3,OP_EQ, smartlist_get(sl,3));
+ tt_ptr_op(v4,OP_EQ, smartlist_get(sl,4));
+ tt_ptr_op(v555,OP_EQ, smartlist_get(sl,5));
/* Try deleting in the middle. */
smartlist_del(sl, 1);
- test_eq_ptr((void*)555, smartlist_get(sl, 1));
+ tt_ptr_op(v555,OP_EQ, smartlist_get(sl, 1));
/* Try deleting at the end. */
smartlist_del(sl, 4);
- test_eq(4, smartlist_len(sl));
+ tt_int_op(4,OP_EQ, smartlist_len(sl));
/* test isin. */
- test_assert(smartlist_contains(sl, (void*)3));
- test_assert(!smartlist_contains(sl, (void*)99));
+ tt_assert(smartlist_contains(sl, v3));
+ tt_assert(!smartlist_contains(sl, v99));
done:
smartlist_free(sl);
+ tor_free(v0);
+ tor_free(v1);
+ tor_free(v2);
+ tor_free(v3);
+ tor_free(v4);
+ tor_free(v22);
+ tor_free(v99);
+ tor_free(v555);
}
/** Run unit tests for smartlist-of-strings functionality. */
static void
-test_container_smartlist_strings(void)
+test_container_smartlist_strings(void *arg)
{
smartlist_t *sl = smartlist_new();
char *cp=NULL, *cp_alloc=NULL;
size_t sz;
/* Test split and join */
- test_eq(0, smartlist_len(sl));
+ (void)arg;
+ tt_int_op(0,OP_EQ, smartlist_len(sl));
smartlist_split_string(sl, "abc", ":", 0, 0);
- test_eq(1, smartlist_len(sl));
- test_streq("abc", smartlist_get(sl, 0));
+ tt_int_op(1,OP_EQ, smartlist_len(sl));
+ tt_str_op("abc",OP_EQ, smartlist_get(sl, 0));
smartlist_split_string(sl, "a::bc::", "::", 0, 0);
- test_eq(4, smartlist_len(sl));
- test_streq("a", smartlist_get(sl, 1));
- test_streq("bc", smartlist_get(sl, 2));
- test_streq("", smartlist_get(sl, 3));
+ tt_int_op(4,OP_EQ, smartlist_len(sl));
+ tt_str_op("a",OP_EQ, smartlist_get(sl, 1));
+ tt_str_op("bc",OP_EQ, smartlist_get(sl, 2));
+ tt_str_op("",OP_EQ, smartlist_get(sl, 3));
cp_alloc = smartlist_join_strings(sl, "", 0, NULL);
- test_streq(cp_alloc, "abcabc");
+ tt_str_op(cp_alloc,OP_EQ, "abcabc");
tor_free(cp_alloc);
cp_alloc = smartlist_join_strings(sl, "!", 0, NULL);
- test_streq(cp_alloc, "abc!a!bc!");
+ tt_str_op(cp_alloc,OP_EQ, "abc!a!bc!");
tor_free(cp_alloc);
cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
- test_streq(cp_alloc, "abcXYaXYbcXY");
+ tt_str_op(cp_alloc,OP_EQ, "abcXYaXYbcXY");
tor_free(cp_alloc);
cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
- test_streq(cp_alloc, "abcXYaXYbcXYXY");
+ tt_str_op(cp_alloc,OP_EQ, "abcXYaXYbcXYXY");
tor_free(cp_alloc);
cp_alloc = smartlist_join_strings(sl, "", 1, NULL);
- test_streq(cp_alloc, "abcabc");
+ tt_str_op(cp_alloc,OP_EQ, "abcabc");
tor_free(cp_alloc);
smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
- test_eq(8, smartlist_len(sl));
- test_streq("", smartlist_get(sl, 4));
- test_streq("def", smartlist_get(sl, 5));
- test_streq(" ", smartlist_get(sl, 6));
- test_streq("ghijk", smartlist_get(sl, 7));
+ tt_int_op(8,OP_EQ, smartlist_len(sl));
+ tt_str_op("",OP_EQ, smartlist_get(sl, 4));
+ tt_str_op("def",OP_EQ, smartlist_get(sl, 5));
+ tt_str_op(" ",OP_EQ, smartlist_get(sl, 6));
+ tt_str_op("ghijk",OP_EQ, smartlist_get(sl, 7));
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
- test_eq(3, smartlist_len(sl));
- test_streq("a", smartlist_get(sl,0));
- test_streq("bbd", smartlist_get(sl,1));
- test_streq("cdef", smartlist_get(sl,2));
+ tt_int_op(3,OP_EQ, smartlist_len(sl));
+ tt_str_op("a",OP_EQ, smartlist_get(sl,0));
+ tt_str_op("bbd",OP_EQ, smartlist_get(sl,1));
+ tt_str_op("cdef",OP_EQ, smartlist_get(sl,2));
smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
SPLIT_SKIP_SPACE, 0);
- test_eq(8, smartlist_len(sl));
- test_streq("z", smartlist_get(sl,3));
- test_streq("zhasd", smartlist_get(sl,4));
- test_streq("", smartlist_get(sl,5));
- test_streq("bnud", smartlist_get(sl,6));
- test_streq("", smartlist_get(sl,7));
+ tt_int_op(8,OP_EQ, smartlist_len(sl));
+ tt_str_op("z",OP_EQ, smartlist_get(sl,3));
+ tt_str_op("zhasd",OP_EQ, smartlist_get(sl,4));
+ tt_str_op("",OP_EQ, smartlist_get(sl,5));
+ tt_str_op("bnud",OP_EQ, smartlist_get(sl,6));
+ tt_str_op("",OP_EQ, smartlist_get(sl,7));
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
smartlist_split_string(sl, " ab\tc \td ef ", NULL,
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- test_eq(4, smartlist_len(sl));
- test_streq("ab", smartlist_get(sl,0));
- test_streq("c", smartlist_get(sl,1));
- test_streq("d", smartlist_get(sl,2));
- test_streq("ef", smartlist_get(sl,3));
+ tt_int_op(4,OP_EQ, smartlist_len(sl));
+ tt_str_op("ab",OP_EQ, smartlist_get(sl,0));
+ tt_str_op("c",OP_EQ, smartlist_get(sl,1));
+ tt_str_op("d",OP_EQ, smartlist_get(sl,2));
+ tt_str_op("ef",OP_EQ, smartlist_get(sl,3));
smartlist_split_string(sl, "ghi\tj", NULL,
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- test_eq(6, smartlist_len(sl));
- test_streq("ghi", smartlist_get(sl,4));
- test_streq("j", smartlist_get(sl,5));
+ tt_int_op(6,OP_EQ, smartlist_len(sl));
+ tt_str_op("ghi",OP_EQ, smartlist_get(sl,4));
+ tt_str_op("j",OP_EQ, smartlist_get(sl,5));
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
- test_streq(cp_alloc, "");
+ tt_str_op(cp_alloc,OP_EQ, "");
tor_free(cp_alloc);
cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
- test_streq(cp_alloc, "XY");
+ tt_str_op(cp_alloc,OP_EQ, "XY");
tor_free(cp_alloc);
smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- test_eq(3, smartlist_len(sl));
- test_streq("z", smartlist_get(sl, 0));
- test_streq("zhasd", smartlist_get(sl, 1));
- test_streq("bnud", smartlist_get(sl, 2));
+ tt_int_op(3,OP_EQ, smartlist_len(sl));
+ tt_str_op("z",OP_EQ, smartlist_get(sl, 0));
+ tt_str_op("zhasd",OP_EQ, smartlist_get(sl, 1));
+ tt_str_op("bnud",OP_EQ, smartlist_get(sl, 2));
smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
- test_eq(5, smartlist_len(sl));
- test_streq("z", smartlist_get(sl, 3));
- test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
+ tt_int_op(5,OP_EQ, smartlist_len(sl));
+ tt_str_op("z",OP_EQ, smartlist_get(sl, 3));
+ tt_str_op("zhasd <> <> bnud<>",OP_EQ, smartlist_get(sl, 4));
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
smartlist_split_string(sl, "abcd\n", "\n",
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- test_eq(1, smartlist_len(sl));
- test_streq("abcd", smartlist_get(sl, 0));
+ tt_int_op(1,OP_EQ, smartlist_len(sl));
+ tt_str_op("abcd",OP_EQ, smartlist_get(sl, 0));
smartlist_split_string(sl, "efgh", "\n",
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- test_eq(2, smartlist_len(sl));
- test_streq("efgh", smartlist_get(sl, 1));
+ tt_int_op(2,OP_EQ, smartlist_len(sl));
+ tt_str_op("efgh",OP_EQ, smartlist_get(sl, 1));
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Test swapping, shuffling, and sorting. */
smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
- test_eq(7, smartlist_len(sl));
+ tt_int_op(7,OP_EQ, smartlist_len(sl));
smartlist_sort(sl, compare_strs_);
cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
- test_streq(cp_alloc,"and,arma,by,nickm,onion,router,the");
+ tt_str_op(cp_alloc,OP_EQ, "and,arma,by,nickm,onion,router,the");
tor_free(cp_alloc);
smartlist_swap(sl, 1, 5);
cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
- test_streq(cp_alloc,"and,router,by,nickm,onion,arma,the");
+ tt_str_op(cp_alloc,OP_EQ, "and,router,by,nickm,onion,arma,the");
tor_free(cp_alloc);
smartlist_shuffle(sl);
- test_eq(7, smartlist_len(sl));
- test_assert(smartlist_contains_string(sl, "and"));
- test_assert(smartlist_contains_string(sl, "router"));
- test_assert(smartlist_contains_string(sl, "by"));
- test_assert(smartlist_contains_string(sl, "nickm"));
- test_assert(smartlist_contains_string(sl, "onion"));
- test_assert(smartlist_contains_string(sl, "arma"));
- test_assert(smartlist_contains_string(sl, "the"));
+ tt_int_op(7,OP_EQ, smartlist_len(sl));
+ tt_assert(smartlist_contains_string(sl, "and"));
+ tt_assert(smartlist_contains_string(sl, "router"));
+ tt_assert(smartlist_contains_string(sl, "by"));
+ tt_assert(smartlist_contains_string(sl, "nickm"));
+ tt_assert(smartlist_contains_string(sl, "onion"));
+ tt_assert(smartlist_contains_string(sl, "arma"));
+ tt_assert(smartlist_contains_string(sl, "the"));
/* Test bsearch. */
smartlist_sort(sl, compare_strs_);
- test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
- compare_without_first_ch_));
- test_streq("and", smartlist_bsearch(sl, " AND", compare_without_first_ch_));
- test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", compare_without_first_ch_));
+ tt_str_op("nickm",OP_EQ, smartlist_bsearch(sl, "zNicKM",
+ cmp_without_first_));
+ tt_str_op("and",OP_EQ,
+ smartlist_bsearch(sl, " AND", cmp_without_first_));
+ tt_ptr_op(NULL,OP_EQ, smartlist_bsearch(sl, " ANz", cmp_without_first_));
/* Test bsearch_idx */
{
int f;
smartlist_t *tmp = NULL;
- test_eq(0, smartlist_bsearch_idx(sl," aaa",compare_without_first_ch_,&f));
- test_eq(f, 0);
- test_eq(0, smartlist_bsearch_idx(sl," and",compare_without_first_ch_,&f));
- test_eq(f, 1);
- test_eq(1, smartlist_bsearch_idx(sl," arm",compare_without_first_ch_,&f));
- test_eq(f, 0);
- test_eq(1, smartlist_bsearch_idx(sl," arma",compare_without_first_ch_,&f));
- test_eq(f, 1);
- test_eq(2, smartlist_bsearch_idx(sl," armb",compare_without_first_ch_,&f));
- test_eq(f, 0);
- test_eq(7, smartlist_bsearch_idx(sl," zzzz",compare_without_first_ch_,&f));
- test_eq(f, 0);
+ tt_int_op(0,OP_EQ,smartlist_bsearch_idx(sl," aaa",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 0);
+ tt_int_op(0,OP_EQ, smartlist_bsearch_idx(sl," and",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 1);
+ tt_int_op(1,OP_EQ, smartlist_bsearch_idx(sl," arm",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 0);
+ tt_int_op(1,OP_EQ,
+ smartlist_bsearch_idx(sl," arma",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 1);
+ tt_int_op(2,OP_EQ,
+ smartlist_bsearch_idx(sl," armb",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 0);
+ tt_int_op(7,OP_EQ,
+ smartlist_bsearch_idx(sl," zzzz",cmp_without_first_,&f));
+ tt_int_op(f,OP_EQ, 0);
/* Test trivial cases for list of length 0 or 1 */
tmp = smartlist_new();
- test_eq(0, smartlist_bsearch_idx(tmp, "foo",
+ tt_int_op(0,OP_EQ, smartlist_bsearch_idx(tmp, "foo",
compare_strs_for_bsearch_, &f));
- test_eq(f, 0);
+ tt_int_op(f,OP_EQ, 0);
smartlist_insert(tmp, 0, (void *)("bar"));
- test_eq(1, smartlist_bsearch_idx(tmp, "foo",
+ tt_int_op(1,OP_EQ, smartlist_bsearch_idx(tmp, "foo",
compare_strs_for_bsearch_, &f));
- test_eq(f, 0);
- test_eq(0, smartlist_bsearch_idx(tmp, "aaa",
+ tt_int_op(f,OP_EQ, 0);
+ tt_int_op(0,OP_EQ, smartlist_bsearch_idx(tmp, "aaa",
compare_strs_for_bsearch_, &f));
- test_eq(f, 0);
- test_eq(0, smartlist_bsearch_idx(tmp, "bar",
+ tt_int_op(f,OP_EQ, 0);
+ tt_int_op(0,OP_EQ, smartlist_bsearch_idx(tmp, "bar",
compare_strs_for_bsearch_, &f));
- test_eq(f, 1);
+ tt_int_op(f,OP_EQ, 1);
/* ... and one for length 2 */
smartlist_insert(tmp, 1, (void *)("foo"));
- test_eq(1, smartlist_bsearch_idx(tmp, "foo",
+ tt_int_op(1,OP_EQ, smartlist_bsearch_idx(tmp, "foo",
compare_strs_for_bsearch_, &f));
- test_eq(f, 1);
- test_eq(2, smartlist_bsearch_idx(tmp, "goo",
+ tt_int_op(f,OP_EQ, 1);
+ tt_int_op(2,OP_EQ, smartlist_bsearch_idx(tmp, "goo",
compare_strs_for_bsearch_, &f));
- test_eq(f, 0);
+ tt_int_op(f,OP_EQ, 0);
smartlist_free(tmp);
}
/* Test reverse() and pop_last() */
smartlist_reverse(sl);
cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
- test_streq(cp_alloc,"the,router,onion,nickm,by,arma,and");
+ tt_str_op(cp_alloc,OP_EQ, "the,router,onion,nickm,by,arma,and");
tor_free(cp_alloc);
cp_alloc = smartlist_pop_last(sl);
- test_streq(cp_alloc, "and");
+ tt_str_op(cp_alloc,OP_EQ, "and");
tor_free(cp_alloc);
- test_eq(smartlist_len(sl), 6);
+ tt_int_op(smartlist_len(sl),OP_EQ, 6);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
cp_alloc = smartlist_pop_last(sl);
- test_eq_ptr(cp_alloc, NULL);
+ tt_ptr_op(cp_alloc,OP_EQ, NULL);
/* Test uniq() */
smartlist_split_string(sl,
@@ -276,16 +298,16 @@ test_container_smartlist_strings(void)
smartlist_sort(sl, compare_strs_);
smartlist_uniq(sl, compare_strs_, tor_free_);
cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
- test_streq(cp_alloc, "50,a,canal,man,noon,panama,plan,radar");
+ tt_str_op(cp_alloc,OP_EQ, "50,a,canal,man,noon,panama,plan,radar");
tor_free(cp_alloc);
/* Test contains_string, contains_string_case and contains_int_as_string */
- test_assert(smartlist_contains_string(sl, "noon"));
- test_assert(!smartlist_contains_string(sl, "noonoon"));
- test_assert(smartlist_contains_string_case(sl, "nOOn"));
- test_assert(!smartlist_contains_string_case(sl, "nooNooN"));
- test_assert(smartlist_contains_int_as_string(sl, 50));
- test_assert(!smartlist_contains_int_as_string(sl, 60));
+ tt_assert(smartlist_contains_string(sl, "noon"));
+ tt_assert(!smartlist_contains_string(sl, "noonoon"));
+ tt_assert(smartlist_contains_string_case(sl, "nOOn"));
+ tt_assert(!smartlist_contains_string_case(sl, "nooNooN"));
+ tt_assert(smartlist_contains_int_as_string(sl, 50));
+ tt_assert(!smartlist_contains_int_as_string(sl, 60));
/* Test smartlist_choose */
{
@@ -293,7 +315,7 @@ test_container_smartlist_strings(void)
int allsame = 1;
int allin = 1;
void *first = smartlist_choose(sl);
- test_assert(smartlist_contains(sl, first));
+ tt_assert(smartlist_contains(sl, first));
for (i = 0; i < 100; ++i) {
void *second = smartlist_choose(sl);
if (second != first)
@@ -301,8 +323,8 @@ test_container_smartlist_strings(void)
if (!smartlist_contains(sl, second))
allin = 0;
}
- test_assert(!allsame);
- test_assert(allin);
+ tt_assert(!allsame);
+ tt_assert(allin);
}
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
@@ -312,17 +334,17 @@ test_container_smartlist_strings(void)
"Some say the Earth will end in ice and some in fire",
" ", 0, 0);
cp = smartlist_get(sl, 4);
- test_streq(cp, "will");
+ tt_str_op(cp,OP_EQ, "will");
smartlist_add(sl, cp);
smartlist_remove(sl, cp);
tor_free(cp);
cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
- test_streq(cp_alloc, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
+ tt_str_op(cp_alloc,OP_EQ, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
tor_free(cp_alloc);
smartlist_string_remove(sl, "in");
cp_alloc = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
- test_streq(cp_alloc, "Some+say+the+Earth+fire+end+some+ice+and");
- test_eq((int)sz, 40);
+ tt_str_op(cp_alloc,OP_EQ, "Some+say+the+Earth+fire+end+some+ice+and");
+ tt_int_op((int)sz,OP_EQ, 40);
done:
@@ -333,7 +355,7 @@ test_container_smartlist_strings(void)
/** Run unit tests for smartlist set manipulation functions. */
static void
-test_container_smartlist_overlap(void)
+test_container_smartlist_overlap(void *arg)
{
smartlist_t *sl = smartlist_new();
smartlist_t *ints = smartlist_new();
@@ -341,6 +363,7 @@ test_container_smartlist_overlap(void)
smartlist_t *evens = smartlist_new();
smartlist_t *primes = smartlist_new();
int i;
+ (void)arg;
for (i=1; i < 10; i += 2)
smartlist_add(odds, (void*)(uintptr_t)i);
for (i=0; i < 10; i += 2)
@@ -349,7 +372,7 @@ test_container_smartlist_overlap(void)
/* add_all */
smartlist_add_all(ints, odds);
smartlist_add_all(ints, evens);
- test_eq(smartlist_len(ints), 10);
+ tt_int_op(smartlist_len(ints),OP_EQ, 10);
smartlist_add(primes, (void*)2);
smartlist_add(primes, (void*)3);
@@ -357,24 +380,24 @@ test_container_smartlist_overlap(void)
smartlist_add(primes, (void*)7);
/* overlap */
- test_assert(smartlist_overlap(ints, odds));
- test_assert(smartlist_overlap(odds, primes));
- test_assert(smartlist_overlap(evens, primes));
- test_assert(!smartlist_overlap(odds, evens));
+ tt_assert(smartlist_overlap(ints, odds));
+ tt_assert(smartlist_overlap(odds, primes));
+ tt_assert(smartlist_overlap(evens, primes));
+ tt_assert(!smartlist_overlap(odds, evens));
/* intersect */
smartlist_add_all(sl, odds);
smartlist_intersect(sl, primes);
- test_eq(smartlist_len(sl), 3);
- test_assert(smartlist_contains(sl, (void*)3));
- test_assert(smartlist_contains(sl, (void*)5));
- test_assert(smartlist_contains(sl, (void*)7));
+ tt_int_op(smartlist_len(sl),OP_EQ, 3);
+ tt_assert(smartlist_contains(sl, (void*)3));
+ tt_assert(smartlist_contains(sl, (void*)5));
+ tt_assert(smartlist_contains(sl, (void*)7));
/* subtract */
smartlist_add_all(sl, primes);
smartlist_subtract(sl, odds);
- test_eq(smartlist_len(sl), 1);
- test_assert(smartlist_contains(sl, (void*)2));
+ tt_int_op(smartlist_len(sl),OP_EQ, 1);
+ tt_assert(smartlist_contains(sl, (void*)2));
done:
smartlist_free(odds);
@@ -386,31 +409,32 @@ test_container_smartlist_overlap(void)
/** Run unit tests for smartlist-of-digests functions. */
static void
-test_container_smartlist_digests(void)
+test_container_smartlist_digests(void *arg)
{
smartlist_t *sl = smartlist_new();
/* contains_digest */
+ (void)arg;
smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
- test_eq(0, smartlist_contains_digest(NULL, "AAAAAAAAAAAAAAAAAAAA"));
- test_assert(smartlist_contains_digest(sl, "AAAAAAAAAAAAAAAAAAAA"));
- test_assert(smartlist_contains_digest(sl, "\00090AAB2AAAAaasdAAAAA"));
- test_eq(0, smartlist_contains_digest(sl, "\00090AAB2AAABaasdAAAAA"));
+ tt_int_op(0,OP_EQ, smartlist_contains_digest(NULL, "AAAAAAAAAAAAAAAAAAAA"));
+ tt_assert(smartlist_contains_digest(sl, "AAAAAAAAAAAAAAAAAAAA"));
+ tt_assert(smartlist_contains_digest(sl, "\00090AAB2AAAAaasdAAAAA"));
+ tt_int_op(0,OP_EQ, smartlist_contains_digest(sl, "\00090AAB2AAABaasdAAAAA"));
/* sort digests */
smartlist_sort_digests(sl);
- test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
- test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
- test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
- test_eq(3, smartlist_len(sl));
+ tt_mem_op(smartlist_get(sl, 0),OP_EQ, "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
+ tt_mem_op(smartlist_get(sl, 1),OP_EQ, "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
+ tt_mem_op(smartlist_get(sl, 2),OP_EQ, "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
+ tt_int_op(3,OP_EQ, smartlist_len(sl));
/* uniq_digests */
smartlist_uniq_digests(sl);
- test_eq(2, smartlist_len(sl));
- test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
- test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
+ tt_int_op(2,OP_EQ, smartlist_len(sl));
+ tt_mem_op(smartlist_get(sl, 0),OP_EQ, "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
+ tt_mem_op(smartlist_get(sl, 1),OP_EQ, "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
done:
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
@@ -419,13 +443,14 @@ test_container_smartlist_digests(void)
/** Run unit tests for concatenate-a-smartlist-of-strings functions. */
static void
-test_container_smartlist_join(void)
+test_container_smartlist_join(void *arg)
{
smartlist_t *sl = smartlist_new();
smartlist_t *sl2 = smartlist_new(), *sl3 = smartlist_new(),
*sl4 = smartlist_new();
char *joined=NULL;
/* unique, sorted. */
+ (void)arg;
smartlist_split_string(sl,
"Abashments Ambush Anchorman Bacon Banks Borscht "
"Bunks Inhumane Insurance Knish Know Manners "
@@ -441,21 +466,22 @@ test_container_smartlist_join(void)
sl2, char *, cp2,
strcmp(cp1,cp2),
smartlist_add(sl3, cp2)) {
- test_streq(cp1, cp2);
+ tt_str_op(cp1,OP_EQ, cp2);
smartlist_add(sl4, cp1);
} SMARTLIST_FOREACH_JOIN_END(cp1, cp2);
SMARTLIST_FOREACH(sl3, const char *, cp,
- test_assert(smartlist_contains(sl2, cp) &&
+ tt_assert(smartlist_contains(sl2, cp) &&
!smartlist_contains_string(sl, cp)));
SMARTLIST_FOREACH(sl4, const char *, cp,
- test_assert(smartlist_contains(sl, cp) &&
+ tt_assert(smartlist_contains(sl, cp) &&
smartlist_contains_string(sl2, cp)));
joined = smartlist_join_strings(sl3, ",", 0, NULL);
- test_streq(joined, "Anemias,Anemias,Crossbowmen,Work");
+ tt_str_op(joined,OP_EQ, "Anemias,Anemias,Crossbowmen,Work");
tor_free(joined);
joined = smartlist_join_strings(sl4, ",", 0, NULL);
- test_streq(joined, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
+ tt_str_op(joined,OP_EQ,
+ "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
"Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
tor_free(joined);
@@ -470,6 +496,43 @@ test_container_smartlist_join(void)
}
static void
+test_container_smartlist_pos(void *arg)
+{
+ (void) arg;
+ smartlist_t *sl = smartlist_new();
+
+ smartlist_add(sl, tor_strdup("This"));
+ smartlist_add(sl, tor_strdup("is"));
+ smartlist_add(sl, tor_strdup("a"));
+ smartlist_add(sl, tor_strdup("test"));
+ smartlist_add(sl, tor_strdup("for"));
+ smartlist_add(sl, tor_strdup("a"));
+ smartlist_add(sl, tor_strdup("function"));
+
+ /* Test string_pos */
+ tt_int_op(smartlist_string_pos(NULL, "Fred"), ==, -1);
+ tt_int_op(smartlist_string_pos(sl, "Fred"), ==, -1);
+ tt_int_op(smartlist_string_pos(sl, "This"), ==, 0);
+ tt_int_op(smartlist_string_pos(sl, "a"), ==, 2);
+ tt_int_op(smartlist_string_pos(sl, "function"), ==, 6);
+
+ /* Test pos */
+ tt_int_op(smartlist_pos(NULL, "Fred"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "Fred"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "This"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "a"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "function"), ==, -1);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,0)), ==, 0);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,2)), ==, 2);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,5)), ==, 5);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,6)), ==, 6);
+
+ done:
+ SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
+ smartlist_free(sl);
+}
+
+static void
test_container_smartlist_ints_eq(void *arg)
{
smartlist_t *sl1 = NULL, *sl2 = NULL;
@@ -516,18 +579,19 @@ test_container_smartlist_ints_eq(void *arg)
/** Run unit tests for bitarray code */
static void
-test_container_bitarray(void)
+test_container_bitarray(void *arg)
{
bitarray_t *ba = NULL;
int i, j, ok=1;
+ (void)arg;
ba = bitarray_init_zero(1);
- test_assert(ba);
- test_assert(! bitarray_is_set(ba, 0));
+ tt_assert(ba);
+ tt_assert(! bitarray_is_set(ba, 0));
bitarray_set(ba, 0);
- test_assert(bitarray_is_set(ba, 0));
+ tt_assert(bitarray_is_set(ba, 0));
bitarray_clear(ba, 0);
- test_assert(! bitarray_is_set(ba, 0));
+ tt_assert(! bitarray_is_set(ba, 0));
bitarray_free(ba);
ba = bitarray_init_zero(1023);
@@ -542,7 +606,7 @@ test_container_bitarray(void)
if (!bool_eq(bitarray_is_set(ba, j), j%i))
ok = 0;
}
- test_assert(ok);
+ tt_assert(ok);
if (i < 7)
++i;
else if (i == 28)
@@ -559,7 +623,7 @@ test_container_bitarray(void)
/** Run unit tests for digest set code (implemented as a hashtable or as a
* bloom filter) */
static void
-test_container_digestset(void)
+test_container_digestset(void *arg)
{
smartlist_t *included = smartlist_new();
char d[DIGEST_LEN];
@@ -568,6 +632,7 @@ test_container_digestset(void)
int false_positives = 0;
digestset_t *set = NULL;
+ (void)arg;
for (i = 0; i < 1000; ++i) {
crypto_rand(d, DIGEST_LEN);
smartlist_add(included, tor_memdup(d, DIGEST_LEN));
@@ -576,19 +641,19 @@ test_container_digestset(void)
SMARTLIST_FOREACH(included, const char *, cp,
if (digestset_contains(set, cp))
ok = 0);
- test_assert(ok);
+ tt_assert(ok);
SMARTLIST_FOREACH(included, const char *, cp,
digestset_add(set, cp));
SMARTLIST_FOREACH(included, const char *, cp,
if (!digestset_contains(set, cp))
ok = 0);
- test_assert(ok);
+ tt_assert(ok);
for (i = 0; i < 1000; ++i) {
crypto_rand(d, DIGEST_LEN);
if (digestset_contains(set, d))
++false_positives;
}
- test_assert(false_positives < 50); /* Should be far lower. */
+ tt_int_op(50, OP_GT, false_positives); /* Should be far lower. */
done:
if (set)
@@ -612,7 +677,7 @@ compare_strings_for_pqueue_(const void *p1, const void *p2)
/** Run unit tests for heap-based priority queue functions. */
static void
-test_container_pqueue(void)
+test_container_pqueue(void *arg)
{
smartlist_t *sl = smartlist_new();
int (*cmp)(const void *, const void*);
@@ -634,6 +699,8 @@ test_container_pqueue(void)
#define OK() smartlist_pqueue_assert_ok(sl, cmp, offset)
+ (void)arg;
+
cmp = compare_strings_for_pqueue_;
smartlist_pqueue_add(sl, cmp, offset, &cows);
smartlist_pqueue_add(sl, cmp, offset, &zebras);
@@ -649,31 +716,31 @@ test_container_pqueue(void)
OK();
- test_eq(smartlist_len(sl), 11);
- test_eq_ptr(smartlist_get(sl, 0), &apples);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &apples);
- test_eq(smartlist_len(sl), 10);
+ tt_int_op(smartlist_len(sl),OP_EQ, 11);
+ tt_ptr_op(smartlist_get(sl, 0),OP_EQ, &apples);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &apples);
+ tt_int_op(smartlist_len(sl),OP_EQ, 10);
OK();
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &cows);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &daschunds);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &cows);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &daschunds);
smartlist_pqueue_add(sl, cmp, offset, &chinchillas);
OK();
smartlist_pqueue_add(sl, cmp, offset, &fireflies);
OK();
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &chinchillas);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &eggplants);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &fireflies);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &chinchillas);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &eggplants);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &fireflies);
OK();
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &fish);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &frogs);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &lobsters);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &roquefort);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &fish);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &frogs);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &lobsters);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &roquefort);
OK();
- test_eq(smartlist_len(sl), 3);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &squid);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &weissbier);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &zebras);
- test_eq(smartlist_len(sl), 0);
+ tt_int_op(smartlist_len(sl),OP_EQ, 3);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &squid);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &weissbier);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &zebras);
+ tt_int_op(smartlist_len(sl),OP_EQ, 0);
OK();
/* Now test remove. */
@@ -683,21 +750,21 @@ test_container_pqueue(void)
smartlist_pqueue_add(sl, cmp, offset, &apples);
smartlist_pqueue_add(sl, cmp, offset, &squid);
smartlist_pqueue_add(sl, cmp, offset, &zebras);
- test_eq(smartlist_len(sl), 6);
+ tt_int_op(smartlist_len(sl),OP_EQ, 6);
OK();
smartlist_pqueue_remove(sl, cmp, offset, &zebras);
- test_eq(smartlist_len(sl), 5);
+ tt_int_op(smartlist_len(sl),OP_EQ, 5);
OK();
smartlist_pqueue_remove(sl, cmp, offset, &cows);
- test_eq(smartlist_len(sl), 4);
+ tt_int_op(smartlist_len(sl),OP_EQ, 4);
OK();
smartlist_pqueue_remove(sl, cmp, offset, &apples);
- test_eq(smartlist_len(sl), 3);
+ tt_int_op(smartlist_len(sl),OP_EQ, 3);
OK();
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &fish);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &frogs);
- test_eq_ptr(smartlist_pqueue_pop(sl, cmp, offset), &squid);
- test_eq(smartlist_len(sl), 0);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &fish);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &frogs);
+ tt_ptr_op(smartlist_pqueue_pop(sl, cmp, offset),OP_EQ, &squid);
+ tt_int_op(smartlist_len(sl),OP_EQ, 0);
OK();
#undef OK
@@ -709,7 +776,7 @@ test_container_pqueue(void)
/** Run unit tests for string-to-void* map functions */
static void
-test_container_strmap(void)
+test_container_strmap(void *arg)
{
strmap_t *map;
strmap_iter_t *iter;
@@ -717,36 +784,45 @@ test_container_strmap(void)
void *v;
char *visited = NULL;
smartlist_t *found_keys = NULL;
+ char *v1 = tor_strdup("v1");
+ char *v99 = tor_strdup("v99");
+ char *v100 = tor_strdup("v100");
+ char *v101 = tor_strdup("v101");
+ char *v102 = tor_strdup("v102");
+ char *v103 = tor_strdup("v103");
+ char *v104 = tor_strdup("v104");
+ char *v105 = tor_strdup("v105");
+ (void)arg;
map = strmap_new();
- test_assert(map);
- test_eq(strmap_size(map), 0);
- test_assert(strmap_isempty(map));
- v = strmap_set(map, "K1", (void*)99);
- test_eq_ptr(v, NULL);
- test_assert(!strmap_isempty(map));
- v = strmap_set(map, "K2", (void*)101);
- test_eq_ptr(v, NULL);
- v = strmap_set(map, "K1", (void*)100);
- test_eq_ptr(v, (void*)99);
- test_eq_ptr(strmap_get(map,"K1"), (void*)100);
- test_eq_ptr(strmap_get(map,"K2"), (void*)101);
- test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
+ tt_assert(map);
+ tt_int_op(strmap_size(map),OP_EQ, 0);
+ tt_assert(strmap_isempty(map));
+ v = strmap_set(map, "K1", v99);
+ tt_ptr_op(v,OP_EQ, NULL);
+ tt_assert(!strmap_isempty(map));
+ v = strmap_set(map, "K2", v101);
+ tt_ptr_op(v,OP_EQ, NULL);
+ v = strmap_set(map, "K1", v100);
+ tt_ptr_op(v,OP_EQ, v99);
+ tt_ptr_op(strmap_get(map,"K1"),OP_EQ, v100);
+ tt_ptr_op(strmap_get(map,"K2"),OP_EQ, v101);
+ tt_ptr_op(strmap_get(map,"K-not-there"),OP_EQ, NULL);
strmap_assert_ok(map);
v = strmap_remove(map,"K2");
strmap_assert_ok(map);
- test_eq_ptr(v, (void*)101);
- test_eq_ptr(strmap_get(map,"K2"), NULL);
- test_eq_ptr(strmap_remove(map,"K2"), NULL);
-
- strmap_set(map, "K2", (void*)101);
- strmap_set(map, "K3", (void*)102);
- strmap_set(map, "K4", (void*)103);
- test_eq(strmap_size(map), 4);
+ tt_ptr_op(v,OP_EQ, v101);
+ tt_ptr_op(strmap_get(map,"K2"),OP_EQ, NULL);
+ tt_ptr_op(strmap_remove(map,"K2"),OP_EQ, NULL);
+
+ strmap_set(map, "K2", v101);
+ strmap_set(map, "K3", v102);
+ strmap_set(map, "K4", v103);
+ tt_int_op(strmap_size(map),OP_EQ, 4);
strmap_assert_ok(map);
- strmap_set(map, "K5", (void*)104);
- strmap_set(map, "K6", (void*)105);
+ strmap_set(map, "K5", v104);
+ strmap_set(map, "K6", v105);
strmap_assert_ok(map);
/* Test iterator. */
@@ -755,7 +831,7 @@ test_container_strmap(void)
while (!strmap_iter_done(iter)) {
strmap_iter_get(iter,&k,&v);
smartlist_add(found_keys, tor_strdup(k));
- test_eq_ptr(v, strmap_get(map, k));
+ tt_ptr_op(v,OP_EQ, strmap_get(map, k));
if (!strcmp(k, "K2")) {
iter = strmap_iter_next_rmv(map,iter);
@@ -765,12 +841,12 @@ test_container_strmap(void)
}
/* Make sure we removed K2, but not the others. */
- test_eq_ptr(strmap_get(map, "K2"), NULL);
- test_eq_ptr(strmap_get(map, "K5"), (void*)104);
+ tt_ptr_op(strmap_get(map, "K2"),OP_EQ, NULL);
+ tt_ptr_op(strmap_get(map, "K5"),OP_EQ, v104);
/* Make sure we visited everyone once */
smartlist_sort_strings(found_keys);
visited = smartlist_join_strings(found_keys, ":", 0, NULL);
- test_streq(visited, "K1:K2:K3:K4:K5:K6");
+ tt_str_op(visited,OP_EQ, "K1:K2:K3:K4:K5:K6");
strmap_assert_ok(map);
/* Clean up after ourselves. */
@@ -779,14 +855,14 @@ test_container_strmap(void)
/* Now try some lc functions. */
map = strmap_new();
- strmap_set_lc(map,"Ab.C", (void*)1);
- test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
+ strmap_set_lc(map,"Ab.C", v1);
+ tt_ptr_op(strmap_get(map,"ab.c"),OP_EQ, v1);
strmap_assert_ok(map);
- test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
- test_eq_ptr(strmap_get(map,"AB.C"), NULL);
- test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
+ tt_ptr_op(strmap_get_lc(map,"AB.C"),OP_EQ, v1);
+ tt_ptr_op(strmap_get(map,"AB.C"),OP_EQ, NULL);
+ tt_ptr_op(strmap_remove_lc(map,"aB.C"),OP_EQ, v1);
strmap_assert_ok(map);
- test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
+ tt_ptr_op(strmap_get_lc(map,"AB.C"),OP_EQ, NULL);
done:
if (map)
@@ -796,34 +872,92 @@ test_container_strmap(void)
smartlist_free(found_keys);
}
tor_free(visited);
+ tor_free(v1);
+ tor_free(v99);
+ tor_free(v100);
+ tor_free(v101);
+ tor_free(v102);
+ tor_free(v103);
+ tor_free(v104);
+ tor_free(v105);
}
/** Run unit tests for getting the median of a list. */
static void
-test_container_order_functions(void)
+test_container_order_functions(void *arg)
{
int lst[25], n = 0;
+ uint32_t lst_2[25];
// int a=12,b=24,c=25,d=60,e=77;
#define median() median_int(lst, n)
+ (void)arg;
lst[n++] = 12;
- test_eq(12, median()); /* 12 */
+ tt_int_op(12,OP_EQ, median()); /* 12 */
lst[n++] = 77;
//smartlist_shuffle(sl);
- test_eq(12, median()); /* 12, 77 */
+ tt_int_op(12,OP_EQ, median()); /* 12, 77 */
lst[n++] = 77;
//smartlist_shuffle(sl);
- test_eq(77, median()); /* 12, 77, 77 */
+ tt_int_op(77,OP_EQ, median()); /* 12, 77, 77 */
lst[n++] = 24;
- test_eq(24, median()); /* 12,24,77,77 */
+ tt_int_op(24,OP_EQ, median()); /* 12,24,77,77 */
lst[n++] = 60;
lst[n++] = 12;
lst[n++] = 25;
//smartlist_shuffle(sl);
- test_eq(25, median()); /* 12,12,24,25,60,77,77 */
+ tt_int_op(25,OP_EQ, median()); /* 12,12,24,25,60,77,77 */
#undef median
+#define third_quartile() third_quartile_uint32(lst_2, n)
+
+ n = 0;
+ lst_2[n++] = 1;
+ tt_int_op(1,OP_EQ, third_quartile()); /* ~1~ */
+ lst_2[n++] = 2;
+ tt_int_op(2,OP_EQ, third_quartile()); /* 1, ~2~ */
+ lst_2[n++] = 3;
+ lst_2[n++] = 4;
+ lst_2[n++] = 5;
+ tt_int_op(4,OP_EQ, third_quartile()); /* 1, 2, 3, ~4~, 5 */
+ lst_2[n++] = 6;
+ lst_2[n++] = 7;
+ lst_2[n++] = 8;
+ lst_2[n++] = 9;
+ tt_int_op(7,OP_EQ, third_quartile()); /* 1, 2, 3, 4, 5, 6, ~7~, 8, 9 */
+ lst_2[n++] = 10;
+ lst_2[n++] = 11;
+ /* 1, 2, 3, 4, 5, 6, 7, 8, ~9~, 10, 11 */
+ tt_int_op(9,OP_EQ, third_quartile());
+
+#undef third_quartile
+
+ double dbls[] = { 1.0, 10.0, 100.0, 1e4, 1e5, 1e6 };
+ tt_double_eq(1.0, median_double(dbls, 1));
+ tt_double_eq(1.0, median_double(dbls, 2));
+ tt_double_eq(10.0, median_double(dbls, 3));
+ tt_double_eq(10.0, median_double(dbls, 4));
+ tt_double_eq(100.0, median_double(dbls, 5));
+ tt_double_eq(100.0, median_double(dbls, 6));
+
+ time_t times[] = { 5, 10, 20, 25, 15 };
+
+ tt_assert(5 == median_time(times, 1));
+ tt_assert(5 == median_time(times, 2));
+ tt_assert(10 == median_time(times, 3));
+ tt_assert(10 == median_time(times, 4));
+ tt_assert(15 == median_time(times, 5));
+
+ int32_t int32s[] = { -5, -10, -50, 100 };
+ tt_int_op(-5, ==, median_int32(int32s, 1));
+ tt_int_op(-10, ==, median_int32(int32s, 2));
+ tt_int_op(-10, ==, median_int32(int32s, 3));
+ tt_int_op(-10, ==, median_int32(int32s, 4));
+
+ long longs[] = { -30, 30, 100, -100, 7 };
+ tt_int_op(7, ==, find_nth_long(longs, 5, 2));
+
done:
;
}
@@ -844,26 +978,26 @@ test_container_di_map(void *arg)
(void)arg;
/* Try searching on an empty map. */
- tt_ptr_op(NULL, ==, dimap_search(map, key1, NULL));
- tt_ptr_op(NULL, ==, dimap_search(map, key2, NULL));
- tt_ptr_op(v3, ==, dimap_search(map, key2, v3));
+ tt_ptr_op(NULL, OP_EQ, dimap_search(map, key1, NULL));
+ tt_ptr_op(NULL, OP_EQ, dimap_search(map, key2, NULL));
+ tt_ptr_op(v3, OP_EQ, dimap_search(map, key2, v3));
dimap_free(map, NULL);
map = NULL;
/* Add a single entry. */
dimap_add_entry(&map, key1, v1);
- tt_ptr_op(NULL, ==, dimap_search(map, key2, NULL));
- tt_ptr_op(v3, ==, dimap_search(map, key2, v3));
- tt_ptr_op(v1, ==, dimap_search(map, key1, NULL));
+ tt_ptr_op(NULL, OP_EQ, dimap_search(map, key2, NULL));
+ tt_ptr_op(v3, OP_EQ, dimap_search(map, key2, v3));
+ tt_ptr_op(v1, OP_EQ, dimap_search(map, key1, NULL));
/* Now try it with three entries in the map. */
dimap_add_entry(&map, key2, v2);
dimap_add_entry(&map, key3, v3);
- tt_ptr_op(v1, ==, dimap_search(map, key1, NULL));
- tt_ptr_op(v2, ==, dimap_search(map, key2, NULL));
- tt_ptr_op(v3, ==, dimap_search(map, key3, NULL));
- tt_ptr_op(NULL, ==, dimap_search(map, key4, NULL));
- tt_ptr_op(v1, ==, dimap_search(map, key4, v1));
+ tt_ptr_op(v1, OP_EQ, dimap_search(map, key1, NULL));
+ tt_ptr_op(v2, OP_EQ, dimap_search(map, key2, NULL));
+ tt_ptr_op(v3, OP_EQ, dimap_search(map, key3, NULL));
+ tt_ptr_op(NULL, OP_EQ, dimap_search(map, key4, NULL));
+ tt_ptr_op(v1, OP_EQ, dimap_search(map, key4, v1));
done:
tor_free(v1);
@@ -874,18 +1008,26 @@ test_container_di_map(void *arg)
/** Run unit tests for fp_pair-to-void* map functions */
static void
-test_container_fp_pair_map(void)
+test_container_fp_pair_map(void *arg)
{
fp_pair_map_t *map;
fp_pair_t fp1, fp2, fp3, fp4, fp5, fp6;
void *v;
fp_pair_map_iter_t *iter;
fp_pair_t k;
+ char *v99 = tor_strdup("99");
+ char *v100 = tor_strdup("v100");
+ char *v101 = tor_strdup("v101");
+ char *v102 = tor_strdup("v102");
+ char *v103 = tor_strdup("v103");
+ char *v104 = tor_strdup("v104");
+ char *v105 = tor_strdup("v105");
+ (void)arg;
map = fp_pair_map_new();
- test_assert(map);
- test_eq(fp_pair_map_size(map), 0);
- test_assert(fp_pair_map_isempty(map));
+ tt_assert(map);
+ tt_int_op(fp_pair_map_size(map),OP_EQ, 0);
+ tt_assert(fp_pair_map_isempty(map));
memset(fp1.first, 0x11, DIGEST_LEN);
memset(fp1.second, 0x12, DIGEST_LEN);
@@ -900,38 +1042,38 @@ test_container_fp_pair_map(void)
memset(fp6.first, 0x61, DIGEST_LEN);
memset(fp6.second, 0x62, DIGEST_LEN);
- v = fp_pair_map_set(map, &fp1, (void*)99);
- tt_ptr_op(v, ==, NULL);
- test_assert(!fp_pair_map_isempty(map));
- v = fp_pair_map_set(map, &fp2, (void*)101);
- tt_ptr_op(v, ==, NULL);
- v = fp_pair_map_set(map, &fp1, (void*)100);
- tt_ptr_op(v, ==, (void*)99);
- test_eq_ptr(fp_pair_map_get(map, &fp1), (void*)100);
- test_eq_ptr(fp_pair_map_get(map, &fp2), (void*)101);
- test_eq_ptr(fp_pair_map_get(map, &fp3), NULL);
+ v = fp_pair_map_set(map, &fp1, v99);
+ tt_ptr_op(v, OP_EQ, NULL);
+ tt_assert(!fp_pair_map_isempty(map));
+ v = fp_pair_map_set(map, &fp2, v101);
+ tt_ptr_op(v, OP_EQ, NULL);
+ v = fp_pair_map_set(map, &fp1, v100);
+ tt_ptr_op(v, OP_EQ, v99);
+ tt_ptr_op(fp_pair_map_get(map, &fp1),OP_EQ, v100);
+ tt_ptr_op(fp_pair_map_get(map, &fp2),OP_EQ, v101);
+ tt_ptr_op(fp_pair_map_get(map, &fp3),OP_EQ, NULL);
fp_pair_map_assert_ok(map);
v = fp_pair_map_remove(map, &fp2);
fp_pair_map_assert_ok(map);
- test_eq_ptr(v, (void*)101);
- test_eq_ptr(fp_pair_map_get(map, &fp2), NULL);
- test_eq_ptr(fp_pair_map_remove(map, &fp2), NULL);
-
- fp_pair_map_set(map, &fp2, (void*)101);
- fp_pair_map_set(map, &fp3, (void*)102);
- fp_pair_map_set(map, &fp4, (void*)103);
- test_eq(fp_pair_map_size(map), 4);
+ tt_ptr_op(v,OP_EQ, v101);
+ tt_ptr_op(fp_pair_map_get(map, &fp2),OP_EQ, NULL);
+ tt_ptr_op(fp_pair_map_remove(map, &fp2),OP_EQ, NULL);
+
+ fp_pair_map_set(map, &fp2, v101);
+ fp_pair_map_set(map, &fp3, v102);
+ fp_pair_map_set(map, &fp4, v103);
+ tt_int_op(fp_pair_map_size(map),OP_EQ, 4);
fp_pair_map_assert_ok(map);
- fp_pair_map_set(map, &fp5, (void*)104);
- fp_pair_map_set(map, &fp6, (void*)105);
+ fp_pair_map_set(map, &fp5, v104);
+ fp_pair_map_set(map, &fp6, v105);
fp_pair_map_assert_ok(map);
/* Test iterator. */
iter = fp_pair_map_iter_init(map);
while (!fp_pair_map_iter_done(iter)) {
fp_pair_map_iter_get(iter, &k, &v);
- test_eq_ptr(v, fp_pair_map_get(map, &k));
+ tt_ptr_op(v,OP_EQ, fp_pair_map_get(map, &k));
if (tor_memeq(&fp2, &k, sizeof(fp2))) {
iter = fp_pair_map_iter_next_rmv(map, iter);
@@ -941,8 +1083,8 @@ test_container_fp_pair_map(void)
}
/* Make sure we removed fp2, but not the others. */
- test_eq_ptr(fp_pair_map_get(map, &fp2), NULL);
- test_eq_ptr(fp_pair_map_get(map, &fp5), (void*)104);
+ tt_ptr_op(fp_pair_map_get(map, &fp2),OP_EQ, NULL);
+ tt_ptr_op(fp_pair_map_get(map, &fp5),OP_EQ, v104);
fp_pair_map_assert_ok(map);
/* Clean up after ourselves. */
@@ -952,10 +1094,140 @@ test_container_fp_pair_map(void)
done:
if (map)
fp_pair_map_free(map, NULL);
+ tor_free(v99);
+ tor_free(v100);
+ tor_free(v101);
+ tor_free(v102);
+ tor_free(v103);
+ tor_free(v104);
+ tor_free(v105);
+}
+
+static void
+test_container_smartlist_most_frequent(void *arg)
+{
+ (void) arg;
+ smartlist_t *sl = smartlist_new();
+
+ int count = -1;
+ const char *cp;
+
+ cp = smartlist_get_most_frequent_string_(sl, &count);
+ tt_int_op(count, ==, 0);
+ tt_ptr_op(cp, ==, NULL);
+
+ /* String must be sorted before we call get_most_frequent */
+ smartlist_split_string(sl, "abc:def:ghi", ":", 0, 0);
+
+ cp = smartlist_get_most_frequent_string_(sl, &count);
+ tt_int_op(count, ==, 1);
+ tt_str_op(cp, ==, "ghi"); /* Ties broken in favor of later element */
+
+ smartlist_split_string(sl, "def:ghi", ":", 0, 0);
+ smartlist_sort_strings(sl);
+
+ cp = smartlist_get_most_frequent_string_(sl, &count);
+ tt_int_op(count, ==, 2);
+ tt_ptr_op(cp, !=, NULL);
+ tt_str_op(cp, ==, "ghi"); /* Ties broken in favor of later element */
+
+ smartlist_split_string(sl, "def:abc:qwop", ":", 0, 0);
+ smartlist_sort_strings(sl);
+
+ cp = smartlist_get_most_frequent_string_(sl, &count);
+ tt_int_op(count, ==, 3);
+ tt_ptr_op(cp, !=, NULL);
+ tt_str_op(cp, ==, "def"); /* No tie */
+
+ done:
+ SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
+ smartlist_free(sl);
+}
+
+static void
+test_container_smartlist_sort_ptrs(void *arg)
+{
+ (void)arg;
+ int array[10];
+ int *arrayptrs[11];
+ smartlist_t *sl = smartlist_new();
+ unsigned i=0, j;
+
+ for (j = 0; j < ARRAY_LENGTH(array); ++j) {
+ smartlist_add(sl, &array[j]);
+ arrayptrs[i++] = &array[j];
+ if (j == 5) {
+ smartlist_add(sl, &array[j]);
+ arrayptrs[i++] = &array[j];
+ }
+ }
+
+ for (i = 0; i < 10; ++i) {
+ smartlist_shuffle(sl);
+ smartlist_sort_pointers(sl);
+ for (j = 0; j < ARRAY_LENGTH(arrayptrs); ++j) {
+ tt_ptr_op(smartlist_get(sl, j), ==, arrayptrs[j]);
+ }
+ }
+
+ done:
+ smartlist_free(sl);
+}
+
+static void
+test_container_smartlist_strings_eq(void *arg)
+{
+ (void)arg;
+ smartlist_t *sl1 = smartlist_new();
+ smartlist_t *sl2 = smartlist_new();
+#define EQ_SHOULD_SAY(s1,s2,val) \
+ do { \
+ SMARTLIST_FOREACH(sl1, char *, cp, tor_free(cp)); \
+ SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp)); \
+ smartlist_clear(sl1); \
+ smartlist_clear(sl2); \
+ smartlist_split_string(sl1, (s1), ":", 0, 0); \
+ smartlist_split_string(sl2, (s2), ":", 0, 0); \
+ tt_int_op((val), OP_EQ, smartlist_strings_eq(sl1, sl2)); \
+ } while (0)
+
+ /* Both NULL, so equal */
+ tt_int_op(1, ==, smartlist_strings_eq(NULL, NULL));
+
+ /* One NULL, not equal. */
+ tt_int_op(0, ==, smartlist_strings_eq(NULL, sl1));
+ tt_int_op(0, ==, smartlist_strings_eq(sl1, NULL));
+
+ /* Both empty, both equal. */
+ EQ_SHOULD_SAY("", "", 1);
+
+ /* One empty, not equal */
+ EQ_SHOULD_SAY("", "ab", 0);
+ EQ_SHOULD_SAY("", "xy:z", 0);
+ EQ_SHOULD_SAY("abc", "", 0);
+ EQ_SHOULD_SAY("abc:cd", "", 0);
+
+ /* Different lengths, not equal. */
+ EQ_SHOULD_SAY("hello:world", "hello", 0);
+ EQ_SHOULD_SAY("hello", "hello:friends", 0);
+
+ /* Same lengths, not equal */
+ EQ_SHOULD_SAY("Hello:world", "goodbye:world", 0);
+ EQ_SHOULD_SAY("Hello:world", "Hello:stars", 0);
+
+ /* Actually equal */
+ EQ_SHOULD_SAY("ABC", "ABC", 1);
+ EQ_SHOULD_SAY(" ab : cd : e", " ab : cd : e", 1);
+
+ done:
+ SMARTLIST_FOREACH(sl1, char *, cp, tor_free(cp));
+ SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
+ smartlist_free(sl1);
+ smartlist_free(sl2);
}
#define CONTAINER_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_container_ ## name }
+ { #name, test_container_ ## name , 0, NULL, NULL }
#define CONTAINER(name, flags) \
{ #name, test_container_ ## name, (flags), NULL, NULL }
@@ -966,6 +1238,7 @@ struct testcase_t container_tests[] = {
CONTAINER_LEGACY(smartlist_overlap),
CONTAINER_LEGACY(smartlist_digests),
CONTAINER_LEGACY(smartlist_join),
+ CONTAINER_LEGACY(smartlist_pos),
CONTAINER(smartlist_ints_eq, 0),
CONTAINER_LEGACY(bitarray),
CONTAINER_LEGACY(digestset),
@@ -974,6 +1247,9 @@ struct testcase_t container_tests[] = {
CONTAINER_LEGACY(order_functions),
CONTAINER(di_map, 0),
CONTAINER_LEGACY(fp_pair_map),
+ CONTAINER(smartlist_most_frequent, 0),
+ CONTAINER(smartlist_sort_ptrs, 0),
+ CONTAINER(smartlist_strings_eq, 0),
END_OF_TESTCASES
};
diff --git a/src/test/test_controller.c b/src/test/test_controller.c
new file mode 100644
index 0000000000..7f9db4312f
--- /dev/null
+++ b/src/test/test_controller.c
@@ -0,0 +1,163 @@
+/* Copyright (c) 2015-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define CONTROL_PRIVATE
+#include "or.h"
+#include "control.h"
+#include "rendservice.h"
+#include "test.h"
+
+static void
+test_add_onion_helper_keyarg(void *arg)
+{
+ crypto_pk_t *pk = NULL;
+ crypto_pk_t *pk2 = NULL;
+ const char *key_new_alg = NULL;
+ char *key_new_blob = NULL;
+ char *err_msg = NULL;
+ char *encoded = NULL;
+ char *arg_str = NULL;
+
+ (void) arg;
+
+ /* Test explicit RSA1024 key generation. */
+ pk = add_onion_helper_keyarg("NEW:RSA1024", 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(pk);
+ tt_str_op(key_new_alg, OP_EQ, "RSA1024");
+ tt_assert(key_new_blob);
+ tt_assert(!err_msg);
+
+ /* Test "BEST" key generation (Assumes BEST = RSA1024). */
+ crypto_pk_free(pk);
+ tor_free(key_new_blob);
+ pk = add_onion_helper_keyarg("NEW:BEST", 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(pk);
+ tt_str_op(key_new_alg, OP_EQ, "RSA1024");
+ tt_assert(key_new_blob);
+ tt_assert(!err_msg);
+
+ /* Test discarding the private key. */
+ crypto_pk_free(pk);
+ tor_free(key_new_blob);
+ pk = add_onion_helper_keyarg("NEW:BEST", 1, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(pk);
+ tt_assert(!key_new_alg);
+ tt_assert(!key_new_blob);
+ tt_assert(!err_msg);
+
+ /* Test generating a invalid key type. */
+ crypto_pk_free(pk);
+ pk = add_onion_helper_keyarg("NEW:RSA512", 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(!pk);
+ tt_assert(!key_new_alg);
+ tt_assert(!key_new_blob);
+ tt_assert(err_msg);
+
+ /* Test loading a RSA1024 key. */
+ tor_free(err_msg);
+ pk = pk_generate(0);
+ tt_int_op(0, OP_EQ, crypto_pk_base64_encode(pk, &encoded));
+ tor_asprintf(&arg_str, "RSA1024:%s", encoded);
+ pk2 = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(pk2);
+ tt_assert(!key_new_alg);
+ tt_assert(!key_new_blob);
+ tt_assert(!err_msg);
+ tt_assert(crypto_pk_cmp_keys(pk, pk2) == 0);
+
+ /* Test loading a invalid key type. */
+ tor_free(arg_str);
+ crypto_pk_free(pk); pk = NULL;
+ tor_asprintf(&arg_str, "RSA512:%s", encoded);
+ pk = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(!pk);
+ tt_assert(!key_new_alg);
+ tt_assert(!key_new_blob);
+ tt_assert(err_msg);
+
+ /* Test loading a invalid key. */
+ tor_free(arg_str);
+ crypto_pk_free(pk); pk = NULL;
+ tor_free(err_msg);
+ encoded[strlen(encoded)/2] = '\0';
+ tor_asprintf(&arg_str, "RSA1024:%s", encoded);
+ pk = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
+ &err_msg);
+ tt_assert(!pk);
+ tt_assert(!key_new_alg);
+ tt_assert(!key_new_blob);
+ tt_assert(err_msg);
+
+ done:
+ crypto_pk_free(pk);
+ crypto_pk_free(pk2);
+ tor_free(key_new_blob);
+ tor_free(err_msg);
+ tor_free(encoded);
+ tor_free(arg_str);
+}
+
+static void
+test_rend_service_parse_port_config(void *arg)
+{
+ const char *sep = ",";
+ rend_service_port_config_t *cfg = NULL;
+ char *err_msg = NULL;
+
+ (void)arg;
+
+ /* Test "VIRTPORT" only. */
+ cfg = rend_service_parse_port_config("80", sep, &err_msg);
+ tt_assert(cfg);
+ tt_assert(!err_msg);
+
+ /* Test "VIRTPORT,TARGET" (Target is port). */
+ rend_service_port_config_free(cfg);
+ cfg = rend_service_parse_port_config("80,8080", sep, &err_msg);
+ tt_assert(cfg);
+ tt_assert(!err_msg);
+
+ /* Test "VIRTPORT,TARGET" (Target is IPv4:port). */
+ rend_service_port_config_free(cfg);
+ cfg = rend_service_parse_port_config("80,192.0.2.1:8080", sep, &err_msg);
+ tt_assert(cfg);
+ tt_assert(!err_msg);
+
+ /* Test "VIRTPORT,TARGET" (Target is IPv6:port). */
+ rend_service_port_config_free(cfg);
+ cfg = rend_service_parse_port_config("80,[2001:db8::1]:8080", sep, &err_msg);
+ tt_assert(cfg);
+ tt_assert(!err_msg);
+
+ /* XXX: Someone should add tests for AF_UNIX targets if supported. */
+
+ /* Test empty config. */
+ rend_service_port_config_free(cfg);
+ cfg = rend_service_parse_port_config("", sep, &err_msg);
+ tt_assert(!cfg);
+ tt_assert(err_msg);
+
+ /* Test invalid port. */
+ tor_free(err_msg);
+ cfg = rend_service_parse_port_config("90001", sep, &err_msg);
+ tt_assert(!cfg);
+ tt_assert(err_msg);
+
+ done:
+ rend_service_port_config_free(cfg);
+ tor_free(err_msg);
+}
+
+struct testcase_t controller_tests[] = {
+ { "add_onion_helper_keyarg", test_add_onion_helper_keyarg, 0, NULL, NULL },
+ { "rend_service_parse_port_config", test_rend_service_parse_port_config, 0,
+ NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_controller_events.c b/src/test/test_controller_events.c
index b45e97a417..11e1e3dc8f 100644
--- a/src/test/test_controller_events.c
+++ b/src/test/test_controller_events.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define CONNECTION_PRIVATE
@@ -22,7 +22,7 @@ help_test_bucket_note_empty(uint32_t expected_msec_since_midnight,
tvnow.tv_usec = (msec_since_epoch % 1000) * 1000;
connection_buckets_note_empty_ts(&timestamp_var, tokens_before,
tokens_removed, &tvnow);
- tt_int_op(expected_msec_since_midnight, ==, timestamp_var);
+ tt_int_op(expected_msec_since_midnight, OP_EQ, timestamp_var);
done:
;
@@ -57,20 +57,20 @@ test_cntev_bucket_millis_empty(void *arg)
tvnow.tv_usec = 200000;
/* Bucket has not been refilled. */
- tt_int_op(0, ==, bucket_millis_empty(0, 42120, 0, 100, &tvnow));
- tt_int_op(0, ==, bucket_millis_empty(-10, 42120, -10, 100, &tvnow));
+ tt_int_op(0, OP_EQ, bucket_millis_empty(0, 42120, 0, 100, &tvnow));
+ tt_int_op(0, OP_EQ, bucket_millis_empty(-10, 42120, -10, 100, &tvnow));
/* Bucket was not empty. */
- tt_int_op(0, ==, bucket_millis_empty(10, 42120, 20, 100, &tvnow));
+ tt_int_op(0, OP_EQ, bucket_millis_empty(10, 42120, 20, 100, &tvnow));
/* Bucket has been emptied 80 msec ago and has just been refilled. */
- tt_int_op(80, ==, bucket_millis_empty(-20, 42120, -10, 100, &tvnow));
- tt_int_op(80, ==, bucket_millis_empty(-10, 42120, 0, 100, &tvnow));
- tt_int_op(80, ==, bucket_millis_empty(0, 42120, 10, 100, &tvnow));
+ tt_int_op(80, OP_EQ, bucket_millis_empty(-20, 42120, -10, 100, &tvnow));
+ tt_int_op(80, OP_EQ, bucket_millis_empty(-10, 42120, 0, 100, &tvnow));
+ tt_int_op(80, OP_EQ, bucket_millis_empty(0, 42120, 10, 100, &tvnow));
/* Bucket has been emptied 180 msec ago, last refill was 100 msec ago
* which was insufficient to make it positive, so cap msec at 100. */
- tt_int_op(100, ==, bucket_millis_empty(0, 42020, 1, 100, &tvnow));
+ tt_int_op(100, OP_EQ, bucket_millis_empty(0, 42020, 1, 100, &tvnow));
/* 1970-01-02 00:00:00:050000 */
tvnow.tv_sec = 86400;
@@ -78,7 +78,7 @@ test_cntev_bucket_millis_empty(void *arg)
/* Last emptied 30 msec before midnight, tvnow is 50 msec after
* midnight, that's 80 msec in total. */
- tt_int_op(80, ==, bucket_millis_empty(0, 86400000 - 30, 1, 100, &tvnow));
+ tt_int_op(80, OP_EQ, bucket_millis_empty(0, 86400000 - 30, 1, 100, &tvnow));
done:
;
@@ -118,26 +118,26 @@ test_cntev_sum_up_cell_stats(void *arg)
cell_stats = tor_malloc_zero(sizeof(cell_stats_t));
add_testing_cell_stats_entry(circ, CELL_RELAY, 0, 0, 0);
sum_up_cell_stats_by_command(circ, cell_stats);
- tt_u64_op(1, ==, cell_stats->added_cells_appward[CELL_RELAY]);
+ tt_u64_op(1, OP_EQ, cell_stats->added_cells_appward[CELL_RELAY]);
/* A single RELAY cell was added to the exitward queue. */
add_testing_cell_stats_entry(circ, CELL_RELAY, 0, 0, 1);
sum_up_cell_stats_by_command(circ, cell_stats);
- tt_u64_op(1, ==, cell_stats->added_cells_exitward[CELL_RELAY]);
+ tt_u64_op(1, OP_EQ, cell_stats->added_cells_exitward[CELL_RELAY]);
/* A single RELAY cell was removed from the appward queue where it spent
* 20 msec. */
add_testing_cell_stats_entry(circ, CELL_RELAY, 2, 1, 0);
sum_up_cell_stats_by_command(circ, cell_stats);
- tt_u64_op(20, ==, cell_stats->total_time_appward[CELL_RELAY]);
- tt_u64_op(1, ==, cell_stats->removed_cells_appward[CELL_RELAY]);
+ tt_u64_op(20, OP_EQ, cell_stats->total_time_appward[CELL_RELAY]);
+ tt_u64_op(1, OP_EQ, cell_stats->removed_cells_appward[CELL_RELAY]);
/* A single RELAY cell was removed from the exitward queue where it
* spent 30 msec. */
add_testing_cell_stats_entry(circ, CELL_RELAY, 3, 1, 1);
sum_up_cell_stats_by_command(circ, cell_stats);
- tt_u64_op(30, ==, cell_stats->total_time_exitward[CELL_RELAY]);
- tt_u64_op(1, ==, cell_stats->removed_cells_exitward[CELL_RELAY]);
+ tt_u64_op(30, OP_EQ, cell_stats->total_time_exitward[CELL_RELAY]);
+ tt_u64_op(1, OP_EQ, cell_stats->removed_cells_exitward[CELL_RELAY]);
done:
tor_free(cell_stats);
@@ -164,7 +164,7 @@ test_cntev_append_cell_stats(void *arg)
append_cell_stats_by_command(event_parts, key,
include_if_non_zero,
number_to_include);
- tt_int_op(0, ==, smartlist_len(event_parts));
+ tt_int_op(0, OP_EQ, smartlist_len(event_parts));
/* There's a RELAY cell to include, but the corresponding field in
* include_if_non_zero is still zero. */
@@ -172,7 +172,7 @@ test_cntev_append_cell_stats(void *arg)
append_cell_stats_by_command(event_parts, key,
include_if_non_zero,
number_to_include);
- tt_int_op(0, ==, smartlist_len(event_parts));
+ tt_int_op(0, OP_EQ, smartlist_len(event_parts));
/* Now include single RELAY cell. */
include_if_non_zero[CELL_RELAY] = 2;
@@ -180,7 +180,7 @@ test_cntev_append_cell_stats(void *arg)
include_if_non_zero,
number_to_include);
cp = smartlist_pop_last(event_parts);
- tt_str_op("Z=relay:1", ==, cp);
+ tt_str_op("Z=relay:1", OP_EQ, cp);
tor_free(cp);
/* Add four CREATE cells. */
@@ -190,7 +190,7 @@ test_cntev_append_cell_stats(void *arg)
include_if_non_zero,
number_to_include);
cp = smartlist_pop_last(event_parts);
- tt_str_op("Z=create:4,relay:1", ==, cp);
+ tt_str_op("Z=create:4,relay:1", OP_EQ, cp);
done:
tor_free(cp);
@@ -220,14 +220,14 @@ test_cntev_format_cell_stats(void *arg)
/* Origin circuit was completely idle. */
cell_stats = tor_malloc_zero(sizeof(cell_stats_t));
format_cell_stats(&event_string, TO_CIRCUIT(ocirc), cell_stats);
- tt_str_op("ID=2 OutboundQueue=3 OutboundConn=1", ==, event_string);
+ tt_str_op("ID=2 OutboundQueue=3 OutboundConn=1", OP_EQ, event_string);
tor_free(event_string);
/* Origin circuit had 4 RELAY cells added to its exitward queue. */
cell_stats->added_cells_exitward[CELL_RELAY] = 4;
format_cell_stats(&event_string, TO_CIRCUIT(ocirc), cell_stats);
tt_str_op("ID=2 OutboundQueue=3 OutboundConn=1 OutboundAdded=relay:4",
- ==, event_string);
+ OP_EQ, event_string);
tor_free(event_string);
/* Origin circuit also had 5 CREATE2 cells added to its exitward
@@ -235,7 +235,7 @@ test_cntev_format_cell_stats(void *arg)
cell_stats->added_cells_exitward[CELL_CREATE2] = 5;
format_cell_stats(&event_string, TO_CIRCUIT(ocirc), cell_stats);
tt_str_op("ID=2 OutboundQueue=3 OutboundConn=1 OutboundAdded=relay:4,"
- "create2:5", ==, event_string);
+ "create2:5", OP_EQ, event_string);
tor_free(event_string);
/* Origin circuit also had 7 RELAY cells removed from its exitward queue
@@ -245,7 +245,7 @@ test_cntev_format_cell_stats(void *arg)
format_cell_stats(&event_string, TO_CIRCUIT(ocirc), cell_stats);
tt_str_op("ID=2 OutboundQueue=3 OutboundConn=1 OutboundAdded=relay:4,"
"create2:5 OutboundRemoved=relay:7 OutboundTime=relay:6",
- ==, event_string);
+ OP_EQ, event_string);
tor_free(event_string);
p_chan = tor_malloc_zero(sizeof(channel_tls_t));
@@ -265,14 +265,14 @@ test_cntev_format_cell_stats(void *arg)
cell_stats = tor_malloc_zero(sizeof(cell_stats_t));
format_cell_stats(&event_string, TO_CIRCUIT(or_circ), cell_stats);
tt_str_op("InboundQueue=8 InboundConn=2 OutboundQueue=9 OutboundConn=1",
- ==, event_string);
+ OP_EQ, event_string);
tor_free(event_string);
/* OR circuit had 3 RELAY cells added to its appward queue. */
cell_stats->added_cells_appward[CELL_RELAY] = 3;
format_cell_stats(&event_string, TO_CIRCUIT(or_circ), cell_stats);
tt_str_op("InboundQueue=8 InboundConn=2 InboundAdded=relay:3 "
- "OutboundQueue=9 OutboundConn=1", ==, event_string);
+ "OutboundQueue=9 OutboundConn=1", OP_EQ, event_string);
tor_free(event_string);
/* OR circuit had 7 RELAY cells removed from its appward queue which
@@ -282,7 +282,7 @@ test_cntev_format_cell_stats(void *arg)
format_cell_stats(&event_string, TO_CIRCUIT(or_circ), cell_stats);
tt_str_op("InboundQueue=8 InboundConn=2 InboundAdded=relay:3 "
"InboundRemoved=relay:7 InboundTime=relay:6 "
- "OutboundQueue=9 OutboundConn=1", ==, event_string);
+ "OutboundQueue=9 OutboundConn=1", OP_EQ, event_string);
done:
tor_free(cell_stats);
@@ -293,15 +293,114 @@ test_cntev_format_cell_stats(void *arg)
tor_free(n_chan);
}
+static void
+test_cntev_event_mask(void *arg)
+{
+ unsigned int test_event, selected_event;
+ (void)arg;
+
+ /* Check that nothing is interesting when no events are set */
+ control_testing_set_global_event_mask(EVENT_MASK_NONE_);
+
+ /* Check that nothing is interesting between EVENT_MIN_ and EVENT_MAX_ */
+ for (test_event = EVENT_MIN_; test_event <= EVENT_MAX_; test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+
+ /* Check that nothing is interesting outside EVENT_MIN_ to EVENT_MAX_
+ * This will break if control_event_is_interesting() checks its arguments */
+ for (test_event = 0; test_event < EVENT_MIN_; test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ for (test_event = EVENT_MAX_ + 1;
+ test_event < EVENT_CAPACITY_;
+ test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+
+ /* Check that all valid events are interesting when all events are set */
+ control_testing_set_global_event_mask(EVENT_MASK_ALL_);
+
+ /* Check that everything is interesting between EVENT_MIN_ and EVENT_MAX_ */
+ for (test_event = EVENT_MIN_; test_event <= EVENT_MAX_; test_event++)
+ tt_assert(control_event_is_interesting(test_event));
+
+ /* Check that nothing is interesting outside EVENT_MIN_ to EVENT_MAX_
+ * This will break if control_event_is_interesting() checks its arguments */
+ for (test_event = 0; test_event < EVENT_MIN_; test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ for (test_event = EVENT_MAX_ + 1;
+ test_event < EVENT_CAPACITY_;
+ test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+
+ /* Check that only that event is interesting when a single event is set */
+ for (selected_event = EVENT_MIN_;
+ selected_event <= EVENT_MAX_;
+ selected_event++) {
+ control_testing_set_global_event_mask(EVENT_MASK_(selected_event));
+
+ /* Check that only this event is interesting
+ * between EVENT_MIN_ and EVENT_MAX_ */
+ for (test_event = EVENT_MIN_; test_event <= EVENT_MAX_; test_event++) {
+ if (test_event == selected_event) {
+ tt_assert(control_event_is_interesting(test_event));
+ } else {
+ tt_assert(!control_event_is_interesting(test_event));
+ }
+ }
+
+ /* Check that nothing is interesting outside EVENT_MIN_ to EVENT_MAX_
+ * This will break if control_event_is_interesting checks its arguments */
+ for (test_event = 0; test_event < EVENT_MIN_; test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ for (test_event = EVENT_MAX_ + 1;
+ test_event < EVENT_CAPACITY_;
+ test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ }
+
+ /* Check that only that event is not-interesting
+ * when a single event is un-set */
+ for (selected_event = EVENT_MIN_;
+ selected_event <= EVENT_MAX_;
+ selected_event++) {
+ control_testing_set_global_event_mask(
+ EVENT_MASK_ALL_
+ & ~(EVENT_MASK_(selected_event))
+ );
+
+ /* Check that only this event is not-interesting
+ * between EVENT_MIN_ and EVENT_MAX_ */
+ for (test_event = EVENT_MIN_; test_event <= EVENT_MAX_; test_event++) {
+ if (test_event == selected_event) {
+ tt_assert(!control_event_is_interesting(test_event));
+ } else {
+ tt_assert(control_event_is_interesting(test_event));
+ }
+ }
+
+ /* Check that nothing is interesting outside EVENT_MIN_ to EVENT_MAX_
+ * This will break if control_event_is_interesting checks its arguments */
+ for (test_event = 0; test_event < EVENT_MIN_; test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ for (test_event = EVENT_MAX_ + 1;
+ test_event < EVENT_CAPACITY_;
+ test_event++)
+ tt_assert(!control_event_is_interesting(test_event));
+ }
+
+ done:
+ ;
+}
+
#define TEST(name, flags) \
{ #name, test_cntev_ ## name, flags, 0, NULL }
struct testcase_t controller_event_tests[] = {
- TEST(bucket_note_empty, 0),
- TEST(bucket_millis_empty, 0),
- TEST(sum_up_cell_stats, 0),
- TEST(append_cell_stats, 0),
- TEST(format_cell_stats, 0),
+ TEST(bucket_note_empty, TT_FORK),
+ TEST(bucket_millis_empty, TT_FORK),
+ TEST(sum_up_cell_stats, TT_FORK),
+ TEST(append_cell_stats, TT_FORK),
+ TEST(format_cell_stats, TT_FORK),
+ TEST(event_mask, TT_FORK),
END_OF_TESTCASES
};
diff --git a/src/test/test_crypto.c b/src/test/test_crypto.c
index 5d8edb6550..6a95e92733 100644
--- a/src/test/test_crypto.c
+++ b/src/test/test_crypto.c
@@ -1,18 +1,22 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
#define CRYPTO_CURVE25519_PRIVATE
+#define CRYPTO_PRIVATE
#include "or.h"
#include "test.h"
#include "aes.h"
#include "util.h"
#include "siphash.h"
-#ifdef CURVE25519_ENABLED
#include "crypto_curve25519.h"
-#endif
+#include "crypto_ed25519.h"
+#include "ed25519_vectors.inc"
+
+#include <openssl/evp.h>
+#include <openssl/rand.h>
extern const char AUTHORITY_SIGNKEY_3[];
extern const char AUTHORITY_SIGNKEY_A_DIGEST[];
@@ -20,7 +24,7 @@ extern const char AUTHORITY_SIGNKEY_A_DIGEST256[];
/** Run unit tests for Diffie-Hellman functionality. */
static void
-test_crypto_dh(void)
+test_crypto_dh(void *arg)
{
crypto_dh_t *dh1 = crypto_dh_new(DH_TYPE_CIRCUIT);
crypto_dh_t *dh2 = crypto_dh_new(DH_TYPE_CIRCUIT);
@@ -30,24 +34,25 @@ test_crypto_dh(void)
char s2[DH_BYTES];
ssize_t s1len, s2len;
- test_eq(crypto_dh_get_bytes(dh1), DH_BYTES);
- test_eq(crypto_dh_get_bytes(dh2), DH_BYTES);
+ (void)arg;
+ tt_int_op(crypto_dh_get_bytes(dh1),OP_EQ, DH_BYTES);
+ tt_int_op(crypto_dh_get_bytes(dh2),OP_EQ, DH_BYTES);
memset(p1, 0, DH_BYTES);
memset(p2, 0, DH_BYTES);
- test_memeq(p1, p2, DH_BYTES);
- test_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
- test_memneq(p1, p2, DH_BYTES);
- test_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
- test_memneq(p1, p2, DH_BYTES);
+ tt_mem_op(p1,OP_EQ, p2, DH_BYTES);
+ tt_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
+ tt_mem_op(p1,OP_NE, p2, DH_BYTES);
+ tt_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
+ tt_mem_op(p1,OP_NE, p2, DH_BYTES);
memset(s1, 0, DH_BYTES);
memset(s2, 0xFF, DH_BYTES);
s1len = crypto_dh_compute_secret(LOG_WARN, dh1, p2, DH_BYTES, s1, 50);
s2len = crypto_dh_compute_secret(LOG_WARN, dh2, p1, DH_BYTES, s2, 50);
- test_assert(s1len > 0);
- test_eq(s1len, s2len);
- test_memeq(s1, s2, s1len);
+ tt_assert(s1len > 0);
+ tt_int_op(s1len,OP_EQ, s2len);
+ tt_mem_op(s1,OP_EQ, s2, s1len);
{
/* XXXX Now fabricate some bad values and make sure they get caught,
@@ -63,17 +68,18 @@ test_crypto_dh(void)
/** Run unit tests for our random number generation function and its wrappers.
*/
static void
-test_crypto_rng(void)
+test_crypto_rng(void *arg)
{
int i, j, allok;
char data1[100], data2[100];
double d;
/* Try out RNG. */
- test_assert(! crypto_seed_rng(0));
+ (void)arg;
+ tt_assert(! crypto_seed_rng());
crypto_rand(data1, 100);
crypto_rand(data2, 100);
- test_memneq(data1,data2,100);
+ tt_mem_op(data1,OP_NE, data2,100);
allok = 1;
for (i = 0; i < 100; ++i) {
uint64_t big;
@@ -88,8 +94,8 @@ test_crypto_rng(void)
if (big >= 5)
allok = 0;
d = crypto_rand_double();
- test_assert(d >= 0);
- test_assert(d < 1.0);
+ tt_assert(d >= 0);
+ tt_assert(d < 1.0);
host = crypto_random_hostname(3,8,"www.",".onion");
if (strcmpstart(host,"www.") ||
strcmpend(host,".onion") ||
@@ -98,7 +104,63 @@ test_crypto_rng(void)
allok = 0;
tor_free(host);
}
- test_assert(allok);
+ tt_assert(allok);
+ done:
+ ;
+}
+
+static void
+test_crypto_rng_range(void *arg)
+{
+ int got_smallest = 0, got_largest = 0;
+ int i;
+
+ (void)arg;
+ for (i = 0; i < 1000; ++i) {
+ int x = crypto_rand_int_range(5,9);
+ tt_int_op(x, OP_GE, 5);
+ tt_int_op(x, OP_LT, 9);
+ if (x == 5)
+ got_smallest = 1;
+ if (x == 8)
+ got_largest = 1;
+ }
+
+ /* These fail with probability 1/10^603. */
+ tt_assert(got_smallest);
+ tt_assert(got_largest);
+ done:
+ ;
+}
+
+/* Test for rectifying openssl RAND engine. */
+static void
+test_crypto_rng_engine(void *arg)
+{
+ (void)arg;
+ RAND_METHOD dummy_method;
+ memset(&dummy_method, 0, sizeof(dummy_method));
+
+ /* We should be a no-op if we're already on RAND_OpenSSL */
+ tt_int_op(0, ==, crypto_force_rand_ssleay());
+ tt_assert(RAND_get_rand_method() == RAND_OpenSSL());
+
+ /* We should correct the method if it's a dummy. */
+ RAND_set_rand_method(&dummy_method);
+#ifdef LIBRESSL_VERSION_NUMBER
+ /* On libressl, you can't override the RNG. */
+ tt_assert(RAND_get_rand_method() == RAND_OpenSSL());
+ tt_int_op(0, ==, crypto_force_rand_ssleay());
+#else
+ tt_assert(RAND_get_rand_method() == &dummy_method);
+ tt_int_op(1, ==, crypto_force_rand_ssleay());
+#endif
+ tt_assert(RAND_get_rand_method() == RAND_OpenSSL());
+
+ /* Make sure we aren't calling dummy_method */
+ crypto_rand((void *) &dummy_method, sizeof(dummy_method));
+ crypto_rand((void *) &dummy_method, sizeof(dummy_method));
+
done:
;
}
@@ -128,15 +190,15 @@ test_crypto_aes(void *arg)
memset(data2, 0, 1024);
memset(data3, 0, 1024);
env1 = crypto_cipher_new(NULL);
- test_neq_ptr(env1, 0);
+ tt_ptr_op(env1, OP_NE, NULL);
env2 = crypto_cipher_new(crypto_cipher_get_key(env1));
- test_neq_ptr(env2, 0);
+ tt_ptr_op(env2, OP_NE, NULL);
/* Try encrypting 512 chars. */
crypto_cipher_encrypt(env1, data2, data1, 512);
crypto_cipher_decrypt(env2, data3, data2, 512);
- test_memeq(data1, data3, 512);
- test_memneq(data1, data2, 512);
+ tt_mem_op(data1,OP_EQ, data3, 512);
+ tt_mem_op(data1,OP_NE, data2, 512);
/* Now encrypt 1 at a time, and get 1 at a time. */
for (j = 512; j < 560; ++j) {
@@ -145,7 +207,7 @@ test_crypto_aes(void *arg)
for (j = 512; j < 560; ++j) {
crypto_cipher_decrypt(env2, data3+j, data2+j, 1);
}
- test_memeq(data1, data3, 560);
+ tt_mem_op(data1,OP_EQ, data3, 560);
/* Now encrypt 3 at a time, and get 5 at a time. */
for (j = 560; j < 1024-5; j += 3) {
crypto_cipher_encrypt(env1, data2+j, data1+j, 3);
@@ -153,7 +215,7 @@ test_crypto_aes(void *arg)
for (j = 560; j < 1024-5; j += 5) {
crypto_cipher_decrypt(env2, data3+j, data2+j, 5);
}
- test_memeq(data1, data3, 1024-5);
+ tt_mem_op(data1,OP_EQ, data3, 1024-5);
/* Now make sure that when we encrypt with different chunk sizes, we get
the same results. */
crypto_cipher_free(env2);
@@ -161,7 +223,7 @@ test_crypto_aes(void *arg)
memset(data3, 0, 1024);
env2 = crypto_cipher_new(crypto_cipher_get_key(env1));
- test_neq_ptr(env2, NULL);
+ tt_ptr_op(env2, OP_NE, NULL);
for (j = 0; j < 1024-16; j += 17) {
crypto_cipher_encrypt(env2, data3+j, data1+j, 17);
}
@@ -170,7 +232,7 @@ test_crypto_aes(void *arg)
printf("%d: %d\t%d\n", j, (int) data2[j], (int) data3[j]);
}
}
- test_memeq(data2, data3, 1024-16);
+ tt_mem_op(data2,OP_EQ, data3, 1024-16);
crypto_cipher_free(env1);
env1 = NULL;
crypto_cipher_free(env2);
@@ -237,7 +299,7 @@ test_crypto_aes(void *arg)
"\xff\xff\xff\xff\xff\xff\xff\xff"
"\xff\xff\xff\xff\xff\xff\xff\xff");
crypto_cipher_crypt_inplace(env1, data2, 64);
- test_assert(tor_mem_is_zero(data2, 64));
+ tt_assert(tor_mem_is_zero(data2, 64));
done:
tor_free(mem_op_hex_tmp);
@@ -252,38 +314,47 @@ test_crypto_aes(void *arg)
/** Run unit tests for our SHA-1 functionality */
static void
-test_crypto_sha(void)
+test_crypto_sha(void *arg)
{
crypto_digest_t *d1 = NULL, *d2 = NULL;
int i;
- char key[160];
- char digest[32];
- char data[50];
- char d_out1[DIGEST_LEN], d_out2[DIGEST256_LEN];
+#define RFC_4231_MAX_KEY_SIZE 131
+ char key[RFC_4231_MAX_KEY_SIZE];
+ char digest[DIGEST256_LEN];
+ char data[DIGEST512_LEN];
+ char d_out1[DIGEST512_LEN], d_out2[DIGEST512_LEN];
char *mem_op_hex_tmp=NULL;
/* Test SHA-1 with a test vector from the specification. */
+ (void)arg;
i = crypto_digest(data, "abc", 3);
test_memeq_hex(data, "A9993E364706816ABA3E25717850C26C9CD0D89D");
- tt_int_op(i, ==, 0);
+ tt_int_op(i, OP_EQ, 0);
/* Test SHA-256 with a test vector from the specification. */
i = crypto_digest256(data, "abc", 3, DIGEST_SHA256);
test_memeq_hex(data, "BA7816BF8F01CFEA414140DE5DAE2223B00361A3"
"96177A9CB410FF61F20015AD");
- tt_int_op(i, ==, 0);
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Test SHA-512 with a test vector from the specification. */
+ i = crypto_digest512(data, "abc", 3, DIGEST_SHA512);
+ test_memeq_hex(data, "ddaf35a193617abacc417349ae20413112e6fa4e89a97"
+ "ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3"
+ "feebbd454d4423643ce80e2a9ac94fa54ca49f");
+ tt_int_op(i, OP_EQ, 0);
/* Test HMAC-SHA256 with test cases from wikipedia and RFC 4231 */
/* Case empty (wikipedia) */
crypto_hmac_sha256(digest, "", 0, "", 0);
- test_streq(hex_str(digest, 32),
+ tt_str_op(hex_str(digest, 32),OP_EQ,
"B613679A0814D9EC772F95D778C35FC5FF1697C493715653C6C712144292C5AD");
/* Case quick-brown (wikipedia) */
crypto_hmac_sha256(digest, "key", 3,
"The quick brown fox jumps over the lazy dog", 43);
- test_streq(hex_str(digest, 32),
+ tt_str_op(hex_str(digest, 32),OP_EQ,
"F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8");
/* "Test Case 1" from RFC 4231 */
@@ -344,43 +415,64 @@ test_crypto_sha(void)
/* Incremental digest code. */
d1 = crypto_digest_new();
- test_assert(d1);
+ tt_assert(d1);
crypto_digest_add_bytes(d1, "abcdef", 6);
d2 = crypto_digest_dup(d1);
- test_assert(d2);
+ tt_assert(d2);
crypto_digest_add_bytes(d2, "ghijkl", 6);
- crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
+ crypto_digest_get_digest(d2, d_out1, DIGEST_LEN);
crypto_digest(d_out2, "abcdefghijkl", 12);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST_LEN);
crypto_digest_assign(d2, d1);
crypto_digest_add_bytes(d2, "mno", 3);
- crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
+ crypto_digest_get_digest(d2, d_out1, DIGEST_LEN);
crypto_digest(d_out2, "abcdefmno", 9);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
- crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST_LEN);
+ crypto_digest_get_digest(d1, d_out1, DIGEST_LEN);
crypto_digest(d_out2, "abcdef", 6);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST_LEN);
crypto_digest_free(d1);
crypto_digest_free(d2);
/* Incremental digest code with sha256 */
d1 = crypto_digest256_new(DIGEST_SHA256);
- test_assert(d1);
+ tt_assert(d1);
crypto_digest_add_bytes(d1, "abcdef", 6);
d2 = crypto_digest_dup(d1);
- test_assert(d2);
+ tt_assert(d2);
crypto_digest_add_bytes(d2, "ghijkl", 6);
- crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
+ crypto_digest_get_digest(d2, d_out1, DIGEST256_LEN);
crypto_digest256(d_out2, "abcdefghijkl", 12, DIGEST_SHA256);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
crypto_digest_assign(d2, d1);
crypto_digest_add_bytes(d2, "mno", 3);
- crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
+ crypto_digest_get_digest(d2, d_out1, DIGEST256_LEN);
crypto_digest256(d_out2, "abcdefmno", 9, DIGEST_SHA256);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
- crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
+ crypto_digest_get_digest(d1, d_out1, DIGEST256_LEN);
crypto_digest256(d_out2, "abcdef", 6, DIGEST_SHA256);
- test_memeq(d_out1, d_out2, DIGEST_LEN);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
+ crypto_digest_free(d1);
+ crypto_digest_free(d2);
+
+ /* Incremental digest code with sha512 */
+ d1 = crypto_digest512_new(DIGEST_SHA512);
+ tt_assert(d1);
+ crypto_digest_add_bytes(d1, "abcdef", 6);
+ d2 = crypto_digest_dup(d1);
+ tt_assert(d2);
+ crypto_digest_add_bytes(d2, "ghijkl", 6);
+ crypto_digest_get_digest(d2, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdefghijkl", 12, DIGEST_SHA512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
+ crypto_digest_assign(d2, d1);
+ crypto_digest_add_bytes(d2, "mno", 3);
+ crypto_digest_get_digest(d2, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdefmno", 9, DIGEST_SHA512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
+ crypto_digest_get_digest(d1, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdef", 6, DIGEST_SHA512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
done:
if (d1)
@@ -390,9 +482,397 @@ test_crypto_sha(void)
tor_free(mem_op_hex_tmp);
}
+static void
+test_crypto_sha3(void *arg)
+{
+ crypto_digest_t *d1 = NULL, *d2 = NULL;
+ int i;
+ char data[DIGEST512_LEN];
+ char d_out1[DIGEST512_LEN], d_out2[DIGEST512_LEN];
+ char *mem_op_hex_tmp=NULL;
+ char *large = NULL;
+
+ (void)arg;
+
+ /* Test SHA3-[256,512] with a test vectors from the Keccak Code Package.
+ *
+ * NB: The code package's test vectors have length expressed in bits.
+ */
+
+ /* Len = 8, Msg = CC */
+ const uint8_t keccak_kat_msg8[] = { 0xcc };
+ i = crypto_digest256(data, (const char*)keccak_kat_msg8, 1, DIGEST_SHA3_256);
+ test_memeq_hex(data, "677035391CD3701293D385F037BA3279"
+ "6252BB7CE180B00B582DD9B20AAAD7F0");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, (const char*)keccak_kat_msg8, 1, DIGEST_SHA3_512);
+ test_memeq_hex(data, "3939FCC8B57B63612542DA31A834E5DC"
+ "C36E2EE0F652AC72E02624FA2E5ADEEC"
+ "C7DD6BB3580224B4D6138706FC6E8059"
+ "7B528051230B00621CC2B22999EAA205");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 24, Msg = 1F877C */
+ const uint8_t keccak_kat_msg24[] = { 0x1f, 0x87, 0x7c };
+ i = crypto_digest256(data, (const char*)keccak_kat_msg24, 3,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "BC22345E4BD3F792A341CF18AC0789F1"
+ "C9C966712A501B19D1B6632CCD408EC5");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, (const char*)keccak_kat_msg24, 3,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "CB20DCF54955F8091111688BECCEF48C"
+ "1A2F0D0608C3A575163751F002DB30F4"
+ "0F2F671834B22D208591CFAF1F5ECFE4"
+ "3C49863A53B3225BDFD7C6591BA7658B");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1080, Msg = B771D5CEF... ...C35AC81B5 (SHA3-256 rate - 1) */
+ const uint8_t keccak_kat_msg1080[] = {
+ 0xB7, 0x71, 0xD5, 0xCE, 0xF5, 0xD1, 0xA4, 0x1A, 0x93, 0xD1,
+ 0x56, 0x43, 0xD7, 0x18, 0x1D, 0x2A, 0x2E, 0xF0, 0xA8, 0xE8,
+ 0x4D, 0x91, 0x81, 0x2F, 0x20, 0xED, 0x21, 0xF1, 0x47, 0xBE,
+ 0xF7, 0x32, 0xBF, 0x3A, 0x60, 0xEF, 0x40, 0x67, 0xC3, 0x73,
+ 0x4B, 0x85, 0xBC, 0x8C, 0xD4, 0x71, 0x78, 0x0F, 0x10, 0xDC,
+ 0x9E, 0x82, 0x91, 0xB5, 0x83, 0x39, 0xA6, 0x77, 0xB9, 0x60,
+ 0x21, 0x8F, 0x71, 0xE7, 0x93, 0xF2, 0x79, 0x7A, 0xEA, 0x34,
+ 0x94, 0x06, 0x51, 0x28, 0x29, 0x06, 0x5D, 0x37, 0xBB, 0x55,
+ 0xEA, 0x79, 0x6F, 0xA4, 0xF5, 0x6F, 0xD8, 0x89, 0x6B, 0x49,
+ 0xB2, 0xCD, 0x19, 0xB4, 0x32, 0x15, 0xAD, 0x96, 0x7C, 0x71,
+ 0x2B, 0x24, 0xE5, 0x03, 0x2D, 0x06, 0x52, 0x32, 0xE0, 0x2C,
+ 0x12, 0x74, 0x09, 0xD2, 0xED, 0x41, 0x46, 0xB9, 0xD7, 0x5D,
+ 0x76, 0x3D, 0x52, 0xDB, 0x98, 0xD9, 0x49, 0xD3, 0xB0, 0xFE,
+ 0xD6, 0xA8, 0x05, 0x2F, 0xBB,
+ };
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1080, 135,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "A19EEE92BB2097B64E823D597798AA18"
+ "BE9B7C736B8059ABFD6779AC35AC81B5");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1080, 135,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "7575A1FB4FC9A8F9C0466BD5FCA496D1"
+ "CB78696773A212A5F62D02D14E3259D1"
+ "92A87EBA4407DD83893527331407B6DA"
+ "DAAD920DBC46489B677493CE5F20B595");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1088, Msg = B32D95B0... ...8E380C04 (SHA3-256 rate) */
+ const uint8_t keccak_kat_msg1088[] = {
+ 0xB3, 0x2D, 0x95, 0xB0, 0xB9, 0xAA, 0xD2, 0xA8, 0x81, 0x6D,
+ 0xE6, 0xD0, 0x6D, 0x1F, 0x86, 0x00, 0x85, 0x05, 0xBD, 0x8C,
+ 0x14, 0x12, 0x4F, 0x6E, 0x9A, 0x16, 0x3B, 0x5A, 0x2A, 0xDE,
+ 0x55, 0xF8, 0x35, 0xD0, 0xEC, 0x38, 0x80, 0xEF, 0x50, 0x70,
+ 0x0D, 0x3B, 0x25, 0xE4, 0x2C, 0xC0, 0xAF, 0x05, 0x0C, 0xCD,
+ 0x1B, 0xE5, 0xE5, 0x55, 0xB2, 0x30, 0x87, 0xE0, 0x4D, 0x7B,
+ 0xF9, 0x81, 0x36, 0x22, 0x78, 0x0C, 0x73, 0x13, 0xA1, 0x95,
+ 0x4F, 0x87, 0x40, 0xB6, 0xEE, 0x2D, 0x3F, 0x71, 0xF7, 0x68,
+ 0xDD, 0x41, 0x7F, 0x52, 0x04, 0x82, 0xBD, 0x3A, 0x08, 0xD4,
+ 0xF2, 0x22, 0xB4, 0xEE, 0x9D, 0xBD, 0x01, 0x54, 0x47, 0xB3,
+ 0x35, 0x07, 0xDD, 0x50, 0xF3, 0xAB, 0x42, 0x47, 0xC5, 0xDE,
+ 0x9A, 0x8A, 0xBD, 0x62, 0xA8, 0xDE, 0xCE, 0xA0, 0x1E, 0x3B,
+ 0x87, 0xC8, 0xB9, 0x27, 0xF5, 0xB0, 0x8B, 0xEB, 0x37, 0x67,
+ 0x4C, 0x6F, 0x8E, 0x38, 0x0C, 0x04,
+ };
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1088, 136,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "DF673F4105379FF6B755EEAB20CEB0DC"
+ "77B5286364FE16C59CC8A907AFF07732");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1088, 136,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "2E293765022D48996CE8EFF0BE54E87E"
+ "FB94A14C72DE5ACD10D0EB5ECE029CAD"
+ "FA3BA17A40B2FFA2163991B17786E51C"
+ "ABA79E5E0FFD34CF085E2A098BE8BACB");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1096, Msg = 04410E310... ...601016A0D (SHA3-256 rate + 1) */
+ const uint8_t keccak_kat_msg1096[] = {
+ 0x04, 0x41, 0x0E, 0x31, 0x08, 0x2A, 0x47, 0x58, 0x4B, 0x40,
+ 0x6F, 0x05, 0x13, 0x98, 0xA6, 0xAB, 0xE7, 0x4E, 0x4D, 0xA5,
+ 0x9B, 0xB6, 0xF8, 0x5E, 0x6B, 0x49, 0xE8, 0xA1, 0xF7, 0xF2,
+ 0xCA, 0x00, 0xDF, 0xBA, 0x54, 0x62, 0xC2, 0xCD, 0x2B, 0xFD,
+ 0xE8, 0xB6, 0x4F, 0xB2, 0x1D, 0x70, 0xC0, 0x83, 0xF1, 0x13,
+ 0x18, 0xB5, 0x6A, 0x52, 0xD0, 0x3B, 0x81, 0xCA, 0xC5, 0xEE,
+ 0xC2, 0x9E, 0xB3, 0x1B, 0xD0, 0x07, 0x8B, 0x61, 0x56, 0x78,
+ 0x6D, 0xA3, 0xD6, 0xD8, 0xC3, 0x30, 0x98, 0xC5, 0xC4, 0x7B,
+ 0xB6, 0x7A, 0xC6, 0x4D, 0xB1, 0x41, 0x65, 0xAF, 0x65, 0xB4,
+ 0x45, 0x44, 0xD8, 0x06, 0xDD, 0xE5, 0xF4, 0x87, 0xD5, 0x37,
+ 0x3C, 0x7F, 0x97, 0x92, 0xC2, 0x99, 0xE9, 0x68, 0x6B, 0x7E,
+ 0x58, 0x21, 0xE7, 0xC8, 0xE2, 0x45, 0x83, 0x15, 0xB9, 0x96,
+ 0xB5, 0x67, 0x7D, 0x92, 0x6D, 0xAC, 0x57, 0xB3, 0xF2, 0x2D,
+ 0xA8, 0x73, 0xC6, 0x01, 0x01, 0x6A, 0x0D,
+ };
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1096, 137,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "D52432CF3B6B4B949AA848E058DCD62D"
+ "735E0177279222E7AC0AF8504762FAA0");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1096, 137,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "BE8E14B6757FFE53C9B75F6DDE9A7B6C"
+ "40474041DE83D4A60645A826D7AF1ABE"
+ "1EEFCB7B74B62CA6A514E5F2697D585B"
+ "FECECE12931BBE1D4ED7EBF7B0BE660E");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1144, Msg = EA40E83C... ...66DFAFEC (SHA3-512 rate *2 - 1) */
+ const uint8_t keccak_kat_msg1144[] = {
+ 0xEA, 0x40, 0xE8, 0x3C, 0xB1, 0x8B, 0x3A, 0x24, 0x2C, 0x1E,
+ 0xCC, 0x6C, 0xCD, 0x0B, 0x78, 0x53, 0xA4, 0x39, 0xDA, 0xB2,
+ 0xC5, 0x69, 0xCF, 0xC6, 0xDC, 0x38, 0xA1, 0x9F, 0x5C, 0x90,
+ 0xAC, 0xBF, 0x76, 0xAE, 0xF9, 0xEA, 0x37, 0x42, 0xFF, 0x3B,
+ 0x54, 0xEF, 0x7D, 0x36, 0xEB, 0x7C, 0xE4, 0xFF, 0x1C, 0x9A,
+ 0xB3, 0xBC, 0x11, 0x9C, 0xFF, 0x6B, 0xE9, 0x3C, 0x03, 0xE2,
+ 0x08, 0x78, 0x33, 0x35, 0xC0, 0xAB, 0x81, 0x37, 0xBE, 0x5B,
+ 0x10, 0xCD, 0xC6, 0x6F, 0xF3, 0xF8, 0x9A, 0x1B, 0xDD, 0xC6,
+ 0xA1, 0xEE, 0xD7, 0x4F, 0x50, 0x4C, 0xBE, 0x72, 0x90, 0x69,
+ 0x0B, 0xB2, 0x95, 0xA8, 0x72, 0xB9, 0xE3, 0xFE, 0x2C, 0xEE,
+ 0x9E, 0x6C, 0x67, 0xC4, 0x1D, 0xB8, 0xEF, 0xD7, 0xD8, 0x63,
+ 0xCF, 0x10, 0xF8, 0x40, 0xFE, 0x61, 0x8E, 0x79, 0x36, 0xDA,
+ 0x3D, 0xCA, 0x5C, 0xA6, 0xDF, 0x93, 0x3F, 0x24, 0xF6, 0x95,
+ 0x4B, 0xA0, 0x80, 0x1A, 0x12, 0x94, 0xCD, 0x8D, 0x7E, 0x66,
+ 0xDF, 0xAF, 0xEC,
+ };
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1144, 143,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "3A8E938C45F3F177991296B24565D9A6"
+ "605516615D96A062C8BE53A0D6C5A648"
+ "7BE35D2A8F3CF6620D0C2DBA2C560D68"
+ "295F284BE7F82F3B92919033C9CE5D80");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1144, 143,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "E58A947E98D6DD7E932D2FE02D9992E6"
+ "118C0C2C606BDCDA06E7943D2C95E0E5");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1152, Msg = 157D5B7E... ...79EE00C63 (SHA3-512 rate * 2) */
+ const uint8_t keccak_kat_msg1152[] = {
+ 0x15, 0x7D, 0x5B, 0x7E, 0x45, 0x07, 0xF6, 0x6D, 0x9A, 0x26,
+ 0x74, 0x76, 0xD3, 0x38, 0x31, 0xE7, 0xBB, 0x76, 0x8D, 0x4D,
+ 0x04, 0xCC, 0x34, 0x38, 0xDA, 0x12, 0xF9, 0x01, 0x02, 0x63,
+ 0xEA, 0x5F, 0xCA, 0xFB, 0xDE, 0x25, 0x79, 0xDB, 0x2F, 0x6B,
+ 0x58, 0xF9, 0x11, 0xD5, 0x93, 0xD5, 0xF7, 0x9F, 0xB0, 0x5F,
+ 0xE3, 0x59, 0x6E, 0x3F, 0xA8, 0x0F, 0xF2, 0xF7, 0x61, 0xD1,
+ 0xB0, 0xE5, 0x70, 0x80, 0x05, 0x5C, 0x11, 0x8C, 0x53, 0xE5,
+ 0x3C, 0xDB, 0x63, 0x05, 0x52, 0x61, 0xD7, 0xC9, 0xB2, 0xB3,
+ 0x9B, 0xD9, 0x0A, 0xCC, 0x32, 0x52, 0x0C, 0xBB, 0xDB, 0xDA,
+ 0x2C, 0x4F, 0xD8, 0x85, 0x6D, 0xBC, 0xEE, 0x17, 0x31, 0x32,
+ 0xA2, 0x67, 0x91, 0x98, 0xDA, 0xF8, 0x30, 0x07, 0xA9, 0xB5,
+ 0xC5, 0x15, 0x11, 0xAE, 0x49, 0x76, 0x6C, 0x79, 0x2A, 0x29,
+ 0x52, 0x03, 0x88, 0x44, 0x4E, 0xBE, 0xFE, 0x28, 0x25, 0x6F,
+ 0xB3, 0x3D, 0x42, 0x60, 0x43, 0x9C, 0xBA, 0x73, 0xA9, 0x47,
+ 0x9E, 0xE0, 0x0C, 0x63,
+ };
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1152, 144,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "FE45289874879720CE2A844AE34BB735"
+ "22775DCB6019DCD22B8885994672A088"
+ "9C69E8115C641DC8B83E39F7311815A1"
+ "64DC46E0BA2FCA344D86D4BC2EF2532C");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1152, 144,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "A936FB9AF87FB67857B3EAD5C76226AD"
+ "84DA47678F3C2FFE5A39FDB5F7E63FFB");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Len = 1160, Msg = 836B34B5... ...11044C53 (SHA3-512 rate * 2 + 1) */
+ const uint8_t keccak_kat_msg1160[] = {
+ 0x83, 0x6B, 0x34, 0xB5, 0x15, 0x47, 0x6F, 0x61, 0x3F, 0xE4,
+ 0x47, 0xA4, 0xE0, 0xC3, 0xF3, 0xB8, 0xF2, 0x09, 0x10, 0xAC,
+ 0x89, 0xA3, 0x97, 0x70, 0x55, 0xC9, 0x60, 0xD2, 0xD5, 0xD2,
+ 0xB7, 0x2B, 0xD8, 0xAC, 0xC7, 0x15, 0xA9, 0x03, 0x53, 0x21,
+ 0xB8, 0x67, 0x03, 0xA4, 0x11, 0xDD, 0xE0, 0x46, 0x6D, 0x58,
+ 0xA5, 0x97, 0x69, 0x67, 0x2A, 0xA6, 0x0A, 0xD5, 0x87, 0xB8,
+ 0x48, 0x1D, 0xE4, 0xBB, 0xA5, 0x52, 0xA1, 0x64, 0x57, 0x79,
+ 0x78, 0x95, 0x01, 0xEC, 0x53, 0xD5, 0x40, 0xB9, 0x04, 0x82,
+ 0x1F, 0x32, 0xB0, 0xBD, 0x18, 0x55, 0xB0, 0x4E, 0x48, 0x48,
+ 0xF9, 0xF8, 0xCF, 0xE9, 0xEB, 0xD8, 0x91, 0x1B, 0xE9, 0x57,
+ 0x81, 0xA7, 0x59, 0xD7, 0xAD, 0x97, 0x24, 0xA7, 0x10, 0x2D,
+ 0xBE, 0x57, 0x67, 0x76, 0xB7, 0xC6, 0x32, 0xBC, 0x39, 0xB9,
+ 0xB5, 0xE1, 0x90, 0x57, 0xE2, 0x26, 0x55, 0x2A, 0x59, 0x94,
+ 0xC1, 0xDB, 0xB3, 0xB5, 0xC7, 0x87, 0x1A, 0x11, 0xF5, 0x53,
+ 0x70, 0x11, 0x04, 0x4C, 0x53,
+ };
+ i = crypto_digest512(data, (const char*)keccak_kat_msg1160, 145,
+ DIGEST_SHA3_512);
+ test_memeq_hex(data, "AFF61C6E11B98E55AC213B1A0BC7DE04"
+ "05221AC5EFB1229842E4614F4A029C9B"
+ "D14A0ED7FD99AF3681429F3F309FDB53"
+ "166AA9A3CD9F1F1223D04B4A9015E94A");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest256(data, (const char*)keccak_kat_msg1160, 145,
+ DIGEST_SHA3_256);
+ test_memeq_hex(data, "3A654B88F88086C2751EDAE6D3924814"
+ "3CF6235C6B0B7969342C45A35194B67E");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* SHA3-[256,512] Empty case (wikipedia) */
+ i = crypto_digest256(data, "", 0, DIGEST_SHA3_256);
+ test_memeq_hex(data, "a7ffc6f8bf1ed76651c14756a061d662"
+ "f580ff4de43b49fa82d80a4b80f8434a");
+ tt_int_op(i, OP_EQ, 0);
+ i = crypto_digest512(data, "", 0, DIGEST_SHA3_512);
+ test_memeq_hex(data, "a69f73cca23a9ac5c8b567dc185a756e"
+ "97c982164fe25859e0d1dcc1475c80a6"
+ "15b2123af1f5f94c11e3e9402c3ac558"
+ "f500199d95b6d3e301758586281dcd26");
+ tt_int_op(i, OP_EQ, 0);
+
+ /* Incremental digest code with SHA3-256 */
+ d1 = crypto_digest256_new(DIGEST_SHA3_256);
+ tt_assert(d1);
+ crypto_digest_add_bytes(d1, "abcdef", 6);
+ d2 = crypto_digest_dup(d1);
+ tt_assert(d2);
+ crypto_digest_add_bytes(d2, "ghijkl", 6);
+ crypto_digest_get_digest(d2, d_out1, DIGEST256_LEN);
+ crypto_digest256(d_out2, "abcdefghijkl", 12, DIGEST_SHA3_256);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
+ crypto_digest_assign(d2, d1);
+ crypto_digest_add_bytes(d2, "mno", 3);
+ crypto_digest_get_digest(d2, d_out1, DIGEST256_LEN);
+ crypto_digest256(d_out2, "abcdefmno", 9, DIGEST_SHA3_256);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
+ crypto_digest_get_digest(d1, d_out1, DIGEST256_LEN);
+ crypto_digest256(d_out2, "abcdef", 6, DIGEST_SHA3_256);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST256_LEN);
+ crypto_digest_free(d1);
+ crypto_digest_free(d2);
+
+ /* Incremental digest code with SHA3-512 */
+ d1 = crypto_digest512_new(DIGEST_SHA3_512);
+ tt_assert(d1);
+ crypto_digest_add_bytes(d1, "abcdef", 6);
+ d2 = crypto_digest_dup(d1);
+ tt_assert(d2);
+ crypto_digest_add_bytes(d2, "ghijkl", 6);
+ crypto_digest_get_digest(d2, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdefghijkl", 12, DIGEST_SHA3_512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
+ crypto_digest_assign(d2, d1);
+ crypto_digest_add_bytes(d2, "mno", 3);
+ crypto_digest_get_digest(d2, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdefmno", 9, DIGEST_SHA3_512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
+ crypto_digest_get_digest(d1, d_out1, DIGEST512_LEN);
+ crypto_digest512(d_out2, "abcdef", 6, DIGEST_SHA3_512);
+ tt_mem_op(d_out1,OP_EQ, d_out2, DIGEST512_LEN);
+ crypto_digest_free(d1);
+
+ /* Attempt to exercise the incremental hashing code by creating a randomized
+ * 100 KiB buffer, and hashing rand[1, 5 * Rate] bytes at a time. SHA3-512
+ * is used because it has a lowest rate of the family (the code is common,
+ * but the slower rate exercises more of it).
+ */
+ const size_t bufsz = 100 * 1024;
+ size_t j = 0;
+ large = tor_malloc(bufsz);
+ crypto_rand(large, bufsz);
+ d1 = crypto_digest512_new(DIGEST_SHA3_512); /* Running digest. */
+ while (j < bufsz) {
+ /* Pick how much data to add to the running digest. */
+ size_t incr = (size_t)crypto_rand_int_range(1, 72 * 5);
+ incr = MIN(bufsz - j, incr);
+
+ /* Add the data, and calculate the hash. */
+ crypto_digest_add_bytes(d1, large + j, incr);
+ crypto_digest_get_digest(d1, d_out1, DIGEST512_LEN);
+
+ /* One-shot hash the buffer up to the data that was just added,
+ * and ensure that the values match up.
+ *
+ * XXX/yawning: If this actually fails, it'll be rather difficult to
+ * reproduce. Improvements welcome.
+ */
+ i = crypto_digest512(d_out2, large, j + incr, DIGEST_SHA3_512);
+ tt_int_op(i, OP_EQ, 0);
+ tt_mem_op(d_out1, OP_EQ, d_out2, DIGEST512_LEN);
+
+ j += incr;
+ }
+
+ done:
+ if (d1)
+ crypto_digest_free(d1);
+ if (d2)
+ crypto_digest_free(d2);
+ tor_free(large);
+ tor_free(mem_op_hex_tmp);
+}
+
+/** Run unit tests for our XOF. */
+static void
+test_crypto_sha3_xof(void *arg)
+{
+ uint8_t msg[255];
+ uint8_t out[512];
+ crypto_xof_t *xof;
+ char *mem_op_hex_tmp=NULL;
+
+ (void)arg;
+
+ /* SHAKE256 test vector (Len = 2040) from the Keccak Code Package. */
+ base16_decode((char *)msg, 255,
+ "3A3A819C48EFDE2AD914FBF00E18AB6BC4F14513AB27D0C178A188B61431"
+ "E7F5623CB66B23346775D386B50E982C493ADBBFC54B9A3CD383382336A1"
+ "A0B2150A15358F336D03AE18F666C7573D55C4FD181C29E6CCFDE63EA35F"
+ "0ADF5885CFC0A3D84A2B2E4DD24496DB789E663170CEF74798AA1BBCD457"
+ "4EA0BBA40489D764B2F83AADC66B148B4A0CD95246C127D5871C4F114186"
+ "90A5DDF01246A0C80A43C70088B6183639DCFDA4125BD113A8F49EE23ED3"
+ "06FAAC576C3FB0C1E256671D817FC2534A52F5B439F72E424DE376F4C565"
+ "CCA82307DD9EF76DA5B7C4EB7E085172E328807C02D011FFBF33785378D7"
+ "9DC266F6A5BE6BB0E4A92ECEEBAEB1", 510);
+ const char *squeezed_hex =
+ "8A5199B4A7E133E264A86202720655894D48CFF344A928CF8347F48379CE"
+ "F347DFC5BCFFAB99B27B1F89AA2735E23D30088FFA03B9EDB02B9635470A"
+ "B9F1038985D55F9CA774572DD006470EA65145469609F9FA0831BF1FFD84"
+ "2DC24ACADE27BD9816E3B5BF2876CB112232A0EB4475F1DFF9F5C713D9FF"
+ "D4CCB89AE5607FE35731DF06317949EEF646E9591CF3BE53ADD6B7DD2B60"
+ "96E2B3FB06E662EC8B2D77422DAAD9463CD155204ACDBD38E319613F39F9"
+ "9B6DFB35CA9365160066DB19835888C2241FF9A731A4ACBB5663727AAC34"
+ "A401247FBAA7499E7D5EE5B69D31025E63D04C35C798BCA1262D5673A9CF"
+ "0930B5AD89BD485599DC184528DA4790F088EBD170B635D9581632D2FF90"
+ "DB79665CED430089AF13C9F21F6D443A818064F17AEC9E9C5457001FA8DC"
+ "6AFBADBE3138F388D89D0E6F22F66671255B210754ED63D81DCE75CE8F18"
+ "9B534E6D6B3539AA51E837C42DF9DF59C71E6171CD4902FE1BDC73FB1775"
+ "B5C754A1ED4EA7F3105FC543EE0418DAD256F3F6118EA77114A16C15355B"
+ "42877A1DB2A7DF0E155AE1D8670ABCEC3450F4E2EEC9838F895423EF63D2"
+ "61138BAAF5D9F104CB5A957AEA06C0B9B8C78B0D441796DC0350DDEABB78"
+ "A33B6F1F9E68EDE3D1805C7B7E2CFD54E0FAD62F0D8CA67A775DC4546AF9"
+ "096F2EDB221DB42843D65327861282DC946A0BA01A11863AB2D1DFD16E39"
+ "73D4";
+
+ /* Test oneshot absorb/squeeze. */
+ xof = crypto_xof_new();
+ tt_assert(xof);
+ crypto_xof_add_bytes(xof, msg, sizeof(msg));
+ crypto_xof_squeeze_bytes(xof, out, sizeof(out));
+ test_memeq_hex(out, squeezed_hex);
+ crypto_xof_free(xof);
+ memset(out, 0, sizeof(out));
+
+ /* Test incremental absorb/squeeze. */
+ xof = crypto_xof_new();
+ tt_assert(xof);
+ for (size_t i = 0; i < sizeof(msg); i++)
+ crypto_xof_add_bytes(xof, msg + i, 1);
+ for (size_t i = 0; i < sizeof(out); i++)
+ crypto_xof_squeeze_bytes(xof, out + i, 1);
+ test_memeq_hex(out, squeezed_hex);
+
+ done:
+ if (xof)
+ crypto_xof_free(xof);
+ tor_free(mem_op_hex_tmp);
+}
+
/** Run unit tests for our public key crypto functions */
static void
-test_crypto_pk(void)
+test_crypto_pk(void *arg)
{
crypto_pk_t *pk1 = NULL, *pk2 = NULL;
char *encoded = NULL;
@@ -401,74 +881,83 @@ test_crypto_pk(void)
int i, len;
/* Public-key ciphers */
+ (void)arg;
pk1 = pk_generate(0);
pk2 = crypto_pk_new();
- test_assert(pk1 && pk2);
- test_assert(! crypto_pk_write_public_key_to_string(pk1, &encoded, &size));
- test_assert(! crypto_pk_read_public_key_from_string(pk2, encoded, size));
- test_eq(0, crypto_pk_cmp_keys(pk1, pk2));
+ tt_assert(pk1 && pk2);
+ tt_assert(! crypto_pk_write_public_key_to_string(pk1, &encoded, &size));
+ tt_assert(! crypto_pk_read_public_key_from_string(pk2, encoded, size));
+ tt_int_op(0,OP_EQ, crypto_pk_cmp_keys(pk1, pk2));
/* comparison between keys and NULL */
- tt_int_op(crypto_pk_cmp_keys(NULL, pk1), <, 0);
- tt_int_op(crypto_pk_cmp_keys(NULL, NULL), ==, 0);
- tt_int_op(crypto_pk_cmp_keys(pk1, NULL), >, 0);
+ tt_int_op(crypto_pk_cmp_keys(NULL, pk1), OP_LT, 0);
+ tt_int_op(crypto_pk_cmp_keys(NULL, NULL), OP_EQ, 0);
+ tt_int_op(crypto_pk_cmp_keys(pk1, NULL), OP_GT, 0);
- test_eq(128, crypto_pk_keysize(pk1));
- test_eq(1024, crypto_pk_num_bits(pk1));
- test_eq(128, crypto_pk_keysize(pk2));
- test_eq(1024, crypto_pk_num_bits(pk2));
+ tt_int_op(128,OP_EQ, crypto_pk_keysize(pk1));
+ tt_int_op(1024,OP_EQ, crypto_pk_num_bits(pk1));
+ tt_int_op(128,OP_EQ, crypto_pk_keysize(pk2));
+ tt_int_op(1024,OP_EQ, crypto_pk_num_bits(pk2));
- test_eq(128, crypto_pk_public_encrypt(pk2, data1, sizeof(data1),
+ tt_int_op(128,OP_EQ, crypto_pk_public_encrypt(pk2, data1, sizeof(data1),
"Hello whirled.", 15,
PK_PKCS1_OAEP_PADDING));
- test_eq(128, crypto_pk_public_encrypt(pk1, data2, sizeof(data1),
+ tt_int_op(128,OP_EQ, crypto_pk_public_encrypt(pk1, data2, sizeof(data1),
"Hello whirled.", 15,
PK_PKCS1_OAEP_PADDING));
/* oaep padding should make encryption not match */
- test_memneq(data1, data2, 128);
- test_eq(15, crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data1, 128,
+ tt_mem_op(data1,OP_NE, data2, 128);
+ tt_int_op(15,OP_EQ,
+ crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data1, 128,
PK_PKCS1_OAEP_PADDING,1));
- test_streq(data3, "Hello whirled.");
+ tt_str_op(data3,OP_EQ, "Hello whirled.");
memset(data3, 0, 1024);
- test_eq(15, crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data2, 128,
+ tt_int_op(15,OP_EQ,
+ crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data2, 128,
PK_PKCS1_OAEP_PADDING,1));
- test_streq(data3, "Hello whirled.");
+ tt_str_op(data3,OP_EQ, "Hello whirled.");
/* Can't decrypt with public key. */
- test_eq(-1, crypto_pk_private_decrypt(pk2, data3, sizeof(data3), data2, 128,
+ tt_int_op(-1,OP_EQ,
+ crypto_pk_private_decrypt(pk2, data3, sizeof(data3), data2, 128,
PK_PKCS1_OAEP_PADDING,1));
/* Try again with bad padding */
memcpy(data2+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
- test_eq(-1, crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data2, 128,
+ tt_int_op(-1,OP_EQ,
+ crypto_pk_private_decrypt(pk1, data3, sizeof(data3), data2, 128,
PK_PKCS1_OAEP_PADDING,1));
/* File operations: save and load private key */
- test_assert(! crypto_pk_write_private_key_to_filename(pk1,
+ tt_assert(! crypto_pk_write_private_key_to_filename(pk1,
get_fname("pkey1")));
/* failing case for read: can't read. */
- test_assert(crypto_pk_read_private_key_from_filename(pk2,
+ tt_assert(crypto_pk_read_private_key_from_filename(pk2,
get_fname("xyzzy")) < 0);
write_str_to_file(get_fname("xyzzy"), "foobar", 6);
/* Failing case for read: no key. */
- test_assert(crypto_pk_read_private_key_from_filename(pk2,
+ tt_assert(crypto_pk_read_private_key_from_filename(pk2,
get_fname("xyzzy")) < 0);
- test_assert(! crypto_pk_read_private_key_from_filename(pk2,
+ tt_assert(! crypto_pk_read_private_key_from_filename(pk2,
get_fname("pkey1")));
- test_eq(15, crypto_pk_private_decrypt(pk2, data3, sizeof(data3), data1, 128,
+ tt_int_op(15,OP_EQ,
+ crypto_pk_private_decrypt(pk2, data3, sizeof(data3), data1, 128,
PK_PKCS1_OAEP_PADDING,1));
/* Now try signing. */
strlcpy(data1, "Ossifrage", 1024);
- test_eq(128, crypto_pk_private_sign(pk1, data2, sizeof(data2), data1, 10));
- test_eq(10,
+ tt_int_op(128,OP_EQ,
+ crypto_pk_private_sign(pk1, data2, sizeof(data2), data1, 10));
+ tt_int_op(10,OP_EQ,
crypto_pk_public_checksig(pk1, data3, sizeof(data3), data2, 128));
- test_streq(data3, "Ossifrage");
+ tt_str_op(data3,OP_EQ, "Ossifrage");
/* Try signing digests. */
- test_eq(128, crypto_pk_private_sign_digest(pk1, data2, sizeof(data2),
+ tt_int_op(128,OP_EQ, crypto_pk_private_sign_digest(pk1, data2, sizeof(data2),
data1, 10));
- test_eq(20,
+ tt_int_op(20,OP_EQ,
crypto_pk_public_checksig(pk1, data3, sizeof(data3), data2, 128));
- test_eq(0, crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
- test_eq(-1, crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
+ tt_int_op(0,OP_EQ,
+ crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
+ tt_int_op(-1,OP_EQ,
+ crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
/*XXXX test failed signing*/
@@ -476,9 +965,9 @@ test_crypto_pk(void)
crypto_pk_free(pk2);
pk2 = NULL;
i = crypto_pk_asn1_encode(pk1, data1, 1024);
- test_assert(i>0);
+ tt_int_op(i, OP_GT, 0);
pk2 = crypto_pk_asn1_decode(data1, i);
- test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
+ tt_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
/* Try with hybrid encryption wrappers. */
crypto_rand(data1, 1024);
@@ -487,19 +976,19 @@ test_crypto_pk(void)
memset(data3,0,1024);
len = crypto_pk_public_hybrid_encrypt(pk1,data2,sizeof(data2),
data1,i,PK_PKCS1_OAEP_PADDING,0);
- test_assert(len>=0);
+ tt_int_op(len, OP_GE, 0);
len = crypto_pk_private_hybrid_decrypt(pk1,data3,sizeof(data3),
data2,len,PK_PKCS1_OAEP_PADDING,1);
- test_eq(len,i);
- test_memeq(data1,data3,i);
+ tt_int_op(len,OP_EQ, i);
+ tt_mem_op(data1,OP_EQ, data3,i);
}
/* Try copy_full */
crypto_pk_free(pk2);
pk2 = crypto_pk_copy_full(pk1);
- test_assert(pk2 != NULL);
- test_neq_ptr(pk1, pk2);
- test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
+ tt_assert(pk2 != NULL);
+ tt_ptr_op(pk1, OP_NE, pk2);
+ tt_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
done:
if (pk1)
@@ -525,33 +1014,33 @@ test_crypto_pk_fingerprints(void *arg)
pk = pk_generate(1);
tt_assert(pk);
n = crypto_pk_asn1_encode(pk, encoded, sizeof(encoded));
- tt_int_op(n, >, 0);
- tt_int_op(n, >, 128);
- tt_int_op(n, <, 256);
+ tt_int_op(n, OP_GT, 0);
+ tt_int_op(n, OP_GT, 128);
+ tt_int_op(n, OP_LT, 256);
/* Is digest as expected? */
crypto_digest(d, encoded, n);
- tt_int_op(0, ==, crypto_pk_get_digest(pk, d2));
- test_memeq(d, d2, DIGEST_LEN);
+ tt_int_op(0, OP_EQ, crypto_pk_get_digest(pk, d2));
+ tt_mem_op(d,OP_EQ, d2, DIGEST_LEN);
/* Is fingerprint right? */
- tt_int_op(0, ==, crypto_pk_get_fingerprint(pk, fingerprint, 0));
- tt_int_op(strlen(fingerprint), ==, DIGEST_LEN * 2);
+ tt_int_op(0, OP_EQ, crypto_pk_get_fingerprint(pk, fingerprint, 0));
+ tt_int_op(strlen(fingerprint), OP_EQ, DIGEST_LEN * 2);
test_memeq_hex(d, fingerprint);
/* Are spaces right? */
- tt_int_op(0, ==, crypto_pk_get_fingerprint(pk, fingerprint, 1));
+ tt_int_op(0, OP_EQ, crypto_pk_get_fingerprint(pk, fingerprint, 1));
for (i = 4; i < strlen(fingerprint); i += 5) {
- tt_int_op(fingerprint[i], ==, ' ');
+ tt_int_op(fingerprint[i], OP_EQ, ' ');
}
tor_strstrip(fingerprint, " ");
- tt_int_op(strlen(fingerprint), ==, DIGEST_LEN * 2);
+ tt_int_op(strlen(fingerprint), OP_EQ, DIGEST_LEN * 2);
test_memeq_hex(d, fingerprint);
/* Now hash again and check crypto_pk_get_hashed_fingerprint. */
crypto_digest(d2, d, sizeof(d));
- tt_int_op(0, ==, crypto_pk_get_hashed_fingerprint(pk, fingerprint));
- tt_int_op(strlen(fingerprint), ==, DIGEST_LEN * 2);
+ tt_int_op(0, OP_EQ, crypto_pk_get_hashed_fingerprint(pk, fingerprint));
+ tt_int_op(strlen(fingerprint), OP_EQ, DIGEST_LEN * 2);
test_memeq_hex(d2, fingerprint);
done:
@@ -559,90 +1048,173 @@ test_crypto_pk_fingerprints(void *arg)
tor_free(mem_op_hex_tmp);
}
+static void
+test_crypto_pk_base64(void *arg)
+{
+ crypto_pk_t *pk1 = NULL;
+ crypto_pk_t *pk2 = NULL;
+ char *encoded = NULL;
+
+ (void)arg;
+
+ /* Test Base64 encoding a key. */
+ pk1 = pk_generate(0);
+ tt_assert(pk1);
+ tt_int_op(0, OP_EQ, crypto_pk_base64_encode(pk1, &encoded));
+ tt_assert(encoded);
+
+ /* Test decoding a valid key. */
+ pk2 = crypto_pk_base64_decode(encoded, strlen(encoded));
+ tt_assert(pk2);
+ tt_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
+ crypto_pk_free(pk2);
+
+ /* Test decoding a invalid key (not Base64). */
+ static const char *invalid_b64 = "The key is in another castle!";
+ pk2 = crypto_pk_base64_decode(invalid_b64, strlen(invalid_b64));
+ tt_assert(!pk2);
+
+ /* Test decoding a truncated Base64 blob. */
+ pk2 = crypto_pk_base64_decode(encoded, strlen(encoded)/2);
+ tt_assert(!pk2);
+
+ done:
+ crypto_pk_free(pk1);
+ crypto_pk_free(pk2);
+ tor_free(encoded);
+}
+
/** Sanity check for crypto pk digests */
static void
-test_crypto_digests(void)
+test_crypto_digests(void *arg)
{
crypto_pk_t *k = NULL;
ssize_t r;
- digests_t pkey_digests;
+ common_digests_t pkey_digests;
char digest[DIGEST_LEN];
+ (void)arg;
k = crypto_pk_new();
- test_assert(k);
+ tt_assert(k);
r = crypto_pk_read_private_key_from_string(k, AUTHORITY_SIGNKEY_3, -1);
- test_assert(!r);
+ tt_assert(!r);
r = crypto_pk_get_digest(k, digest);
- test_assert(r == 0);
- test_memeq(hex_str(digest, DIGEST_LEN),
+ tt_assert(r == 0);
+ tt_mem_op(hex_str(digest, DIGEST_LEN),OP_EQ,
AUTHORITY_SIGNKEY_A_DIGEST, HEX_DIGEST_LEN);
- r = crypto_pk_get_all_digests(k, &pkey_digests);
+ r = crypto_pk_get_common_digests(k, &pkey_digests);
- test_memeq(hex_str(pkey_digests.d[DIGEST_SHA1], DIGEST_LEN),
+ tt_mem_op(hex_str(pkey_digests.d[DIGEST_SHA1], DIGEST_LEN),OP_EQ,
AUTHORITY_SIGNKEY_A_DIGEST, HEX_DIGEST_LEN);
- test_memeq(hex_str(pkey_digests.d[DIGEST_SHA256], DIGEST256_LEN),
+ tt_mem_op(hex_str(pkey_digests.d[DIGEST_SHA256], DIGEST256_LEN),OP_EQ,
AUTHORITY_SIGNKEY_A_DIGEST256, HEX_DIGEST256_LEN);
done:
crypto_pk_free(k);
}
+#ifndef OPENSSL_1_1_API
+#define EVP_ENCODE_CTX_new() tor_malloc_zero(sizeof(EVP_ENCODE_CTX))
+#define EVP_ENCODE_CTX_free(ctx) tor_free(ctx)
+#endif
+
+/** Encode src into dest with OpenSSL's EVP Encode interface, returning the
+ * length of the encoded data in bytes.
+ */
+static int
+base64_encode_evp(char *dest, char *src, size_t srclen)
+{
+ const unsigned char *s = (unsigned char*)src;
+ EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
+ int len, ret;
+
+ EVP_EncodeInit(ctx);
+ EVP_EncodeUpdate(ctx, (unsigned char *)dest, &len, s, (int)srclen);
+ EVP_EncodeFinal(ctx, (unsigned char *)(dest + len), &ret);
+ EVP_ENCODE_CTX_free(ctx);
+ return ret+ len;
+}
+
/** Run unit tests for misc crypto formatting functionality (base64, base32,
* fingerprints, etc) */
static void
-test_crypto_formats(void)
+test_crypto_formats(void *arg)
{
char *data1 = NULL, *data2 = NULL, *data3 = NULL;
int i, j, idx;
+ (void)arg;
data1 = tor_malloc(1024);
data2 = tor_malloc(1024);
data3 = tor_malloc(1024);
- test_assert(data1 && data2 && data3);
+ tt_assert(data1 && data2 && data3);
/* Base64 tests */
memset(data1, 6, 1024);
for (idx = 0; idx < 10; ++idx) {
- i = base64_encode(data2, 1024, data1, idx);
- test_assert(i >= 0);
+ i = base64_encode(data2, 1024, data1, idx, 0);
+ tt_int_op(i, OP_GE, 0);
+ tt_int_op(i, OP_EQ, strlen(data2));
j = base64_decode(data3, 1024, data2, i);
- test_eq(j,idx);
- test_memeq(data3, data1, idx);
+ tt_int_op(j,OP_EQ, idx);
+ tt_mem_op(data3,OP_EQ, data1, idx);
+
+ i = base64_encode_nopad(data2, 1024, (uint8_t*)data1, idx);
+ tt_int_op(i, OP_GE, 0);
+ tt_int_op(i, OP_EQ, strlen(data2));
+ tt_assert(! strchr(data2, '='));
+ j = base64_decode_nopad((uint8_t*)data3, 1024, data2, i);
+ tt_int_op(j, OP_EQ, idx);
+ tt_mem_op(data3,OP_EQ, data1, idx);
}
strlcpy(data1, "Test string that contains 35 chars.", 1024);
strlcat(data1, " 2nd string that contains 35 chars.", 1024);
- i = base64_encode(data2, 1024, data1, 71);
- test_assert(i >= 0);
+ i = base64_encode(data2, 1024, data1, 71, 0);
+ tt_int_op(i, OP_GE, 0);
j = base64_decode(data3, 1024, data2, i);
- test_eq(j, 71);
- test_streq(data3, data1);
- test_assert(data2[i] == '\0');
+ tt_int_op(j,OP_EQ, 71);
+ tt_str_op(data3,OP_EQ, data1);
+ tt_int_op(data2[i], OP_EQ, '\0');
crypto_rand(data1, DIGEST_LEN);
memset(data2, 100, 1024);
digest_to_base64(data2, data1);
- test_eq(BASE64_DIGEST_LEN, strlen(data2));
- test_eq(100, data2[BASE64_DIGEST_LEN+2]);
+ tt_int_op(BASE64_DIGEST_LEN,OP_EQ, strlen(data2));
+ tt_int_op(100,OP_EQ, data2[BASE64_DIGEST_LEN+2]);
memset(data3, 99, 1024);
- test_eq(digest_from_base64(data3, data2), 0);
- test_memeq(data1, data3, DIGEST_LEN);
- test_eq(99, data3[DIGEST_LEN+1]);
+ tt_int_op(digest_from_base64(data3, data2),OP_EQ, 0);
+ tt_mem_op(data1,OP_EQ, data3, DIGEST_LEN);
+ tt_int_op(99,OP_EQ, data3[DIGEST_LEN+1]);
+
+ tt_assert(digest_from_base64(data3, "###") < 0);
- test_assert(digest_from_base64(data3, "###") < 0);
+ for (i = 0; i < 256; i++) {
+ /* Test the multiline format Base64 encoder with 0 .. 256 bytes of
+ * output against OpenSSL.
+ */
+ const size_t enclen = base64_encode_size(i, BASE64_ENCODE_MULTILINE);
+ data1[i] = i;
+ j = base64_encode(data2, 1024, data1, i, BASE64_ENCODE_MULTILINE);
+ tt_int_op(j, OP_EQ, enclen);
+ j = base64_encode_evp(data3, data1, i);
+ tt_int_op(j, OP_EQ, enclen);
+ tt_mem_op(data2, OP_EQ, data3, enclen);
+ tt_int_op(j, OP_EQ, strlen(data2));
+ }
/* Encoding SHA256 */
crypto_rand(data2, DIGEST256_LEN);
memset(data2, 100, 1024);
digest256_to_base64(data2, data1);
- test_eq(BASE64_DIGEST256_LEN, strlen(data2));
- test_eq(100, data2[BASE64_DIGEST256_LEN+2]);
+ tt_int_op(BASE64_DIGEST256_LEN,OP_EQ, strlen(data2));
+ tt_int_op(100,OP_EQ, data2[BASE64_DIGEST256_LEN+2]);
memset(data3, 99, 1024);
- test_eq(digest256_from_base64(data3, data2), 0);
- test_memeq(data1, data3, DIGEST256_LEN);
- test_eq(99, data3[DIGEST256_LEN+1]);
+ tt_int_op(digest256_from_base64(data3, data2),OP_EQ, 0);
+ tt_mem_op(data1,OP_EQ, data3, DIGEST256_LEN);
+ tt_int_op(99,OP_EQ, data3[DIGEST256_LEN+1]);
/* Base32 tests */
strlcpy(data1, "5chrs", 1024);
@@ -651,27 +1223,27 @@ test_crypto_formats(void)
* By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
*/
base32_encode(data2, 9, data1, 5);
- test_streq(data2, "gvrwq4tt");
+ tt_str_op(data2,OP_EQ, "gvrwq4tt");
strlcpy(data1, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
base32_encode(data2, 30, data1, 10);
- test_streq(data2, "772w2rfobvomsywe");
+ tt_str_op(data2,OP_EQ, "772w2rfobvomsywe");
/* Base16 tests */
strlcpy(data1, "6chrs\xff", 1024);
base16_encode(data2, 13, data1, 6);
- test_streq(data2, "3663687273FF");
+ tt_str_op(data2,OP_EQ, "3663687273FF");
strlcpy(data1, "f0d678affc000100", 1024);
i = base16_decode(data2, 8, data1, 16);
- test_eq(i,0);
- test_memeq(data2, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
+ tt_int_op(i,OP_EQ, 0);
+ tt_mem_op(data2,OP_EQ, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
/* now try some failing base16 decodes */
- test_eq(-1, base16_decode(data2, 8, data1, 15)); /* odd input len */
- test_eq(-1, base16_decode(data2, 7, data1, 16)); /* dest too short */
+ tt_int_op(-1,OP_EQ, base16_decode(data2, 8, data1, 15)); /* odd input len */
+ tt_int_op(-1,OP_EQ, base16_decode(data2, 7, data1, 16)); /* dest too short */
strlcpy(data1, "f0dz!8affc000100", 1024);
- test_eq(-1, base16_decode(data2, 8, data1, 16));
+ tt_int_op(-1,OP_EQ, base16_decode(data2, 8, data1, 16));
tor_free(data1);
tor_free(data2);
@@ -680,10 +1252,11 @@ test_crypto_formats(void)
/* Add spaces to fingerprint */
{
data1 = tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
- test_eq(strlen(data1), 40);
+ tt_int_op(strlen(data1),OP_EQ, 40);
data2 = tor_malloc(FINGERPRINT_LEN+1);
crypto_add_spaces_to_fp(data2, FINGERPRINT_LEN+1, data1);
- test_streq(data2, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
+ tt_str_op(data2, OP_EQ,
+ "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
tor_free(data1);
tor_free(data2);
}
@@ -694,39 +1267,6 @@ test_crypto_formats(void)
tor_free(data3);
}
-/** Run unit tests for our secret-to-key passphrase hashing functionality. */
-static void
-test_crypto_s2k(void)
-{
- char buf[29];
- char buf2[29];
- char *buf3 = NULL;
- int i;
-
- memset(buf, 0, sizeof(buf));
- memset(buf2, 0, sizeof(buf2));
- buf3 = tor_malloc(65536);
- memset(buf3, 0, 65536);
-
- secret_to_key(buf+9, 20, "", 0, buf);
- crypto_digest(buf2+9, buf3, 1024);
- test_memeq(buf, buf2, 29);
-
- memcpy(buf,"vrbacrda",8);
- memcpy(buf2,"vrbacrda",8);
- buf[8] = 96;
- buf2[8] = 96;
- secret_to_key(buf+9, 20, "12345678", 8, buf);
- for (i = 0; i < 65536; i += 16) {
- memcpy(buf3+i, "vrbacrda12345678", 16);
- }
- crypto_digest(buf2+9, buf3, 65536);
- test_memeq(buf, buf2, 29);
-
- done:
- tor_free(buf3);
-}
-
/** Test AES-CTR encryption and decryption with IV. */
static void
test_crypto_aes_iv(void *arg)
@@ -757,79 +1297,79 @@ test_crypto_aes_iv(void *arg)
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted1, 16 + 4095,
plain, 4095);
- test_eq(encrypted_size, 16 + 4095);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 4095);
tt_assert(encrypted_size > 0); /* This is obviously true, since 4111 is
* greater than 0, but its truth is not
* obvious to all analysis tools. */
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 4095,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 4095);
+ tt_int_op(decrypted_size,OP_EQ, 4095);
tt_assert(decrypted_size > 0);
- test_memeq(plain, decrypted1, 4095);
+ tt_mem_op(plain,OP_EQ, decrypted1, 4095);
/* Encrypt a second time (with a new random initialization vector). */
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted2, 16 + 4095,
plain, 4095);
- test_eq(encrypted_size, 16 + 4095);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 4095);
tt_assert(encrypted_size > 0);
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted2, 4095,
encrypted2, encrypted_size);
- test_eq(decrypted_size, 4095);
+ tt_int_op(decrypted_size,OP_EQ, 4095);
tt_assert(decrypted_size > 0);
- test_memeq(plain, decrypted2, 4095);
- test_memneq(encrypted1, encrypted2, encrypted_size);
+ tt_mem_op(plain,OP_EQ, decrypted2, 4095);
+ tt_mem_op(encrypted1,OP_NE, encrypted2, encrypted_size);
/* Decrypt with the wrong key. */
decrypted_size = crypto_cipher_decrypt_with_iv(key2, decrypted2, 4095,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 4095);
- test_memneq(plain, decrypted2, decrypted_size);
+ tt_int_op(decrypted_size,OP_EQ, 4095);
+ tt_mem_op(plain,OP_NE, decrypted2, decrypted_size);
/* Alter the initialization vector. */
encrypted1[0] += 42;
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 4095,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 4095);
- test_memneq(plain, decrypted2, 4095);
+ tt_int_op(decrypted_size,OP_EQ, 4095);
+ tt_mem_op(plain,OP_NE, decrypted2, 4095);
/* Special length case: 1. */
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted1, 16 + 1,
plain_1, 1);
- test_eq(encrypted_size, 16 + 1);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 1);
tt_assert(encrypted_size > 0);
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 1,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 1);
+ tt_int_op(decrypted_size,OP_EQ, 1);
tt_assert(decrypted_size > 0);
- test_memeq(plain_1, decrypted1, 1);
+ tt_mem_op(plain_1,OP_EQ, decrypted1, 1);
/* Special length case: 15. */
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted1, 16 + 15,
plain_15, 15);
- test_eq(encrypted_size, 16 + 15);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 15);
tt_assert(encrypted_size > 0);
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 15,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 15);
+ tt_int_op(decrypted_size,OP_EQ, 15);
tt_assert(decrypted_size > 0);
- test_memeq(plain_15, decrypted1, 15);
+ tt_mem_op(plain_15,OP_EQ, decrypted1, 15);
/* Special length case: 16. */
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted1, 16 + 16,
plain_16, 16);
- test_eq(encrypted_size, 16 + 16);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 16);
tt_assert(encrypted_size > 0);
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 16,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 16);
+ tt_int_op(decrypted_size,OP_EQ, 16);
tt_assert(decrypted_size > 0);
- test_memeq(plain_16, decrypted1, 16);
+ tt_mem_op(plain_16,OP_EQ, decrypted1, 16);
/* Special length case: 17. */
encrypted_size = crypto_cipher_encrypt_with_iv(key1, encrypted1, 16 + 17,
plain_17, 17);
- test_eq(encrypted_size, 16 + 17);
+ tt_int_op(encrypted_size,OP_EQ, 16 + 17);
tt_assert(encrypted_size > 0);
decrypted_size = crypto_cipher_decrypt_with_iv(key1, decrypted1, 17,
encrypted1, encrypted_size);
- test_eq(decrypted_size, 17);
+ tt_int_op(decrypted_size,OP_EQ, 17);
tt_assert(decrypted_size > 0);
- test_memeq(plain_17, decrypted1, 17);
+ tt_mem_op(plain_17,OP_EQ, decrypted1, 17);
done:
/* Free memory. */
@@ -842,34 +1382,35 @@ test_crypto_aes_iv(void *arg)
/** Test base32 decoding. */
static void
-test_crypto_base32_decode(void)
+test_crypto_base32_decode(void *arg)
{
char plain[60], encoded[96 + 1], decoded[60];
int res;
+ (void)arg;
crypto_rand(plain, 60);
/* Encode and decode a random string. */
base32_encode(encoded, 96 + 1, plain, 60);
res = base32_decode(decoded, 60, encoded, 96);
- test_eq(res, 0);
- test_memeq(plain, decoded, 60);
+ tt_int_op(res,OP_EQ, 0);
+ tt_mem_op(plain,OP_EQ, decoded, 60);
/* Encode, uppercase, and decode a random string. */
base32_encode(encoded, 96 + 1, plain, 60);
tor_strupper(encoded);
res = base32_decode(decoded, 60, encoded, 96);
- test_eq(res, 0);
- test_memeq(plain, decoded, 60);
+ tt_int_op(res,OP_EQ, 0);
+ tt_mem_op(plain,OP_EQ, decoded, 60);
/* Change encoded string and decode. */
if (encoded[0] == 'A' || encoded[0] == 'a')
encoded[0] = 'B';
else
encoded[0] = 'A';
res = base32_decode(decoded, 60, encoded, 96);
- test_eq(res, 0);
- test_memneq(plain, decoded, 60);
+ tt_int_op(res,OP_EQ, 0);
+ tt_mem_op(plain,OP_NE, decoded, 60);
/* Bad encodings. */
encoded[0] = '!';
res = base32_decode(decoded, 60, encoded, 96);
- test_assert(res < 0);
+ tt_int_op(0, OP_GT, res);
done:
;
@@ -892,7 +1433,7 @@ test_crypto_kdf_TAP(void *arg)
* your own. */
memset(key_material, 0, sizeof(key_material));
EXPAND("");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"5ba93c9db0cff93f52b521d7420e43f6eda2784fbf8b4530d8"
"d246dd74ac53a13471bba17941dff7c4ea21bb365bbeeaf5f2"
@@ -900,7 +1441,7 @@ test_crypto_kdf_TAP(void *arg)
"f07b01e13da42c6cf1de3abfdea9b95f34687cbbe92b9a7383");
EXPAND("Tor");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"776c6214fc647aaa5f683c737ee66ec44f03d0372e1cce6922"
"7950f236ddf1e329a7ce7c227903303f525a8c6662426e8034"
@@ -908,7 +1449,7 @@ test_crypto_kdf_TAP(void *arg)
"3f45dfda1a80bdc8b80de01b23e3e0ffae099b3e4ccf28dc28");
EXPAND("AN ALARMING ITEM TO FIND ON A MONTHLY AUTO-DEBIT NOTICE");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"a340b5d126086c3ab29c2af4179196dbf95e1c72431419d331"
"4844bf8f6afb6098db952b95581fb6c33625709d6f4400b8e7"
@@ -944,7 +1485,7 @@ test_crypto_hkdf_sha256(void *arg)
/* Test vectors generated with ntor_ref.py */
memset(key_material, 0, sizeof(key_material));
EXPAND("");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"d3490ed48b12a48f9547861583573fe3f19aafe3f81dc7fc75"
"eeed96d741b3290f941576c1f9f0b2d463d1ec7ab2c6bf71cd"
@@ -952,7 +1493,7 @@ test_crypto_hkdf_sha256(void *arg)
"dcf6abe0d20c77cf363e8ffe358927817a3d3e73712cee28d8");
EXPAND("Tor");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"5521492a85139a8d9107a2d5c0d9c91610d0f95989975ebee6"
"c02a4f8d622a6cfdf9b7c7edd3832e2760ded1eac309b76f8d"
@@ -960,7 +1501,7 @@ test_crypto_hkdf_sha256(void *arg)
"961be9fdb9f93197ea8e5977180801926d3321fa21513e59ac");
EXPAND("AN ALARMING ITEM TO FIND ON YOUR CREDIT-RATING STATEMENT");
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
test_memeq_hex(key_material,
"a2aa9b50da7e481d30463adb8f233ff06e9571a0ca6ab6df0f"
"b206fa34e5bc78d063fc291501beec53b36e5a0e434561200c"
@@ -972,7 +1513,6 @@ test_crypto_hkdf_sha256(void *arg)
#undef EXPAND
}
-#ifdef CURVE25519_ENABLED
static void
test_crypto_curve25519_impl(void *arg)
{
@@ -1024,7 +1564,7 @@ test_crypto_curve25519_impl(void *arg)
e2k[31] |= (byte & 0x80);
}
curve25519_impl(e1e2k,e1,e2k);
- test_memeq(e1e2k, e2e1k, 32);
+ tt_mem_op(e1e2k,OP_EQ, e2e1k, 32);
if (loop == loop_max-1) {
break;
}
@@ -1042,6 +1582,29 @@ test_crypto_curve25519_impl(void *arg)
}
static void
+test_crypto_curve25519_basepoint(void *arg)
+{
+ uint8_t secret[32];
+ uint8_t public1[32];
+ uint8_t public2[32];
+ const int iters = 2048;
+ int i;
+ (void) arg;
+
+ for (i = 0; i < iters; ++i) {
+ crypto_rand((char*)secret, 32);
+ curve25519_set_impl_params(1); /* Use optimization */
+ curve25519_basepoint_impl(public1, secret);
+ curve25519_set_impl_params(0); /* Disable optimization */
+ curve25519_basepoint_impl(public2, secret);
+ tt_mem_op(public1, OP_EQ, public2, 32);
+ }
+
+ done:
+ ;
+}
+
+static void
test_crypto_curve25519_wrappers(void *arg)
{
curve25519_public_key_t pubkey1, pubkey2;
@@ -1056,11 +1619,11 @@ test_crypto_curve25519_wrappers(void *arg)
curve25519_secret_key_generate(&seckey2, 1);
curve25519_public_key_generate(&pubkey1, &seckey1);
curve25519_public_key_generate(&pubkey2, &seckey2);
- test_assert(curve25519_public_key_is_ok(&pubkey1));
- test_assert(curve25519_public_key_is_ok(&pubkey2));
+ tt_assert(curve25519_public_key_is_ok(&pubkey1));
+ tt_assert(curve25519_public_key_is_ok(&pubkey2));
curve25519_handshake(output1, &seckey1, &pubkey2);
curve25519_handshake(output2, &seckey2, &pubkey1);
- test_memeq(output1, output2, sizeof(output1));
+ tt_mem_op(output1,OP_EQ, output2, sizeof(output1));
done:
;
@@ -1077,26 +1640,26 @@ test_crypto_curve25519_encode(void *arg)
curve25519_secret_key_generate(&seckey, 0);
curve25519_public_key_generate(&key1, &seckey);
- tt_int_op(0, ==, curve25519_public_to_base64(buf, &key1));
- tt_int_op(CURVE25519_BASE64_PADDED_LEN, ==, strlen(buf));
+ tt_int_op(0, OP_EQ, curve25519_public_to_base64(buf, &key1));
+ tt_int_op(CURVE25519_BASE64_PADDED_LEN, OP_EQ, strlen(buf));
- tt_int_op(0, ==, curve25519_public_from_base64(&key2, buf));
- test_memeq(key1.public_key, key2.public_key, CURVE25519_PUBKEY_LEN);
+ tt_int_op(0, OP_EQ, curve25519_public_from_base64(&key2, buf));
+ tt_mem_op(key1.public_key,OP_EQ, key2.public_key, CURVE25519_PUBKEY_LEN);
buf[CURVE25519_BASE64_PADDED_LEN - 1] = '\0';
- tt_int_op(CURVE25519_BASE64_PADDED_LEN-1, ==, strlen(buf));
- tt_int_op(0, ==, curve25519_public_from_base64(&key3, buf));
- test_memeq(key1.public_key, key3.public_key, CURVE25519_PUBKEY_LEN);
+ tt_int_op(CURVE25519_BASE64_PADDED_LEN-1, OP_EQ, strlen(buf));
+ tt_int_op(0, OP_EQ, curve25519_public_from_base64(&key3, buf));
+ tt_mem_op(key1.public_key,OP_EQ, key3.public_key, CURVE25519_PUBKEY_LEN);
/* Now try bogus parses. */
strlcpy(buf, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=", sizeof(buf));
- tt_int_op(-1, ==, curve25519_public_from_base64(&key3, buf));
+ tt_int_op(-1, OP_EQ, curve25519_public_from_base64(&key3, buf));
strlcpy(buf, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$", sizeof(buf));
- tt_int_op(-1, ==, curve25519_public_from_base64(&key3, buf));
+ tt_int_op(-1, OP_EQ, curve25519_public_from_base64(&key3, buf));
strlcpy(buf, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf));
- tt_int_op(-1, ==, curve25519_public_from_base64(&key3, buf));
+ tt_int_op(-1, OP_EQ, curve25519_public_from_base64(&key3, buf));
done:
;
@@ -1115,45 +1678,49 @@ test_crypto_curve25519_persist(void *arg)
(void)arg;
- tt_int_op(0,==,curve25519_keypair_generate(&keypair, 0));
+ tt_int_op(0,OP_EQ,curve25519_keypair_generate(&keypair, 0));
- tt_int_op(0,==,curve25519_keypair_write_to_file(&keypair, fname, "testing"));
- tt_int_op(0,==,curve25519_keypair_read_from_file(&keypair2, &tag, fname));
- tt_str_op(tag,==,"testing");
+ tt_int_op(0,OP_EQ,
+ curve25519_keypair_write_to_file(&keypair, fname, "testing"));
+ tt_int_op(0,OP_EQ,curve25519_keypair_read_from_file(&keypair2, &tag, fname));
+ tt_str_op(tag,OP_EQ,"testing");
tor_free(tag);
- test_memeq(keypair.pubkey.public_key,
+ tt_mem_op(keypair.pubkey.public_key,OP_EQ,
keypair2.pubkey.public_key,
CURVE25519_PUBKEY_LEN);
- test_memeq(keypair.seckey.secret_key,
+ tt_mem_op(keypair.seckey.secret_key,OP_EQ,
keypair2.seckey.secret_key,
CURVE25519_SECKEY_LEN);
content = read_file_to_str(fname, RFTS_BIN, &st);
tt_assert(content);
taglen = strlen("== c25519v1: testing ==");
- tt_u64_op((uint64_t)st.st_size, ==,
+ tt_u64_op((uint64_t)st.st_size, OP_EQ,
32+CURVE25519_PUBKEY_LEN+CURVE25519_SECKEY_LEN);
tt_assert(fast_memeq(content, "== c25519v1: testing ==", taglen));
tt_assert(tor_mem_is_zero(content+taglen, 32-taglen));
cp = content + 32;
- test_memeq(keypair.seckey.secret_key,
+ tt_mem_op(keypair.seckey.secret_key,OP_EQ,
cp,
CURVE25519_SECKEY_LEN);
cp += CURVE25519_SECKEY_LEN;
- test_memeq(keypair.pubkey.public_key,
+ tt_mem_op(keypair.pubkey.public_key,OP_EQ,
cp,
CURVE25519_SECKEY_LEN);
tor_free(fname);
fname = tor_strdup(get_fname("bogus_keypair"));
- tt_int_op(-1, ==, curve25519_keypair_read_from_file(&keypair2, &tag, fname));
+ tt_int_op(-1, OP_EQ,
+ curve25519_keypair_read_from_file(&keypair2, &tag, fname));
tor_free(tag);
content[69] ^= 0xff;
- tt_int_op(0, ==, write_bytes_to_file(fname, content, (size_t)st.st_size, 1));
- tt_int_op(-1, ==, curve25519_keypair_read_from_file(&keypair2, &tag, fname));
+ tt_int_op(0, OP_EQ,
+ write_bytes_to_file(fname, content, (size_t)st.st_size, 1));
+ tt_int_op(-1, OP_EQ,
+ curve25519_keypair_read_from_file(&keypair2, &tag, fname));
done:
tor_free(fname);
@@ -1161,7 +1728,459 @@ test_crypto_curve25519_persist(void *arg)
tor_free(tag);
}
-#endif
+static void *
+ed25519_testcase_setup(const struct testcase_t *testcase)
+{
+ crypto_ed25519_testing_force_impl(testcase->setup_data);
+ return testcase->setup_data;
+}
+static int
+ed25519_testcase_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ (void)testcase;
+ (void)ptr;
+ crypto_ed25519_testing_restore_impl();
+ return 1;
+}
+static const struct testcase_setup_t ed25519_test_setup = {
+ ed25519_testcase_setup, ed25519_testcase_cleanup
+};
+
+static void
+test_crypto_ed25519_simple(void *arg)
+{
+ ed25519_keypair_t kp1, kp2;
+ ed25519_public_key_t pub1, pub2;
+ ed25519_secret_key_t sec1, sec2;
+ ed25519_signature_t sig1, sig2;
+ const uint8_t msg[] =
+ "GNU will be able to run Unix programs, "
+ "but will not be identical to Unix.";
+ const uint8_t msg2[] =
+ "Microsoft Windows extends the features of the DOS operating system, "
+ "yet is compatible with most existing applications that run under DOS.";
+ size_t msg_len = strlen((const char*)msg);
+ size_t msg2_len = strlen((const char*)msg2);
+
+ (void)arg;
+
+ tt_int_op(0, OP_EQ, ed25519_secret_key_generate(&sec1, 0));
+ tt_int_op(0, OP_EQ, ed25519_secret_key_generate(&sec2, 1));
+
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pub1, &sec1));
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pub2, &sec1));
+
+ tt_mem_op(pub1.pubkey, OP_EQ, pub2.pubkey, sizeof(pub1.pubkey));
+ tt_assert(ed25519_pubkey_eq(&pub1, &pub2));
+ tt_assert(ed25519_pubkey_eq(&pub1, &pub1));
+
+ memcpy(&kp1.pubkey, &pub1, sizeof(pub1));
+ memcpy(&kp1.seckey, &sec1, sizeof(sec1));
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig1, msg, msg_len, &kp1));
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig2, msg, msg_len, &kp1));
+
+ /* Ed25519 signatures are deterministic */
+ tt_mem_op(sig1.sig, OP_EQ, sig2.sig, sizeof(sig1.sig));
+
+ /* Basic signature is valid. */
+ tt_int_op(0, OP_EQ, ed25519_checksig(&sig1, msg, msg_len, &pub1));
+
+ /* Altered signature doesn't work. */
+ sig1.sig[0] ^= 3;
+ tt_int_op(-1, OP_EQ, ed25519_checksig(&sig1, msg, msg_len, &pub1));
+
+ /* Wrong public key doesn't work. */
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pub2, &sec2));
+ tt_int_op(-1, OP_EQ, ed25519_checksig(&sig2, msg, msg_len, &pub2));
+ tt_assert(! ed25519_pubkey_eq(&pub1, &pub2));
+
+ /* Wrong message doesn't work. */
+ tt_int_op(0, OP_EQ, ed25519_checksig(&sig2, msg, msg_len, &pub1));
+ tt_int_op(-1, OP_EQ, ed25519_checksig(&sig2, msg, msg_len-1, &pub1));
+ tt_int_op(-1, OP_EQ, ed25519_checksig(&sig2, msg2, msg2_len, &pub1));
+
+ /* Batch signature checking works with some bad. */
+ tt_int_op(0, OP_EQ, ed25519_keypair_generate(&kp2, 0));
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig1, msg, msg_len, &kp2));
+ {
+ ed25519_checkable_t ch[] = {
+ { &pub1, sig2, msg, msg_len }, /*ok*/
+ { &pub1, sig2, msg, msg_len-1 }, /*bad*/
+ { &kp2.pubkey, sig2, msg2, msg2_len }, /*bad*/
+ { &kp2.pubkey, sig1, msg, msg_len }, /*ok*/
+ };
+ int okay[4];
+ tt_int_op(-2, OP_EQ, ed25519_checksig_batch(okay, ch, 4));
+ tt_int_op(okay[0], OP_EQ, 1);
+ tt_int_op(okay[1], OP_EQ, 0);
+ tt_int_op(okay[2], OP_EQ, 0);
+ tt_int_op(okay[3], OP_EQ, 1);
+ tt_int_op(-2, OP_EQ, ed25519_checksig_batch(NULL, ch, 4));
+ }
+
+ /* Batch signature checking works with all good. */
+ {
+ ed25519_checkable_t ch[] = {
+ { &pub1, sig2, msg, msg_len }, /*ok*/
+ { &kp2.pubkey, sig1, msg, msg_len }, /*ok*/
+ };
+ int okay[2];
+ tt_int_op(0, OP_EQ, ed25519_checksig_batch(okay, ch, 2));
+ tt_int_op(okay[0], OP_EQ, 1);
+ tt_int_op(okay[1], OP_EQ, 1);
+ tt_int_op(0, OP_EQ, ed25519_checksig_batch(NULL, ch, 2));
+ }
+
+ done:
+ ;
+}
+
+static void
+test_crypto_ed25519_test_vectors(void *arg)
+{
+ char *mem_op_hex_tmp=NULL;
+ int i;
+ struct {
+ const char *sk;
+ const char *pk;
+ const char *sig;
+ const char *msg;
+ } items[] = {
+ /* These test vectors were generated with the "ref" implementation of
+ * ed25519 from SUPERCOP-20130419 */
+ { "4c6574277320686f706520746865726520617265206e6f206275677320696e20",
+ "f3e0e493b30f56e501aeb868fc912fe0c8b76621efca47a78f6d75875193dd87",
+ "b5d7fd6fd3adf643647ce1fe87a2931dedd1a4e38e6c662bedd35cdd80bfac51"
+ "1b2c7d1ee6bd929ac213014e1a8dc5373854c7b25dbe15ec96bf6c94196fae06",
+ "506c6561736520657863757365206d7920667269656e642e2048652069736e2774"
+ "204e554c2d7465726d696e617465642e"
+ },
+
+ { "74686520696d706c656d656e746174696f6e20776869636820617265206e6f74",
+ "407f0025a1e1351a4cb68e92f5c0ebaf66e7aaf93a4006a4d1a66e3ede1cfeac",
+ "02884fde1c3c5944d0ecf2d133726fc820c303aae695adceabf3a1e01e95bf28"
+ "da88c0966f5265e9c6f8edc77b3b96b5c91baec3ca993ccd21a3f64203600601",
+ "506c6561736520657863757365206d7920667269656e642e2048652069736e2774"
+ "204e554c2d7465726d696e617465642e"
+ },
+ { "6578706f73656420627920456e676c697368207465787420617320696e707574",
+ "61681cb5fbd69f9bc5a462a21a7ab319011237b940bc781cdc47fcbe327e7706",
+ "6a127d0414de7510125d4bc214994ffb9b8857a46330832d05d1355e882344ad"
+ "f4137e3ca1f13eb9cc75c887ef2309b98c57528b4acd9f6376c6898889603209",
+ "506c6561736520657863757365206d7920667269656e642e2048652069736e2774"
+ "204e554c2d7465726d696e617465642e"
+ },
+
+ /* These come from "sign.input" in ed25519's page */
+ { "5b5a619f8ce1c66d7ce26e5a2ae7b0c04febcd346d286c929e19d0d5973bfef9",
+ "6fe83693d011d111131c4f3fbaaa40a9d3d76b30012ff73bb0e39ec27ab18257",
+ "0f9ad9793033a2fa06614b277d37381e6d94f65ac2a5a94558d09ed6ce922258"
+ "c1a567952e863ac94297aec3c0d0c8ddf71084e504860bb6ba27449b55adc40e",
+ "5a8d9d0a22357e6655f9c785"
+ },
+ { "940c89fe40a81dafbdb2416d14ae469119869744410c3303bfaa0241dac57800",
+ "a2eb8c0501e30bae0cf842d2bde8dec7386f6b7fc3981b8c57c9792bb94cf2dd",
+ "d8bb64aad8c9955a115a793addd24f7f2b077648714f49c4694ec995b330d09d"
+ "640df310f447fd7b6cb5c14f9fe9f490bcf8cfadbfd2169c8ac20d3b8af49a0c",
+ "b87d3813e03f58cf19fd0b6395"
+ },
+ { "9acad959d216212d789a119252ebfe0c96512a23c73bd9f3b202292d6916a738",
+ "cf3af898467a5b7a52d33d53bc037e2642a8da996903fc252217e9c033e2f291",
+ "6ee3fe81e23c60eb2312b2006b3b25e6838e02106623f844c44edb8dafd66ab0"
+ "671087fd195df5b8f58a1d6e52af42908053d55c7321010092748795ef94cf06",
+ "55c7fa434f5ed8cdec2b7aeac173",
+ },
+ { "d5aeee41eeb0e9d1bf8337f939587ebe296161e6bf5209f591ec939e1440c300",
+ "fd2a565723163e29f53c9de3d5e8fbe36a7ab66e1439ec4eae9c0a604af291a5",
+ "f68d04847e5b249737899c014d31c805c5007a62c0a10d50bb1538c5f3550395"
+ "1fbc1e08682f2cc0c92efe8f4985dec61dcbd54d4b94a22547d24451271c8b00",
+ "0a688e79be24f866286d4646b5d81c"
+ },
+
+ { NULL, NULL, NULL, NULL}
+ };
+
+ (void)arg;
+
+ for (i = 0; items[i].pk; ++i) {
+ ed25519_keypair_t kp;
+ ed25519_signature_t sig;
+ uint8_t sk_seed[32];
+ uint8_t *msg;
+ size_t msg_len;
+ base16_decode((char*)sk_seed, sizeof(sk_seed),
+ items[i].sk, 64);
+ ed25519_secret_key_from_seed(&kp.seckey, sk_seed);
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&kp.pubkey, &kp.seckey));
+ test_memeq_hex(kp.pubkey.pubkey, items[i].pk);
+
+ msg_len = strlen(items[i].msg) / 2;
+ msg = tor_malloc(msg_len);
+ base16_decode((char*)msg, msg_len, items[i].msg, strlen(items[i].msg));
+
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig, msg, msg_len, &kp));
+ test_memeq_hex(sig.sig, items[i].sig);
+
+ tor_free(msg);
+ }
+
+ done:
+ tor_free(mem_op_hex_tmp);
+}
+
+static void
+test_crypto_ed25519_encode(void *arg)
+{
+ char buf[ED25519_SIG_BASE64_LEN+1];
+ ed25519_keypair_t kp;
+ ed25519_public_key_t pk;
+ ed25519_signature_t sig1, sig2;
+ char *mem_op_hex_tmp = NULL;
+ (void) arg;
+
+ /* Test roundtrip. */
+ tt_int_op(0, OP_EQ, ed25519_keypair_generate(&kp, 0));
+ tt_int_op(0, OP_EQ, ed25519_public_to_base64(buf, &kp.pubkey));
+ tt_int_op(ED25519_BASE64_LEN, OP_EQ, strlen(buf));
+ tt_int_op(0, OP_EQ, ed25519_public_from_base64(&pk, buf));
+ tt_mem_op(kp.pubkey.pubkey, OP_EQ, pk.pubkey, ED25519_PUBKEY_LEN);
+
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig1, (const uint8_t*)"ABC", 3, &kp));
+ tt_int_op(0, OP_EQ, ed25519_signature_to_base64(buf, &sig1));
+ tt_int_op(0, OP_EQ, ed25519_signature_from_base64(&sig2, buf));
+ tt_mem_op(sig1.sig, OP_EQ, sig2.sig, ED25519_SIG_LEN);
+
+ /* Test known value. */
+ tt_int_op(0, OP_EQ, ed25519_public_from_base64(&pk,
+ "lVIuIctLjbGZGU5wKMNXxXlSE3cW4kaqkqm04u6pxvM"));
+ test_memeq_hex(pk.pubkey,
+ "95522e21cb4b8db199194e7028c357c57952137716e246aa92a9b4e2eea9c6f3");
+
+ done:
+ tor_free(mem_op_hex_tmp);
+}
+
+static void
+test_crypto_ed25519_convert(void *arg)
+{
+ const uint8_t msg[] =
+ "The eyes are not here / There are no eyes here.";
+ const int N = 30;
+ int i;
+ (void)arg;
+
+ for (i = 0; i < N; ++i) {
+ curve25519_keypair_t curve25519_keypair;
+ ed25519_keypair_t ed25519_keypair;
+ ed25519_public_key_t ed25519_pubkey;
+
+ int bit=0;
+ ed25519_signature_t sig;
+
+ tt_int_op(0,OP_EQ,curve25519_keypair_generate(&curve25519_keypair, i&1));
+ tt_int_op(0,OP_EQ,ed25519_keypair_from_curve25519_keypair(
+ &ed25519_keypair, &bit, &curve25519_keypair));
+ tt_int_op(0,OP_EQ,ed25519_public_key_from_curve25519_public_key(
+ &ed25519_pubkey, &curve25519_keypair.pubkey, bit));
+ tt_mem_op(ed25519_pubkey.pubkey, OP_EQ, ed25519_keypair.pubkey.pubkey, 32);
+
+ tt_int_op(0,OP_EQ,ed25519_sign(&sig, msg, sizeof(msg), &ed25519_keypair));
+ tt_int_op(0,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg),
+ &ed25519_pubkey));
+
+ tt_int_op(-1,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg)-1,
+ &ed25519_pubkey));
+ sig.sig[0] ^= 15;
+ tt_int_op(-1,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg),
+ &ed25519_pubkey));
+ }
+
+ done:
+ ;
+}
+
+static void
+test_crypto_ed25519_blinding(void *arg)
+{
+ const uint8_t msg[] =
+ "Eyes I dare not meet in dreams / In death's dream kingdom";
+
+ const int N = 30;
+ int i;
+ (void)arg;
+
+ for (i = 0; i < N; ++i) {
+ uint8_t blinding[32];
+ ed25519_keypair_t ed25519_keypair;
+ ed25519_keypair_t ed25519_keypair_blinded;
+ ed25519_public_key_t ed25519_pubkey_blinded;
+
+ ed25519_signature_t sig;
+
+ crypto_rand((char*) blinding, sizeof(blinding));
+
+ tt_int_op(0,OP_EQ,ed25519_keypair_generate(&ed25519_keypair, 0));
+ tt_int_op(0,OP_EQ,ed25519_keypair_blind(&ed25519_keypair_blinded,
+ &ed25519_keypair, blinding));
+
+ tt_int_op(0,OP_EQ,ed25519_public_blind(&ed25519_pubkey_blinded,
+ &ed25519_keypair.pubkey, blinding));
+
+ tt_mem_op(ed25519_pubkey_blinded.pubkey, OP_EQ,
+ ed25519_keypair_blinded.pubkey.pubkey, 32);
+
+ tt_int_op(0,OP_EQ,ed25519_sign(&sig, msg, sizeof(msg),
+ &ed25519_keypair_blinded));
+
+ tt_int_op(0,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg),
+ &ed25519_pubkey_blinded));
+
+ tt_int_op(-1,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg)-1,
+ &ed25519_pubkey_blinded));
+ sig.sig[0] ^= 15;
+ tt_int_op(-1,OP_EQ,ed25519_checksig(&sig, msg, sizeof(msg),
+ &ed25519_pubkey_blinded));
+ }
+
+ done:
+ ;
+}
+
+static void
+test_crypto_ed25519_testvectors(void *arg)
+{
+ unsigned i;
+ char *mem_op_hex_tmp = NULL;
+ (void)arg;
+
+ for (i = 0; i < ARRAY_LENGTH(ED25519_SECRET_KEYS); ++i) {
+ uint8_t sk[32];
+ ed25519_secret_key_t esk;
+ ed25519_public_key_t pk, blind_pk, pkfromcurve;
+ ed25519_keypair_t keypair, blind_keypair;
+ curve25519_keypair_t curvekp;
+ uint8_t blinding_param[32];
+ ed25519_signature_t sig;
+ int sign;
+
+#define DECODE(p,s) base16_decode((char*)(p),sizeof(p),(s),strlen(s))
+#define EQ(a,h) test_memeq_hex((const char*)(a), (h))
+
+ tt_int_op(0, OP_EQ, DECODE(sk, ED25519_SECRET_KEYS[i]));
+ tt_int_op(0, OP_EQ, DECODE(blinding_param, ED25519_BLINDING_PARAMS[i]));
+
+ tt_int_op(0, OP_EQ, ed25519_secret_key_from_seed(&esk, sk));
+ EQ(esk.seckey, ED25519_EXPANDED_SECRET_KEYS[i]);
+
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pk, &esk));
+ EQ(pk.pubkey, ED25519_PUBLIC_KEYS[i]);
+
+ memcpy(&curvekp.seckey.secret_key, esk.seckey, 32);
+ curve25519_public_key_generate(&curvekp.pubkey, &curvekp.seckey);
+
+ tt_int_op(0, OP_EQ,
+ ed25519_keypair_from_curve25519_keypair(&keypair, &sign, &curvekp));
+ tt_int_op(0, OP_EQ, ed25519_public_key_from_curve25519_public_key(
+ &pkfromcurve, &curvekp.pubkey, sign));
+ tt_mem_op(keypair.pubkey.pubkey, OP_EQ, pkfromcurve.pubkey, 32);
+ EQ(curvekp.pubkey.public_key, ED25519_CURVE25519_PUBLIC_KEYS[i]);
+
+ /* Self-signing */
+ memcpy(&keypair.seckey, &esk, sizeof(esk));
+ memcpy(&keypair.pubkey, &pk, sizeof(pk));
+
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig, pk.pubkey, 32, &keypair));
+
+ EQ(sig.sig, ED25519_SELF_SIGNATURES[i]);
+
+ /* Blinding */
+ tt_int_op(0, OP_EQ,
+ ed25519_keypair_blind(&blind_keypair, &keypair, blinding_param));
+ tt_int_op(0, OP_EQ,
+ ed25519_public_blind(&blind_pk, &pk, blinding_param));
+
+ EQ(blind_keypair.seckey.seckey, ED25519_BLINDED_SECRET_KEYS[i]);
+ EQ(blind_pk.pubkey, ED25519_BLINDED_PUBLIC_KEYS[i]);
+
+ tt_mem_op(blind_pk.pubkey, OP_EQ, blind_keypair.pubkey.pubkey, 32);
+
+#undef DECODE
+#undef EQ
+ }
+ done:
+ tor_free(mem_op_hex_tmp);
+}
+
+static void
+test_crypto_ed25519_fuzz_donna(void *arg)
+{
+ const unsigned iters = 1024;
+ uint8_t msg[1024];
+ unsigned i;
+ (void)arg;
+
+ tt_assert(sizeof(msg) == iters);
+ crypto_rand((char*) msg, sizeof(msg));
+
+ /* Fuzz Ed25519-donna vs ref10, alternating the implementation used to
+ * generate keys/sign per iteration.
+ */
+ for (i = 0; i < iters; ++i) {
+ const int use_donna = i & 1;
+ uint8_t blinding[32];
+ curve25519_keypair_t ckp;
+ ed25519_keypair_t kp, kp_blind, kp_curve25519;
+ ed25519_public_key_t pk, pk_blind, pk_curve25519;
+ ed25519_signature_t sig, sig_blind;
+ int bit = 0;
+
+ crypto_rand((char*) blinding, sizeof(blinding));
+
+ /* Impl. A:
+ * 1. Generate a keypair.
+ * 2. Blinded the keypair.
+ * 3. Sign a message (unblinded).
+ * 4. Sign a message (blinded).
+ * 5. Generate a curve25519 keypair, and convert it to Ed25519.
+ */
+ ed25519_set_impl_params(use_donna);
+ tt_int_op(0, OP_EQ, ed25519_keypair_generate(&kp, i&1));
+ tt_int_op(0, OP_EQ, ed25519_keypair_blind(&kp_blind, &kp, blinding));
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig, msg, i, &kp));
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig_blind, msg, i, &kp_blind));
+
+ tt_int_op(0, OP_EQ, curve25519_keypair_generate(&ckp, i&1));
+ tt_int_op(0, OP_EQ, ed25519_keypair_from_curve25519_keypair(
+ &kp_curve25519, &bit, &ckp));
+
+ /* Impl. B:
+ * 1. Validate the public key by rederiving it.
+ * 2. Validate the blinded public key by rederiving it.
+ * 3. Validate the unblinded signature (and test a invalid signature).
+ * 4. Validate the blinded signature.
+ * 5. Validate the public key (from Curve25519) by rederiving it.
+ */
+ ed25519_set_impl_params(!use_donna);
+ tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pk, &kp.seckey));
+ tt_mem_op(pk.pubkey, OP_EQ, kp.pubkey.pubkey, 32);
+
+ tt_int_op(0, OP_EQ, ed25519_public_blind(&pk_blind, &kp.pubkey, blinding));
+ tt_mem_op(pk_blind.pubkey, OP_EQ, kp_blind.pubkey.pubkey, 32);
+
+ tt_int_op(0, OP_EQ, ed25519_checksig(&sig, msg, i, &pk));
+ sig.sig[0] ^= 15;
+ tt_int_op(-1, OP_EQ, ed25519_checksig(&sig, msg, sizeof(msg), &pk));
+
+ tt_int_op(0, OP_EQ, ed25519_checksig(&sig_blind, msg, i, &pk_blind));
+
+ tt_int_op(0, OP_EQ, ed25519_public_key_from_curve25519_public_key(
+ &pk_curve25519, &ckp.pubkey, bit));
+ tt_mem_op(pk_curve25519.pubkey, OP_EQ, kp_curve25519.pubkey.pubkey, 32);
+ }
+
+ done:
+ ;
+}
static void
test_crypto_siphash(void *arg)
@@ -1251,7 +2270,7 @@ test_crypto_siphash(void *arg)
for (i = 0; i < 64; ++i) {
uint64_t r = siphash24(input, i, &K);
for (j = 0; j < 8; ++j) {
- tt_int_op( (r >> (j*8)) & 0xff, ==, VECTORS[i][j]);
+ tt_int_op( (r >> (j*8)) & 0xff, OP_EQ, VECTORS[i][j]);
}
}
@@ -1259,49 +2278,159 @@ test_crypto_siphash(void *arg)
;
}
-static void *
-pass_data_setup_fn(const struct testcase_t *testcase)
+/* We want the likelihood that the random buffer exhibits any regular pattern
+ * to be far less than the memory bit error rate in the int return value.
+ * Using 2048 bits provides a failure rate of 1/(3 * 10^616), and we call
+ * 3 functions, leading to an overall error rate of 1/10^616.
+ * This is comparable with the 1/10^603 failure rate of test_crypto_rng_range.
+ */
+#define FAILURE_MODE_BUFFER_SIZE (2048/8)
+
+/** Check crypto_rand for a failure mode where it does nothing to the buffer,
+ * or it sets the buffer to all zeroes. Return 0 when the check passes,
+ * or -1 when it fails. */
+static int
+crypto_rand_check_failure_mode_zero(void)
{
- return testcase->setup_data;
+ char buf[FAILURE_MODE_BUFFER_SIZE];
+
+ memset(buf, 0, FAILURE_MODE_BUFFER_SIZE);
+ crypto_rand(buf, FAILURE_MODE_BUFFER_SIZE);
+
+ for (size_t i = 0; i < FAILURE_MODE_BUFFER_SIZE; i++) {
+ if (buf[i] != 0) {
+ return 0;
+ }
+ }
+
+ return -1;
}
+
+/** Check crypto_rand for a failure mode where every int64_t in the buffer is
+ * the same. Return 0 when the check passes, or -1 when it fails. */
static int
-pass_data_cleanup_fn(const struct testcase_t *testcase, void *ptr)
+crypto_rand_check_failure_mode_identical(void)
{
- (void)ptr;
- (void)testcase;
- return 1;
+ /* just in case the buffer size isn't a multiple of sizeof(int64_t) */
+#define FAILURE_MODE_BUFFER_SIZE_I64 \
+ (FAILURE_MODE_BUFFER_SIZE/SIZEOF_INT64_T)
+#define FAILURE_MODE_BUFFER_SIZE_I64_BYTES \
+ (FAILURE_MODE_BUFFER_SIZE_I64*SIZEOF_INT64_T)
+
+#if FAILURE_MODE_BUFFER_SIZE_I64 < 2
+#error FAILURE_MODE_BUFFER_SIZE needs to be at least 2*SIZEOF_INT64_T
+#endif
+
+ int64_t buf[FAILURE_MODE_BUFFER_SIZE_I64];
+
+ memset(buf, 0, FAILURE_MODE_BUFFER_SIZE_I64_BYTES);
+ crypto_rand((char *)buf, FAILURE_MODE_BUFFER_SIZE_I64_BYTES);
+
+ for (size_t i = 1; i < FAILURE_MODE_BUFFER_SIZE_I64; i++) {
+ if (buf[i] != buf[i-1]) {
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+/** Check crypto_rand for a failure mode where it increments the "random"
+ * value by 1 for every byte in the buffer. (This is OpenSSL's PREDICT mode.)
+ * Return 0 when the check passes, or -1 when it fails. */
+static int
+crypto_rand_check_failure_mode_predict(void)
+{
+ unsigned char buf[FAILURE_MODE_BUFFER_SIZE];
+
+ memset(buf, 0, FAILURE_MODE_BUFFER_SIZE);
+ crypto_rand((char *)buf, FAILURE_MODE_BUFFER_SIZE);
+
+ for (size_t i = 1; i < FAILURE_MODE_BUFFER_SIZE; i++) {
+ /* check if the last byte was incremented by 1, including integer
+ * wrapping */
+ if (buf[i] - buf[i-1] != 1 && buf[i-1] - buf[i] != 255) {
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+#undef FAILURE_MODE_BUFFER_SIZE
+
+static void
+test_crypto_failure_modes(void *arg)
+{
+ int rv = 0;
+ (void)arg;
+
+ rv = crypto_early_init();
+ tt_assert(rv == 0);
+
+ /* Check random works */
+ rv = crypto_rand_check_failure_mode_zero();
+ tt_assert(rv == 0);
+
+ rv = crypto_rand_check_failure_mode_identical();
+ tt_assert(rv == 0);
+
+ rv = crypto_rand_check_failure_mode_predict();
+ tt_assert(rv == 0);
+
+ done:
+ ;
}
-static const struct testcase_setup_t pass_data = {
- pass_data_setup_fn, pass_data_cleanup_fn
-};
#define CRYPTO_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_crypto_ ## name }
+ { #name, test_crypto_ ## name , 0, NULL, NULL }
+
+#define ED25519_TEST_ONE(name, fl, which) \
+ { #name "/ed25519_" which, test_crypto_ed25519_ ## name, (fl), \
+ &ed25519_test_setup, (void*)which }
+
+#define ED25519_TEST(name, fl) \
+ ED25519_TEST_ONE(name, (fl), "donna"), \
+ ED25519_TEST_ONE(name, (fl), "ref10")
struct testcase_t crypto_tests[] = {
CRYPTO_LEGACY(formats),
CRYPTO_LEGACY(rng),
- { "aes_AES", test_crypto_aes, TT_FORK, &pass_data, (void*)"aes" },
- { "aes_EVP", test_crypto_aes, TT_FORK, &pass_data, (void*)"evp" },
+ { "rng_range", test_crypto_rng_range, 0, NULL, NULL },
+ { "rng_engine", test_crypto_rng_engine, TT_FORK, NULL, NULL },
+ { "aes_AES", test_crypto_aes, TT_FORK, &passthrough_setup, (void*)"aes" },
+ { "aes_EVP", test_crypto_aes, TT_FORK, &passthrough_setup, (void*)"evp" },
CRYPTO_LEGACY(sha),
CRYPTO_LEGACY(pk),
{ "pk_fingerprints", test_crypto_pk_fingerprints, TT_FORK, NULL, NULL },
+ { "pk_base64", test_crypto_pk_base64, TT_FORK, NULL, NULL },
CRYPTO_LEGACY(digests),
+ { "sha3", test_crypto_sha3, TT_FORK, NULL, NULL},
+ { "sha3_xof", test_crypto_sha3_xof, TT_FORK, NULL, NULL},
CRYPTO_LEGACY(dh),
- CRYPTO_LEGACY(s2k),
- { "aes_iv_AES", test_crypto_aes_iv, TT_FORK, &pass_data, (void*)"aes" },
- { "aes_iv_EVP", test_crypto_aes_iv, TT_FORK, &pass_data, (void*)"evp" },
+ { "aes_iv_AES", test_crypto_aes_iv, TT_FORK, &passthrough_setup,
+ (void*)"aes" },
+ { "aes_iv_EVP", test_crypto_aes_iv, TT_FORK, &passthrough_setup,
+ (void*)"evp" },
CRYPTO_LEGACY(base32_decode),
{ "kdf_TAP", test_crypto_kdf_TAP, 0, NULL, NULL },
{ "hkdf_sha256", test_crypto_hkdf_sha256, 0, NULL, NULL },
-#ifdef CURVE25519_ENABLED
{ "curve25519_impl", test_crypto_curve25519_impl, 0, NULL, NULL },
{ "curve25519_impl_hibit", test_crypto_curve25519_impl, 0, NULL, (void*)"y"},
+ { "curve25519_basepoint",
+ test_crypto_curve25519_basepoint, TT_FORK, NULL, NULL },
{ "curve25519_wrappers", test_crypto_curve25519_wrappers, 0, NULL, NULL },
{ "curve25519_encode", test_crypto_curve25519_encode, 0, NULL, NULL },
{ "curve25519_persist", test_crypto_curve25519_persist, 0, NULL, NULL },
-#endif
+ ED25519_TEST(simple, 0),
+ ED25519_TEST(test_vectors, 0),
+ ED25519_TEST(encode, 0),
+ ED25519_TEST(convert, 0),
+ ED25519_TEST(blinding, 0),
+ ED25519_TEST(testvectors, 0),
+ ED25519_TEST(fuzz_donna, TT_FORK),
{ "siphash", test_crypto_siphash, 0, NULL, NULL },
+ { "failure_modes", test_crypto_failure_modes, TT_FORK, NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_crypto_slow.c b/src/test/test_crypto_slow.c
new file mode 100644
index 0000000000..6f3e40e0ab
--- /dev/null
+++ b/src/test/test_crypto_slow.c
@@ -0,0 +1,532 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#define CRYPTO_S2K_PRIVATE
+#include "or.h"
+#include "test.h"
+#include "crypto_s2k.h"
+#include "crypto_pwbox.h"
+
+#if defined(HAVE_LIBSCRYPT_H) && defined(HAVE_LIBSCRYPT_SCRYPT)
+#define HAVE_LIBSCRYPT
+#include <libscrypt.h>
+#endif
+
+#include <openssl/evp.h>
+
+/** Run unit tests for our secret-to-key passphrase hashing functionality. */
+static void
+test_crypto_s2k_rfc2440(void *arg)
+{
+ char buf[29];
+ char buf2[29];
+ char *buf3 = NULL;
+ int i;
+
+ (void)arg;
+ memset(buf, 0, sizeof(buf));
+ memset(buf2, 0, sizeof(buf2));
+ buf3 = tor_malloc(65536);
+ memset(buf3, 0, 65536);
+
+ secret_to_key_rfc2440(buf+9, 20, "", 0, buf);
+ crypto_digest(buf2+9, buf3, 1024);
+ tt_mem_op(buf,OP_EQ, buf2, 29);
+
+ memcpy(buf,"vrbacrda",8);
+ memcpy(buf2,"vrbacrda",8);
+ buf[8] = 96;
+ buf2[8] = 96;
+ secret_to_key_rfc2440(buf+9, 20, "12345678", 8, buf);
+ for (i = 0; i < 65536; i += 16) {
+ memcpy(buf3+i, "vrbacrda12345678", 16);
+ }
+ crypto_digest(buf2+9, buf3, 65536);
+ tt_mem_op(buf,OP_EQ, buf2, 29);
+
+ done:
+ tor_free(buf3);
+}
+
+static void
+run_s2k_tests(const unsigned flags, const unsigned type,
+ int speclen, const int keylen, int legacy)
+{
+ uint8_t buf[S2K_MAXLEN], buf2[S2K_MAXLEN], buf3[S2K_MAXLEN];
+ int r;
+ size_t sz;
+ const char pw1[] = "You can't come in here unless you say swordfish!";
+ const char pw2[] = "Now, I give you one more guess.";
+
+ r = secret_to_key_new(buf, sizeof(buf), &sz,
+ pw1, strlen(pw1), flags);
+ tt_int_op(r, OP_EQ, S2K_OKAY);
+ tt_int_op(buf[0], OP_EQ, type);
+
+ tt_int_op(sz, OP_EQ, keylen + speclen);
+
+ if (legacy) {
+ memmove(buf, buf+1, sz-1);
+ --sz;
+ --speclen;
+ }
+
+ tt_int_op(S2K_OKAY, OP_EQ,
+ secret_to_key_check(buf, sz, pw1, strlen(pw1)));
+
+ tt_int_op(S2K_BAD_SECRET, OP_EQ,
+ secret_to_key_check(buf, sz, pw2, strlen(pw2)));
+
+ /* Move key to buf2, and clear it. */
+ memset(buf3, 0, sizeof(buf3));
+ memcpy(buf2, buf+speclen, keylen);
+ memset(buf+speclen, 0, sz - speclen);
+
+ /* Derivekey should produce the same results. */
+ tt_int_op(S2K_OKAY, OP_EQ,
+ secret_to_key_derivekey(buf3, keylen, buf, speclen, pw1, strlen(pw1)));
+
+ tt_mem_op(buf2, OP_EQ, buf3, keylen);
+
+ /* Derivekey with a longer output should fill the output. */
+ memset(buf2, 0, sizeof(buf2));
+ tt_int_op(S2K_OKAY, OP_EQ,
+ secret_to_key_derivekey(buf2, sizeof(buf2), buf, speclen,
+ pw1, strlen(pw1)));
+
+ tt_mem_op(buf2, OP_NE, buf3, sizeof(buf2));
+
+ memset(buf3, 0, sizeof(buf3));
+ tt_int_op(S2K_OKAY, OP_EQ,
+ secret_to_key_derivekey(buf3, sizeof(buf3), buf, speclen,
+ pw1, strlen(pw1)));
+ tt_mem_op(buf2, OP_EQ, buf3, sizeof(buf3));
+ tt_assert(!tor_mem_is_zero((char*)buf2+keylen, sizeof(buf2)-keylen));
+
+ done:
+ ;
+}
+
+static void
+test_crypto_s2k_general(void *arg)
+{
+ const char *which = arg;
+
+ if (!strcmp(which, "scrypt")) {
+ run_s2k_tests(0, 2, 19, 32, 0);
+ } else if (!strcmp(which, "scrypt-low")) {
+ run_s2k_tests(S2K_FLAG_LOW_MEM, 2, 19, 32, 0);
+ } else if (!strcmp(which, "pbkdf2")) {
+ run_s2k_tests(S2K_FLAG_USE_PBKDF2, 1, 18, 20, 0);
+ } else if (!strcmp(which, "rfc2440")) {
+ run_s2k_tests(S2K_FLAG_NO_SCRYPT, 0, 10, 20, 0);
+ } else if (!strcmp(which, "rfc2440-legacy")) {
+ run_s2k_tests(S2K_FLAG_NO_SCRYPT, 0, 10, 20, 1);
+ } else {
+ tt_fail();
+ }
+}
+
+#if defined(HAVE_LIBSCRYPT) && defined(HAVE_EVP_PBE_SCRYPT)
+static void
+test_libscrypt_eq_openssl(void *arg)
+{
+ uint8_t buf1[64];
+ uint8_t buf2[64];
+
+ uint64_t N, r, p;
+ uint64_t maxmem = 0; // --> SCRYPT_MAX_MEM in OpenSSL.
+
+ int libscrypt_retval, openssl_retval;
+
+ size_t dk_len = 64;
+
+ (void)arg;
+
+ memset(buf1,0,64);
+ memset(buf2,0,64);
+
+ /* NOTE: we're using N,r the way OpenSSL and libscrypt define them,
+ * not the way draft-josefsson-scrypt-kdf-00.txt define them.
+ */
+ N = 16;
+ r = 1;
+ p = 1;
+
+ libscrypt_retval =
+ libscrypt_scrypt((const uint8_t *)"", 0, (const uint8_t *)"", 0,
+ N, r, p, buf1, dk_len);
+ openssl_retval =
+ EVP_PBE_scrypt((const char *)"", 0, (const unsigned char *)"", 0,
+ N, r, p, maxmem, buf2, dk_len);
+
+ tt_int_op(libscrypt_retval, ==, 0);
+ tt_int_op(openssl_retval, ==, 1);
+
+ tt_mem_op(buf1, ==, buf2, 64);
+
+ memset(buf1,0,64);
+ memset(buf2,0,64);
+
+ N = 1024;
+ r = 8;
+ p = 16;
+
+ libscrypt_retval =
+ libscrypt_scrypt((const uint8_t *)"password", strlen("password"),
+ (const uint8_t *)"NaCl", strlen("NaCl"),
+ N, r, p, buf1, dk_len);
+ openssl_retval =
+ EVP_PBE_scrypt((const char *)"password", strlen("password"),
+ (const unsigned char *)"NaCl", strlen("NaCl"),
+ N, r, p, maxmem, buf2, dk_len);
+
+ tt_int_op(libscrypt_retval, ==, 0);
+ tt_int_op(openssl_retval, ==, 1);
+
+ tt_mem_op(buf1, ==, buf2, 64);
+
+ memset(buf1,0,64);
+ memset(buf2,0,64);
+
+ N = 16384;
+ r = 8;
+ p = 1;
+
+ libscrypt_retval =
+ libscrypt_scrypt((const uint8_t *)"pleaseletmein",
+ strlen("pleaseletmein"),
+ (const uint8_t *)"SodiumChloride",
+ strlen("SodiumChloride"),
+ N, r, p, buf1, dk_len);
+ openssl_retval =
+ EVP_PBE_scrypt((const char *)"pleaseletmein",
+ strlen("pleaseletmein"),
+ (const unsigned char *)"SodiumChloride",
+ strlen("SodiumChloride"),
+ N, r, p, maxmem, buf2, dk_len);
+
+ tt_int_op(libscrypt_retval, ==, 0);
+ tt_int_op(openssl_retval, ==, 1);
+
+ tt_mem_op(buf1, ==, buf2, 64);
+
+ memset(buf1,0,64);
+ memset(buf2,0,64);
+
+ N = 1048576;
+ maxmem = 2 * 1024 * 1024 * (uint64_t)1024; // 2 GB
+
+ libscrypt_retval =
+ libscrypt_scrypt((const uint8_t *)"pleaseletmein",
+ strlen("pleaseletmein"),
+ (const uint8_t *)"SodiumChloride",
+ strlen("SodiumChloride"),
+ N, r, p, buf1, dk_len);
+ openssl_retval =
+ EVP_PBE_scrypt((const char *)"pleaseletmein",
+ strlen("pleaseletmein"),
+ (const unsigned char *)"SodiumChloride",
+ strlen("SodiumChloride"),
+ N, r, p, maxmem, buf2, dk_len);
+
+ tt_int_op(libscrypt_retval, ==, 0);
+ tt_int_op(openssl_retval, ==, 1);
+
+ tt_mem_op(buf1, ==, buf2, 64);
+
+ done:
+ return;
+}
+#endif
+
+static void
+test_crypto_s2k_errors(void *arg)
+{
+ uint8_t buf[S2K_MAXLEN], buf2[S2K_MAXLEN];
+ size_t sz;
+
+ (void)arg;
+
+ /* Bogus specifiers: simple */
+ tt_int_op(S2K_BAD_LEN, OP_EQ,
+ secret_to_key_derivekey(buf, sizeof(buf),
+ (const uint8_t*)"", 0, "ABC", 3));
+ tt_int_op(S2K_BAD_ALGORITHM, OP_EQ,
+ secret_to_key_derivekey(buf, sizeof(buf),
+ (const uint8_t*)"\x10", 1, "ABC", 3));
+ tt_int_op(S2K_BAD_LEN, OP_EQ,
+ secret_to_key_derivekey(buf, sizeof(buf),
+ (const uint8_t*)"\x01\x02", 2, "ABC", 3));
+
+ tt_int_op(S2K_BAD_LEN, OP_EQ,
+ secret_to_key_check((const uint8_t*)"", 0, "ABC", 3));
+ tt_int_op(S2K_BAD_ALGORITHM, OP_EQ,
+ secret_to_key_check((const uint8_t*)"\x10", 1, "ABC", 3));
+ tt_int_op(S2K_BAD_LEN, OP_EQ,
+ secret_to_key_check((const uint8_t*)"\x01\x02", 2, "ABC", 3));
+
+ /* too long gets "BAD_LEN" too */
+ memset(buf, 0, sizeof(buf));
+ buf[0] = 2;
+ tt_int_op(S2K_BAD_LEN, OP_EQ,
+ secret_to_key_derivekey(buf2, sizeof(buf2),
+ buf, sizeof(buf), "ABC", 3));
+
+ /* Truncated output */
+#ifdef HAVE_LIBSCRYPT
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_new(buf, 50, &sz,
+ "ABC", 3, 0));
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_new(buf, 50, &sz,
+ "ABC", 3, S2K_FLAG_LOW_MEM));
+#endif
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_new(buf, 37, &sz,
+ "ABC", 3, S2K_FLAG_USE_PBKDF2));
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_new(buf, 29, &sz,
+ "ABC", 3, S2K_FLAG_NO_SCRYPT));
+
+#ifdef HAVE_LIBSCRYPT
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_make_specifier(buf, 18, 0));
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_make_specifier(buf, 18,
+ S2K_FLAG_LOW_MEM));
+#endif
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_make_specifier(buf, 17,
+ S2K_FLAG_USE_PBKDF2));
+ tt_int_op(S2K_TRUNCATED, OP_EQ, secret_to_key_make_specifier(buf, 9,
+ S2K_FLAG_NO_SCRYPT));
+
+ /* Now try using type-specific bogus specifiers. */
+
+ /* It's a bad pbkdf2 buffer if it has an iteration count that would overflow
+ * int32_t. */
+ memset(buf, 0, sizeof(buf));
+ buf[0] = 1; /* pbkdf2 */
+ buf[17] = 100; /* 1<<100 is much bigger than INT32_MAX */
+ tt_int_op(S2K_BAD_PARAMS, OP_EQ,
+ secret_to_key_derivekey(buf2, sizeof(buf2),
+ buf, 18, "ABC", 3));
+
+#ifdef HAVE_LIBSCRYPT
+ /* It's a bad scrypt buffer if N would overflow uint64 */
+ memset(buf, 0, sizeof(buf));
+ buf[0] = 2; /* scrypt */
+ buf[17] = 100; /* 1<<100 is much bigger than UINT64_MAX */
+ tt_int_op(S2K_BAD_PARAMS, OP_EQ,
+ secret_to_key_derivekey(buf2, sizeof(buf2),
+ buf, 19, "ABC", 3));
+#endif
+
+ done:
+ ;
+}
+
+static void
+test_crypto_scrypt_vectors(void *arg)
+{
+ char *mem_op_hex_tmp = NULL;
+ uint8_t spec[64], out[64];
+
+ (void)arg;
+#ifndef HAVE_LIBSCRYPT
+ if (1)
+ tt_skip();
+#endif
+
+ /* Test vectors from
+ http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-00 section 11.
+
+ Note that the names of 'r' and 'N' are switched in that section. Or
+ possibly in libscrypt.
+ */
+
+ base16_decode((char*)spec, sizeof(spec),
+ "0400", 4);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(64, OP_EQ,
+ secret_to_key_compute_key(out, 64, spec, 2, "", 0, 2));
+ test_memeq_hex(out,
+ "77d6576238657b203b19ca42c18a0497"
+ "f16b4844e3074ae8dfdffa3fede21442"
+ "fcd0069ded0948f8326a753a0fc81f17"
+ "e8d3e0fb2e0d3628cf35e20c38d18906");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "4e61436c" "0A34", 12);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(64, OP_EQ,
+ secret_to_key_compute_key(out, 64, spec, 6, "password", 8, 2));
+ test_memeq_hex(out,
+ "fdbabe1c9d3472007856e7190d01e9fe"
+ "7c6ad7cbc8237830e77376634b373162"
+ "2eaf30d92e22a3886ff109279d9830da"
+ "c727afb94a83ee6d8360cbdfa2cc0640");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "536f6469756d43686c6f72696465" "0e30", 32);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(64, OP_EQ,
+ secret_to_key_compute_key(out, 64, spec, 16,
+ "pleaseletmein", 13, 2));
+ test_memeq_hex(out,
+ "7023bdcb3afd7348461c06cd81fd38eb"
+ "fda8fbba904f8e3ea9b543f6545da1f2"
+ "d5432955613f0fcf62d49705242a9af9"
+ "e61e85dc0d651e40dfcf017b45575887");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "536f6469756d43686c6f72696465" "1430", 32);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(64, OP_EQ,
+ secret_to_key_compute_key(out, 64, spec, 16,
+ "pleaseletmein", 13, 2));
+ test_memeq_hex(out,
+ "2101cb9b6a511aaeaddbbe09cf70f881"
+ "ec568d574a2ffd4dabe5ee9820adaa47"
+ "8e56fd8f4ba5d09ffa1c6d927c40f4c3"
+ "37304049e8a952fbcbf45c6fa77a41a4");
+
+ done:
+ tor_free(mem_op_hex_tmp);
+}
+
+static void
+test_crypto_pbkdf2_vectors(void *arg)
+{
+ char *mem_op_hex_tmp = NULL;
+ uint8_t spec[64], out[64];
+ (void)arg;
+
+ /* Test vectors from RFC6070, section 2 */
+ base16_decode((char*)spec, sizeof(spec),
+ "73616c74" "00" , 10);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(20, OP_EQ,
+ secret_to_key_compute_key(out, 20, spec, 5, "password", 8, 1));
+ test_memeq_hex(out, "0c60c80f961f0e71f3a9b524af6012062fe037a6");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "73616c74" "01" , 10);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(20, OP_EQ,
+ secret_to_key_compute_key(out, 20, spec, 5, "password", 8, 1));
+ test_memeq_hex(out, "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "73616c74" "0C" , 10);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(20, OP_EQ,
+ secret_to_key_compute_key(out, 20, spec, 5, "password", 8, 1));
+ test_memeq_hex(out, "4b007901b765489abead49d926f721d065a429c1");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "73616c74" "18" , 10);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(20, OP_EQ,
+ secret_to_key_compute_key(out, 20, spec, 5, "password", 8, 1));
+ test_memeq_hex(out, "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "73616c7453414c5473616c7453414c5473616c745"
+ "3414c5473616c7453414c5473616c74" "0C" , 74);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(25, OP_EQ,
+ secret_to_key_compute_key(out, 25, spec, 37,
+ "passwordPASSWORDpassword", 24, 1));
+ test_memeq_hex(out, "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038");
+
+ base16_decode((char*)spec, sizeof(spec),
+ "7361006c74" "0c" , 12);
+ memset(out, 0x00, sizeof(out));
+ tt_int_op(16, OP_EQ,
+ secret_to_key_compute_key(out, 16, spec, 6, "pass\0word", 9, 1));
+ test_memeq_hex(out, "56fa6aa75548099dcc37d7f03425e0c3");
+
+ done:
+ tor_free(mem_op_hex_tmp);
+}
+
+static void
+test_crypto_pwbox(void *arg)
+{
+ uint8_t *boxed=NULL, *decoded=NULL;
+ size_t len, dlen;
+ unsigned i;
+ const char msg[] = "This bunny reminds you that you still have a "
+ "salamander in your sylladex. She is holding the bunny Dave got you. "
+ "It’s sort of uncanny how similar they are, aside from the knitted "
+ "enhancements. Seriously, what are the odds?? So weird.";
+ const char pw[] = "I'm a night owl and a wise bird too";
+
+ const unsigned flags[] = { 0,
+ S2K_FLAG_NO_SCRYPT,
+ S2K_FLAG_LOW_MEM,
+ S2K_FLAG_NO_SCRYPT|S2K_FLAG_LOW_MEM,
+ S2K_FLAG_USE_PBKDF2 };
+ (void)arg;
+
+ for (i = 0; i < ARRAY_LENGTH(flags); ++i) {
+ tt_int_op(0, OP_EQ, crypto_pwbox(&boxed, &len,
+ (const uint8_t*)msg, strlen(msg),
+ pw, strlen(pw), flags[i]));
+ tt_assert(boxed);
+ tt_assert(len > 128+32);
+
+ tt_int_op(0, OP_EQ, crypto_unpwbox(&decoded, &dlen, boxed, len,
+ pw, strlen(pw)));
+
+ tt_assert(decoded);
+ tt_uint_op(dlen, OP_EQ, strlen(msg));
+ tt_mem_op(decoded, OP_EQ, msg, dlen);
+
+ tor_free(decoded);
+
+ tt_int_op(UNPWBOX_BAD_SECRET, OP_EQ, crypto_unpwbox(&decoded, &dlen,
+ boxed, len,
+ pw, strlen(pw)-1));
+ boxed[len-1] ^= 1;
+ tt_int_op(UNPWBOX_BAD_SECRET, OP_EQ, crypto_unpwbox(&decoded, &dlen,
+ boxed, len,
+ pw, strlen(pw)));
+ boxed[0] = 255;
+ tt_int_op(UNPWBOX_CORRUPTED, OP_EQ, crypto_unpwbox(&decoded, &dlen,
+ boxed, len,
+ pw, strlen(pw)));
+
+ tor_free(boxed);
+ }
+
+ done:
+ tor_free(boxed);
+ tor_free(decoded);
+}
+
+#define CRYPTO_LEGACY(name) \
+ { #name, test_crypto_ ## name , 0, NULL, NULL }
+
+struct testcase_t slow_crypto_tests[] = {
+ CRYPTO_LEGACY(s2k_rfc2440),
+#ifdef HAVE_LIBSCRYPT
+ { "s2k_scrypt", test_crypto_s2k_general, 0, &passthrough_setup,
+ (void*)"scrypt" },
+ { "s2k_scrypt_low", test_crypto_s2k_general, 0, &passthrough_setup,
+ (void*)"scrypt-low" },
+#ifdef HAVE_EVP_PBE_SCRYPT
+ { "libscrypt_eq_openssl", test_libscrypt_eq_openssl, 0, NULL, NULL },
+#endif
+#endif
+ { "s2k_pbkdf2", test_crypto_s2k_general, 0, &passthrough_setup,
+ (void*)"pbkdf2" },
+ { "s2k_rfc2440_general", test_crypto_s2k_general, 0, &passthrough_setup,
+ (void*)"rfc2440" },
+ { "s2k_rfc2440_legacy", test_crypto_s2k_general, 0, &passthrough_setup,
+ (void*)"rfc2440-legacy" },
+ { "s2k_errors", test_crypto_s2k_errors, 0, NULL, NULL },
+ { "scrypt_vectors", test_crypto_scrypt_vectors, 0, NULL, NULL },
+ { "pbkdf2_vectors", test_crypto_pbkdf2_vectors, 0, NULL, NULL },
+ { "pwbox", test_crypto_pwbox, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_data.c b/src/test/test_data.c
index 0c51c98f1e..32de54bc84 100644
--- a/src/test/test_data.c
+++ b/src/test/test_data.c
@@ -1,6 +1,6 @@
/* Copyright 2001-2004 Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/* Our unit test expect that the AUTHORITY_CERT_* public keys will sort
diff --git a/src/test/test_descriptors.inc b/src/test/test_descriptors.inc
new file mode 100644
index 0000000000..ecbccbd43a
--- /dev/null
+++ b/src/test/test_descriptors.inc
@@ -0,0 +1,305 @@
+const char TEST_DESCRIPTORS[] =
+"@uploaded-at 2014-06-08 19:20:11\n"
+"@source \"127.0.0.1\"\n"
+"router test000a 127.0.0.1 5000 0 7000\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint C7E7 CCB8 179F 8CC3 7F5C 8A04 2B3A 180B 934B 14BA\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 67A152A4C7686FB07664F872620635F194D76D95\n"
+"caches-extra-info\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAOuBUIEBARMkkka/TGyaQNgUEDLP0KG7sy6KNQTNOlZHUresPr/vlVjo\n"
+"HPpLMfu9M2z18c51YX/muWwY9x4MyQooD56wI4+AqXQcJRwQfQlPn3Ay82uZViA9\n"
+"DpBajRieLlKKkl145KjArpD7F5BVsqccvjErgFYXvhhjSrx7BVLnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAN6NLnSxWQnFXxqZi5D3b0BMgV6y9NJLGjYQVP+eWtPZWgqyv4zeYsqv\n"
+"O9y6c5lvxyUxmNHfoAbe/s8f2Vf3/YaC17asAVSln4ktrr3e9iY74a9RMWHv1Gzk\n"
+"3042nMcqj3PEhRN0PoLkcOZNjjmNbaqki6qy9bWWZDNTdo+uI44dAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"contact auth0@test.test\n"
+"ntor-onion-key pK4bs08ERYN591jj7ca17Rn9Q02TIEfhnjR6hSq+fhU=\n"
+"reject *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"rx88DuM3Y7tODlHNDDEVzKpwh3csaG1or+T4l2Xs1oq3iHHyPEtB6QTLYrC60trG\n"
+"aAPsj3DEowGfjga1b248g2dtic8Ab+0exfjMm1RHXfDam5TXXZU3A0wMyoHjqHuf\n"
+"eChGPgFNUvEc+5YtD27qEDcUjcinYztTs7/dzxBT4PE=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:11\n"
+"@source \"127.0.0.1\"\n"
+"router test001a 127.0.0.1 5001 0 7001\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint 35DA 711C FC62 F88B C243 DE32 DC0B C28A 3F62 2610\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 9E12278D6CF7608071FE98CE9DCEE48FA264518A\n"
+"caches-extra-info\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAPbyUrorqoXMW4oezqd307ZGxgobqvQs2nb3TdQyWrwsHtJmS3utdrJS\n"
+"xJUZPNHOQ2hrDWW1VvevYqRTGeXGZr9TDZ3+t/gVUttqYRhuzzgEKVAZSsTo5ctO\n"
+"QNHnzJ6Xx/w/trhWqPTeJ7R0TCyAbWW7aE3KaKdwvZilRZp/oRUnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALwOJ7XZHBnjJEuwF3Os6eashNbTH9YnH8TBZBdKgu3iFJYqDslcMIPX\n"
+"gWCJ9apPHyh1+/8OLRWeEYlwoZzgGi0rjm/+BNeOOmJbjfyjk97DuB9/2O5zr1BM\n"
+"CvOHqQSzMD+vz1ebvfM039a2mO8lXruUFPZQaFVxk8371XP2khqhAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"contact auth1@test.test\n"
+"ntor-onion-key t5bI1ksTdigOksMKRHUDwx/34ajEvDN1IpArOxIEWgk=\n"
+"reject *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"KtMW7A/pzu+np6aKJSy6d7drIb4yjz8SPCo+oQNxj2IqNHJir2O2nWu69xy+K0c1\n"
+"RL05KkcDaYzr5hC80FD1H+sTpGYD28SPkQkzPw+0pReSDl93pVXh0rU6Cdcm75FC\n"
+"t0UZzDt4TsMuFB0ZYpM3phKcQPpiDG6aR0LskL/YUvY=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:11\n"
+"@source \"127.0.0.1\"\n"
+"router test004r 127.0.0.1 5004 0 7004\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:10\n"
+"fingerprint CC6A 48BD 52BD 9A2C 6670 5863 AC31 AE17 6E63 8B02\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest B5CC249CEF394B5AFCA0C77FA7D5605615FA487C\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAMze36Hupy7HACcF3TMv5mJuZbx3d3cS0WYLl6vTeChBgpS5CEXq6zIu\n"
+"d31YmtUcxH6fOjDOudhbnXuoh1nH4CP+LocVHAdlGG1giAm7u8yZudVvVJiIqFgQ\n"
+"wVDcWx8LbGCi5P9J/ZPKAIVsSyS7xkOqHjz3VMo/uYLbQCFAwfkdAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAM/qGP365x6bH+ug7rKVy7V5lC9Ff2Jfk0wlTFIzzwn+DMSG6xDvulKe\n"
+"wcIzgGNdQu7qlKlQUif3GPMr0KSS32cRsmoRQJcsm9+lGUK871NyZ8AyrHT+LhyF\n"
+"cs718P0iN5yKF2FikNr727kEANCzvC1l9eP4qF5GGzsNtglbJ7bTAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"ntor-onion-key a9Pavqnx7DFhMWUO0d17qF9Py8+iie4FnxTHaTgfIXY=\n"
+"reject *:25\n"
+"reject *:119\n"
+"reject *:135-139\n"
+"reject *:445\n"
+"reject *:563\n"
+"reject *:1214\n"
+"reject *:4661-4666\n"
+"reject *:6346-6429\n"
+"reject *:6699\n"
+"reject *:6881-6999\n"
+"accept *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"HVW7kjBgEt+Qdvcrq+NQE1F9B8uV9D38KA2Bp6cYHLWCxL6N4GS8JQqbOEtnqaj7\n"
+"Vxrv7uy1Fzb15Zr+1sUVMxNv+LLRfr+JzfETMNYVkYDrNgr1cAAVEQzFWbIziond\n"
+"xMFp64yjEW9/I+82lb5GBZEiKdEd4QqWMmQosoYMTM8=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:12\n"
+"@source \"127.0.0.1\"\n"
+"router test002a 127.0.0.1 5002 0 7002\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint 29C7 BBB6 C437 32D5 BDF1 5671 F5C5 F1FB 6E36 4B47\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 9BB181EA86E0130680C3CC04AD7DE4C341ADC2C7\n"
+"caches-extra-info\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALNH19oF8Ajf+djlH/g7L+enFBf5Wwjmf3bPwNKWZ9G+B+Lg8SpfhZiw\n"
+"rUqi7h21f45BV/dN05dK6leWD8rj1T9kuM9TKBOEZxIWeq7zbXihyu4XPxP4FNTS\n"
+"+0G7BhdP4biALENmeyLhUCZaw5Ic/jFkHT4gV9S0iVZiEDwC9twXAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALeyQGMQBHgTxpO/i30uHjflTm9MNi3ZBNcOKpvBXWYgY42qTqOZ7Uam\n"
+"c5pmZhTLrQ1W8XlGDw8Cl8ktZ0ylodLZyUNajBtJvSFWTb8iwdZsshW6Ahb8TyfI\n"
+"Y7MwTlQ/7xw4mj1NEaui6bwGgEZUs18RTqhDrUc2Mcj1Yf61Rq+7AgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"contact auth2@test.test\n"
+"ntor-onion-key ukR41RjtiZ69KO0SrFTvL0LoZK/ZTT01FQWmCXTCUlE=\n"
+"reject *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"IY2s/RY4tdahrgfGG+vW7lOvpfofoxxSo7guGpSKGxVApiroCQtumoYifnnJ88G2\n"
+"K4IbxwEO8pgO8fnz1mibblUWw2vdDNjCifc1wtXJUE+ONA0UcLRlfQ94GbL8h2PG\n"
+"72z6i1+NN0QahXMk7MUbzI7bOXTJOiO8e2Zjk9vRnxI=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:12\n"
+"@source \"127.0.0.1\"\n"
+"router test006r 127.0.0.1 5006 0 7006\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint 829B 3FAA A42B 605A EB0B F380 8F32 8ED1 73E7 0D25\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 7ECB757002EB9B5838B13AE6F2357A5E585131B8\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALsNBChcLVndlS4HNXL3hxBJVgXctATz6yXcJt3bkDB5cjv7Q9fqN3Ue\n"
+"j3SI1OUBx4YrLcSLD/hELHVilLrrfbaraAFfAsydlRLjTVcMRx5FFlDd0E7TAadc\n"
+"71CkTipNnjwqz1mTRKkEFeepnh/JaFDidY9ER1rMBA5JRyBvqrD9AgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAPgipA8yLj1kqrMlAH7cK7IQEdmqmfNHGXdkYQ+TKtfLh0zeEIvvh9yh\n"
+"k+vKHS+HVoHo3tecB9QjJyDyyJTiETXCupSOY+ebG648JADAvv8v1WiE+KBXtjpl\n"
+"qgDTrDj5CwGuY6cvQdej5yg1UAVlMMZSg3thL3tCYtQbOq66lAlnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"ntor-onion-key q02F3AQsCX7+zXNpfTqBF8O8lusPhRJpQVxOnBvbOwc=\n"
+"reject *:25\n"
+"reject *:119\n"
+"reject *:135-139\n"
+"reject *:445\n"
+"reject *:563\n"
+"reject *:1214\n"
+"reject *:4661-4666\n"
+"reject *:6346-6429\n"
+"reject *:6699\n"
+"reject *:6881-6999\n"
+"accept *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"L1fdgoN/eXgdzIIXO63W4yGoC9lRozMU+T0Fimhd/XFV8qxeUT83Vgf63vxLUHIb\n"
+"D4a80Wj7Pm4y5a766qLGXxlz2FYjCdkp070UpgZneB+VifUlFd/bNAjsiYTstBKM\n"
+"EI2L0mhl9d/7KK8vgtadHdX1z1u7QjyF6ccnzhfqeiY=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:12\n"
+"@source \"127.0.0.1\"\n"
+"router test003r 127.0.0.1 5003 0 7003\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint 71FD 3A35 F705 8020 D595 B711 D52A 9A0A 99BB B467\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 3796BE0A95B699595445DFD3453CA2074E75BCE8\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAL44ctIioIfCYFzMTYNfK5qFAPGGUpsAFmS8pThQEY/tJU14+frJDBrC\n"
+"BkLvBs05Bw7xOUb0f2geiYGowBA6028smiq5HzTO7Kaga8vfV7AnANPX+n9cfHCr\n"
+"/2cMnKkT/GZzpdk0WbUw5Kc/G1ATIPFQHA8gZAi1fsSIDDn3GRV5AgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALlPo5AI1mVTi+194yOSf40caoFlxSTfXt8KjGVa1dO/bpX7L3noOjYg\n"
+"goU4Aqim7BHmBWQDE/tZNTrchFoLQFHi9N4pv/0ND3sY904pzqGpe3FeTuU8P9Jg\n"
+"q2w3MeO3GwG8CJf4FOdSkgi8UKkJhOld4g4kViQbrFLXfdFvnT/zAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"ntor-onion-key qluYCRrsesOTkavCLnNK6H1ToywyDquCyYeP0h/qol4=\n"
+"reject *:25\n"
+"reject *:119\n"
+"reject *:135-139\n"
+"reject *:445\n"
+"reject *:563\n"
+"reject *:1214\n"
+"reject *:4661-4666\n"
+"reject *:6346-6429\n"
+"reject *:6699\n"
+"reject *:6881-6999\n"
+"accept *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"d09K7rW/OpVzoUpfZXJuJW7a+P4pROCOZTgvDUIy/Nv+EAjcYqv95PlJ8cAMqnn3\n"
+"1oQibRmmQwn0OmG5cB8NaZiueaVIRheGzHEM8rndpHn5oFXdFvV7KKjScvfuBbTk\n"
+"RYME8XyawRaqsEZnwirDDlZuiZOjdQs8bbGsko3grJE=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:12\n"
+"@source \"127.0.0.1\"\n"
+"router test005r 127.0.0.1 5005 0 7005\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint EB6E 42ED E6BF 5EE0 19F5 EFC1 53AD 094C 1327 7B76\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest C031EE4E1AE826C1E3C4E21D81C961869E63F5D2\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAMd9Fm4KTSjFDzEABPZ1fwBCC2DNgee6nAmlde8FRbCVfcIHRiJyv9YG\n"
+"h530yUJal3hBfiWwy/SBA4LDz1flNCEwJm81s3waj4T9c676dAOLPcnOcJM5SbaQ\n"
+"hYPDrIZLEZHAk+IoM+avKYYocwCJXwx6WTtsedF0wJBZ9mQAJERJAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAKT7ldhV43S1CgoER/pU0Rigf0NzcSy25DQJrMRQnNmXnL03Dwuv/Iu7\n"
+"dCjgg64odnvSkXHFhkbjGcg8aXikvfbMyZTbsD8NrrP6FS6pfgPgZD9W2TK7QdHI\n"
+"QXwx1IYaaJK4nDUNfJhjrclydEdxmHbO1nLG1aS0ypn/G0EBpOSnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"ntor-onion-key umFmyRPA0dIsi0CFYCbGIPe2+OUkyslTkKKDEohjQQg=\n"
+"reject *:25\n"
+"reject *:119\n"
+"reject *:135-139\n"
+"reject *:445\n"
+"reject *:563\n"
+"reject *:1214\n"
+"reject *:4661-4666\n"
+"reject *:6346-6429\n"
+"reject *:6699\n"
+"reject *:6881-6999\n"
+"accept *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"JiXEbqPgDPWEb9DzCYINRXfmvMIc/IRtvshS8Vmmn7DW67TrTLKCEAnisGo92gMA\n"
+"bhxGb9G5Mxq/8YqGoqdI2Vp6tfKlz/9AmjHzFAo01y42gafXIdr1oUS2RimA8jfF\n"
+"hwfQkbG0FYEsJrH3EUa8sMhcjsEaohK/kgklMR7OgQY=\n"
+"-----END SIGNATURE-----\n"
+"@uploaded-at 2014-06-08 19:20:12\n"
+"@source \"127.0.0.1\"\n"
+"router test007r 127.0.0.1 5007 0 7007\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint DABD 2AAF 8C9F 3B71 7839 9C08 DCD8 CD9D 341D 0002\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest F80104A0DFFB4EB429325D41D1F71E5BF8C6C726\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAL42fYAriR/JeB/9NpVq5Y5EEHca+ugIpaSdRfbopWDtFjXLEk2jmO5A\n"
+"KoAGIkTKDr7e9101x63H+0Nh/7w3uYs/WqTXEH8/1sHwe+0PY2HL0S6qhlOo6X54\n"
+"EfK0nDDBAWFOpyiAMHRk8JVikKb56+FVIhCJgi1RIbLIiUQK2/kxAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAKQj2U5hmB68V6NQBqD8DfIkJjovvM8t6nGfYpkT8ORsROnmgI5mjM38\n"
+"cmh5GIjY9RgoOWolLmsWQ4SXtS0FvrPft1M61UMTSHzlrEeuod5KenV7vGlX2TxT\n"
+"0DoA5TL9yY7CmxCk8CNRCtN/g7WocgIiP4KCIiEZ4VE6LIb6sxUnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"ntor-onion-key 1UBS8rTlL39u9YxRJWhz+GTG1dS15VRi4au1i5qZOyI=\n"
+"reject *:25\n"
+"reject *:119\n"
+"reject *:135-139\n"
+"reject *:445\n"
+"reject *:563\n"
+"reject *:1214\n"
+"reject *:4661-4666\n"
+"reject *:6346-6429\n"
+"reject *:6699\n"
+"reject *:6881-6999\n"
+"accept *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"m7xHh+XPdLN+qcMLz1dBAEAmcdCFrtdseMHCc0FyAP2kXdayxqe3o2IOOHN++bTH\n"
+"Y5iHsZembsIJJ+D/d0YEKWKh42TUWCXBu0Gbfc4OcNuR6PFlTWO2wk7rDT3HOiFr\n"
+"pe3wJqZYkLxlBDamROAlMMRe71iag89H/4EulC18opw=\n"
+"-----END SIGNATURE-----\n";
diff --git a/src/test/test_dir.c b/src/test/test_dir.c
index c03b63be27..26b0e72a9a 100644
--- a/src/test/test_dir.c
+++ b/src/test/test_dir.c
@@ -1,79 +1,102 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
#include <math.h>
+#define CONFIG_PRIVATE
#define DIRSERV_PRIVATE
#define DIRVOTE_PRIVATE
#define ROUTER_PRIVATE
#define ROUTERLIST_PRIVATE
#define HIBERNATE_PRIVATE
#define NETWORKSTATUS_PRIVATE
+#define RELAY_PRIVATE
+
#include "or.h"
+#include "confparse.h"
#include "config.h"
+#include "crypto_ed25519.h"
#include "directory.h"
#include "dirserv.h"
#include "dirvote.h"
#include "hibernate.h"
+#include "memarea.h"
#include "networkstatus.h"
#include "router.h"
+#include "routerkeys.h"
#include "routerlist.h"
#include "routerparse.h"
+#include "routerset.h"
#include "test.h"
+#include "test_dir_common.h"
+#include "torcert.h"
+#include "relay.h"
+
+#define NS_MODULE dir
static void
-test_dir_nicknames(void)
+test_dir_nicknames(void *arg)
{
- test_assert( is_legal_nickname("a"));
- test_assert(!is_legal_nickname(""));
- test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
- test_assert(!is_legal_nickname("hyphen-")); /* bad char */
- test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
- test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
+ (void)arg;
+ tt_assert( is_legal_nickname("a"));
+ tt_assert(!is_legal_nickname(""));
+ tt_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
+ tt_assert(!is_legal_nickname("hyphen-")); /* bad char */
+ tt_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
+ tt_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
/* valid */
- test_assert( is_legal_nickname_or_hexdigest(
+ tt_assert( is_legal_nickname_or_hexdigest(
"$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
- test_assert( is_legal_nickname_or_hexdigest(
+ tt_assert( is_legal_nickname_or_hexdigest(
"$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
- test_assert( is_legal_nickname_or_hexdigest(
+ tt_assert( is_legal_nickname_or_hexdigest(
"$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
/* too short */
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
/* illegal char */
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
/* hex part too long */
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
/* Bad nickname */
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
"abcdefghijklmnoppqrst"));
/* Bad extra char. */
- test_assert(!is_legal_nickname_or_hexdigest(
+ tt_assert(!is_legal_nickname_or_hexdigest(
"$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
- test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
- test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
- test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
+ tt_assert(is_legal_nickname_or_hexdigest("xyzzy"));
+ tt_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
+ tt_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
done:
;
}
+static smartlist_t *mocked_configured_ports = NULL;
+
+/** Returns mocked_configured_ports */
+static const smartlist_t *
+mock_get_configured_ports(void)
+{
+ return mocked_configured_ports;
+}
+
/** Run unit tests for router descriptor generation logic. */
static void
-test_dir_formats(void)
+test_dir_formats(void *arg)
{
char *buf = NULL;
char buf2[8192];
@@ -86,13 +109,17 @@ test_dir_formats(void)
routerinfo_t *rp1 = NULL, *rp2 = NULL;
addr_policy_t *ex1, *ex2;
routerlist_t *dir1 = NULL, *dir2 = NULL;
+ uint8_t *rsa_cc = NULL;
or_options_t *options = get_options_mutable();
const addr_policy_t *p;
+ time_t now = time(NULL);
+ port_cfg_t orport, dirport;
+ (void)arg;
pk1 = pk_generate(0);
pk2 = pk_generate(1);
- test_assert(pk1 && pk2);
+ tt_assert(pk1 && pk2);
hibernate_set_state_for_testing_(HIBERNATE_STATE_LIVE);
@@ -102,6 +129,7 @@ test_dir_formats(void)
r1->cache_info.published_on = 0;
r1->or_port = 9000;
r1->dir_port = 9003;
+ r1->supports_tunnelled_dir_requests = 1;
tor_addr_parse(&r1->ipv6_addr, "1:2:3:4::");
r1->ipv6_orport = 9999;
r1->onion_pkey = crypto_pk_dup_key(pk1);
@@ -125,14 +153,33 @@ test_dir_formats(void)
ex2->prt_min = ex2->prt_max = 24;
r2 = tor_malloc_zero(sizeof(routerinfo_t));
r2->addr = 0x0a030201u; /* 10.3.2.1 */
+ ed25519_keypair_t kp1, kp2;
+ ed25519_secret_key_from_seed(&kp1.seckey,
+ (const uint8_t*)"YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
+ ed25519_public_key_generate(&kp1.pubkey, &kp1.seckey);
+ ed25519_secret_key_from_seed(&kp2.seckey,
+ (const uint8_t*)"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
+ ed25519_public_key_generate(&kp2.pubkey, &kp2.seckey);
+ r2->cache_info.signing_key_cert = tor_cert_create(&kp1,
+ CERT_TYPE_ID_SIGNING,
+ &kp2.pubkey,
+ now, 86400,
+ CERT_FLAG_INCLUDE_SIGNING_KEY);
+ char cert_buf[256];
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (const char*)r2->cache_info.signing_key_cert->encoded,
+ r2->cache_info.signing_key_cert->encoded_len,
+ BASE64_ENCODE_MULTILINE);
r2->platform = tor_strdup(platform);
r2->cache_info.published_on = 5;
r2->or_port = 9005;
r2->dir_port = 0;
+ r2->supports_tunnelled_dir_requests = 1;
r2->onion_pkey = crypto_pk_dup_key(pk2);
- r2->onion_curve25519_pkey = tor_malloc_zero(sizeof(curve25519_public_key_t));
- curve25519_public_from_base64(r2->onion_curve25519_pkey,
- "skyinAnvardNostarsNomoonNowindormistsorsnow");
+ curve25519_keypair_t r2_onion_keypair;
+ curve25519_keypair_generate(&r2_onion_keypair, 0);
+ r2->onion_curve25519_pkey = tor_memdup(&r2_onion_keypair.pubkey,
+ sizeof(curve25519_public_key_t));
r2->identity_pkey = crypto_pk_dup_key(pk1);
r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
r2->exit_policy = smartlist_new();
@@ -140,17 +187,41 @@ test_dir_formats(void)
smartlist_add(r2->exit_policy, ex2);
r2->nickname = tor_strdup("Fred");
- test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
+ tt_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
&pk1_str_len));
- test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
+ tt_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
&pk2_str_len));
/* XXXX025 router_dump_to_string should really take this from ri.*/
options->ContactInfo = tor_strdup("Magri White "
"<magri@elsewhere.example.com>");
- buf = router_dump_router_to_string(r1, pk2);
+ /* Skip reachability checks for DirPort and tunnelled-dir-server */
+ options->AssumeReachable = 1;
+
+ /* Fake just enough of an ORPort and DirPort to get by */
+ MOCK(get_configured_ports, mock_get_configured_ports);
+ mocked_configured_ports = smartlist_new();
+
+ memset(&orport, 0, sizeof(orport));
+ orport.type = CONN_TYPE_OR_LISTENER;
+ orport.addr.family = AF_INET;
+ orport.port = 9000;
+ smartlist_add(mocked_configured_ports, &orport);
+
+ memset(&dirport, 0, sizeof(dirport));
+ dirport.type = CONN_TYPE_DIR_LISTENER;
+ dirport.addr.family = AF_INET;
+ dirport.port = 9003;
+ smartlist_add(mocked_configured_ports, &dirport);
+
+ buf = router_dump_router_to_string(r1, pk2, NULL, NULL, NULL);
+
+ UNMOCK(get_configured_ports);
+ smartlist_free(mocked_configured_ports);
+ mocked_configured_ports = NULL;
+
tor_free(options->ContactInfo);
- test_assert(buf);
+ tt_assert(buf);
strlcpy(buf2, "router Magri 192.168.0.1 9000 0 9003\n"
"or-address [1:2:3:4::]:9999\n"
@@ -160,7 +231,7 @@ test_dir_formats(void)
"protocols Link 1 2 Circuit 1\n"
"published 1970-01-01 00:00:00\n"
"fingerprint ", sizeof(buf2));
- test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
+ tt_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
strlcat(buf2, fingerprint, sizeof(buf2));
strlcat(buf2, "\nuptime 0\n"
/* XXX the "0" above is hard-coded, but even if we made it reflect
@@ -174,38 +245,53 @@ test_dir_formats(void)
strlcat(buf2, "hidden-service-dir\n", sizeof(buf2));
strlcat(buf2, "contact Magri White <magri@elsewhere.example.com>\n",
sizeof(buf2));
- strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
+ strlcat(buf2, "reject *:*\n", sizeof(buf2));
+ strlcat(buf2, "tunnelled-dir-server\nrouter-signature\n", sizeof(buf2));
buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
* twice */
- test_streq(buf, buf2);
+ tt_str_op(buf,OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r1, pk2);
- test_assert(buf);
+ buf = router_dump_router_to_string(r1, pk2, NULL, NULL, NULL);
+ tt_assert(buf);
cp = buf;
- rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
- test_assert(rp1);
- test_eq(rp1->addr, r1->addr);
- test_eq(rp1->or_port, r1->or_port);
- //test_eq(rp1->dir_port, r1->dir_port);
- test_eq(rp1->bandwidthrate, r1->bandwidthrate);
- test_eq(rp1->bandwidthburst, r1->bandwidthburst);
- test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
- test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
- test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
- //test_assert(rp1->exit_policy == NULL);
+ rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
+ tt_assert(rp1);
+ tt_int_op(rp1->addr,OP_EQ, r1->addr);
+ tt_int_op(rp1->or_port,OP_EQ, r1->or_port);
+ tt_int_op(rp1->dir_port,OP_EQ, r1->dir_port);
+ tt_int_op(rp1->bandwidthrate,OP_EQ, r1->bandwidthrate);
+ tt_int_op(rp1->bandwidthburst,OP_EQ, r1->bandwidthburst);
+ tt_int_op(rp1->bandwidthcapacity,OP_EQ, r1->bandwidthcapacity);
+ tt_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
+ tt_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
+ tt_assert(rp1->supports_tunnelled_dir_requests);
+ //tt_assert(rp1->exit_policy == NULL);
tor_free(buf);
strlcpy(buf2,
"router Fred 10.3.2.1 9005 0 0\n"
- "platform Tor "VERSION" on ", sizeof(buf2));
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n", sizeof(buf2));
+ strlcat(buf2, cert_buf, sizeof(buf2));
+ strlcat(buf2, "-----END ED25519 CERT-----\n", sizeof(buf2));
+ strlcat(buf2, "master-key-ed25519 ", sizeof(buf2));
+ {
+ char k[ED25519_BASE64_LEN+1];
+ tt_assert(ed25519_public_to_base64(k,
+ &r2->cache_info.signing_key_cert->signing_key)
+ >= 0);
+ strlcat(buf2, k, sizeof(buf2));
+ strlcat(buf2, "\n", sizeof(buf2));
+ }
+ strlcat(buf2, "platform Tor "VERSION" on ", sizeof(buf2));
strlcat(buf2, get_uname(), sizeof(buf2));
strlcat(buf2, "\n"
"protocols Link 1 2 Circuit 1\n"
"published 1970-01-01 00:00:05\n"
"fingerprint ", sizeof(buf2));
- test_assert(!crypto_pk_get_fingerprint(pk1, fingerprint, 1));
+ tt_assert(!crypto_pk_get_fingerprint(pk1, fingerprint, 1));
strlcat(buf2, fingerprint, sizeof(buf2));
strlcat(buf2, "\nuptime 0\n"
"bandwidth 3000 3000 3000\n", sizeof(buf2));
@@ -213,62 +299,113 @@ test_dir_formats(void)
strlcat(buf2, pk2_str, sizeof(buf2));
strlcat(buf2, "signing-key\n", sizeof(buf2));
strlcat(buf2, pk1_str, sizeof(buf2));
+ int rsa_cc_len;
+ rsa_cc = make_tap_onion_key_crosscert(pk2,
+ &kp1.pubkey,
+ pk1,
+ &rsa_cc_len);
+ tt_assert(rsa_cc);
+ base64_encode(cert_buf, sizeof(cert_buf), (char*)rsa_cc, rsa_cc_len,
+ BASE64_ENCODE_MULTILINE);
+ strlcat(buf2, "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n", sizeof(buf2));
+ strlcat(buf2, cert_buf, sizeof(buf2));
+ strlcat(buf2, "-----END CROSSCERT-----\n", sizeof(buf2));
+ int ntor_cc_sign;
+ {
+ tor_cert_t *ntor_cc = NULL;
+ ntor_cc = make_ntor_onion_key_crosscert(&r2_onion_keypair,
+ &kp1.pubkey,
+ r2->cache_info.published_on,
+ MIN_ONION_KEY_LIFETIME,
+ &ntor_cc_sign);
+ tt_assert(ntor_cc);
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (char*)ntor_cc->encoded, ntor_cc->encoded_len,
+ BASE64_ENCODE_MULTILINE);
+ tor_cert_free(ntor_cc);
+ }
+ tor_snprintf(buf2+strlen(buf2), sizeof(buf2)-strlen(buf2),
+ "ntor-onion-key-crosscert %d\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "%s"
+ "-----END ED25519 CERT-----\n", ntor_cc_sign, cert_buf);
+
strlcat(buf2, "hidden-service-dir\n", sizeof(buf2));
-#ifdef CURVE25519_ENABLED
- strlcat(buf2, "ntor-onion-key "
- "skyinAnvardNostarsNomoonNowindormistsorsnow=\n", sizeof(buf2));
-#endif
+ strlcat(buf2, "ntor-onion-key ", sizeof(buf2));
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (const char*)r2_onion_keypair.pubkey.public_key, 32,
+ BASE64_ENCODE_MULTILINE);
+ strlcat(buf2, cert_buf, sizeof(buf2));
strlcat(buf2, "accept *:80\nreject 18.0.0.0/8:24\n", sizeof(buf2));
- strlcat(buf2, "router-signature\n", sizeof(buf2));
+ strlcat(buf2, "tunnelled-dir-server\n", sizeof(buf2));
+ strlcat(buf2, "router-sig-ed25519 ", sizeof(buf2));
- buf = router_dump_router_to_string(r2, pk1);
+ /* Fake just enough of an ORPort to get by */
+ MOCK(get_configured_ports, mock_get_configured_ports);
+ mocked_configured_ports = smartlist_new();
+
+ memset(&orport, 0, sizeof(orport));
+ orport.type = CONN_TYPE_OR_LISTENER;
+ orport.addr.family = AF_INET;
+ orport.port = 9005;
+ smartlist_add(mocked_configured_ports, &orport);
+
+ buf = router_dump_router_to_string(r2, pk1, pk2, &r2_onion_keypair, &kp2);
+ tt_assert(buf);
buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
* twice */
- test_streq(buf, buf2);
+
+ tt_str_op(buf, OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r2, pk1);
+ buf = router_dump_router_to_string(r2, pk1, NULL, NULL, NULL);
+
+ UNMOCK(get_configured_ports);
+ smartlist_free(mocked_configured_ports);
+ mocked_configured_ports = NULL;
+
+ /* Reset for later */
cp = buf;
- rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
- test_assert(rp2);
- test_eq(rp2->addr, r2->addr);
- test_eq(rp2->or_port, r2->or_port);
- test_eq(rp2->dir_port, r2->dir_port);
- test_eq(rp2->bandwidthrate, r2->bandwidthrate);
- test_eq(rp2->bandwidthburst, r2->bandwidthburst);
- test_eq(rp2->bandwidthcapacity, r2->bandwidthcapacity);
-#ifdef CURVE25519_ENABLED
- test_memeq(rp2->onion_curve25519_pkey->public_key,
+ rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
+ tt_assert(rp2);
+ tt_int_op(rp2->addr,OP_EQ, r2->addr);
+ tt_int_op(rp2->or_port,OP_EQ, r2->or_port);
+ tt_int_op(rp2->dir_port,OP_EQ, r2->dir_port);
+ tt_int_op(rp2->bandwidthrate,OP_EQ, r2->bandwidthrate);
+ tt_int_op(rp2->bandwidthburst,OP_EQ, r2->bandwidthburst);
+ tt_int_op(rp2->bandwidthcapacity,OP_EQ, r2->bandwidthcapacity);
+ tt_mem_op(rp2->onion_curve25519_pkey->public_key,OP_EQ,
r2->onion_curve25519_pkey->public_key,
CURVE25519_PUBKEY_LEN);
-#endif
- test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
- test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
+ tt_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
+ tt_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
+ tt_assert(rp2->supports_tunnelled_dir_requests);
- test_eq(smartlist_len(rp2->exit_policy), 2);
+ tt_int_op(smartlist_len(rp2->exit_policy),OP_EQ, 2);
p = smartlist_get(rp2->exit_policy, 0);
- test_eq(p->policy_type, ADDR_POLICY_ACCEPT);
- test_assert(tor_addr_is_null(&p->addr));
- test_eq(p->maskbits, 0);
- test_eq(p->prt_min, 80);
- test_eq(p->prt_max, 80);
+ tt_int_op(p->policy_type,OP_EQ, ADDR_POLICY_ACCEPT);
+ tt_assert(tor_addr_is_null(&p->addr));
+ tt_int_op(p->maskbits,OP_EQ, 0);
+ tt_int_op(p->prt_min,OP_EQ, 80);
+ tt_int_op(p->prt_max,OP_EQ, 80);
p = smartlist_get(rp2->exit_policy, 1);
- test_eq(p->policy_type, ADDR_POLICY_REJECT);
- test_assert(tor_addr_eq(&p->addr, &ex2->addr));
- test_eq(p->maskbits, 8);
- test_eq(p->prt_min, 24);
- test_eq(p->prt_max, 24);
+ tt_int_op(p->policy_type,OP_EQ, ADDR_POLICY_REJECT);
+ tt_assert(tor_addr_eq(&p->addr, &ex2->addr));
+ tt_int_op(p->maskbits,OP_EQ, 8);
+ tt_int_op(p->prt_min,OP_EQ, 24);
+ tt_int_op(p->prt_max,OP_EQ, 24);
#if 0
/* Okay, now for the directories. */
{
fingerprint_list = smartlist_new();
crypto_pk_get_fingerprint(pk2, buf, 1);
- add_fingerprint_to_dir("Magri", buf, fingerprint_list);
+ add_fingerprint_to_dir(buf, fingerprint_list, 0);
crypto_pk_get_fingerprint(pk1, buf, 1);
- add_fingerprint_to_dir("Fred", buf, fingerprint_list);
+ add_fingerprint_to_dir(buf, fingerprint_list, 0);
}
#endif
@@ -282,6 +419,7 @@ test_dir_formats(void)
if (rp2)
routerinfo_free(rp2);
+ tor_free(rsa_cc);
tor_free(buf);
tor_free(pk1_str);
tor_free(pk2_str);
@@ -292,56 +430,649 @@ test_dir_formats(void)
tor_free(dir2); /* And more !*/
}
+#include "failing_routerdescs.inc"
+
+static void
+test_dir_routerinfo_parsing(void *arg)
+{
+ (void) arg;
+
+ int again;
+ routerinfo_t *ri = NULL;
+
+#define CHECK_OK(s) \
+ do { \
+ routerinfo_free(ri); \
+ ri = router_parse_entry_from_string((s), NULL, 0, 0, NULL, NULL); \
+ tt_assert(ri); \
+ } while (0)
+#define CHECK_FAIL(s, againval) \
+ do { \
+ routerinfo_free(ri); \
+ again = 999; \
+ ri = router_parse_entry_from_string((s), NULL, 0, 0, NULL, &again); \
+ tt_assert(ri == NULL); \
+ tt_int_op(again, OP_EQ, (againval)); \
+ } while (0)
+
+ CHECK_OK(EX_RI_MINIMAL);
+ CHECK_OK(EX_RI_MAXIMAL);
+
+ CHECK_OK(EX_RI_MINIMAL_ED);
+
+ /* good annotations prepended */
+ routerinfo_free(ri);
+ ri = router_parse_entry_from_string(EX_RI_MINIMAL, NULL, 0, 0,
+ "@purpose bridge\n", NULL);
+ tt_assert(ri != NULL);
+ tt_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
+ routerinfo_free(ri);
+
+ /* bad annotations prepended. */
+ ri = router_parse_entry_from_string(EX_RI_MINIMAL,
+ NULL, 0, 0, "@purpose\n", NULL);
+ tt_assert(ri == NULL);
+
+ /* bad annotations on router. */
+ ri = router_parse_entry_from_string("@purpose\nrouter x\n", NULL, 0, 1,
+ NULL, NULL);
+ tt_assert(ri == NULL);
+
+ /* unwanted annotations on router. */
+ ri = router_parse_entry_from_string("@purpose foo\nrouter x\n", NULL, 0, 0,
+ NULL, NULL);
+ tt_assert(ri == NULL);
+
+ /* No signature. */
+ ri = router_parse_entry_from_string("router x\n", NULL, 0, 0,
+ NULL, NULL);
+ tt_assert(ri == NULL);
+
+ /* Not a router */
+ routerinfo_free(ri);
+ ri = router_parse_entry_from_string("hello\n", NULL, 0, 0, NULL, NULL);
+ tt_assert(ri == NULL);
+
+ CHECK_FAIL(EX_RI_BAD_SIG1, 1);
+ CHECK_FAIL(EX_RI_BAD_SIG2, 1);
+ CHECK_FAIL(EX_RI_BAD_TOKENS, 0);
+ CHECK_FAIL(EX_RI_BAD_PUBLISHED, 0);
+ CHECK_FAIL(EX_RI_NEG_BANDWIDTH, 0);
+ CHECK_FAIL(EX_RI_BAD_BANDWIDTH, 0);
+ CHECK_FAIL(EX_RI_BAD_BANDWIDTH2, 0);
+ CHECK_FAIL(EX_RI_BAD_ONIONKEY1, 0);
+ CHECK_FAIL(EX_RI_BAD_ONIONKEY2, 0);
+ CHECK_FAIL(EX_RI_BAD_PORTS, 0);
+ CHECK_FAIL(EX_RI_BAD_IP, 0);
+ CHECK_FAIL(EX_RI_BAD_DIRPORT, 0);
+ CHECK_FAIL(EX_RI_BAD_NAME2, 0);
+ CHECK_FAIL(EX_RI_BAD_UPTIME, 0);
+
+ CHECK_FAIL(EX_RI_BAD_BANDWIDTH3, 0);
+ CHECK_FAIL(EX_RI_BAD_NTOR_KEY, 0);
+ CHECK_FAIL(EX_RI_BAD_FINGERPRINT, 0);
+ CHECK_FAIL(EX_RI_MISMATCHED_FINGERPRINT, 0);
+ CHECK_FAIL(EX_RI_BAD_HAS_ACCEPT6, 0);
+ CHECK_FAIL(EX_RI_BAD_NO_EXIT_POLICY, 0);
+ CHECK_FAIL(EX_RI_BAD_IPV6_EXIT_POLICY, 0);
+ CHECK_FAIL(EX_RI_BAD_FAMILY, 0);
+ CHECK_FAIL(EX_RI_ZERO_ORPORT, 0);
+
+ CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT, 0);
+ CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT2, 0);
+ CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT_SIGN, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_SIG1, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_SIG2, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_SIG3, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_SIG4, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT1, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT3, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT4, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT5, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT6, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT7, 0);
+ CHECK_FAIL(EX_RI_ED_MISPLACED1, 0);
+ CHECK_FAIL(EX_RI_ED_MISPLACED2, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CERT1, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CERT2, 0);
+ CHECK_FAIL(EX_RI_ED_BAD_CERT3, 0);
+
+ /* This is allowed; we just ignore it. */
+ CHECK_OK(EX_RI_BAD_EI_DIGEST);
+ CHECK_OK(EX_RI_BAD_EI_DIGEST2);
+
+#undef CHECK_FAIL
+#undef CHECK_OK
+ done:
+ routerinfo_free(ri);
+}
+
+#include "example_extrainfo.inc"
+
+static void
+routerinfo_free_wrapper_(void *arg)
+{
+ routerinfo_free(arg);
+}
+
+static void
+test_dir_extrainfo_parsing(void *arg)
+{
+ (void) arg;
+
+#define CHECK_OK(s) \
+ do { \
+ extrainfo_free(ei); \
+ ei = extrainfo_parse_entry_from_string((s), NULL, 0, map, NULL); \
+ tt_assert(ei); \
+ } while (0)
+#define CHECK_FAIL(s, againval) \
+ do { \
+ extrainfo_free(ei); \
+ again = 999; \
+ ei = extrainfo_parse_entry_from_string((s), NULL, 0, map, &again); \
+ tt_assert(ei == NULL); \
+ tt_int_op(again, OP_EQ, (againval)); \
+ } while (0)
+#define ADD(name) \
+ do { \
+ ri = tor_malloc_zero(sizeof(routerinfo_t)); \
+ crypto_pk_t *pk = ri->identity_pkey = crypto_pk_new(); \
+ tt_assert(! crypto_pk_read_public_key_from_string(pk, \
+ name##_KEY, strlen(name##_KEY))); \
+ tt_int_op(0,OP_EQ,base16_decode(d, 20, name##_FP, strlen(name##_FP))); \
+ digestmap_set((digestmap_t*)map, d, ri); \
+ ri = NULL; \
+ } while (0)
+
+ routerinfo_t *ri = NULL;
+ char d[20];
+ struct digest_ri_map_t *map = NULL;
+ extrainfo_t *ei = NULL;
+ int again;
+
+ CHECK_OK(EX_EI_MINIMAL);
+ tt_assert(ei->pending_sig);
+ CHECK_OK(EX_EI_MAXIMAL);
+ tt_assert(ei->pending_sig);
+ CHECK_OK(EX_EI_GOOD_ED_EI);
+ tt_assert(ei->pending_sig);
+
+ map = (struct digest_ri_map_t *)digestmap_new();
+ ADD(EX_EI_MINIMAL);
+ ADD(EX_EI_MAXIMAL);
+ ADD(EX_EI_GOOD_ED_EI);
+ ADD(EX_EI_BAD_FP);
+ ADD(EX_EI_BAD_NICKNAME);
+ ADD(EX_EI_BAD_TOKENS);
+ ADD(EX_EI_BAD_START);
+ ADD(EX_EI_BAD_PUBLISHED);
+
+ ADD(EX_EI_ED_MISSING_SIG);
+ ADD(EX_EI_ED_MISSING_CERT);
+ ADD(EX_EI_ED_BAD_CERT1);
+ ADD(EX_EI_ED_BAD_CERT2);
+ ADD(EX_EI_ED_BAD_SIG1);
+ ADD(EX_EI_ED_BAD_SIG2);
+ ADD(EX_EI_ED_MISPLACED_CERT);
+ ADD(EX_EI_ED_MISPLACED_SIG);
+
+ CHECK_OK(EX_EI_MINIMAL);
+ tt_assert(!ei->pending_sig);
+ CHECK_OK(EX_EI_MAXIMAL);
+ tt_assert(!ei->pending_sig);
+ CHECK_OK(EX_EI_GOOD_ED_EI);
+ tt_assert(!ei->pending_sig);
+
+ CHECK_FAIL(EX_EI_BAD_SIG1,1);
+ CHECK_FAIL(EX_EI_BAD_SIG2,1);
+ CHECK_FAIL(EX_EI_BAD_SIG3,1);
+ CHECK_FAIL(EX_EI_BAD_FP,0);
+ CHECK_FAIL(EX_EI_BAD_NICKNAME,0);
+ CHECK_FAIL(EX_EI_BAD_TOKENS,0);
+ CHECK_FAIL(EX_EI_BAD_START,0);
+ CHECK_FAIL(EX_EI_BAD_PUBLISHED,0);
+
+ CHECK_FAIL(EX_EI_ED_MISSING_SIG,0);
+ CHECK_FAIL(EX_EI_ED_MISSING_CERT,0);
+ CHECK_FAIL(EX_EI_ED_BAD_CERT1,0);
+ CHECK_FAIL(EX_EI_ED_BAD_CERT2,0);
+ CHECK_FAIL(EX_EI_ED_BAD_SIG1,0);
+ CHECK_FAIL(EX_EI_ED_BAD_SIG2,0);
+ CHECK_FAIL(EX_EI_ED_MISPLACED_CERT,0);
+ CHECK_FAIL(EX_EI_ED_MISPLACED_SIG,0);
+
+#undef CHECK_OK
+#undef CHECK_FAIL
+
+ done:
+ escaped(NULL);
+ extrainfo_free(ei);
+ routerinfo_free(ri);
+ digestmap_free((digestmap_t*)map, routerinfo_free_wrapper_);
+}
+
static void
-test_dir_versions(void)
+test_dir_parse_router_list(void *arg)
+{
+ (void) arg;
+ smartlist_t *invalid = smartlist_new();
+ smartlist_t *dest = smartlist_new();
+ smartlist_t *chunks = smartlist_new();
+ int dest_has_ri = 1;
+ char *list = NULL;
+ const char *cp;
+ digestmap_t *map = NULL;
+ char *mem_op_hex_tmp = NULL;
+ routerinfo_t *ri = NULL;
+ char d[DIGEST_LEN];
+
+ smartlist_add(chunks, tor_strdup(EX_RI_MINIMAL)); // ri 0
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_PORTS)); // bad ri 0
+ smartlist_add(chunks, tor_strdup(EX_EI_MAXIMAL)); // ei 0
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_SIG2)); // bad ei --
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_NICKNAME));// bad ei 0
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_SIG1)); // bad ri --
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_PUBLISHED)); // bad ei 1
+ smartlist_add(chunks, tor_strdup(EX_RI_MAXIMAL)); // ri 1
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_FAMILY)); // bad ri 1
+ smartlist_add(chunks, tor_strdup(EX_EI_MINIMAL)); // ei 1
+
+ list = smartlist_join_strings(chunks, "", 0, NULL);
+
+ /* First, parse the routers. */
+ cp = list;
+ tt_int_op(0,OP_EQ,
+ router_parse_list_from_string(&cp, NULL, dest, SAVED_NOWHERE,
+ 0, 0, NULL, invalid));
+ tt_int_op(2, OP_EQ, smartlist_len(dest));
+ tt_ptr_op(cp, OP_EQ, list + strlen(list));
+
+ routerinfo_t *r = smartlist_get(dest, 0);
+ tt_mem_op(r->cache_info.signed_descriptor_body, OP_EQ,
+ EX_RI_MINIMAL, strlen(EX_RI_MINIMAL));
+ r = smartlist_get(dest, 1);
+ tt_mem_op(r->cache_info.signed_descriptor_body, OP_EQ,
+ EX_RI_MAXIMAL, strlen(EX_RI_MAXIMAL));
+
+ tt_int_op(2, OP_EQ, smartlist_len(invalid));
+ test_memeq_hex(smartlist_get(invalid, 0),
+ "ab9eeaa95e7d45740185b4e519c76ead756277a9");
+ test_memeq_hex(smartlist_get(invalid, 1),
+ "9a651ee03b64325959e8f1b46f2b689b30750b4c");
+
+ /* Now tidy up */
+ SMARTLIST_FOREACH(dest, routerinfo_t *, ri, routerinfo_free(ri));
+ SMARTLIST_FOREACH(invalid, uint8_t *, d, tor_free(d));
+ smartlist_clear(dest);
+ smartlist_clear(invalid);
+
+ /* And check extrainfos. */
+ dest_has_ri = 0;
+ map = (digestmap_t*)router_get_routerlist()->identity_map;
+ ADD(EX_EI_MINIMAL);
+ ADD(EX_EI_MAXIMAL);
+ ADD(EX_EI_BAD_NICKNAME);
+ ADD(EX_EI_BAD_PUBLISHED);
+ cp = list;
+ tt_int_op(0,OP_EQ,
+ router_parse_list_from_string(&cp, NULL, dest, SAVED_NOWHERE,
+ 1, 0, NULL, invalid));
+ tt_int_op(2, OP_EQ, smartlist_len(dest));
+ extrainfo_t *e = smartlist_get(dest, 0);
+ tt_mem_op(e->cache_info.signed_descriptor_body, OP_EQ,
+ EX_EI_MAXIMAL, strlen(EX_EI_MAXIMAL));
+ e = smartlist_get(dest, 1);
+ tt_mem_op(e->cache_info.signed_descriptor_body, OP_EQ,
+ EX_EI_MINIMAL, strlen(EX_EI_MINIMAL));
+
+ tt_int_op(2, OP_EQ, smartlist_len(invalid));
+ test_memeq_hex(smartlist_get(invalid, 0),
+ "d5df4aa62ee9ffc9543d41150c9864908e0390af");
+ test_memeq_hex(smartlist_get(invalid, 1),
+ "f61efd2a7f4531f3687a9043e0de90a862ec64ba");
+
+ done:
+ tor_free(list);
+ if (dest_has_ri)
+ SMARTLIST_FOREACH(dest, routerinfo_t *, rt, routerinfo_free(rt));
+ else
+ SMARTLIST_FOREACH(dest, extrainfo_t *, ei, extrainfo_free(ei));
+ smartlist_free(dest);
+ SMARTLIST_FOREACH(invalid, uint8_t *, d, tor_free(d));
+ smartlist_free(invalid);
+ SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
+ smartlist_free(chunks);
+ routerinfo_free(ri);
+ if (map) {
+ digestmap_free((digestmap_t*)map, routerinfo_free_wrapper_);
+ router_get_routerlist()->identity_map =
+ (struct digest_ri_map_t*)digestmap_new();
+ }
+ tor_free(mem_op_hex_tmp);
+
+#undef ADD
+}
+
+static download_status_t dls_minimal;
+static download_status_t dls_maximal;
+static download_status_t dls_bad_fingerprint;
+static download_status_t dls_bad_sig2;
+static download_status_t dls_bad_ports;
+static download_status_t dls_bad_tokens;
+
+static int mock_router_get_dl_status_unrecognized = 0;
+static int mock_router_get_dl_status_calls = 0;
+
+static download_status_t *
+mock_router_get_dl_status(const char *d)
+{
+ ++mock_router_get_dl_status_calls;
+ char hex[HEX_DIGEST_LEN+1];
+ base16_encode(hex, sizeof(hex), d, DIGEST_LEN);
+ if (!strcmp(hex, "3E31D19A69EB719C00B02EC60D13356E3F7A3452")) {
+ return &dls_minimal;
+ } else if (!strcmp(hex, "581D8A368A0FA854ECDBFAB841D88B3F1B004038")) {
+ return &dls_maximal;
+ } else if (!strcmp(hex, "2578AE227C6116CDE29B3F0E95709B9872DEE5F1")) {
+ return &dls_bad_fingerprint;
+ } else if (!strcmp(hex, "16D387D3A58F7DB3CF46638F8D0B90C45C7D769C")) {
+ return &dls_bad_sig2;
+ } else if (!strcmp(hex, "AB9EEAA95E7D45740185B4E519C76EAD756277A9")) {
+ return &dls_bad_ports;
+ } else if (!strcmp(hex, "A0CC2CEFAD59DBF19F468BFEE60E0868C804B422")) {
+ return &dls_bad_tokens;
+ } else {
+ ++mock_router_get_dl_status_unrecognized;
+ return NULL;
+ }
+}
+
+static void
+test_dir_load_routers(void *arg)
+{
+ (void) arg;
+ smartlist_t *chunks = smartlist_new();
+ smartlist_t *wanted = smartlist_new();
+ char buf[DIGEST_LEN];
+ char *mem_op_hex_tmp = NULL;
+ char *list = NULL;
+
+#define ADD(str) \
+ do { \
+ tt_int_op(0,OP_EQ,router_get_router_hash(str, strlen(str), buf)); \
+ smartlist_add(wanted, tor_strdup(hex_str(buf, DIGEST_LEN))); \
+ } while (0)
+
+ MOCK(router_get_dl_status_by_descriptor_digest, mock_router_get_dl_status);
+
+ update_approx_time(1412510400);
+
+ smartlist_add(chunks, tor_strdup(EX_RI_MINIMAL));
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_FINGERPRINT));
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_SIG2));
+ smartlist_add(chunks, tor_strdup(EX_RI_MAXIMAL));
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_PORTS));
+ smartlist_add(chunks, tor_strdup(EX_RI_BAD_TOKENS));
+
+ /* not ADDing MINIMIAL */
+ ADD(EX_RI_MAXIMAL);
+ ADD(EX_RI_BAD_FINGERPRINT);
+ ADD(EX_RI_BAD_SIG2);
+ /* Not ADDing BAD_PORTS */
+ ADD(EX_RI_BAD_TOKENS);
+
+ list = smartlist_join_strings(chunks, "", 0, NULL);
+ tt_int_op(1, OP_EQ,
+ router_load_routers_from_string(list, NULL, SAVED_IN_JOURNAL,
+ wanted, 1, NULL));
+
+ /* The "maximal" router was added. */
+ /* "minimal" was not. */
+ tt_int_op(smartlist_len(router_get_routerlist()->routers),OP_EQ,1);
+ routerinfo_t *r = smartlist_get(router_get_routerlist()->routers, 0);
+ test_memeq_hex(r->cache_info.signed_descriptor_digest,
+ "581D8A368A0FA854ECDBFAB841D88B3F1B004038");
+ tt_int_op(dls_minimal.n_download_failures, OP_EQ, 0);
+ tt_int_op(dls_maximal.n_download_failures, OP_EQ, 0);
+
+ /* "Bad fingerprint" and "Bad tokens" should have gotten marked
+ * non-retriable. */
+ tt_want_int_op(mock_router_get_dl_status_calls, OP_EQ, 2);
+ tt_want_int_op(mock_router_get_dl_status_unrecognized, OP_EQ, 0);
+ tt_int_op(dls_bad_fingerprint.n_download_failures, OP_EQ, 255);
+ tt_int_op(dls_bad_tokens.n_download_failures, OP_EQ, 255);
+
+ /* bad_sig2 and bad ports" are retriable -- one since only the signature
+ * was bad, and one because we didn't ask for it. */
+ tt_int_op(dls_bad_sig2.n_download_failures, OP_EQ, 0);
+ tt_int_op(dls_bad_ports.n_download_failures, OP_EQ, 0);
+
+ /* Wanted still contains "BAD_SIG2" */
+ tt_int_op(smartlist_len(wanted), OP_EQ, 1);
+ tt_str_op(smartlist_get(wanted, 0), OP_EQ,
+ "E0A3753CEFD54128EAB239F294954121DB23D2EF");
+
+#undef ADD
+
+ done:
+ tor_free(mem_op_hex_tmp);
+ UNMOCK(router_get_dl_status_by_descriptor_digest);
+ SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
+ smartlist_free(chunks);
+ SMARTLIST_FOREACH(wanted, char *, cp, tor_free(cp));
+ smartlist_free(wanted);
+ tor_free(list);
+}
+
+static int mock_get_by_ei_dd_calls = 0;
+static int mock_get_by_ei_dd_unrecognized = 0;
+
+static signed_descriptor_t sd_ei_minimal;
+static signed_descriptor_t sd_ei_bad_nickname;
+static signed_descriptor_t sd_ei_maximal;
+static signed_descriptor_t sd_ei_bad_tokens;
+static signed_descriptor_t sd_ei_bad_sig2;
+
+static signed_descriptor_t *
+mock_get_by_ei_desc_digest(const char *d)
+{
+
+ ++mock_get_by_ei_dd_calls;
+ char hex[HEX_DIGEST_LEN+1];
+ base16_encode(hex, sizeof(hex), d, DIGEST_LEN);
+
+ if (!strcmp(hex, "11E0EDF526950739F7769810FCACAB8C882FAEEE")) {
+ return &sd_ei_minimal;
+ } else if (!strcmp(hex, "47803B02A0E70E9E8BDA226CB1D74DE354D67DFF")) {
+ return &sd_ei_maximal;
+ } else if (!strcmp(hex, "D5DF4AA62EE9FFC9543D41150C9864908E0390AF")) {
+ return &sd_ei_bad_nickname;
+ } else if (!strcmp(hex, "16D387D3A58F7DB3CF46638F8D0B90C45C7D769C")) {
+ return &sd_ei_bad_sig2;
+ } else if (!strcmp(hex, "9D90F8C42955BBC57D54FB05E54A3F083AF42E8B")) {
+ return &sd_ei_bad_tokens;
+ } else {
+ ++mock_get_by_ei_dd_unrecognized;
+ return NULL;
+ }
+}
+
+static smartlist_t *mock_ei_insert_list = NULL;
+static was_router_added_t
+mock_ei_insert(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible)
+{
+ (void) rl;
+ (void) warn_if_incompatible;
+ smartlist_add(mock_ei_insert_list, ei);
+ return ROUTER_ADDED_SUCCESSFULLY;
+}
+
+static void
+test_dir_load_extrainfo(void *arg)
+{
+ (void) arg;
+ smartlist_t *chunks = smartlist_new();
+ smartlist_t *wanted = smartlist_new();
+ char buf[DIGEST_LEN];
+ char *mem_op_hex_tmp = NULL;
+ char *list = NULL;
+
+#define ADD(str) \
+ do { \
+ tt_int_op(0,OP_EQ,router_get_extrainfo_hash(str, strlen(str), buf)); \
+ smartlist_add(wanted, tor_strdup(hex_str(buf, DIGEST_LEN))); \
+ } while (0)
+
+ mock_ei_insert_list = smartlist_new();
+ MOCK(router_get_by_extrainfo_digest, mock_get_by_ei_desc_digest);
+ MOCK(extrainfo_insert, mock_ei_insert);
+
+ smartlist_add(chunks, tor_strdup(EX_EI_MINIMAL));
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_NICKNAME));
+ smartlist_add(chunks, tor_strdup(EX_EI_MAXIMAL));
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_PUBLISHED));
+ smartlist_add(chunks, tor_strdup(EX_EI_BAD_TOKENS));
+
+ /* not ADDing MINIMIAL */
+ ADD(EX_EI_MAXIMAL);
+ ADD(EX_EI_BAD_NICKNAME);
+ /* Not ADDing BAD_PUBLISHED */
+ ADD(EX_EI_BAD_TOKENS);
+ ADD(EX_EI_BAD_SIG2);
+
+ list = smartlist_join_strings(chunks, "", 0, NULL);
+ router_load_extrainfo_from_string(list, NULL, SAVED_IN_JOURNAL, wanted, 1);
+
+ /* The "maximal" router was added. */
+ /* "minimal" was also added, even though we didn't ask for it, since
+ * that's what we do with extrainfos. */
+ tt_int_op(smartlist_len(mock_ei_insert_list),OP_EQ,2);
+
+ extrainfo_t *e = smartlist_get(mock_ei_insert_list, 0);
+ test_memeq_hex(e->cache_info.signed_descriptor_digest,
+ "11E0EDF526950739F7769810FCACAB8C882FAEEE");
+
+ e = smartlist_get(mock_ei_insert_list, 1);
+ test_memeq_hex(e->cache_info.signed_descriptor_digest,
+ "47803B02A0E70E9E8BDA226CB1D74DE354D67DFF");
+ tt_int_op(dls_minimal.n_download_failures, OP_EQ, 0);
+ tt_int_op(dls_maximal.n_download_failures, OP_EQ, 0);
+
+ /* "Bad nickname" and "Bad tokens" should have gotten marked
+ * non-retriable. */
+ tt_want_int_op(mock_get_by_ei_dd_calls, OP_EQ, 2);
+ tt_want_int_op(mock_get_by_ei_dd_unrecognized, OP_EQ, 0);
+ tt_int_op(sd_ei_bad_nickname.ei_dl_status.n_download_failures, OP_EQ, 255);
+ tt_int_op(sd_ei_bad_tokens.ei_dl_status.n_download_failures, OP_EQ, 255);
+
+ /* bad_ports is retriable -- because we didn't ask for it. */
+ tt_int_op(dls_bad_ports.n_download_failures, OP_EQ, 0);
+
+ /* Wanted still contains "BAD_SIG2" */
+ tt_int_op(smartlist_len(wanted), OP_EQ, 1);
+ tt_str_op(smartlist_get(wanted, 0), OP_EQ,
+ "16D387D3A58F7DB3CF46638F8D0B90C45C7D769C");
+
+#undef ADD
+
+ done:
+ tor_free(mem_op_hex_tmp);
+ UNMOCK(router_get_by_extrainfo_digest);
+ SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
+ smartlist_free(chunks);
+ SMARTLIST_FOREACH(wanted, char *, cp, tor_free(cp));
+ smartlist_free(wanted);
+ tor_free(list);
+}
+
+static void
+test_dir_versions(void *arg)
{
tor_version_t ver1;
/* Try out version parsing functionality */
- test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
- test_eq(0, ver1.major);
- test_eq(3, ver1.minor);
- test_eq(4, ver1.micro);
- test_eq(VER_PRE, ver1.status);
- test_eq(2, ver1.patchlevel);
- test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
- test_eq(0, ver1.major);
- test_eq(3, ver1.minor);
- test_eq(4, ver1.micro);
- test_eq(VER_RC, ver1.status);
- test_eq(1, ver1.patchlevel);
- test_eq(0, tor_version_parse("1.3.4", &ver1));
- test_eq(1, ver1.major);
- test_eq(3, ver1.minor);
- test_eq(4, ver1.micro);
- test_eq(VER_RELEASE, ver1.status);
- test_eq(0, ver1.patchlevel);
- test_eq(0, tor_version_parse("1.3.4.999", &ver1));
- test_eq(1, ver1.major);
- test_eq(3, ver1.minor);
- test_eq(4, ver1.micro);
- test_eq(VER_RELEASE, ver1.status);
- test_eq(999, ver1.patchlevel);
- test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
- test_eq(0, ver1.major);
- test_eq(1, ver1.minor);
- test_eq(2, ver1.micro);
- test_eq(4, ver1.patchlevel);
- test_eq(VER_RELEASE, ver1.status);
- test_streq("alpha", ver1.status_tag);
- test_eq(0, tor_version_parse("0.1.2.4", &ver1));
- test_eq(0, ver1.major);
- test_eq(1, ver1.minor);
- test_eq(2, ver1.micro);
- test_eq(4, ver1.patchlevel);
- test_eq(VER_RELEASE, ver1.status);
- test_streq("", ver1.status_tag);
+ (void)arg;
+ tt_int_op(0,OP_EQ, tor_version_parse("0.3.4pre2-cvs", &ver1));
+ tt_int_op(0,OP_EQ, ver1.major);
+ tt_int_op(3,OP_EQ, ver1.minor);
+ tt_int_op(4,OP_EQ, ver1.micro);
+ tt_int_op(VER_PRE,OP_EQ, ver1.status);
+ tt_int_op(2,OP_EQ, ver1.patchlevel);
+ tt_int_op(0,OP_EQ, tor_version_parse("0.3.4rc1", &ver1));
+ tt_int_op(0,OP_EQ, ver1.major);
+ tt_int_op(3,OP_EQ, ver1.minor);
+ tt_int_op(4,OP_EQ, ver1.micro);
+ tt_int_op(VER_RC,OP_EQ, ver1.status);
+ tt_int_op(1,OP_EQ, ver1.patchlevel);
+ tt_int_op(0,OP_EQ, tor_version_parse("1.3.4", &ver1));
+ tt_int_op(1,OP_EQ, ver1.major);
+ tt_int_op(3,OP_EQ, ver1.minor);
+ tt_int_op(4,OP_EQ, ver1.micro);
+ tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
+ tt_int_op(0,OP_EQ, ver1.patchlevel);
+ tt_int_op(0,OP_EQ, tor_version_parse("1.3.4.999", &ver1));
+ tt_int_op(1,OP_EQ, ver1.major);
+ tt_int_op(3,OP_EQ, ver1.minor);
+ tt_int_op(4,OP_EQ, ver1.micro);
+ tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
+ tt_int_op(999,OP_EQ, ver1.patchlevel);
+ tt_int_op(0,OP_EQ, tor_version_parse("0.1.2.4-alpha", &ver1));
+ tt_int_op(0,OP_EQ, ver1.major);
+ tt_int_op(1,OP_EQ, ver1.minor);
+ tt_int_op(2,OP_EQ, ver1.micro);
+ tt_int_op(4,OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
+ tt_str_op("alpha",OP_EQ, ver1.status_tag);
+ tt_int_op(0,OP_EQ, tor_version_parse("0.1.2.4", &ver1));
+ tt_int_op(0,OP_EQ, ver1.major);
+ tt_int_op(1,OP_EQ, ver1.minor);
+ tt_int_op(2,OP_EQ, ver1.micro);
+ tt_int_op(4,OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
+ tt_str_op("",OP_EQ, ver1.status_tag);
+
+ tt_int_op(0, OP_EQ, tor_version_parse("10.1", &ver1));
+ tt_int_op(10, OP_EQ, ver1.major);
+ tt_int_op(1, OP_EQ, ver1.minor);
+ tt_int_op(0, OP_EQ, ver1.micro);
+ tt_int_op(0, OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
+ tt_str_op("", OP_EQ, ver1.status_tag);
+ tt_int_op(0, OP_EQ, tor_version_parse("5.99.999", &ver1));
+ tt_int_op(5, OP_EQ, ver1.major);
+ tt_int_op(99, OP_EQ, ver1.minor);
+ tt_int_op(999, OP_EQ, ver1.micro);
+ tt_int_op(0, OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
+ tt_str_op("", OP_EQ, ver1.status_tag);
+ tt_int_op(0, OP_EQ, tor_version_parse("10.1-alpha", &ver1));
+ tt_int_op(10, OP_EQ, ver1.major);
+ tt_int_op(1, OP_EQ, ver1.minor);
+ tt_int_op(0, OP_EQ, ver1.micro);
+ tt_int_op(0, OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
+ tt_str_op("alpha", OP_EQ, ver1.status_tag);
+ tt_int_op(0, OP_EQ, tor_version_parse("2.1.700-alpha", &ver1));
+ tt_int_op(2, OP_EQ, ver1.major);
+ tt_int_op(1, OP_EQ, ver1.minor);
+ tt_int_op(700, OP_EQ, ver1.micro);
+ tt_int_op(0, OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
+ tt_str_op("alpha", OP_EQ, ver1.status_tag);
+ tt_int_op(0, OP_EQ, tor_version_parse("1.6.8-alpha-dev", &ver1));
+ tt_int_op(1, OP_EQ, ver1.major);
+ tt_int_op(6, OP_EQ, ver1.minor);
+ tt_int_op(8, OP_EQ, ver1.micro);
+ tt_int_op(0, OP_EQ, ver1.patchlevel);
+ tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
+ tt_str_op("alpha-dev", OP_EQ, ver1.status_tag);
#define tt_versionstatus_op(vs1, op, vs2) \
tt_assert_test_type(vs1,vs2,#vs1" "#op" "#vs2,version_status_t, \
(val1_ op val2_),"%d",TT_EXIT_TEST_FUNCTION)
#define test_v_i_o(val, ver, lst) \
- tt_versionstatus_op(val, ==, tor_version_is_obsolete(ver, lst))
+ tt_versionstatus_op(val, OP_EQ, tor_version_is_obsolete(ver, lst))
/* make sure tor_version_is_obsolete() works */
test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
@@ -368,53 +1099,55 @@ test_dir_versions(void)
/* On list, not newer than any on same series. */
test_v_i_o(VS_UNRECOMMENDED,
"0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
- test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
- test_eq(1, tor_version_as_new_as(
+ tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
+ tt_int_op(1,OP_EQ, tor_version_as_new_as(
"Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
"sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
"0.0.8rc2"));
- test_eq(0, tor_version_as_new_as(
+ tt_int_op(0,OP_EQ, tor_version_as_new_as(
"Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
"sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
/* Now try svn revisions. */
- test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
+ tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
"Tor 0.2.1.0-dev (r99)"));
- test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
+ tt_int_op(1,OP_EQ, tor_version_as_new_as(
+ "Tor 0.2.1.0-dev (r100) on Banana Jr",
"Tor 0.2.1.0-dev (r99) on Hal 9000"));
- test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
+ tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
"Tor 0.2.1.0-dev on Colossus"));
- test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
+ tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
"Tor 0.2.1.0-dev (r100)"));
- test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
+ tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
"Tor 0.2.1.0-dev (r100) on AM"));
- test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
+ tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev",
"Tor 0.2.1.0-dev (r99)"));
- test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
+ tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.1",
"Tor 0.2.1.0-dev (r99)"));
/* Now try git revisions */
- test_eq(0, tor_version_parse("0.5.6.7 (git-ff00ff)", &ver1));
- test_eq(0, ver1.major);
- test_eq(5, ver1.minor);
- test_eq(6, ver1.micro);
- test_eq(7, ver1.patchlevel);
- test_eq(3, ver1.git_tag_len);
- test_memeq(ver1.git_tag, "\xff\x00\xff", 3);
- test_eq(-1, tor_version_parse("0.5.6.7 (git-ff00xx)", &ver1));
- test_eq(-1, tor_version_parse("0.5.6.7 (git-ff00fff)", &ver1));
- test_eq(0, tor_version_parse("0.5.6.7 (git ff00fff)", &ver1));
+ tt_int_op(0,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00ff)", &ver1));
+ tt_int_op(0,OP_EQ, ver1.major);
+ tt_int_op(5,OP_EQ, ver1.minor);
+ tt_int_op(6,OP_EQ, ver1.micro);
+ tt_int_op(7,OP_EQ, ver1.patchlevel);
+ tt_int_op(3,OP_EQ, ver1.git_tag_len);
+ tt_mem_op(ver1.git_tag,OP_EQ, "\xff\x00\xff", 3);
+ tt_int_op(-1,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00xx)", &ver1));
+ tt_int_op(-1,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00fff)", &ver1));
+ tt_int_op(0,OP_EQ, tor_version_parse("0.5.6.7 (git ff00fff)", &ver1));
done:
;
}
/** Run unit tests for directory fp_pair functions. */
static void
-test_dir_fp_pairs(void)
+test_dir_fp_pairs(void *arg)
{
smartlist_t *sl = smartlist_new();
fp_pair_t *pair;
+ (void)arg;
dir_split_resource_into_fingerprint_pairs(
/* Two pairs, out of order, with one duplicate. */
"73656372657420646174612E0000000000FFFFFF-"
@@ -424,13 +1157,14 @@ test_dir_fp_pairs(void)
"48657861646563696d616c2069736e277420736f-"
"676f6f6420666f7220686964696e6720796f7572.z", sl);
- test_eq(smartlist_len(sl), 2);
+ tt_int_op(smartlist_len(sl),OP_EQ, 2);
pair = smartlist_get(sl, 0);
- test_memeq(pair->first, "Hexadecimal isn't so", DIGEST_LEN);
- test_memeq(pair->second, "good for hiding your", DIGEST_LEN);
+ tt_mem_op(pair->first,OP_EQ, "Hexadecimal isn't so", DIGEST_LEN);
+ tt_mem_op(pair->second,OP_EQ, "good for hiding your", DIGEST_LEN);
pair = smartlist_get(sl, 1);
- test_memeq(pair->first, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN);
- test_memeq(pair->second, "Use AES-256 instead.", DIGEST_LEN);
+ tt_mem_op(pair->first,OP_EQ, "secret data.\0\0\0\0\0\xff\xff\xff",
+ DIGEST_LEN);
+ tt_mem_op(pair->second,OP_EQ, "Use AES-256 instead.", DIGEST_LEN);
done:
SMARTLIST_FOREACH(sl, fp_pair_t *, pair, tor_free(pair));
@@ -461,56 +1195,56 @@ test_dir_split_fps(void *testdata)
/* no flags set */
dir_split_resource_into_fingerprints("A+C+B", sl, NULL, 0);
- tt_int_op(smartlist_len(sl), ==, 3);
- tt_str_op(smartlist_get(sl, 0), ==, "A");
- tt_str_op(smartlist_get(sl, 1), ==, "C");
- tt_str_op(smartlist_get(sl, 2), ==, "B");
+ tt_int_op(smartlist_len(sl), OP_EQ, 3);
+ tt_str_op(smartlist_get(sl, 0), OP_EQ, "A");
+ tt_str_op(smartlist_get(sl, 1), OP_EQ, "C");
+ tt_str_op(smartlist_get(sl, 2), OP_EQ, "B");
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* uniq strings. */
dir_split_resource_into_fingerprints("A+C+B+A+B+B", sl, NULL, DSR_SORT_UNIQ);
- tt_int_op(smartlist_len(sl), ==, 3);
- tt_str_op(smartlist_get(sl, 0), ==, "A");
- tt_str_op(smartlist_get(sl, 1), ==, "B");
- tt_str_op(smartlist_get(sl, 2), ==, "C");
+ tt_int_op(smartlist_len(sl), OP_EQ, 3);
+ tt_str_op(smartlist_get(sl, 0), OP_EQ, "A");
+ tt_str_op(smartlist_get(sl, 1), OP_EQ, "B");
+ tt_str_op(smartlist_get(sl, 2), OP_EQ, "C");
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Decode hex. */
dir_split_resource_into_fingerprints(HEX1"+"HEX2, sl, NULL, DSR_HEX);
- tt_int_op(smartlist_len(sl), ==, 2);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX1);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX2);
+ tt_int_op(smartlist_len(sl), OP_EQ, 2);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* decode hex and drop weirdness. */
dir_split_resource_into_fingerprints(HEX1"+bogus+"HEX2"+"HEX256_1,
sl, NULL, DSR_HEX);
- tt_int_op(smartlist_len(sl), ==, 2);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX1);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX2);
+ tt_int_op(smartlist_len(sl), OP_EQ, 2);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Decode long hex */
dir_split_resource_into_fingerprints(HEX256_1"+"HEX256_2"+"HEX2"+"HEX256_3,
sl, NULL, DSR_HEX|DSR_DIGEST256);
- tt_int_op(smartlist_len(sl), ==, 3);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX256_1);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX256_2);
- test_mem_op_hex(smartlist_get(sl, 2), ==, HEX256_3);
+ tt_int_op(smartlist_len(sl), OP_EQ, 3);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
+ test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX256_3);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Decode hex and sort. */
dir_split_resource_into_fingerprints(HEX1"+"HEX2"+"HEX3"+"HEX2,
sl, NULL, DSR_HEX|DSR_SORT_UNIQ);
- tt_int_op(smartlist_len(sl), ==, 3);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX3);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX2);
- test_mem_op_hex(smartlist_get(sl, 2), ==, HEX1);
+ tt_int_op(smartlist_len(sl), OP_EQ, 3);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX3);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
+ test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX1);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
@@ -519,34 +1253,34 @@ test_dir_split_fps(void *testdata)
"+"HEX256_1,
sl, NULL,
DSR_HEX|DSR_DIGEST256|DSR_SORT_UNIQ);
- tt_int_op(smartlist_len(sl), ==, 3);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX256_3);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX256_2);
- test_mem_op_hex(smartlist_get(sl, 2), ==, HEX256_1);
+ tt_int_op(smartlist_len(sl), OP_EQ, 3);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_3);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
+ test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX256_1);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Decode base64 */
dir_split_resource_into_fingerprints(B64_1"-"B64_2, sl, NULL, DSR_BASE64);
- tt_int_op(smartlist_len(sl), ==, 2);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX1);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX2);
+ tt_int_op(smartlist_len(sl), OP_EQ, 2);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
/* Decode long base64 */
dir_split_resource_into_fingerprints(B64_256_1"-"B64_256_2,
sl, NULL, DSR_BASE64|DSR_DIGEST256);
- tt_int_op(smartlist_len(sl), ==, 2);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX256_1);
- test_mem_op_hex(smartlist_get(sl, 1), ==, HEX256_2);
+ tt_int_op(smartlist_len(sl), OP_EQ, 2);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
+ test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
dir_split_resource_into_fingerprints(B64_256_1,
sl, NULL, DSR_BASE64|DSR_DIGEST256);
- tt_int_op(smartlist_len(sl), ==, 1);
- test_mem_op_hex(smartlist_get(sl, 0), ==, HEX256_1);
+ tt_int_op(smartlist_len(sl), OP_EQ, 1);
+ test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
smartlist_clear(sl);
@@ -557,7 +1291,7 @@ test_dir_split_fps(void *testdata)
}
static void
-test_dir_measured_bw_kb(void)
+test_dir_measured_bw_kb(void *arg)
{
measured_bw_line_t mbwl;
int i;
@@ -605,16 +1339,17 @@ test_dir_measured_bw_kb(void)
"end"
};
+ (void)arg;
for (i = 0; strcmp(lines_fail[i], "end"); i++) {
//fprintf(stderr, "Testing: %s\n", lines_fail[i]);
- test_assert(measured_bw_line_parse(&mbwl, lines_fail[i]) == -1);
+ tt_assert(measured_bw_line_parse(&mbwl, lines_fail[i]) == -1);
}
for (i = 0; strcmp(lines_pass[i], "end"); i++) {
//fprintf(stderr, "Testing: %s %d\n", lines_pass[i], TOR_ISSPACE('\n'));
- test_assert(measured_bw_line_parse(&mbwl, lines_pass[i]) == 0);
- test_assert(mbwl.bw_kb == 1024);
- test_assert(strcmp(mbwl.node_hex,
+ tt_assert(measured_bw_line_parse(&mbwl, lines_pass[i]) == 0);
+ tt_assert(mbwl.bw_kb == 1024);
+ tt_assert(strcmp(mbwl.node_hex,
"557365204145532d32353620696e73746561642e") == 0);
}
@@ -626,7 +1361,7 @@ test_dir_measured_bw_kb(void)
/** Do the measured bandwidth cache unit test */
static void
-test_dir_measured_bw_kb_cache(void)
+test_dir_measured_bw_kb_cache(void *arg)
{
/* Initial fake time_t for testing */
time_t curr = MBWC_INIT_TIME;
@@ -637,8 +1372,9 @@ test_dir_measured_bw_kb_cache(void)
time_t as_of;
/* First, clear the cache and assert that it's empty */
+ (void)arg;
dirserv_clear_measured_bw_cache();
- test_eq(dirserv_get_measured_bw_cache_size(), 0);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
/*
* Set up test mbwls; none of the dirserv_cache_*() functions care about
* the node_hex field.
@@ -651,56 +1387,56 @@ test_dir_measured_bw_kb_cache(void)
mbwl[2].bw_kb = 80;
/* Try caching something */
dirserv_cache_measured_bw(&(mbwl[0]), curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 1);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
/* Okay, let's see if we can retrieve it */
- test_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, &as_of));
- test_eq(bw, 20);
- test_eq(as_of, MBWC_INIT_TIME);
+ tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, &as_of));
+ tt_int_op(bw,OP_EQ, 20);
+ tt_int_op(as_of,OP_EQ, MBWC_INIT_TIME);
/* Try retrieving it without some outputs */
- test_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL, NULL));
- test_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, NULL));
- test_eq(bw, 20);
- test_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL,&as_of));
- test_eq(as_of, MBWC_INIT_TIME);
+ tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL, NULL));
+ tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, NULL));
+ tt_int_op(bw,OP_EQ, 20);
+ tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL,&as_of));
+ tt_int_op(as_of,OP_EQ, MBWC_INIT_TIME);
/* Now expire it */
curr += MAX_MEASUREMENT_AGE + 1;
dirserv_expire_measured_bw_cache(curr);
/* Check that the cache is empty */
- test_eq(dirserv_get_measured_bw_cache_size(), 0);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
/* Check that we can't retrieve it */
- test_assert(!dirserv_query_measured_bw_cache_kb(mbwl[0].node_id, NULL,NULL));
+ tt_assert(!dirserv_query_measured_bw_cache_kb(mbwl[0].node_id, NULL,NULL));
/* Try caching a few things now */
dirserv_cache_measured_bw(&(mbwl[0]), curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 1);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
curr += MAX_MEASUREMENT_AGE / 4;
dirserv_cache_measured_bw(&(mbwl[1]), curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 2);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 2);
curr += MAX_MEASUREMENT_AGE / 4;
dirserv_cache_measured_bw(&(mbwl[2]), curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 3);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 3);
curr += MAX_MEASUREMENT_AGE / 4 + 1;
/* Do an expire that's too soon to get any of them */
dirserv_expire_measured_bw_cache(curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 3);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 3);
/* Push the oldest one off the cliff */
curr += MAX_MEASUREMENT_AGE / 4;
dirserv_expire_measured_bw_cache(curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 2);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 2);
/* And another... */
curr += MAX_MEASUREMENT_AGE / 4;
dirserv_expire_measured_bw_cache(curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 1);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
/* This should empty it out again */
curr += MAX_MEASUREMENT_AGE / 4;
dirserv_expire_measured_bw_cache(curr);
- test_eq(dirserv_get_measured_bw_cache_size(), 0);
+ tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
done:
return;
}
static void
-test_dir_param_voting(void)
+test_dir_param_voting(void *arg)
{
networkstatus_t vote1, vote2, vote3, vote4;
smartlist_t *votes = smartlist_new();
@@ -709,6 +1445,7 @@ test_dir_param_voting(void)
/* dirvote_compute_params only looks at the net_params field of the votes,
so that's all we need to set.
*/
+ (void)arg;
memset(&vote1, 0, sizeof(vote1));
memset(&vote2, 0, sizeof(vote2));
memset(&vote3, 0, sizeof(vote3));
@@ -725,87 +1462,71 @@ test_dir_param_voting(void)
"abcd=20 c=60 cw=500 x-yz=-9 zzzzz=101", NULL, 0, 0);
smartlist_split_string(vote4.net_params,
"ab=900 abcd=200 c=1 cw=51 x-yz=100", NULL, 0, 0);
- test_eq(100, networkstatus_get_param(&vote4, "x-yz", 50, 0, 300));
- test_eq(222, networkstatus_get_param(&vote4, "foobar", 222, 0, 300));
- test_eq(80, networkstatus_get_param(&vote4, "ab", 12, 0, 80));
- test_eq(-8, networkstatus_get_param(&vote4, "ab", -12, -100, -8));
- test_eq(0, networkstatus_get_param(&vote4, "foobar", 0, -100, 8));
+ tt_int_op(100,OP_EQ, networkstatus_get_param(&vote4, "x-yz", 50, 0, 300));
+ tt_int_op(222,OP_EQ, networkstatus_get_param(&vote4, "foobar", 222, 0, 300));
+ tt_int_op(80,OP_EQ, networkstatus_get_param(&vote4, "ab", 12, 0, 80));
+ tt_int_op(-8,OP_EQ, networkstatus_get_param(&vote4, "ab", -12, -100, -8));
+ tt_int_op(0,OP_EQ, networkstatus_get_param(&vote4, "foobar", 0, -100, 8));
smartlist_add(votes, &vote1);
/* Do the first tests without adding all the other votes, for
* networks without many dirauths. */
- res = dirvote_compute_params(votes, 11, 6);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-99");
- tor_free(res);
-
res = dirvote_compute_params(votes, 12, 2);
- test_streq(res, "");
+ tt_str_op(res,OP_EQ, "");
tor_free(res);
res = dirvote_compute_params(votes, 12, 1);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-99");
+ tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-99");
tor_free(res);
smartlist_add(votes, &vote2);
- res = dirvote_compute_params(votes, 11, 2);
- test_streq(res, "ab=27 abcd=20 cw=5 x-yz=-99");
- tor_free(res);
-
res = dirvote_compute_params(votes, 12, 2);
- test_streq(res, "ab=27 cw=5 x-yz=-99");
+ tt_str_op(res,OP_EQ, "ab=27 cw=5 x-yz=-99");
tor_free(res);
res = dirvote_compute_params(votes, 12, 3);
- test_streq(res, "ab=27 cw=5 x-yz=-99");
+ tt_str_op(res,OP_EQ, "ab=27 cw=5 x-yz=-99");
tor_free(res);
res = dirvote_compute_params(votes, 12, 6);
- test_streq(res, "");
+ tt_str_op(res,OP_EQ, "");
tor_free(res);
smartlist_add(votes, &vote3);
- res = dirvote_compute_params(votes, 11, 3);
- test_streq(res, "ab=27 abcd=20 c=60 cw=50 x-yz=-9 zzzzz=101");
- tor_free(res);
-
res = dirvote_compute_params(votes, 12, 3);
- test_streq(res, "ab=27 abcd=20 cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "ab=27 abcd=20 cw=50 x-yz=-9");
tor_free(res);
res = dirvote_compute_params(votes, 12, 5);
- test_streq(res, "cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "cw=50 x-yz=-9");
tor_free(res);
res = dirvote_compute_params(votes, 12, 9);
- test_streq(res, "cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "cw=50 x-yz=-9");
tor_free(res);
smartlist_add(votes, &vote4);
- res = dirvote_compute_params(votes, 11, 4);
- test_streq(res, "ab=90 abcd=20 c=1 cw=50 x-yz=-9 zzzzz=101");
- tor_free(res);
-
res = dirvote_compute_params(votes, 12, 4);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
tor_free(res);
res = dirvote_compute_params(votes, 12, 5);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
tor_free(res);
/* Test that the special-cased "at least three dirauths voted for
* this param" logic works as expected. */
res = dirvote_compute_params(votes, 12, 6);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
tor_free(res);
res = dirvote_compute_params(votes, 12, 10);
- test_streq(res, "ab=90 abcd=20 cw=50 x-yz=-9");
+ tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
tor_free(res);
done:
@@ -823,13 +1544,6 @@ test_dir_param_voting(void)
return;
}
-extern const char AUTHORITY_CERT_1[];
-extern const char AUTHORITY_SIGNKEY_1[];
-extern const char AUTHORITY_CERT_2[];
-extern const char AUTHORITY_SIGNKEY_2[];
-extern const char AUTHORITY_CERT_3[];
-extern const char AUTHORITY_SIGNKEY_3[];
-
/** Helper: Test that two networkstatus_voter_info_t do in fact represent the
* same voting authority, and that they do in fact have all the same
* information. */
@@ -837,53 +1551,18 @@ static void
test_same_voter(networkstatus_voter_info_t *v1,
networkstatus_voter_info_t *v2)
{
- test_streq(v1->nickname, v2->nickname);
- test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
- test_streq(v1->address, v2->address);
- test_eq(v1->addr, v2->addr);
- test_eq(v1->dir_port, v2->dir_port);
- test_eq(v1->or_port, v2->or_port);
- test_streq(v1->contact, v2->contact);
- test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
+ tt_str_op(v1->nickname,OP_EQ, v2->nickname);
+ tt_mem_op(v1->identity_digest,OP_EQ, v2->identity_digest, DIGEST_LEN);
+ tt_str_op(v1->address,OP_EQ, v2->address);
+ tt_int_op(v1->addr,OP_EQ, v2->addr);
+ tt_int_op(v1->dir_port,OP_EQ, v2->dir_port);
+ tt_int_op(v1->or_port,OP_EQ, v2->or_port);
+ tt_str_op(v1->contact,OP_EQ, v2->contact);
+ tt_mem_op(v1->vote_digest,OP_EQ, v2->vote_digest, DIGEST_LEN);
done:
;
}
-/** Helper: Make a new routerinfo containing the right information for a
- * given vote_routerstatus_t. */
-static routerinfo_t *
-generate_ri_from_rs(const vote_routerstatus_t *vrs)
-{
- routerinfo_t *r;
- const routerstatus_t *rs = &vrs->status;
- static time_t published = 0;
-
- r = tor_malloc_zero(sizeof(routerinfo_t));
- memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
- memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
- DIGEST_LEN);
- r->cache_info.do_not_cache = 1;
- r->cache_info.routerlist_index = -1;
- r->cache_info.signed_descriptor_body =
- tor_strdup("123456789012345678901234567890123");
- r->cache_info.signed_descriptor_len =
- strlen(r->cache_info.signed_descriptor_body);
- r->exit_policy = smartlist_new();
- r->cache_info.published_on = ++published + time(NULL);
- if (rs->has_bandwidth) {
- /*
- * Multiply by 1000 because the routerinfo_t and the routerstatus_t
- * seem to use different units (*sigh*) and because we seem stuck on
- * icky and perverse decimal kilobytes (*double sigh*) - see
- * router_get_advertised_bandwidth_capped() of routerlist.c and
- * routerstatus_format_entry() of dirserv.c.
- */
- r->bandwidthrate = rs->bandwidth_kb * 1000;
- r->bandwidthcapacity = rs->bandwidth_kb * 1000;
- }
- return r;
-}
-
/** Helper: get a detached signatures document for one or two
* consensuses. */
static char *
@@ -901,100 +1580,6 @@ get_detached_sigs(networkstatus_t *ns, networkstatus_t *ns2)
return r;
}
-/**
- * Generate a routerstatus for v3_networkstatus test
- */
-static vote_routerstatus_t *
-gen_routerstatus_for_v3ns(int idx, time_t now)
-{
- vote_routerstatus_t *vrs=NULL;
- routerstatus_t *rs;
- tor_addr_t addr_ipv6;
-
- switch (idx) {
- case 0:
- /* Generate the first routerstatus. */
- vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
- rs = &vrs->status;
- vrs->version = tor_strdup("0.1.2.14");
- rs->published_on = now-1500;
- strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
- memset(rs->identity_digest, 3, DIGEST_LEN);
- memset(rs->descriptor_digest, 78, DIGEST_LEN);
- rs->addr = 0x99008801;
- rs->or_port = 443;
- rs->dir_port = 8000;
- /* all flags but running cleared */
- rs->is_flagged_running = 1;
- break;
- case 1:
- /* Generate the second routerstatus. */
- vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
- rs = &vrs->status;
- vrs->version = tor_strdup("0.2.0.5");
- rs->published_on = now-1000;
- strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
- memset(rs->identity_digest, 5, DIGEST_LEN);
- memset(rs->descriptor_digest, 77, DIGEST_LEN);
- rs->addr = 0x99009901;
- rs->or_port = 443;
- rs->dir_port = 0;
- tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
- tor_addr_copy(&rs->ipv6_addr, &addr_ipv6);
- rs->ipv6_orport = 4711;
- rs->is_exit = rs->is_stable = rs->is_fast = rs->is_flagged_running =
- rs->is_valid = rs->is_possible_guard = 1;
- break;
- case 2:
- /* Generate the third routerstatus. */
- vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
- rs = &vrs->status;
- vrs->version = tor_strdup("0.1.0.3");
- rs->published_on = now-1000;
- strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
- memset(rs->identity_digest, 33, DIGEST_LEN);
- memset(rs->descriptor_digest, 79, DIGEST_LEN);
- rs->addr = 0xAA009901;
- rs->or_port = 400;
- rs->dir_port = 9999;
- rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
- rs->is_flagged_running = rs->is_valid =
- rs->is_possible_guard = 1;
- break;
- case 3:
- /* Generate a fourth routerstatus that is not running. */
- vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
- rs = &vrs->status;
- vrs->version = tor_strdup("0.1.6.3");
- rs->published_on = now-1000;
- strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
- memset(rs->identity_digest, 34, DIGEST_LEN);
- memset(rs->descriptor_digest, 47, DIGEST_LEN);
- rs->addr = 0xC0000203;
- rs->or_port = 500;
- rs->dir_port = 1999;
- /* Running flag (and others) cleared */
- break;
- case 4:
- /* No more for this test; return NULL */
- vrs = NULL;
- break;
- default:
- /* Shouldn't happen */
- test_assert(0);
- }
- if (vrs) {
- vrs->microdesc = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
- tor_asprintf(&vrs->microdesc->microdesc_hash_line,
- "m 9,10,11,12,13,14,15,16,17 "
- "sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa%d\n",
- idx);
- }
-
- done:
- return vrs;
-}
-
/** Apply tweaks to the vote list for each voter */
static int
vote_tweaks_for_v3ns(networkstatus_t *v, int voter, time_t now)
@@ -1002,14 +1587,14 @@ vote_tweaks_for_v3ns(networkstatus_t *v, int voter, time_t now)
vote_routerstatus_t *vrs;
const char *msg = NULL;
- test_assert(v);
+ tt_assert(v);
(void)now;
if (voter == 1) {
measured_bw_line_t mbw;
memset(mbw.node_id, 33, sizeof(mbw.node_id));
mbw.bw_kb = 1024;
- test_assert(measured_bw_line_apply(&mbw,
+ tt_assert(measured_bw_line_apply(&mbw,
v->routerstatus_list) == 1);
} else if (voter == 2 || voter == 3) {
/* Monkey around with the list a bit */
@@ -1025,8 +1610,8 @@ vote_tweaks_for_v3ns(networkstatus_t *v, int voter, time_t now)
vote_routerstatus_free(vrs);
vrs = smartlist_get(v->routerstatus_list, 0);
memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
- test_assert(router_add_to_routerlist(
- generate_ri_from_rs(vrs), &msg,0,0) >= 0);
+ tt_assert(router_add_to_routerlist(
+ dir_common_generate_ri_from_rs(vrs), &msg,0,0) >= 0);
}
}
@@ -1043,9 +1628,9 @@ test_vrs_for_v3ns(vote_routerstatus_t *vrs, int voter, time_t now)
routerstatus_t *rs;
tor_addr_t addr_ipv6;
- test_assert(vrs);
+ tt_assert(vrs);
rs = &(vrs->status);
- test_assert(rs);
+ tt_assert(rs);
/* Split out by digests to test */
if (tor_memeq(rs->identity_digest,
@@ -1054,48 +1639,48 @@ test_vrs_for_v3ns(vote_routerstatus_t *vrs, int voter, time_t now)
DIGEST_LEN) &&
(voter == 1)) {
/* Check the first routerstatus. */
- test_streq(vrs->version, "0.1.2.14");
- test_eq(rs->published_on, now-1500);
- test_streq(rs->nickname, "router2");
- test_memeq(rs->identity_digest,
+ tt_str_op(vrs->version,OP_EQ, "0.1.2.14");
+ tt_int_op(rs->published_on,OP_EQ, now-1500);
+ tt_str_op(rs->nickname,OP_EQ, "router2");
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
"\x3\x3\x3\x3",
DIGEST_LEN);
- test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
- test_eq(rs->addr, 0x99008801);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 8000);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
+ tt_int_op(rs->addr,OP_EQ, 0x99008801);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 8000);
/* no flags except "running" (16) and "v2dir" (64) */
- tt_u64_op(vrs->flags, ==, U64_LITERAL(80));
+ tt_u64_op(vrs->flags, OP_EQ, U64_LITERAL(80));
} else if (tor_memeq(rs->identity_digest,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5",
DIGEST_LEN) &&
(voter == 1 || voter == 2)) {
- test_memeq(rs->identity_digest,
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5",
DIGEST_LEN);
if (voter == 1) {
/* Check the second routerstatus. */
- test_streq(vrs->version, "0.2.0.5");
- test_eq(rs->published_on, now-1000);
- test_streq(rs->nickname, "router1");
+ tt_str_op(vrs->version,OP_EQ, "0.2.0.5");
+ tt_int_op(rs->published_on,OP_EQ, now-1000);
+ tt_str_op(rs->nickname,OP_EQ, "router1");
}
- test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
- test_eq(rs->addr, 0x99009901);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 0);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
+ tt_int_op(rs->addr,OP_EQ, 0x99009901);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 0);
tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
- test_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
- test_eq(rs->ipv6_orport, 4711);
+ tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
+ tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
if (voter == 1) {
- /* all except "authority" (1) and "v2dir" (64) */
- tt_u64_op(vrs->flags, ==, U64_LITERAL(190));
+ /* all except "authority" (1) */
+ tt_u64_op(vrs->flags, OP_EQ, U64_LITERAL(254));
} else {
- /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) - v2dir(256) */
- tt_u64_op(vrs->flags, ==, U64_LITERAL(718));
+ /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
+ tt_u64_op(vrs->flags, OP_EQ, U64_LITERAL(974));
}
} else if (tor_memeq(rs->identity_digest,
"\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
@@ -1103,14 +1688,14 @@ test_vrs_for_v3ns(vote_routerstatus_t *vrs, int voter, time_t now)
DIGEST_LEN) &&
(voter == 1 || voter == 2)) {
/* Check the measured bandwidth bits */
- test_assert(vrs->has_measured_bw &&
+ tt_assert(vrs->has_measured_bw &&
vrs->measured_bw_kb == 1024);
} else {
/*
* Didn't expect this, but the old unit test only checked some of them,
* so don't assert.
*/
- /* test_assert(0); */
+ /* tt_assert(0); */
}
done:
@@ -1125,9 +1710,9 @@ test_consensus_for_v3ns(networkstatus_t *con, time_t now)
{
(void)now;
- test_assert(con);
- test_assert(!con->cert);
- test_eq(2, smartlist_len(con->routerstatus_list));
+ tt_assert(con);
+ tt_assert(!con->cert);
+ tt_int_op(2,OP_EQ, smartlist_len(con->routerstatus_list));
/* There should be two listed routers: one with identity 3, one with
* identity 5. */
@@ -1143,7 +1728,7 @@ test_routerstatus_for_v3ns(routerstatus_t *rs, time_t now)
{
tor_addr_t addr_ipv6;
- test_assert(rs);
+ tt_assert(rs);
/* There should be two listed routers: one with identity 3, one with
* identity 5. */
@@ -1152,49 +1737,51 @@ test_routerstatus_for_v3ns(routerstatus_t *rs, time_t now)
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
"\x3\x3",
DIGEST_LEN)) {
- test_memeq(rs->identity_digest,
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
DIGEST_LEN);
- test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
- test_assert(!rs->is_authority);
- test_assert(!rs->is_exit);
- test_assert(!rs->is_fast);
- test_assert(!rs->is_possible_guard);
- test_assert(!rs->is_stable);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
+ tt_assert(!rs->is_authority);
+ tt_assert(!rs->is_exit);
+ tt_assert(!rs->is_fast);
+ tt_assert(!rs->is_possible_guard);
+ tt_assert(!rs->is_stable);
/* (If it wasn't running it wouldn't be here) */
- test_assert(rs->is_flagged_running);
- test_assert(!rs->is_valid);
- test_assert(!rs->is_named);
+ tt_assert(rs->is_flagged_running);
+ tt_assert(!rs->is_valid);
+ tt_assert(!rs->is_named);
+ tt_assert(rs->is_v2_dir);
/* XXXX check version */
} else if (tor_memeq(rs->identity_digest,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5",
DIGEST_LEN)) {
/* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
- test_memeq(rs->identity_digest,
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
DIGEST_LEN);
- test_streq(rs->nickname, "router1");
- test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
- test_eq(rs->published_on, now-1000);
- test_eq(rs->addr, 0x99009901);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 0);
+ tt_str_op(rs->nickname,OP_EQ, "router1");
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
+ tt_int_op(rs->published_on,OP_EQ, now-1000);
+ tt_int_op(rs->addr,OP_EQ, 0x99009901);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 0);
tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
- test_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
- test_eq(rs->ipv6_orport, 4711);
- test_assert(!rs->is_authority);
- test_assert(rs->is_exit);
- test_assert(rs->is_fast);
- test_assert(rs->is_possible_guard);
- test_assert(rs->is_stable);
- test_assert(rs->is_flagged_running);
- test_assert(rs->is_valid);
- test_assert(!rs->is_named);
+ tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
+ tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
+ tt_assert(!rs->is_authority);
+ tt_assert(rs->is_exit);
+ tt_assert(rs->is_fast);
+ tt_assert(rs->is_possible_guard);
+ tt_assert(rs->is_stable);
+ tt_assert(rs->is_flagged_running);
+ tt_assert(rs->is_valid);
+ tt_assert(rs->is_v2_dir);
+ tt_assert(!rs->is_named);
/* XXXX check version */
} else {
/* Weren't expecting this... */
- test_assert(0);
+ tt_assert(0);
}
done:
@@ -1214,7 +1801,6 @@ test_a_networkstatus(
authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
crypto_pk_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
crypto_pk_t *sign_skey_leg1=NULL;
- const char *msg=NULL;
/*
* Sum the non-zero returns from vote_tweaks() we've seen; if vote_tweaks()
* returns non-zero, it changed net_params and we should skip the tests for
@@ -1230,8 +1816,7 @@ test_a_networkstatus(
vote_routerstatus_t *vrs;
routerstatus_t *rs;
int idx, n_rs, n_vrs;
- char *v1_text=NULL, *v2_text=NULL, *v3_text=NULL, *consensus_text=NULL,
- *cp=NULL;
+ char *consensus_text=NULL, *cp=NULL;
smartlist_t *votes = smartlist_new();
/* For generating the two other consensuses. */
@@ -1242,154 +1827,67 @@ test_a_networkstatus(
networkstatus_t *con2=NULL, *con_md2=NULL, *con3=NULL, *con_md3=NULL;
ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
- test_assert(vrs_gen);
- test_assert(rs_test);
- test_assert(vrs_test);
-
- /* Parse certificates and keys. */
- cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
- test_assert(cert1);
- cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
- test_assert(cert2);
- cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
- test_assert(cert3);
- sign_skey_1 = crypto_pk_new();
- sign_skey_2 = crypto_pk_new();
- sign_skey_3 = crypto_pk_new();
- sign_skey_leg1 = pk_generate(4);
+ tt_assert(vrs_gen);
+ tt_assert(rs_test);
+ tt_assert(vrs_test);
- test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
- AUTHORITY_SIGNKEY_1, -1));
- test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
- AUTHORITY_SIGNKEY_2, -1));
- test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
- AUTHORITY_SIGNKEY_3, -1));
-
- test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
- test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
-
- /*
- * Set up a vote; generate it; try to parse it.
- */
- vote = tor_malloc_zero(sizeof(networkstatus_t));
- vote->type = NS_TYPE_VOTE;
- vote->published = now;
- vote->valid_after = now+1000;
- vote->fresh_until = now+2000;
- vote->valid_until = now+3000;
- vote->vote_seconds = 100;
- vote->dist_seconds = 200;
- vote->supported_methods = smartlist_new();
- smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
- vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
- vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
- vote->known_flags = smartlist_new();
- smartlist_split_string(vote->known_flags,
- "Authority Exit Fast Guard Running Stable V2Dir Valid",
- 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
- vote->voters = smartlist_new();
- voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
- voter->nickname = tor_strdup("Voter1");
- voter->address = tor_strdup("1.2.3.4");
- voter->addr = 0x01020304;
- voter->dir_port = 80;
- voter->or_port = 9000;
- voter->contact = tor_strdup("voter@example.com");
- crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
- smartlist_add(vote->voters, voter);
- vote->cert = authority_cert_dup(cert1);
- vote->net_params = smartlist_new();
- smartlist_split_string(vote->net_params, "circuitwindow=101 foo=990",
- NULL, 0, 0);
- vote->routerstatus_list = smartlist_new();
- /* add routerstatuses */
- idx = 0;
- do {
- vrs = vrs_gen(idx, now);
- if (vrs) {
- smartlist_add(vote->routerstatus_list, vrs);
- test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs),
- &msg,0,0)>=0);
- ++idx;
- }
- } while (vrs);
- n_vrs = idx;
+ tt_assert(!dir_common_authority_pk_init(&cert1, &cert2, &cert3,
+ &sign_skey_1, &sign_skey_2,
+ &sign_skey_3));
+ sign_skey_leg1 = pk_generate(4);
- /* dump the vote and try to parse it. */
- v1_text = format_networkstatus_vote(sign_skey_1, vote);
- test_assert(v1_text);
- v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
- test_assert(v1);
+ tt_assert(!dir_common_construct_vote_1(&vote, cert1, sign_skey_1, vrs_gen,
+ &v1, &n_vrs, now, 1));
+ tt_assert(v1);
/* Make sure the parsed thing was right. */
- test_eq(v1->type, NS_TYPE_VOTE);
- test_eq(v1->published, vote->published);
- test_eq(v1->valid_after, vote->valid_after);
- test_eq(v1->fresh_until, vote->fresh_until);
- test_eq(v1->valid_until, vote->valid_until);
- test_eq(v1->vote_seconds, vote->vote_seconds);
- test_eq(v1->dist_seconds, vote->dist_seconds);
- test_streq(v1->client_versions, vote->client_versions);
- test_streq(v1->server_versions, vote->server_versions);
- test_assert(v1->voters && smartlist_len(v1->voters));
+ tt_int_op(v1->type,OP_EQ, NS_TYPE_VOTE);
+ tt_int_op(v1->published,OP_EQ, vote->published);
+ tt_int_op(v1->valid_after,OP_EQ, vote->valid_after);
+ tt_int_op(v1->fresh_until,OP_EQ, vote->fresh_until);
+ tt_int_op(v1->valid_until,OP_EQ, vote->valid_until);
+ tt_int_op(v1->vote_seconds,OP_EQ, vote->vote_seconds);
+ tt_int_op(v1->dist_seconds,OP_EQ, vote->dist_seconds);
+ tt_str_op(v1->client_versions,OP_EQ, vote->client_versions);
+ tt_str_op(v1->server_versions,OP_EQ, vote->server_versions);
+ tt_assert(v1->voters && smartlist_len(v1->voters));
voter = smartlist_get(v1->voters, 0);
- test_streq(voter->nickname, "Voter1");
- test_streq(voter->address, "1.2.3.4");
- test_eq(voter->addr, 0x01020304);
- test_eq(voter->dir_port, 80);
- test_eq(voter->or_port, 9000);
- test_streq(voter->contact, "voter@example.com");
- test_assert(v1->cert);
- test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
+ tt_str_op(voter->nickname,OP_EQ, "Voter1");
+ tt_str_op(voter->address,OP_EQ, "1.2.3.4");
+ tt_int_op(voter->addr,OP_EQ, 0x01020304);
+ tt_int_op(voter->dir_port,OP_EQ, 80);
+ tt_int_op(voter->or_port,OP_EQ, 9000);
+ tt_str_op(voter->contact,OP_EQ, "voter@example.com");
+ tt_assert(v1->cert);
+ tt_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
- test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
+ tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
tor_free(cp);
- test_eq(smartlist_len(v1->routerstatus_list), n_vrs);
+ tt_int_op(smartlist_len(v1->routerstatus_list),OP_EQ, n_vrs);
+ networkstatus_vote_free(vote);
+ vote = NULL;
if (vote_tweaks) params_tweaked += vote_tweaks(v1, 1, now);
/* Check the routerstatuses. */
for (idx = 0; idx < n_vrs; ++idx) {
vrs = smartlist_get(v1->routerstatus_list, idx);
- test_assert(vrs);
+ tt_assert(vrs);
vrs_test(vrs, 1, now);
}
/* Generate second vote. It disagrees on some of the times,
- * and doesn't list versions, and knows some crazy flags */
- vote->published = now+1;
- vote->fresh_until = now+3005;
- vote->dist_seconds = 300;
- authority_cert_free(vote->cert);
- vote->cert = authority_cert_dup(cert2);
- SMARTLIST_FOREACH(vote->net_params, char *, c, tor_free(c));
- smartlist_clear(vote->net_params);
- smartlist_split_string(vote->net_params, "bar=2000000000 circuitwindow=20",
- NULL, 0, 0);
- tor_free(vote->client_versions);
- tor_free(vote->server_versions);
- voter = smartlist_get(vote->voters, 0);
- tor_free(voter->nickname);
- tor_free(voter->address);
- voter->nickname = tor_strdup("Voter2");
- voter->address = tor_strdup("2.3.4.5");
- voter->addr = 0x02030405;
- crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
- smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
- smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
- smartlist_sort_strings(vote->known_flags);
-
- /* generate and parse v2. */
- v2_text = format_networkstatus_vote(sign_skey_2, vote);
- test_assert(v2_text);
- v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
- test_assert(v2);
+ * and doesn't list versions, and knows some crazy flags.
+ * Generate and parse v2. */
+ tt_assert(!dir_common_construct_vote_2(&vote, cert2, sign_skey_2, vrs_gen,
+ &v2, &n_vrs, now, 1));
+ tt_assert(v2);
if (vote_tweaks) params_tweaked += vote_tweaks(v2, 2, now);
/* Check that flags come out right.*/
cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
- test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
+ tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
"Running:Stable:V2Dir:Valid");
tor_free(cp);
@@ -1397,38 +1895,16 @@ test_a_networkstatus(
n_vrs = smartlist_len(v2->routerstatus_list);
for (idx = 0; idx < n_vrs; ++idx) {
vrs = smartlist_get(v2->routerstatus_list, idx);
- test_assert(vrs);
+ tt_assert(vrs);
vrs_test(vrs, 2, now);
}
+ networkstatus_vote_free(vote);
+ vote = NULL;
- /* Generate the third vote. */
- vote->published = now;
- vote->fresh_until = now+2003;
- vote->dist_seconds = 250;
- authority_cert_free(vote->cert);
- vote->cert = authority_cert_dup(cert3);
- SMARTLIST_FOREACH(vote->net_params, char *, c, tor_free(c));
- smartlist_clear(vote->net_params);
- smartlist_split_string(vote->net_params, "circuitwindow=80 foo=660",
- NULL, 0, 0);
- smartlist_add(vote->supported_methods, tor_strdup("4"));
- vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
- vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
- voter = smartlist_get(vote->voters, 0);
- tor_free(voter->nickname);
- tor_free(voter->address);
- voter->nickname = tor_strdup("Voter3");
- voter->address = tor_strdup("3.4.5.6");
- voter->addr = 0x03040506;
- crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
- /* This one has a legacy id. */
- memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
-
- v3_text = format_networkstatus_vote(sign_skey_3, vote);
- test_assert(v3_text);
-
- v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
- test_assert(v3);
+ /* Generate the third vote with a legacy id. */
+ tt_assert(!dir_common_construct_vote_3(&vote, cert3, sign_skey_3, vrs_gen,
+ &v3, &n_vrs, now, 1));
+ tt_assert(v3);
if (vote_tweaks) params_tweaked += vote_tweaks(v3, 3, now);
@@ -1442,10 +1918,10 @@ test_a_networkstatus(
"AAAAAAAAAAAAAAAAAAAA",
sign_skey_leg1,
FLAV_NS);
- test_assert(consensus_text);
+ tt_assert(consensus_text);
con = networkstatus_parse_vote_from_string(consensus_text, NULL,
NS_TYPE_CONSENSUS);
- test_assert(con);
+ tt_assert(con);
//log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
// v1_text, v2_text, v3_text);
consensus_text_md = networkstatus_compute_consensus(votes, 3,
@@ -1454,38 +1930,38 @@ test_a_networkstatus(
"AAAAAAAAAAAAAAAAAAAA",
sign_skey_leg1,
FLAV_MICRODESC);
- test_assert(consensus_text_md);
+ tt_assert(consensus_text_md);
con_md = networkstatus_parse_vote_from_string(consensus_text_md, NULL,
NS_TYPE_CONSENSUS);
- test_assert(con_md);
- test_eq(con_md->flavor, FLAV_MICRODESC);
+ tt_assert(con_md);
+ tt_int_op(con_md->flavor,OP_EQ, FLAV_MICRODESC);
/* Check consensus contents. */
- test_assert(con->type == NS_TYPE_CONSENSUS);
- test_eq(con->published, 0); /* this field only appears in votes. */
- test_eq(con->valid_after, now+1000);
- test_eq(con->fresh_until, now+2003); /* median */
- test_eq(con->valid_until, now+3000);
- test_eq(con->vote_seconds, 100);
- test_eq(con->dist_seconds, 250); /* median */
- test_streq(con->client_versions, "0.1.2.14");
- test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
+ tt_assert(con->type == NS_TYPE_CONSENSUS);
+ tt_int_op(con->published,OP_EQ, 0); /* this field only appears in votes. */
+ tt_int_op(con->valid_after,OP_EQ, now+1000);
+ tt_int_op(con->fresh_until,OP_EQ, now+2003); /* median */
+ tt_int_op(con->valid_until,OP_EQ, now+3000);
+ tt_int_op(con->vote_seconds,OP_EQ, 100);
+ tt_int_op(con->dist_seconds,OP_EQ, 250); /* median */
+ tt_str_op(con->client_versions,OP_EQ, "0.1.2.14");
+ tt_str_op(con->server_versions,OP_EQ, "0.1.2.15,0.1.2.16");
cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
- test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
+ tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
"Running:Stable:V2Dir:Valid");
tor_free(cp);
if (!params_tweaked) {
/* Skip this one if vote_tweaks() messed with the param lists */
cp = smartlist_join_strings(con->net_params, ":", 0, NULL);
- test_streq(cp, "circuitwindow=80:foo=660");
+ tt_str_op(cp,OP_EQ, "circuitwindow=80:foo=660");
tor_free(cp);
}
- test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
+ tt_int_op(4,OP_EQ, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
/* The voter id digests should be in this order. */
- test_assert(memcmp(cert2->cache_info.identity_digest,
+ tt_assert(memcmp(cert2->cache_info.identity_digest,
cert1->cache_info.identity_digest,DIGEST_LEN)<0);
- test_assert(memcmp(cert1->cache_info.identity_digest,
+ tt_assert(memcmp(cert1->cache_info.identity_digest,
cert3->cache_info.identity_digest,DIGEST_LEN)<0);
test_same_voter(smartlist_get(con->voters, 1),
smartlist_get(v2->voters, 0));
@@ -1498,28 +1974,36 @@ test_a_networkstatus(
/* Check the routerstatuses. */
n_rs = smartlist_len(con->routerstatus_list);
+ tt_assert(n_rs);
for (idx = 0; idx < n_rs; ++idx) {
rs = smartlist_get(con->routerstatus_list, idx);
- test_assert(rs);
+ tt_assert(rs);
rs_test(rs, now);
}
+ n_rs = smartlist_len(con_md->routerstatus_list);
+ tt_assert(n_rs);
+ for (idx = 0; idx < n_rs; ++idx) {
+ rs = smartlist_get(con_md->routerstatus_list, idx);
+ tt_assert(rs);
+ }
+
/* Check signatures. the first voter is a pseudo-entry with a legacy key.
* The second one hasn't signed. The fourth one has signed: validate it. */
voter = smartlist_get(con->voters, 1);
- test_eq(smartlist_len(voter->sigs), 0);
+ tt_int_op(smartlist_len(voter->sigs),OP_EQ, 0);
voter = smartlist_get(con->voters, 3);
- test_eq(smartlist_len(voter->sigs), 1);
+ tt_int_op(smartlist_len(voter->sigs),OP_EQ, 1);
sig = smartlist_get(voter->sigs, 0);
- test_assert(sig->signature);
- test_assert(!sig->good_signature);
- test_assert(!sig->bad_signature);
+ tt_assert(sig->signature);
+ tt_assert(!sig->good_signature);
+ tt_assert(!sig->bad_signature);
- test_assert(!networkstatus_check_document_signature(con, sig, cert3));
- test_assert(sig->signature);
- test_assert(sig->good_signature);
- test_assert(!sig->bad_signature);
+ tt_assert(!networkstatus_check_document_signature(con, sig, cert3));
+ tt_assert(sig->signature);
+ tt_assert(sig->good_signature);
+ tt_assert(!sig->bad_signature);
{
const char *msg=NULL;
@@ -1542,10 +2026,10 @@ test_a_networkstatus(
cert1->identity_key,
sign_skey_1, NULL,NULL,
FLAV_MICRODESC);
- test_assert(consensus_text2);
- test_assert(consensus_text3);
- test_assert(consensus_text_md2);
- test_assert(consensus_text_md3);
+ tt_assert(consensus_text2);
+ tt_assert(consensus_text3);
+ tt_assert(consensus_text_md2);
+ tt_assert(consensus_text_md3);
con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
NS_TYPE_CONSENSUS);
con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
@@ -1554,17 +2038,19 @@ test_a_networkstatus(
NS_TYPE_CONSENSUS);
con_md3 = networkstatus_parse_vote_from_string(consensus_text_md3, NULL,
NS_TYPE_CONSENSUS);
- test_assert(con2);
- test_assert(con3);
- test_assert(con_md2);
- test_assert(con_md3);
+ tt_assert(con2);
+ tt_assert(con3);
+ tt_assert(con_md2);
+ tt_assert(con_md3);
/* All three should have the same digest. */
- test_memeq(&con->digests, &con2->digests, sizeof(digests_t));
- test_memeq(&con->digests, &con3->digests, sizeof(digests_t));
+ tt_mem_op(&con->digests,OP_EQ, &con2->digests, sizeof(common_digests_t));
+ tt_mem_op(&con->digests,OP_EQ, &con3->digests, sizeof(common_digests_t));
- test_memeq(&con_md->digests, &con_md2->digests, sizeof(digests_t));
- test_memeq(&con_md->digests, &con_md3->digests, sizeof(digests_t));
+ tt_mem_op(&con_md->digests,OP_EQ, &con_md2->digests,
+ sizeof(common_digests_t));
+ tt_mem_op(&con_md->digests,OP_EQ, &con_md3->digests,
+ sizeof(common_digests_t));
/* Extract a detached signature from con3. */
detached_text1 = get_detached_sigs(con3, con_md3);
@@ -1574,50 +2060,51 @@ test_a_networkstatus(
tt_assert(dsig1);
/* Are parsed values as expected? */
- test_eq(dsig1->valid_after, con3->valid_after);
- test_eq(dsig1->fresh_until, con3->fresh_until);
- test_eq(dsig1->valid_until, con3->valid_until);
+ tt_int_op(dsig1->valid_after,OP_EQ, con3->valid_after);
+ tt_int_op(dsig1->fresh_until,OP_EQ, con3->fresh_until);
+ tt_int_op(dsig1->valid_until,OP_EQ, con3->valid_until);
{
- digests_t *dsig_digests = strmap_get(dsig1->digests, "ns");
- test_assert(dsig_digests);
- test_memeq(dsig_digests->d[DIGEST_SHA1], con3->digests.d[DIGEST_SHA1],
- DIGEST_LEN);
+ common_digests_t *dsig_digests = strmap_get(dsig1->digests, "ns");
+ tt_assert(dsig_digests);
+ tt_mem_op(dsig_digests->d[DIGEST_SHA1], OP_EQ,
+ con3->digests.d[DIGEST_SHA1], DIGEST_LEN);
dsig_digests = strmap_get(dsig1->digests, "microdesc");
- test_assert(dsig_digests);
- test_memeq(dsig_digests->d[DIGEST_SHA256],
+ tt_assert(dsig_digests);
+ tt_mem_op(dsig_digests->d[DIGEST_SHA256],OP_EQ,
con_md3->digests.d[DIGEST_SHA256],
DIGEST256_LEN);
}
{
smartlist_t *dsig_signatures = strmap_get(dsig1->signatures, "ns");
- test_assert(dsig_signatures);
- test_eq(1, smartlist_len(dsig_signatures));
+ tt_assert(dsig_signatures);
+ tt_int_op(1,OP_EQ, smartlist_len(dsig_signatures));
sig = smartlist_get(dsig_signatures, 0);
- test_memeq(sig->identity_digest, cert1->cache_info.identity_digest,
+ tt_mem_op(sig->identity_digest,OP_EQ, cert1->cache_info.identity_digest,
DIGEST_LEN);
- test_eq(sig->alg, DIGEST_SHA1);
+ tt_int_op(sig->alg,OP_EQ, DIGEST_SHA1);
dsig_signatures = strmap_get(dsig1->signatures, "microdesc");
- test_assert(dsig_signatures);
- test_eq(1, smartlist_len(dsig_signatures));
+ tt_assert(dsig_signatures);
+ tt_int_op(1,OP_EQ, smartlist_len(dsig_signatures));
sig = smartlist_get(dsig_signatures, 0);
- test_memeq(sig->identity_digest, cert1->cache_info.identity_digest,
+ tt_mem_op(sig->identity_digest,OP_EQ, cert1->cache_info.identity_digest,
DIGEST_LEN);
- test_eq(sig->alg, DIGEST_SHA256);
+ tt_int_op(sig->alg,OP_EQ, DIGEST_SHA256);
}
/* Try adding it to con2. */
detached_text2 = get_detached_sigs(con2,con_md2);
- test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, "test",
- LOG_INFO, &msg));
+ tt_int_op(1,OP_EQ, networkstatus_add_detached_signatures(con2, dsig1,
+ "test", LOG_INFO, &msg));
tor_free(detached_text2);
- test_eq(1, networkstatus_add_detached_signatures(con_md2, dsig1, "test",
+ tt_int_op(1,OP_EQ,
+ networkstatus_add_detached_signatures(con_md2, dsig1, "test",
LOG_INFO, &msg));
tor_free(detached_text2);
detached_text2 = get_detached_sigs(con2,con_md2);
//printf("\n<%s>\n", detached_text2);
dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
- test_assert(dsig2);
+ tt_assert(dsig2);
/*
printf("\n");
SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
@@ -1626,65 +2113,49 @@ test_a_networkstatus(
printf("%s\n", hd);
});
*/
- test_eq(2,
+ tt_int_op(2,OP_EQ,
smartlist_len((smartlist_t*)strmap_get(dsig2->signatures, "ns")));
- test_eq(2,
+ tt_int_op(2,OP_EQ,
smartlist_len((smartlist_t*)strmap_get(dsig2->signatures,
"microdesc")));
/* Try adding to con2 twice; verify that nothing changes. */
- test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, "test",
- LOG_INFO, &msg));
+ tt_int_op(0,OP_EQ, networkstatus_add_detached_signatures(con2, dsig1,
+ "test", LOG_INFO, &msg));
/* Add to con. */
- test_eq(2, networkstatus_add_detached_signatures(con, dsig2, "test",
- LOG_INFO, &msg));
+ tt_int_op(2,OP_EQ, networkstatus_add_detached_signatures(con, dsig2,
+ "test", LOG_INFO, &msg));
/* Check signatures */
voter = smartlist_get(con->voters, 1);
sig = smartlist_get(voter->sigs, 0);
- test_assert(sig);
- test_assert(!networkstatus_check_document_signature(con, sig, cert2));
+ tt_assert(sig);
+ tt_assert(!networkstatus_check_document_signature(con, sig, cert2));
voter = smartlist_get(con->voters, 2);
sig = smartlist_get(voter->sigs, 0);
- test_assert(sig);
- test_assert(!networkstatus_check_document_signature(con, sig, cert1));
+ tt_assert(sig);
+ tt_assert(!networkstatus_check_document_signature(con, sig, cert1));
}
done:
tor_free(cp);
smartlist_free(votes);
- tor_free(v1_text);
- tor_free(v2_text);
- tor_free(v3_text);
tor_free(consensus_text);
tor_free(consensus_text_md);
- if (vote)
- networkstatus_vote_free(vote);
- if (v1)
- networkstatus_vote_free(v1);
- if (v2)
- networkstatus_vote_free(v2);
- if (v3)
- networkstatus_vote_free(v3);
- if (con)
- networkstatus_vote_free(con);
- if (con_md)
- networkstatus_vote_free(con_md);
- if (sign_skey_1)
- crypto_pk_free(sign_skey_1);
- if (sign_skey_2)
- crypto_pk_free(sign_skey_2);
- if (sign_skey_3)
- crypto_pk_free(sign_skey_3);
- if (sign_skey_leg1)
- crypto_pk_free(sign_skey_leg1);
- if (cert1)
- authority_cert_free(cert1);
- if (cert2)
- authority_cert_free(cert2);
- if (cert3)
- authority_cert_free(cert3);
+ networkstatus_vote_free(vote);
+ networkstatus_vote_free(v1);
+ networkstatus_vote_free(v2);
+ networkstatus_vote_free(v3);
+ networkstatus_vote_free(con);
+ networkstatus_vote_free(con_md);
+ crypto_pk_free(sign_skey_1);
+ crypto_pk_free(sign_skey_2);
+ crypto_pk_free(sign_skey_3);
+ crypto_pk_free(sign_skey_leg1);
+ authority_cert_free(cert1);
+ authority_cert_free(cert2);
+ authority_cert_free(cert3);
tor_free(consensus_text2);
tor_free(consensus_text3);
@@ -1692,26 +2163,22 @@ test_a_networkstatus(
tor_free(consensus_text_md3);
tor_free(detached_text1);
tor_free(detached_text2);
- if (con2)
- networkstatus_vote_free(con2);
- if (con3)
- networkstatus_vote_free(con3);
- if (con_md2)
- networkstatus_vote_free(con_md2);
- if (con_md3)
- networkstatus_vote_free(con_md3);
- if (dsig1)
- ns_detached_signatures_free(dsig1);
- if (dsig2)
- ns_detached_signatures_free(dsig2);
+
+ networkstatus_vote_free(con2);
+ networkstatus_vote_free(con3);
+ networkstatus_vote_free(con_md2);
+ networkstatus_vote_free(con_md3);
+ ns_detached_signatures_free(dsig1);
+ ns_detached_signatures_free(dsig2);
}
/** Run unit tests for generating and parsing V3 consensus networkstatus
* documents. */
static void
-test_dir_v3_networkstatus(void)
+test_dir_v3_networkstatus(void *arg)
{
- test_a_networkstatus(gen_routerstatus_for_v3ns,
+ (void)arg;
+ test_a_networkstatus(dir_common_gen_routerstatus_for_v3ns,
vote_tweaks_for_v3ns,
test_vrs_for_v3ns,
test_consensus_for_v3ns,
@@ -1740,7 +2207,7 @@ test_dir_scale_bw(void *testdata)
scale_array_elements_to_u64(vals, 8, &total);
- tt_int_op((int)total, ==, 48);
+ tt_int_op((int)total, OP_EQ, 48);
total = 0;
for (i=0; i<8; ++i) {
total += vals[i].u64;
@@ -1749,10 +2216,37 @@ test_dir_scale_bw(void *testdata)
tt_assert(total <= (U64_LITERAL(1)<<62));
for (i=0; i<8; ++i) {
+ /* vals[2].u64 is the scaled value of 1.0 */
double ratio = ((double)vals[i].u64) / vals[2].u64;
- tt_double_op(fabs(ratio - v[i]), <, .00001);
+ tt_double_op(fabs(ratio - v[i]), OP_LT, .00001);
}
+ /* test handling of no entries */
+ total = 1;
+ scale_array_elements_to_u64(vals, 0, &total);
+ tt_assert(total == 0);
+
+ /* make sure we don't read the array when we have no entries
+ * may require compiler flags to catch NULL dereferences */
+ total = 1;
+ scale_array_elements_to_u64(NULL, 0, &total);
+ tt_assert(total == 0);
+
+ scale_array_elements_to_u64(NULL, 0, NULL);
+
+ /* test handling of zero totals */
+ total = 1;
+ vals[0].dbl = 0.0;
+ scale_array_elements_to_u64(vals, 1, &total);
+ tt_assert(total == 0);
+ tt_assert(vals[0].u64 == 0);
+
+ vals[0].dbl = 0.0;
+ vals[1].dbl = 0.0;
+ scale_array_elements_to_u64(vals, 2, NULL);
+ tt_assert(vals[0].u64 == 0);
+ tt_assert(vals[1].u64 == 0);
+
done:
;
}
@@ -1775,11 +2269,11 @@ test_dir_random_weighted(void *testdata)
inp[i].u64 = vals[i];
total += vals[i];
}
- tt_u64_op(total, ==, 45);
+ tt_u64_op(total, OP_EQ, 45);
for (i=0; i<n; ++i) {
choice = choose_array_element_by_weight(inp, 10);
- tt_int_op(choice, >=, 0);
- tt_int_op(choice, <, 10);
+ tt_int_op(choice, OP_GE, 0);
+ tt_int_op(choice, OP_LT, 10);
histogram[choice]++;
}
@@ -1792,7 +2286,7 @@ test_dir_random_weighted(void *testdata)
if (expected)
frac_diff = (histogram[i] - expected) / ((double)expected);
else
- tt_int_op(histogram[i], ==, 0);
+ tt_int_op(histogram[i], OP_EQ, 0);
sq = frac_diff * frac_diff;
if (sq > max_sq_error)
@@ -1800,12 +2294,12 @@ test_dir_random_weighted(void *testdata)
}
/* It should almost always be much much less than this. If you want to
* figure out the odds, please feel free. */
- tt_double_op(max_sq_error, <, .05);
+ tt_double_op(max_sq_error, OP_LT, .05);
/* Now try a singleton; do we choose it? */
for (i = 0; i < 100; ++i) {
choice = choose_array_element_by_weight(inp, 1);
- tt_int_op(choice, ==, 0);
+ tt_int_op(choice, OP_EQ, 0);
}
/* Now try an array of zeros. We should choose randomly. */
@@ -1814,8 +2308,8 @@ test_dir_random_weighted(void *testdata)
inp[i].u64 = 0;
for (i = 0; i < n; ++i) {
choice = choose_array_element_by_weight(inp, 5);
- tt_int_op(choice, >=, 0);
- tt_int_op(choice, <, 5);
+ tt_int_op(choice, OP_GE, 0);
+ tt_int_op(choice, OP_LT, 5);
histogram[choice]++;
}
/* Now see if we chose things about frequently enough. */
@@ -1831,7 +2325,7 @@ test_dir_random_weighted(void *testdata)
}
/* It should almost always be much much less than this. If you want to
* figure out the odds, please feel free. */
- tt_double_op(max_sq_error, <, .05);
+ tt_double_op(max_sq_error, OP_LT, .05);
done:
;
}
@@ -1958,7 +2452,7 @@ gen_routerstatus_for_umbw(int idx, time_t now)
break;
default:
/* Shouldn't happen */
- test_assert(0);
+ tt_assert(0);
}
if (vrs) {
vrs->microdesc = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
@@ -1980,11 +2474,11 @@ vote_tweaks_for_umbw(networkstatus_t *v, int voter, time_t now)
char *maxbw_param = NULL;
int rv = 0;
- test_assert(v);
+ tt_assert(v);
(void)voter;
(void)now;
- test_assert(v->supported_methods);
+ tt_assert(v->supported_methods);
SMARTLIST_FOREACH(v->supported_methods, char *, c, tor_free(c));
smartlist_clear(v->supported_methods);
/* Method 17 is MIN_METHOD_TO_CLIP_UNMEASURED_BW_KB */
@@ -1994,7 +2488,7 @@ vote_tweaks_for_umbw(networkstatus_t *v, int voter, time_t now)
/* If we're using a non-default clip bandwidth, add it to net_params */
if (alternate_clip_bw > 0) {
tor_asprintf(&maxbw_param, "maxunmeasuredbw=%u", alternate_clip_bw);
- test_assert(maxbw_param);
+ tt_assert(maxbw_param);
if (maxbw_param) {
smartlist_add(v->net_params, maxbw_param);
rv = 1;
@@ -2017,9 +2511,9 @@ test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
alternate_clip_bw : DEFAULT_MAX_UNMEASURED_BW_KB;
(void)voter;
- test_assert(vrs);
+ tt_assert(vrs);
rs = &(vrs->status);
- test_assert(rs);
+ tt_assert(rs);
/* Split out by digests to test */
if (tor_memeq(rs->identity_digest,
@@ -2030,21 +2524,21 @@ test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
* Check the first routerstatus - measured bandwidth below the clip
* cutoff.
*/
- test_streq(vrs->version, "0.1.2.14");
- test_eq(rs->published_on, now-1500);
- test_streq(rs->nickname, "router2");
- test_memeq(rs->identity_digest,
+ tt_str_op(vrs->version,OP_EQ, "0.1.2.14");
+ tt_int_op(rs->published_on,OP_EQ, now-1500);
+ tt_str_op(rs->nickname,OP_EQ, "router2");
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
DIGEST_LEN);
- test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
- test_eq(rs->addr, 0x99008801);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 8000);
- test_assert(rs->has_bandwidth);
- test_assert(vrs->has_measured_bw);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb / 2);
- test_eq(vrs->measured_bw_kb, max_unmeasured_bw_kb / 2);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
+ tt_int_op(rs->addr,OP_EQ, 0x99008801);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 8000);
+ tt_assert(rs->has_bandwidth);
+ tt_assert(vrs->has_measured_bw);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
+ tt_int_op(vrs->measured_bw_kb,OP_EQ, max_unmeasured_bw_kb / 2);
} else if (tor_memeq(rs->identity_digest,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
@@ -2054,24 +2548,24 @@ test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
* Check the second routerstatus - measured bandwidth above the clip
* cutoff.
*/
- test_streq(vrs->version, "0.2.0.5");
- test_eq(rs->published_on, now-1000);
- test_streq(rs->nickname, "router1");
- test_memeq(rs->identity_digest,
+ tt_str_op(vrs->version,OP_EQ, "0.2.0.5");
+ tt_int_op(rs->published_on,OP_EQ, now-1000);
+ tt_str_op(rs->nickname,OP_EQ, "router1");
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
DIGEST_LEN);
- test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
- test_eq(rs->addr, 0x99009901);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 0);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
+ tt_int_op(rs->addr,OP_EQ, 0x99009901);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 0);
tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
- test_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
- test_eq(rs->ipv6_orport, 4711);
- test_assert(rs->has_bandwidth);
- test_assert(vrs->has_measured_bw);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb * 2);
- test_eq(vrs->measured_bw_kb, max_unmeasured_bw_kb * 2);
+ tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
+ tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
+ tt_assert(rs->has_bandwidth);
+ tt_assert(vrs->has_measured_bw);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
+ tt_int_op(vrs->measured_bw_kb,OP_EQ, max_unmeasured_bw_kb * 2);
} else if (tor_memeq(rs->identity_digest,
"\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
"\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33",
@@ -2081,10 +2575,10 @@ test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
* cutoff; this one should be clipped later on in the consensus, but
* appears unclipped in the vote.
*/
- test_assert(rs->has_bandwidth);
- test_assert(!(vrs->has_measured_bw));
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb * 2);
- test_eq(vrs->measured_bw_kb, 0);
+ tt_assert(rs->has_bandwidth);
+ tt_assert(!(vrs->has_measured_bw));
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
+ tt_int_op(vrs->measured_bw_kb,OP_EQ, 0);
} else if (tor_memeq(rs->identity_digest,
"\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34"
"\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34",
@@ -2093,12 +2587,12 @@ test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
* Check the fourth routerstatus - unmeasured bandwidth below the clip
* cutoff; this one should not be clipped.
*/
- test_assert(rs->has_bandwidth);
- test_assert(!(vrs->has_measured_bw));
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb / 2);
- test_eq(vrs->measured_bw_kb, 0);
+ tt_assert(rs->has_bandwidth);
+ tt_assert(!(vrs->has_measured_bw));
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
+ tt_int_op(vrs->measured_bw_kb,OP_EQ, 0);
} else {
- test_assert(0);
+ tt_assert(0);
}
done:
@@ -2113,11 +2607,11 @@ test_consensus_for_umbw(networkstatus_t *con, time_t now)
{
(void)now;
- test_assert(con);
- test_assert(!con->cert);
- // test_assert(con->consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW_KB);
- test_assert(con->consensus_method >= 16);
- test_eq(4, smartlist_len(con->routerstatus_list));
+ tt_assert(con);
+ tt_assert(!con->cert);
+ // tt_assert(con->consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW_KB);
+ tt_assert(con->consensus_method >= 16);
+ tt_int_op(4,OP_EQ, smartlist_len(con->routerstatus_list));
/* There should be four listed routers; all voters saw the same in this */
done:
@@ -2134,61 +2628,61 @@ test_routerstatus_for_umbw(routerstatus_t *rs, time_t now)
uint32_t max_unmeasured_bw_kb = (alternate_clip_bw > 0) ?
alternate_clip_bw : DEFAULT_MAX_UNMEASURED_BW_KB;
- test_assert(rs);
+ tt_assert(rs);
/* There should be four listed routers, as constructed above */
if (tor_memeq(rs->identity_digest,
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
DIGEST_LEN)) {
- test_memeq(rs->identity_digest,
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
"\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
DIGEST_LEN);
- test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
- test_assert(!rs->is_authority);
- test_assert(!rs->is_exit);
- test_assert(!rs->is_fast);
- test_assert(!rs->is_possible_guard);
- test_assert(!rs->is_stable);
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
+ tt_assert(!rs->is_authority);
+ tt_assert(!rs->is_exit);
+ tt_assert(!rs->is_fast);
+ tt_assert(!rs->is_possible_guard);
+ tt_assert(!rs->is_stable);
/* (If it wasn't running it wouldn't be here) */
- test_assert(rs->is_flagged_running);
- test_assert(!rs->is_valid);
- test_assert(!rs->is_named);
+ tt_assert(rs->is_flagged_running);
+ tt_assert(!rs->is_valid);
+ tt_assert(!rs->is_named);
/* This one should have measured bandwidth below the clip cutoff */
- test_assert(rs->has_bandwidth);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb / 2);
- test_assert(!(rs->bw_is_unmeasured));
+ tt_assert(rs->has_bandwidth);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
+ tt_assert(!(rs->bw_is_unmeasured));
} else if (tor_memeq(rs->identity_digest,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
DIGEST_LEN)) {
/* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
- test_memeq(rs->identity_digest,
+ tt_mem_op(rs->identity_digest,OP_EQ,
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
"\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
DIGEST_LEN);
- test_streq(rs->nickname, "router1");
- test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
- test_eq(rs->published_on, now-1000);
- test_eq(rs->addr, 0x99009901);
- test_eq(rs->or_port, 443);
- test_eq(rs->dir_port, 0);
+ tt_str_op(rs->nickname,OP_EQ, "router1");
+ tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
+ tt_int_op(rs->published_on,OP_EQ, now-1000);
+ tt_int_op(rs->addr,OP_EQ, 0x99009901);
+ tt_int_op(rs->or_port,OP_EQ, 443);
+ tt_int_op(rs->dir_port,OP_EQ, 0);
tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
- test_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
- test_eq(rs->ipv6_orport, 4711);
- test_assert(!rs->is_authority);
- test_assert(rs->is_exit);
- test_assert(rs->is_fast);
- test_assert(rs->is_possible_guard);
- test_assert(rs->is_stable);
- test_assert(rs->is_flagged_running);
- test_assert(rs->is_valid);
- test_assert(!rs->is_named);
+ tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
+ tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
+ tt_assert(!rs->is_authority);
+ tt_assert(rs->is_exit);
+ tt_assert(rs->is_fast);
+ tt_assert(rs->is_possible_guard);
+ tt_assert(rs->is_stable);
+ tt_assert(rs->is_flagged_running);
+ tt_assert(rs->is_valid);
+ tt_assert(!rs->is_named);
/* This one should have measured bandwidth above the clip cutoff */
- test_assert(rs->has_bandwidth);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb * 2);
- test_assert(!(rs->bw_is_unmeasured));
+ tt_assert(rs->has_bandwidth);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
+ tt_assert(!(rs->bw_is_unmeasured));
} else if (tor_memeq(rs->identity_digest,
"\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
"\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33",
@@ -2197,9 +2691,9 @@ test_routerstatus_for_umbw(routerstatus_t *rs, time_t now)
* This one should have unmeasured bandwidth above the clip cutoff,
* and so should be clipped
*/
- test_assert(rs->has_bandwidth);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb);
- test_assert(rs->bw_is_unmeasured);
+ tt_assert(rs->has_bandwidth);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb);
+ tt_assert(rs->bw_is_unmeasured);
} else if (tor_memeq(rs->identity_digest,
"\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34"
"\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34",
@@ -2208,12 +2702,12 @@ test_routerstatus_for_umbw(routerstatus_t *rs, time_t now)
* This one should have unmeasured bandwidth below the clip cutoff,
* and so should not be clipped
*/
- test_assert(rs->has_bandwidth);
- test_eq(rs->bandwidth_kb, max_unmeasured_bw_kb / 2);
- test_assert(rs->bw_is_unmeasured);
+ tt_assert(rs->has_bandwidth);
+ tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
+ tt_assert(rs->bw_is_unmeasured);
} else {
/* Weren't expecting this... */
- test_assert(0);
+ tt_assert(0);
}
done:
@@ -2227,9 +2721,10 @@ test_routerstatus_for_umbw(routerstatus_t *rs, time_t now)
*/
static void
-test_dir_clip_unmeasured_bw_kb(void)
+test_dir_clip_unmeasured_bw_kb(void *arg)
{
/* Run the test with the default clip bandwidth */
+ (void)arg;
alternate_clip_bw = 0;
test_a_networkstatus(gen_routerstatus_for_umbw,
vote_tweaks_for_umbw,
@@ -2244,7 +2739,7 @@ test_dir_clip_unmeasured_bw_kb(void)
*/
static void
-test_dir_clip_unmeasured_bw_kb_alt(void)
+test_dir_clip_unmeasured_bw_kb_alt(void *arg)
{
/*
* Try a different one; this value is chosen so that the below-the-cutoff
@@ -2252,6 +2747,7 @@ test_dir_clip_unmeasured_bw_kb_alt(void)
* DEFAULT_MAX_UNMEASURED_BW_KB and if the consensus incorrectly uses that
* cutoff it will fail the test.
*/
+ (void)arg;
alternate_clip_bw = 3 * DEFAULT_MAX_UNMEASURED_BW_KB;
test_a_networkstatus(gen_routerstatus_for_umbw,
vote_tweaks_for_umbw,
@@ -2279,11 +2775,12 @@ test_dir_fmt_control_ns(void *arg)
rs.is_fast = 1;
rs.is_flagged_running = 1;
rs.has_bandwidth = 1;
+ rs.is_v2_dir = 1;
rs.bandwidth_kb = 1000;
s = networkstatus_getinfo_helper_single(&rs);
tt_assert(s);
- tt_str_op(s, ==,
+ tt_str_op(s, OP_EQ,
"r TetsuoMilk U3RhdGVseSwgcGx1bXAgQnVjayA "
"TXVsbGlnYW4gY2FtZSB1cCBmcm8 2013-04-02 17:53:18 "
"32.48.64.80 9001 9002\n"
@@ -2294,6 +2791,281 @@ test_dir_fmt_control_ns(void *arg)
tor_free(s);
}
+static int mock_get_options_calls = 0;
+static or_options_t *mock_options = NULL;
+
+static void
+reset_options(or_options_t *options, int *get_options_calls)
+{
+ memset(options, 0, sizeof(or_options_t));
+ options->TestingTorNetwork = 1;
+
+ *get_options_calls = 0;
+}
+
+static const or_options_t *
+mock_get_options(void)
+{
+ ++mock_get_options_calls;
+ tor_assert(mock_options);
+ return mock_options;
+}
+
+static void
+reset_routerstatus(routerstatus_t *rs,
+ const char *hex_identity_digest,
+ int32_t ipv4_addr)
+{
+ memset(rs, 0, sizeof(routerstatus_t));
+ base16_decode(rs->identity_digest, sizeof(rs->identity_digest),
+ hex_identity_digest, HEX_DIGEST_LEN);
+ /* A zero address matches everything, so the address needs to be set.
+ * But the specific value is irrelevant. */
+ rs->addr = ipv4_addr;
+}
+
+#define ROUTER_A_ID_STR "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+#define ROUTER_A_IPV4 0xAA008801
+#define ROUTER_B_ID_STR "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+#define ROUTER_B_IPV4 0xBB008801
+
+#define ROUTERSET_ALL_STR "*"
+#define ROUTERSET_A_STR ROUTER_A_ID_STR
+#define ROUTERSET_NONE_STR ""
+
+/*
+ * Test that dirserv_set_routerstatus_testing sets router flags correctly
+ * Using "*" sets flags on A and B
+ * Using "A" sets flags on A
+ * Using "" sets flags on Neither
+ * If the router is not included:
+ * - if *Strict is set, the flag is set to 0,
+ * - otherwise, the flag is not modified. */
+static void
+test_dir_dirserv_set_routerstatus_testing(void *arg)
+{
+ (void)arg;
+
+ /* Init options */
+ mock_options = malloc(sizeof(or_options_t));
+ reset_options(mock_options, &mock_get_options_calls);
+
+ MOCK(get_options, mock_get_options);
+
+ /* Init routersets */
+ routerset_t *routerset_all = routerset_new();
+ routerset_parse(routerset_all, ROUTERSET_ALL_STR, "All routers");
+
+ routerset_t *routerset_a = routerset_new();
+ routerset_parse(routerset_a, ROUTERSET_A_STR, "Router A only");
+
+ routerset_t *routerset_none = routerset_new();
+ /* Routersets are empty when provided by routerset_new(),
+ * so this is not strictly necessary */
+ routerset_parse(routerset_none, ROUTERSET_NONE_STR, "No routers");
+
+ /* Init routerstatuses */
+ routerstatus_t *rs_a = malloc(sizeof(routerstatus_t));
+ reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
+
+ routerstatus_t *rs_b = malloc(sizeof(routerstatus_t));
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ /* Sanity check that routersets correspond to routerstatuses.
+ * Return values are {2, 3, 4} */
+
+ /* We want 3 ("*" means match all addresses) */
+ tt_assert(routerset_contains_routerstatus(routerset_all, rs_a, 0) == 3);
+ tt_assert(routerset_contains_routerstatus(routerset_all, rs_b, 0) == 3);
+
+ /* We want 4 (match id_digest [or nickname]) */
+ tt_assert(routerset_contains_routerstatus(routerset_a, rs_a, 0) == 4);
+ tt_assert(routerset_contains_routerstatus(routerset_a, rs_b, 0) == 0);
+
+ tt_assert(routerset_contains_routerstatus(routerset_none, rs_a, 0) == 0);
+ tt_assert(routerset_contains_routerstatus(routerset_none, rs_b, 0) == 0);
+
+ /* Check that "*" sets flags on all routers: Exit
+ * Check the flags aren't being confused with each other */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_all;
+ mock_options->TestingDirAuthVoteExitIsStrict = 0;
+
+ dirserv_set_routerstatus_testing(rs_a);
+ tt_assert(mock_get_options_calls == 1);
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 2);
+
+ tt_assert(rs_a->is_exit == 1);
+ tt_assert(rs_b->is_exit == 1);
+ /* Be paranoid - check no other flags are set */
+ tt_assert(rs_a->is_possible_guard == 0);
+ tt_assert(rs_b->is_possible_guard == 0);
+ tt_assert(rs_a->is_hs_dir == 0);
+ tt_assert(rs_b->is_hs_dir == 0);
+
+ /* Check that "*" sets flags on all routers: Guard & HSDir
+ * Cover the remaining flags in one test */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteGuard = routerset_all;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 0;
+ mock_options->TestingDirAuthVoteHSDir = routerset_all;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 0;
+
+ dirserv_set_routerstatus_testing(rs_a);
+ tt_assert(mock_get_options_calls == 1);
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 2);
+
+ tt_assert(rs_a->is_possible_guard == 1);
+ tt_assert(rs_b->is_possible_guard == 1);
+ tt_assert(rs_a->is_hs_dir == 1);
+ tt_assert(rs_b->is_hs_dir == 1);
+ /* Be paranoid - check exit isn't set */
+ tt_assert(rs_a->is_exit == 0);
+ tt_assert(rs_b->is_exit == 0);
+
+ /* Check routerset A sets all flags on router A,
+ * but leaves router B unmodified */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_a;
+ mock_options->TestingDirAuthVoteExitIsStrict = 0;
+ mock_options->TestingDirAuthVoteGuard = routerset_a;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 0;
+ mock_options->TestingDirAuthVoteHSDir = routerset_a;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 0;
+
+ dirserv_set_routerstatus_testing(rs_a);
+ tt_assert(mock_get_options_calls == 1);
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 2);
+
+ tt_assert(rs_a->is_exit == 1);
+ tt_assert(rs_b->is_exit == 0);
+ tt_assert(rs_a->is_possible_guard == 1);
+ tt_assert(rs_b->is_possible_guard == 0);
+ tt_assert(rs_a->is_hs_dir == 1);
+ tt_assert(rs_b->is_hs_dir == 0);
+
+ /* Check routerset A unsets all flags on router B when Strict is set */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_a;
+ mock_options->TestingDirAuthVoteExitIsStrict = 1;
+ mock_options->TestingDirAuthVoteGuard = routerset_a;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 1;
+ mock_options->TestingDirAuthVoteHSDir = routerset_a;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 1;
+
+ rs_b->is_exit = 1;
+ rs_b->is_possible_guard = 1;
+ rs_b->is_hs_dir = 1;
+
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 1);
+
+ tt_assert(rs_b->is_exit == 0);
+ tt_assert(rs_b->is_possible_guard == 0);
+ tt_assert(rs_b->is_hs_dir == 0);
+
+ /* Check routerset A doesn't modify flags on router B without Strict set */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_a;
+ mock_options->TestingDirAuthVoteExitIsStrict = 0;
+ mock_options->TestingDirAuthVoteGuard = routerset_a;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 0;
+ mock_options->TestingDirAuthVoteHSDir = routerset_a;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 0;
+
+ rs_b->is_exit = 1;
+ rs_b->is_possible_guard = 1;
+ rs_b->is_hs_dir = 1;
+
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 1);
+
+ tt_assert(rs_b->is_exit == 1);
+ tt_assert(rs_b->is_possible_guard == 1);
+ tt_assert(rs_b->is_hs_dir == 1);
+
+ /* Check the empty routerset zeroes all flags
+ * on routers A & B with Strict set */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_none;
+ mock_options->TestingDirAuthVoteExitIsStrict = 1;
+ mock_options->TestingDirAuthVoteGuard = routerset_none;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 1;
+ mock_options->TestingDirAuthVoteHSDir = routerset_none;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 1;
+
+ rs_b->is_exit = 1;
+ rs_b->is_possible_guard = 1;
+ rs_b->is_hs_dir = 1;
+
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 1);
+
+ tt_assert(rs_b->is_exit == 0);
+ tt_assert(rs_b->is_possible_guard == 0);
+ tt_assert(rs_b->is_hs_dir == 0);
+
+ /* Check the empty routerset doesn't modify any flags
+ * on A or B without Strict set */
+ reset_options(mock_options, &mock_get_options_calls);
+ reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
+ reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
+
+ mock_options->TestingDirAuthVoteExit = routerset_none;
+ mock_options->TestingDirAuthVoteExitIsStrict = 0;
+ mock_options->TestingDirAuthVoteGuard = routerset_none;
+ mock_options->TestingDirAuthVoteGuardIsStrict = 0;
+ mock_options->TestingDirAuthVoteHSDir = routerset_none;
+ mock_options->TestingDirAuthVoteHSDirIsStrict = 0;
+
+ rs_b->is_exit = 1;
+ rs_b->is_possible_guard = 1;
+ rs_b->is_hs_dir = 1;
+
+ dirserv_set_routerstatus_testing(rs_a);
+ tt_assert(mock_get_options_calls == 1);
+ dirserv_set_routerstatus_testing(rs_b);
+ tt_assert(mock_get_options_calls == 2);
+
+ tt_assert(rs_a->is_exit == 0);
+ tt_assert(rs_a->is_possible_guard == 0);
+ tt_assert(rs_a->is_hs_dir == 0);
+ tt_assert(rs_b->is_exit == 1);
+ tt_assert(rs_b->is_possible_guard == 1);
+ tt_assert(rs_b->is_hs_dir == 1);
+
+ done:
+ free(mock_options);
+ mock_options = NULL;
+
+ UNMOCK(get_options);
+
+ routerset_free(routerset_all);
+ routerset_free(routerset_a);
+ routerset_free(routerset_none);
+
+ free(rs_a);
+ free(rs_b);
+}
+
static void
test_dir_http_handling(void *args)
{
@@ -2302,75 +3074,1156 @@ test_dir_http_handling(void *args)
/* Parse http url tests: */
/* Good headers */
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1\r\n"
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1\r\n"
"Host: example.com\r\n"
"User-Agent: Mozilla/5.0 (Windows;"
" U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
- &url), 0);
- test_streq(url, "/tor/a/b/c.txt");
+ &url),OP_EQ, 0);
+ tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
tor_free(url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.0\r\n", &url), 0);
- test_streq(url, "/tor/a/b/c.txt");
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.0\r\n", &url),OP_EQ, 0);
+ tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
tor_free(url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.600\r\n", &url), 0);
- test_streq(url, "/tor/a/b/c.txt");
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.600\r\n", &url),
+ OP_EQ, 0);
+ tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
tor_free(url);
/* Should prepend '/tor/' to url if required */
- test_eq(parse_http_url("GET /a/b/c.txt HTTP/1.1\r\n"
+ tt_int_op(parse_http_url("GET /a/b/c.txt HTTP/1.1\r\n"
"Host: example.com\r\n"
"User-Agent: Mozilla/5.0 (Windows;"
" U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
- &url), 0);
- test_streq(url, "/tor/a/b/c.txt");
+ &url),OP_EQ, 0);
+ tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
tor_free(url);
/* Bad headers -- no HTTP/1.x*/
- test_eq(parse_http_url("GET /a/b/c.txt\r\n"
+ tt_int_op(parse_http_url("GET /a/b/c.txt\r\n"
"Host: example.com\r\n"
"User-Agent: Mozilla/5.0 (Windows;"
" U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
- &url), -1);
+ &url),OP_EQ, -1);
tt_assert(!url);
/* Bad headers */
- test_eq(parse_http_url("GET /a/b/c.txt\r\n"
+ tt_int_op(parse_http_url("GET /a/b/c.txt\r\n"
"Host: example.com\r\n"
"User-Agent: Mozilla/5.0 (Windows;"
" U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
- &url), -1);
+ &url),OP_EQ, -1);
tt_assert(!url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt", &url), -1);
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt", &url),OP_EQ, -1);
tt_assert(!url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1", &url), -1);
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1", &url),OP_EQ, -1);
tt_assert(!url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1x\r\n", &url), -1);
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1x\r\n", &url),
+ OP_EQ, -1);
tt_assert(!url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.", &url), -1);
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.", &url),OP_EQ, -1);
tt_assert(!url);
- test_eq(parse_http_url("GET /tor/a/b/c.txt HTTP/1.\r", &url), -1);
+ tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.\r", &url),OP_EQ, -1);
tt_assert(!url);
done:
tor_free(url);
}
-#define DIR_LEGACY(name) \
- { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_dir_ ## name }
+static void
+test_dir_purpose_needs_anonymity(void *arg)
+{
+ (void)arg;
+ tt_int_op(1, ==, purpose_needs_anonymity(0, ROUTER_PURPOSE_BRIDGE));
+ tt_int_op(1, ==, purpose_needs_anonymity(0, ROUTER_PURPOSE_GENERAL));
+ tt_int_op(0, ==, purpose_needs_anonymity(DIR_PURPOSE_FETCH_MICRODESC,
+ ROUTER_PURPOSE_GENERAL));
+ done: ;
+}
+
+static void
+test_dir_fetch_type(void *arg)
+{
+ (void)arg;
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_EXTRAINFO, ROUTER_PURPOSE_BRIDGE,
+ NULL), OP_EQ, EXTRAINFO_DIRINFO | BRIDGE_DIRINFO);
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_EXTRAINFO, ROUTER_PURPOSE_GENERAL,
+ NULL), OP_EQ, EXTRAINFO_DIRINFO | V3_DIRINFO);
+
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_SERVERDESC, ROUTER_PURPOSE_BRIDGE,
+ NULL), OP_EQ, BRIDGE_DIRINFO);
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_SERVERDESC,
+ ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
+
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_STATUS_VOTE,
+ ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
+ ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CERTIFICATE,
+ ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
+
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CONSENSUS, ROUTER_PURPOSE_GENERAL,
+ "microdesc"), OP_EQ, V3_DIRINFO|MICRODESC_DIRINFO);
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CONSENSUS, ROUTER_PURPOSE_GENERAL,
+ NULL), OP_EQ, V3_DIRINFO);
+
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_MICRODESC, ROUTER_PURPOSE_GENERAL,
+ NULL), OP_EQ, MICRODESC_DIRINFO);
+
+ tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_RENDDESC_V2,
+ ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, NO_DIRINFO);
+ done: ;
+}
+
+static void
+test_dir_packages(void *arg)
+{
+ smartlist_t *votes = smartlist_new();
+ char *res = NULL;
+ (void)arg;
+
+#define BAD(s) \
+ tt_int_op(0, ==, validate_recommended_package_line(s));
+#define GOOD(s) \
+ tt_int_op(1, ==, validate_recommended_package_line(s));
+ GOOD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
+ "sha256=sssdlkfjdsklfjdskfljasdklfj");
+ GOOD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
+ "sha256=sssdlkfjdsklfjdskfljasdklfj blake2b=fred");
+ BAD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
+ "sha256=sssdlkfjdsklfjdskfljasdklfj=");
+ BAD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
+ "sha256=sssdlkfjdsklfjdskfljasdklfj blake2b");
+ BAD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz ");
+ BAD("tor 0.2.6.3-alpha "
+ "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz");
+ BAD("tor 0.2.6.3-alpha ");
+ BAD("tor 0.2.6.3-alpha");
+ BAD("tor ");
+ BAD("tor");
+ BAD("");
+ BAD("=foobar sha256="
+ "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
+ BAD("= = sha256="
+ "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
+
+ BAD("sha512= sha256="
+ "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
+
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
+ SMARTLIST_FOREACH(votes, networkstatus_t *, ns,
+ ns->package_lines = smartlist_new());
+
+#define ADD(i, s) \
+ smartlist_add(((networkstatus_t*)smartlist_get(votes, (i)))->package_lines, \
+ (void*)(s));
+
+ /* Only one vote for this one. */
+ ADD(4, "cisco 99z http://foobar.example.com/ sha256=blahblah");
+
+ /* Only two matching entries for this one, but 3 voters */
+ ADD(1, "mystic 99y http://barfoo.example.com/ sha256=blahblah");
+ ADD(3, "mystic 99y http://foobar.example.com/ sha256=blahblah");
+ ADD(4, "mystic 99y http://foobar.example.com/ sha256=blahblah");
+
+ /* Only two matching entries for this one, but at least 4 voters */
+ ADD(1, "mystic 99p http://barfoo.example.com/ sha256=ggggggg");
+ ADD(3, "mystic 99p http://foobar.example.com/ sha256=blahblah");
+ ADD(4, "mystic 99p http://foobar.example.com/ sha256=blahblah");
+ ADD(5, "mystic 99p http://foobar.example.com/ sha256=ggggggg");
+
+ /* This one has only invalid votes. */
+ ADD(0, "haffenreffer 1.2 http://foobar.example.com/ sha256");
+ ADD(1, "haffenreffer 1.2 http://foobar.example.com/ ");
+ ADD(2, "haffenreffer 1.2 ");
+ ADD(3, "haffenreffer ");
+ ADD(4, "haffenreffer");
+
+ /* Three matching votes for this; it should actually go in! */
+ ADD(2, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
+ ADD(3, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
+ ADD(4, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
+ ADD(1, "element 0.66.1 http://quum.example.com/ sha256=abcdef");
+ ADD(0, "element 0.66.1 http://quux.example.com/ sha256=abcde");
+
+ /* Three votes for A, three votes for B */
+ ADD(0, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
+ ADD(1, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
+ ADD(2, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
+ ADD(3, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
+ ADD(4, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
+ ADD(5, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
+
+ /* Three votes for A, two votes for B */
+ ADD(1, "clownshoes 22alpha3 http://quumble.example.com/ blake2=foob");
+ ADD(2, "clownshoes 22alpha3 http://quumble.example.com/ blake2=foob");
+ ADD(3, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
+ ADD(4, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
+ ADD(5, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
+
+ /* Four votes for A, two for B. */
+ ADD(0, "clownshoes 22alpha4 http://quumble.example.com/ blake2=foob");
+ ADD(1, "clownshoes 22alpha4 http://quumble.example.com/ blake2=foob");
+ ADD(2, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
+ ADD(3, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
+ ADD(4, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
+ ADD(5, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
+
+ /* Five votes for A ... all from the same authority. Three for B. */
+ ADD(0, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(1, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(3, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
+
+ /* As above but new replaces old: no two match. */
+ ADD(0, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(1, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(1, "cbc 99.1.11.1.2 http://example.com/cbc/x cubehash=ahooy sha512=m");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
+ ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
+
+ res = compute_consensus_package_lines(votes);
+ tt_assert(res);
+ tt_str_op(res, ==,
+ "package cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m\n"
+ "package clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz\n"
+ "package clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa\n"
+ "package element 0.66.1 http://quux.example.com/ sha256=abcdef\n"
+ "package mystic 99y http://foobar.example.com/ sha256=blahblah\n"
+ );
+
+#undef ADD
+#undef BAD
+#undef GOOD
+ done:
+ SMARTLIST_FOREACH(votes, networkstatus_t *, ns,
+ { smartlist_free(ns->package_lines); tor_free(ns); });
+ smartlist_free(votes);
+ tor_free(res);
+}
+
+static void
+test_dir_download_status_schedule(void *arg)
+{
+ (void)arg;
+ download_status_t dls_failure = { 0, 0, 0, DL_SCHED_GENERIC,
+ DL_WANT_AUTHORITY,
+ DL_SCHED_INCREMENT_FAILURE };
+ download_status_t dls_attempt = { 0, 0, 0, DL_SCHED_CONSENSUS,
+ DL_WANT_ANY_DIRSERVER,
+ DL_SCHED_INCREMENT_ATTEMPT};
+ download_status_t dls_bridge = { 0, 0, 0, DL_SCHED_BRIDGE,
+ DL_WANT_AUTHORITY,
+ DL_SCHED_INCREMENT_FAILURE};
+ int increment = -1;
+ int expected_increment = -1;
+ time_t current_time = time(NULL);
+ int delay1 = -1;
+ int delay2 = -1;
+ smartlist_t *schedule = smartlist_new();
+
+ /* Make a dummy schedule */
+ smartlist_add(schedule, (void *)&delay1);
+ smartlist_add(schedule, (void *)&delay2);
+
+ /* check a range of values */
+ delay1 = 1000;
+ increment = download_status_schedule_get_delay(&dls_failure,
+ schedule,
+ TIME_MIN);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_failure.next_attempt_at == TIME_MIN + expected_increment);
+
+ delay1 = INT_MAX;
+ increment = download_status_schedule_get_delay(&dls_failure,
+ schedule,
+ -1);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_failure.next_attempt_at == TIME_MAX);
+
+ delay1 = 0;
+ increment = download_status_schedule_get_delay(&dls_attempt,
+ schedule,
+ 0);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_attempt.next_attempt_at == 0 + expected_increment);
+
+ delay1 = 1000;
+ increment = download_status_schedule_get_delay(&dls_attempt,
+ schedule,
+ 1);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_attempt.next_attempt_at == 1 + expected_increment);
+
+ delay1 = INT_MAX;
+ increment = download_status_schedule_get_delay(&dls_bridge,
+ schedule,
+ current_time);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_bridge.next_attempt_at == TIME_MAX);
+
+ delay1 = 1;
+ increment = download_status_schedule_get_delay(&dls_bridge,
+ schedule,
+ TIME_MAX);
+ expected_increment = delay1;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_bridge.next_attempt_at == TIME_MAX);
+
+ /* see what happens when we reach the end */
+ dls_attempt.n_download_attempts++;
+ dls_bridge.n_download_failures++;
+
+ delay2 = 100;
+ increment = download_status_schedule_get_delay(&dls_attempt,
+ schedule,
+ current_time);
+ expected_increment = delay2;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_attempt.next_attempt_at == current_time + delay2);
+
+ delay2 = 1;
+ increment = download_status_schedule_get_delay(&dls_bridge,
+ schedule,
+ current_time);
+ expected_increment = delay2;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_bridge.next_attempt_at == current_time + delay2);
+
+ /* see what happens when we try to go off the end */
+ dls_attempt.n_download_attempts++;
+ dls_bridge.n_download_failures++;
+
+ delay2 = 5;
+ increment = download_status_schedule_get_delay(&dls_attempt,
+ schedule,
+ current_time);
+ expected_increment = delay2;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_attempt.next_attempt_at == current_time + delay2);
+
+ delay2 = 17;
+ increment = download_status_schedule_get_delay(&dls_bridge,
+ schedule,
+ current_time);
+ expected_increment = delay2;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_bridge.next_attempt_at == current_time + delay2);
+
+ /* see what happens when we reach IMPOSSIBLE_TO_DOWNLOAD */
+ dls_attempt.n_download_attempts = IMPOSSIBLE_TO_DOWNLOAD;
+ dls_bridge.n_download_failures = IMPOSSIBLE_TO_DOWNLOAD;
+
+ delay2 = 35;
+ increment = download_status_schedule_get_delay(&dls_attempt,
+ schedule,
+ current_time);
+ expected_increment = INT_MAX;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_attempt.next_attempt_at == TIME_MAX);
+
+ delay2 = 99;
+ increment = download_status_schedule_get_delay(&dls_bridge,
+ schedule,
+ current_time);
+ expected_increment = INT_MAX;
+ tt_assert(increment == expected_increment);
+ tt_assert(dls_bridge.next_attempt_at == TIME_MAX);
+
+ done:
+ /* the pointers in schedule are allocated on the stack */
+ smartlist_free(schedule);
+}
+
+static void
+test_dir_download_status_increment(void *arg)
+{
+ (void)arg;
+ download_status_t dls_failure = { 0, 0, 0, DL_SCHED_GENERIC,
+ DL_WANT_AUTHORITY,
+ DL_SCHED_INCREMENT_FAILURE };
+ download_status_t dls_attempt = { 0, 0, 0, DL_SCHED_BRIDGE,
+ DL_WANT_ANY_DIRSERVER,
+ DL_SCHED_INCREMENT_ATTEMPT};
+ int delay0 = -1;
+ int delay1 = -1;
+ int delay2 = -1;
+ smartlist_t *schedule = smartlist_new();
+ or_options_t test_options;
+ time_t next_at = TIME_MAX;
+ time_t current_time = time(NULL);
+
+ /* Provide some values for the schedule */
+ delay0 = 10;
+ delay1 = 99;
+ delay2 = 20;
+
+ /* Make the schedule */
+ smartlist_add(schedule, (void *)&delay0);
+ smartlist_add(schedule, (void *)&delay1);
+ smartlist_add(schedule, (void *)&delay2);
+
+ /* Put it in the options */
+ mock_options = &test_options;
+ reset_options(mock_options, &mock_get_options_calls);
+ mock_options->TestingClientDownloadSchedule = schedule;
+ mock_options->TestingBridgeDownloadSchedule = schedule;
+
+ MOCK(get_options, mock_get_options);
+
+ /* Check that a failure reset works */
+ mock_get_options_calls = 0;
+ download_status_reset(&dls_failure);
+ /* we really want to test that it's equal to time(NULL) + delay0, but that's
+ * an unrealiable test, because time(NULL) might change. */
+ tt_assert(download_status_get_next_attempt_at(&dls_failure)
+ >= current_time + delay0);
+ tt_assert(download_status_get_next_attempt_at(&dls_failure)
+ != TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 0);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* avoid timing inconsistencies */
+ dls_failure.next_attempt_at = current_time + delay0;
+
+ /* check that a reset schedule becomes ready at the right time */
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay0 - 1,
+ 1) == 0);
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay0,
+ 1) == 1);
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay0 + 1,
+ 1) == 1);
+
+ /* Check that a failure increment works */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_failure(&dls_failure, 404, "test", 0,
+ current_time);
+ tt_assert(next_at == current_time + delay1);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 1);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 1);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* check that an incremented schedule becomes ready at the right time */
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay1 - 1,
+ 1) == 0);
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay1,
+ 1) == 1);
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay1 + 1,
+ 1) == 1);
+
+ /* check that a schedule isn't ready if it's had too many failures */
+ tt_assert(download_status_is_ready(&dls_failure,
+ current_time + delay1 + 10,
+ 0) == 0);
+
+ /* Check that failure increments don't happen on 503 for clients, but that
+ * attempt increments do. */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_failure(&dls_failure, 503, "test", 0,
+ current_time);
+ tt_assert(next_at == current_time + delay1);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 1);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 2);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check that failure increments do happen on 503 for servers */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_failure(&dls_failure, 503, "test", 1,
+ current_time);
+ tt_assert(next_at == current_time + delay2);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 2);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 3);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check what happens when we run off the end of the schedule */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_failure(&dls_failure, 404, "test", 0,
+ current_time);
+ tt_assert(next_at == current_time + delay2);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 3);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 4);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check what happens when we hit the failure limit */
+ mock_get_options_calls = 0;
+ download_status_mark_impossible(&dls_failure);
+ next_at = download_status_increment_failure(&dls_failure, 404, "test", 0,
+ current_time);
+ tt_assert(next_at == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_failure)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(download_status_get_n_attempts(&dls_failure)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check that a failure reset doesn't reset at the limit */
+ mock_get_options_calls = 0;
+ download_status_reset(&dls_failure);
+ tt_assert(download_status_get_next_attempt_at(&dls_failure)
+ == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_failure)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(download_status_get_n_attempts(&dls_failure)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(mock_get_options_calls == 0);
+
+ /* Check that a failure reset resets just before the limit */
+ mock_get_options_calls = 0;
+ dls_failure.n_download_failures = IMPOSSIBLE_TO_DOWNLOAD - 1;
+ dls_failure.n_download_attempts = IMPOSSIBLE_TO_DOWNLOAD - 1;
+ download_status_reset(&dls_failure);
+ /* we really want to test that it's equal to time(NULL) + delay0, but that's
+ * an unrealiable test, because time(NULL) might change. */
+ tt_assert(download_status_get_next_attempt_at(&dls_failure)
+ >= current_time + delay0);
+ tt_assert(download_status_get_next_attempt_at(&dls_failure)
+ != TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 0);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check that failure increments do happen on attempt-based schedules,
+ * but that the retry is set at the end of time */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_failure(&dls_attempt, 404, "test", 0,
+ current_time);
+ tt_assert(next_at == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 1);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 0);
+ tt_assert(mock_get_options_calls == 0);
+
+ /* Check that an attempt reset works */
+ mock_get_options_calls = 0;
+ download_status_reset(&dls_attempt);
+ /* we really want to test that it's equal to time(NULL) + delay0, but that's
+ * an unrealiable test, because time(NULL) might change. */
+ tt_assert(download_status_get_next_attempt_at(&dls_attempt)
+ >= current_time + delay0);
+ tt_assert(download_status_get_next_attempt_at(&dls_attempt)
+ != TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 0);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* avoid timing inconsistencies */
+ dls_attempt.next_attempt_at = current_time + delay0;
+
+ /* check that a reset schedule becomes ready at the right time */
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay0 - 1,
+ 1) == 0);
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay0,
+ 1) == 1);
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay0 + 1,
+ 1) == 1);
+
+ /* Check that an attempt increment works */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_attempt(&dls_attempt, "test",
+ current_time);
+ tt_assert(next_at == current_time + delay1);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 1);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* check that an incremented schedule becomes ready at the right time */
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay1 - 1,
+ 1) == 0);
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay1,
+ 1) == 1);
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay1 + 1,
+ 1) == 1);
+
+ /* check that a schedule isn't ready if it's had too many attempts */
+ tt_assert(download_status_is_ready(&dls_attempt,
+ current_time + delay1 + 10,
+ 0) == 0);
+
+ /* Check what happens when we reach then run off the end of the schedule */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_attempt(&dls_attempt, "test",
+ current_time);
+ tt_assert(next_at == current_time + delay2);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 2);
+ tt_assert(mock_get_options_calls >= 1);
+
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_attempt(&dls_attempt, "test",
+ current_time);
+ tt_assert(next_at == current_time + delay2);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 3);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check what happens when we hit the attempt limit */
+ mock_get_options_calls = 0;
+ download_status_mark_impossible(&dls_attempt);
+ next_at = download_status_increment_attempt(&dls_attempt, "test",
+ current_time);
+ tt_assert(next_at == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_attempt)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(download_status_get_n_attempts(&dls_attempt)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check that an attempt reset doesn't reset at the limit */
+ mock_get_options_calls = 0;
+ download_status_reset(&dls_attempt);
+ tt_assert(download_status_get_next_attempt_at(&dls_attempt)
+ == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_attempt)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(download_status_get_n_attempts(&dls_attempt)
+ == IMPOSSIBLE_TO_DOWNLOAD);
+ tt_assert(mock_get_options_calls == 0);
+
+ /* Check that an attempt reset resets just before the limit */
+ mock_get_options_calls = 0;
+ dls_attempt.n_download_failures = IMPOSSIBLE_TO_DOWNLOAD - 1;
+ dls_attempt.n_download_attempts = IMPOSSIBLE_TO_DOWNLOAD - 1;
+ download_status_reset(&dls_attempt);
+ /* we really want to test that it's equal to time(NULL) + delay0, but that's
+ * an unrealiable test, because time(NULL) might change. */
+ tt_assert(download_status_get_next_attempt_at(&dls_attempt)
+ >= current_time + delay0);
+ tt_assert(download_status_get_next_attempt_at(&dls_attempt)
+ != TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_attempt) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_attempt) == 0);
+ tt_assert(mock_get_options_calls >= 1);
+
+ /* Check that attempt increments don't happen on failure-based schedules,
+ * and that the attempt is set at the end of time */
+ mock_get_options_calls = 0;
+ next_at = download_status_increment_attempt(&dls_failure, "test",
+ current_time);
+ tt_assert(next_at == TIME_MAX);
+ tt_assert(download_status_get_n_failures(&dls_failure) == 0);
+ tt_assert(download_status_get_n_attempts(&dls_failure) == 0);
+ tt_assert(mock_get_options_calls == 0);
+
+ done:
+ /* the pointers in schedule are allocated on the stack */
+ smartlist_free(schedule);
+ UNMOCK(get_options);
+ mock_options = NULL;
+ mock_get_options_calls = 0;
+}
+
+static void
+test_dir_authdir_type_to_string(void *data)
+{
+ (void)data;
+ char *res;
+
+ tt_str_op(res = authdir_type_to_string(NO_DIRINFO), OP_EQ,
+ "[Not an authority]");
+ tor_free(res);
+
+ tt_str_op(res = authdir_type_to_string(EXTRAINFO_DIRINFO), OP_EQ,
+ "[Not an authority]");
+ tor_free(res);
+
+ tt_str_op(res = authdir_type_to_string(MICRODESC_DIRINFO), OP_EQ,
+ "[Not an authority]");
+ tor_free(res);
+
+ tt_str_op(res = authdir_type_to_string(V3_DIRINFO), OP_EQ, "V3");
+ tor_free(res);
+
+ tt_str_op(res = authdir_type_to_string(BRIDGE_DIRINFO), OP_EQ, "Bridge");
+ tor_free(res);
+
+ tt_str_op(res = authdir_type_to_string(
+ V3_DIRINFO | BRIDGE_DIRINFO | EXTRAINFO_DIRINFO), OP_EQ,
+ "V3, Bridge");
+ done:
+ tor_free(res);
+}
+
+static void
+test_dir_conn_purpose_to_string(void *data)
+{
+ (void)data;
+
+#define EXPECT_CONN_PURPOSE(purpose, expected) \
+ tt_str_op(dir_conn_purpose_to_string(purpose), OP_EQ, expected);
+
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_DIR, "server descriptor upload");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_VOTE, "server vote upload");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_SIGNATURES,
+ "consensus signature upload");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_SERVERDESC, "server descriptor fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_EXTRAINFO, "extra-info fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_CONSENSUS,
+ "consensus network-status fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_CERTIFICATE, "authority cert fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_STATUS_VOTE, "status vote fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
+ "consensus signature fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_RENDDESC_V2,
+ "hidden-service v2 descriptor fetch");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_RENDDESC_V2,
+ "hidden-service v2 descriptor upload");
+ EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_MICRODESC, "microdescriptor fetch");
+ EXPECT_CONN_PURPOSE(1024, "(unknown)");
+
+ done: ;
+}
+
+NS_DECL(int,
+public_server_mode, (const or_options_t *options));
+
+static int
+NS(public_server_mode)(const or_options_t *options)
+{
+ (void)options;
+
+ if (CALLED(public_server_mode)++ == 0) {
+ return 1;
+ }
+
+ return 0;
+}
+
+static void
+test_dir_should_use_directory_guards(void *data)
+{
+ or_options_t *options;
+ char *errmsg = NULL;
+ (void)data;
+
+ NS_MOCK(public_server_mode);
+
+ options = options_new();
+ options_init(options);
+
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 1);
+
+ options->UseEntryGuardsAsDirGuards = 1;
+ options->UseEntryGuards = 1;
+ options->DownloadExtraInfo = 0;
+ options->FetchDirInfoEarly = 0;
+ options->FetchDirInfoExtraEarly = 0;
+ options->FetchUselessDescriptors = 0;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 1);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 2);
+
+ options->UseEntryGuards = 0;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 3);
+ options->UseEntryGuards = 1;
+
+ options->UseEntryGuardsAsDirGuards = 0;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 4);
+ options->UseEntryGuardsAsDirGuards = 1;
+
+ options->DownloadExtraInfo = 1;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 5);
+ options->DownloadExtraInfo = 0;
+
+ options->FetchDirInfoEarly = 1;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 6);
+ options->FetchDirInfoEarly = 0;
+
+ options->FetchDirInfoExtraEarly = 1;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 7);
+ options->FetchDirInfoExtraEarly = 0;
+
+ options->FetchUselessDescriptors = 1;
+ tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
+ tt_int_op(CALLED(public_server_mode), OP_EQ, 8);
+ options->FetchUselessDescriptors = 0;
+
+ done:
+ NS_UNMOCK(public_server_mode);
+ or_options_free(options);
+ tor_free(errmsg);
+}
+
+NS_DECL(void,
+directory_initiate_command_routerstatus, (const routerstatus_t *status,
+ uint8_t dir_purpose,
+ uint8_t router_purpose,
+ dir_indirection_t indirection,
+ const char *resource,
+ const char *payload,
+ size_t payload_len,
+ time_t if_modified_since));
+
+static void
+test_dir_should_not_init_request_to_ourselves(void *data)
+{
+ char digest[DIGEST_LEN];
+ dir_server_t *ourself = NULL;
+ crypto_pk_t *key = pk_generate(2);
+ (void) data;
+
+ NS_MOCK(directory_initiate_command_routerstatus);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ set_server_identity_key(key);
+ crypto_pk_get_digest(key, (char*) &digest);
+ ourself = trusted_dir_server_new("ourself", "127.0.0.1", 9059, 9060,
+ NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+
+ tt_assert(ourself);
+ dir_server_add(ourself);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 0);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
+ NULL);
+
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(directory_initiate_command_routerstatus);
+ clear_dir_servers();
+ routerlist_free_all();
+ crypto_pk_free(key);
+}
+
+static void
+test_dir_should_not_init_request_to_dir_auths_without_v3_info(void *data)
+{
+ dir_server_t *ds = NULL;
+ dirinfo_type_t dirinfo_type = BRIDGE_DIRINFO | EXTRAINFO_DIRINFO \
+ | MICRODESC_DIRINFO;
+ (void) data;
+
+ NS_MOCK(directory_initiate_command_routerstatus);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ ds = trusted_dir_server_new("ds", "10.0.0.1", 9059, 9060, NULL,
+ "12345678901234567890", NULL, dirinfo_type, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 0);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
+ NULL);
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(directory_initiate_command_routerstatus);
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static void
+test_dir_should_init_request_to_dir_auths(void *data)
+{
+ dir_server_t *ds = NULL;
+ (void) data;
+
+ NS_MOCK(directory_initiate_command_routerstatus);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ ds = trusted_dir_server_new("ds", "10.0.0.1", 9059, 9060, NULL,
+ "12345678901234567890", NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 1);
+
+ directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
+ NULL);
+ tt_int_op(CALLED(directory_initiate_command_routerstatus), OP_EQ, 2);
+
+ done:
+ NS_UNMOCK(directory_initiate_command_routerstatus);
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+void
+NS(directory_initiate_command_routerstatus)(const routerstatus_t *status,
+ uint8_t dir_purpose,
+ uint8_t router_purpose,
+ dir_indirection_t indirection,
+ const char *resource,
+ const char *payload,
+ size_t payload_len,
+ time_t if_modified_since)
+{
+ (void)status;
+ (void)dir_purpose;
+ (void)router_purpose;
+ (void)indirection;
+ (void)resource;
+ (void)payload;
+ (void)payload_len;
+ (void)if_modified_since;
+ CALLED(directory_initiate_command_routerstatus)++;
+}
+
+static void
+test_dir_choose_compression_level(void* data)
+{
+ (void)data;
+
+ /* It starts under_memory_pressure */
+ tt_int_op(have_been_under_memory_pressure(), OP_EQ, 1);
+
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(-1));
+ tt_assert(LOW_COMPRESSION == choose_compression_level(1024-1));
+ tt_assert(MEDIUM_COMPRESSION == choose_compression_level(2048-1));
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(2048));
+
+ /* Reset under_memory_pressure timer */
+ cell_queues_check_size();
+ tt_int_op(have_been_under_memory_pressure(), OP_EQ, 0);
+
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(-1));
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(1024-1));
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(2048-1));
+ tt_assert(HIGH_COMPRESSION == choose_compression_level(2048));
+
+ done: ;
+}
+
+static int mock_networkstatus_consensus_is_bootstrapping_value = 0;
+static int
+mock_networkstatus_consensus_is_bootstrapping(time_t now)
+{
+ (void)now;
+ return mock_networkstatus_consensus_is_bootstrapping_value;
+}
+
+static int mock_networkstatus_consensus_can_use_extra_fallbacks_value = 0;
+static int
+mock_networkstatus_consensus_can_use_extra_fallbacks(
+ const or_options_t *options)
+{
+ (void)options;
+ return mock_networkstatus_consensus_can_use_extra_fallbacks_value;
+}
+
+/* data is a 2 character nul-terminated string.
+ * If data[0] is 'b', set bootstrapping, anything else means not bootstrapping
+ * If data[1] is 'f', set extra fallbacks, anything else means no extra
+ * fallbacks.
+ */
+static void
+test_dir_find_dl_schedule(void* data)
+{
+ const char *str = (const char *)data;
+
+ tt_assert(strlen(data) == 2);
+
+ if (str[0] == 'b') {
+ mock_networkstatus_consensus_is_bootstrapping_value = 1;
+ } else {
+ mock_networkstatus_consensus_is_bootstrapping_value = 0;
+ }
+
+ if (str[1] == 'f') {
+ mock_networkstatus_consensus_can_use_extra_fallbacks_value = 1;
+ } else {
+ mock_networkstatus_consensus_can_use_extra_fallbacks_value = 0;
+ }
+
+ MOCK(networkstatus_consensus_is_bootstrapping,
+ mock_networkstatus_consensus_is_bootstrapping);
+ MOCK(networkstatus_consensus_can_use_extra_fallbacks,
+ mock_networkstatus_consensus_can_use_extra_fallbacks);
+
+ download_status_t dls;
+ smartlist_t server, client, server_cons, client_cons;
+ smartlist_t client_boot_auth_only_cons, client_boot_auth_cons;
+ smartlist_t client_boot_fallback_cons, bridge;
+
+ mock_options = malloc(sizeof(or_options_t));
+ reset_options(mock_options, &mock_get_options_calls);
+ MOCK(get_options, mock_get_options);
+
+ mock_options->TestingServerDownloadSchedule = &server;
+ mock_options->TestingClientDownloadSchedule = &client;
+ mock_options->TestingServerConsensusDownloadSchedule = &server_cons;
+ mock_options->TestingClientConsensusDownloadSchedule = &client_cons;
+ mock_options->ClientBootstrapConsensusAuthorityOnlyDownloadSchedule =
+ &client_boot_auth_only_cons;
+ mock_options->ClientBootstrapConsensusAuthorityDownloadSchedule =
+ &client_boot_auth_cons;
+ mock_options->ClientBootstrapConsensusFallbackDownloadSchedule =
+ &client_boot_fallback_cons;
+ mock_options->TestingBridgeDownloadSchedule = &bridge;
+
+ dls.schedule = DL_SCHED_GENERIC;
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ, &client);
+ mock_options->ClientOnly = 0;
+
+ /* dir mode */
+ mock_options->DirPort_set = 1;
+ mock_options->DirCache = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ, &server);
+ mock_options->DirPort_set = 0;
+ mock_options->DirCache = 0;
+
+ dls.schedule = DL_SCHED_CONSENSUS;
+ /* public server mode */
+ mock_options->ORPort_set = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ, &server_cons);
+ mock_options->ORPort_set = 0;
+
+ /* client and bridge modes */
+ if (networkstatus_consensus_is_bootstrapping(time(NULL))) {
+ if (networkstatus_consensus_can_use_extra_fallbacks(mock_options)) {
+ dls.want_authority = 1;
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_auth_cons);
+ mock_options->ClientOnly = 0;
+
+ /* bridge relay */
+ mock_options->ORPort_set = 1;
+ mock_options->BridgeRelay = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_auth_cons);
+ mock_options->ORPort_set = 0;
+ mock_options->BridgeRelay = 0;
+
+ dls.want_authority = 0;
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_fallback_cons);
+ mock_options->ClientOnly = 0;
+
+ /* bridge relay */
+ mock_options->ORPort_set = 1;
+ mock_options->BridgeRelay = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_fallback_cons);
+ mock_options->ORPort_set = 0;
+ mock_options->BridgeRelay = 0;
+
+ } else {
+ /* dls.want_authority is ignored */
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_auth_only_cons);
+ mock_options->ClientOnly = 0;
+
+ /* bridge relay */
+ mock_options->ORPort_set = 1;
+ mock_options->BridgeRelay = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_boot_auth_only_cons);
+ mock_options->ORPort_set = 0;
+ mock_options->BridgeRelay = 0;
+ }
+ } else {
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_cons);
+ mock_options->ClientOnly = 0;
+
+ /* bridge relay */
+ mock_options->ORPort_set = 1;
+ mock_options->BridgeRelay = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ,
+ &client_cons);
+ mock_options->ORPort_set = 0;
+ mock_options->BridgeRelay = 0;
+ }
+
+ dls.schedule = DL_SCHED_BRIDGE;
+ /* client */
+ mock_options->ClientOnly = 1;
+ tt_ptr_op(find_dl_schedule(&dls, mock_options), OP_EQ, &bridge);
+
+ done:
+ UNMOCK(networkstatus_consensus_is_bootstrapping);
+ UNMOCK(networkstatus_consensus_can_use_extra_fallbacks);
+ UNMOCK(get_options);
+ free(mock_options);
+ mock_options = NULL;
+}
+
+#define DIR_LEGACY(name) \
+ { #name, test_dir_ ## name , TT_FORK, NULL, NULL }
#define DIR(name,flags) \
{ #name, test_dir_##name, (flags), NULL, NULL }
+/* where arg is a string constant */
+#define DIR_ARG(name,flags,arg) \
+ { #name "_" arg, test_dir_##name, (flags), &passthrough_setup, (void*) arg }
+
struct testcase_t dir_tests[] = {
DIR_LEGACY(nicknames),
DIR_LEGACY(formats),
+ DIR(routerinfo_parsing, 0),
+ DIR(extrainfo_parsing, 0),
+ DIR(parse_router_list, TT_FORK),
+ DIR(load_routers, TT_FORK),
+ DIR(load_extrainfo, TT_FORK),
DIR_LEGACY(versions),
DIR_LEGACY(fp_pairs),
DIR(split_fps, 0),
@@ -2383,7 +4236,24 @@ struct testcase_t dir_tests[] = {
DIR_LEGACY(clip_unmeasured_bw_kb),
DIR_LEGACY(clip_unmeasured_bw_kb_alt),
DIR(fmt_control_ns, 0),
+ DIR(dirserv_set_routerstatus_testing, 0),
DIR(http_handling, 0),
+ DIR(purpose_needs_anonymity, 0),
+ DIR(fetch_type, 0),
+ DIR(packages, 0),
+ DIR(download_status_schedule, 0),
+ DIR(download_status_increment, 0),
+ DIR(authdir_type_to_string, 0),
+ DIR(conn_purpose_to_string, 0),
+ DIR(should_use_directory_guards, 0),
+ DIR(should_not_init_request_to_ourselves, TT_FORK),
+ DIR(should_not_init_request_to_dir_auths_without_v3_info, 0),
+ DIR(should_init_request_to_dir_auths, 0),
+ DIR(choose_compression_level, 0),
+ DIR_ARG(find_dl_schedule, TT_FORK, "bf"),
+ DIR_ARG(find_dl_schedule, TT_FORK, "ba"),
+ DIR_ARG(find_dl_schedule, TT_FORK, "cf"),
+ DIR_ARG(find_dl_schedule, TT_FORK, "ca"),
END_OF_TESTCASES
};
diff --git a/src/test/test_dir_common.c b/src/test/test_dir_common.c
new file mode 100644
index 0000000000..0b446c2dfd
--- /dev/null
+++ b/src/test/test_dir_common.c
@@ -0,0 +1,425 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#define DIRVOTE_PRIVATE
+#include "crypto.h"
+#include "test.h"
+#include "container.h"
+#include "or.h"
+#include "dirvote.h"
+#include "nodelist.h"
+#include "routerlist.h"
+#include "test_dir_common.h"
+
+void dir_common_setup_vote(networkstatus_t **vote, time_t now);
+networkstatus_t * dir_common_add_rs_and_parse(networkstatus_t *vote,
+ networkstatus_t **vote_out,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ crypto_pk_t *sign_skey, int *n_vrs,
+ time_t now, int clear_rl);
+
+extern const char AUTHORITY_CERT_1[];
+extern const char AUTHORITY_SIGNKEY_1[];
+extern const char AUTHORITY_CERT_2[];
+extern const char AUTHORITY_SIGNKEY_2[];
+extern const char AUTHORITY_CERT_3[];
+extern const char AUTHORITY_SIGNKEY_3[];
+
+/** Initialize and set auth certs and keys
+ * Returns 0 on success, -1 on failure. Clean up handled by caller.
+ */
+int
+dir_common_authority_pk_init(authority_cert_t **cert1,
+ authority_cert_t **cert2,
+ authority_cert_t **cert3,
+ crypto_pk_t **sign_skey_1,
+ crypto_pk_t **sign_skey_2,
+ crypto_pk_t **sign_skey_3)
+{
+ /* Parse certificates and keys. */
+ authority_cert_t *cert;
+ cert = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
+ tt_assert(cert);
+ tt_assert(cert->identity_key);
+ *cert1 = cert;
+ tt_assert(*cert1);
+ *cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
+ tt_assert(*cert2);
+ *cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
+ tt_assert(*cert3);
+ *sign_skey_1 = crypto_pk_new();
+ *sign_skey_2 = crypto_pk_new();
+ *sign_skey_3 = crypto_pk_new();
+
+ tt_assert(!crypto_pk_read_private_key_from_string(*sign_skey_1,
+ AUTHORITY_SIGNKEY_1, -1));
+ tt_assert(!crypto_pk_read_private_key_from_string(*sign_skey_2,
+ AUTHORITY_SIGNKEY_2, -1));
+ tt_assert(!crypto_pk_read_private_key_from_string(*sign_skey_3,
+ AUTHORITY_SIGNKEY_3, -1));
+
+ tt_assert(!crypto_pk_cmp_keys(*sign_skey_1, (*cert1)->signing_key));
+ tt_assert(!crypto_pk_cmp_keys(*sign_skey_2, (*cert2)->signing_key));
+
+ return 0;
+ done:
+ return -1;
+}
+
+/**
+ * Generate a routerstatus for v3_networkstatus test.
+ */
+vote_routerstatus_t *
+dir_common_gen_routerstatus_for_v3ns(int idx, time_t now)
+{
+ vote_routerstatus_t *vrs=NULL;
+ routerstatus_t *rs = NULL;
+ tor_addr_t addr_ipv6;
+ char *method_list = NULL;
+
+ switch (idx) {
+ case 0:
+ /* Generate the first routerstatus. */
+ vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
+ rs = &vrs->status;
+ vrs->version = tor_strdup("0.1.2.14");
+ rs->published_on = now-1500;
+ strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
+ memset(rs->identity_digest, TEST_DIR_ROUTER_ID_1, DIGEST_LEN);
+ memset(rs->descriptor_digest, TEST_DIR_ROUTER_DD_1, DIGEST_LEN);
+ rs->addr = 0x99008801;
+ rs->or_port = 443;
+ rs->dir_port = 8000;
+ /* all flags but running and v2dir cleared */
+ rs->is_flagged_running = 1;
+ rs->is_v2_dir = 1;
+ break;
+ case 1:
+ /* Generate the second routerstatus. */
+ vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
+ rs = &vrs->status;
+ vrs->version = tor_strdup("0.2.0.5");
+ rs->published_on = now-1000;
+ strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
+ memset(rs->identity_digest, TEST_DIR_ROUTER_ID_2, DIGEST_LEN);
+ memset(rs->descriptor_digest, TEST_DIR_ROUTER_DD_2, DIGEST_LEN);
+ rs->addr = 0x99009901;
+ rs->or_port = 443;
+ rs->dir_port = 0;
+ tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
+ tor_addr_copy(&rs->ipv6_addr, &addr_ipv6);
+ rs->ipv6_orport = 4711;
+ rs->is_exit = rs->is_stable = rs->is_fast = rs->is_flagged_running =
+ rs->is_valid = rs->is_possible_guard = rs->is_v2_dir = 1;
+ break;
+ case 2:
+ /* Generate the third routerstatus. */
+ vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
+ rs = &vrs->status;
+ vrs->version = tor_strdup("0.1.0.3");
+ rs->published_on = now-1000;
+ strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
+ memset(rs->identity_digest, TEST_DIR_ROUTER_ID_3, DIGEST_LEN);
+ memset(rs->descriptor_digest, TEST_DIR_ROUTER_DD_3, DIGEST_LEN);
+ rs->addr = 0xAA009901;
+ rs->or_port = 400;
+ rs->dir_port = 9999;
+ rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
+ rs->is_flagged_running = rs->is_valid = rs->is_v2_dir =
+ rs->is_possible_guard = 1;
+ break;
+ case 3:
+ /* Generate a fourth routerstatus that is not running. */
+ vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
+ rs = &vrs->status;
+ vrs->version = tor_strdup("0.1.6.3");
+ rs->published_on = now-1000;
+ strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
+ memset(rs->identity_digest, TEST_DIR_ROUTER_ID_4, DIGEST_LEN);
+ memset(rs->descriptor_digest, TEST_DIR_ROUTER_DD_4, DIGEST_LEN);
+ rs->addr = 0xC0000203;
+ rs->or_port = 500;
+ rs->dir_port = 1999;
+ rs->is_v2_dir = 1;
+ /* Running flag (and others) cleared */
+ break;
+ case 4:
+ /* No more for this test; return NULL */
+ vrs = NULL;
+ break;
+ default:
+ /* Shouldn't happen */
+ tt_assert(0);
+ }
+ if (vrs) {
+ vrs->microdesc = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
+ method_list = make_consensus_method_list(MIN_SUPPORTED_CONSENSUS_METHOD,
+ MAX_SUPPORTED_CONSENSUS_METHOD,
+ ",");
+ tor_asprintf(&vrs->microdesc->microdesc_hash_line,
+ "m %s "
+ "sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa%d\n",
+ method_list, idx);
+ }
+
+ done:
+ tor_free(method_list);
+ return vrs;
+}
+
+/** Initialize networkstatus vote object attributes. */
+void
+dir_common_setup_vote(networkstatus_t **vote, time_t now)
+{
+ *vote = tor_malloc_zero(sizeof(networkstatus_t));
+ (*vote)->type = NS_TYPE_VOTE;
+ (*vote)->published = now;
+ (*vote)->supported_methods = smartlist_new();
+ (*vote)->known_flags = smartlist_new();
+ (*vote)->net_params = smartlist_new();
+ (*vote)->routerstatus_list = smartlist_new();
+ (*vote)->voters = smartlist_new();
+}
+
+/** Helper: Make a new routerinfo containing the right information for a
+ * given vote_routerstatus_t. */
+routerinfo_t *
+dir_common_generate_ri_from_rs(const vote_routerstatus_t *vrs)
+{
+ routerinfo_t *r;
+ const routerstatus_t *rs = &vrs->status;
+ static time_t published = 0;
+
+ r = tor_malloc_zero(sizeof(routerinfo_t));
+ r->cert_expiration_time = TIME_MAX;
+ memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
+ memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
+ DIGEST_LEN);
+ r->cache_info.do_not_cache = 1;
+ r->cache_info.routerlist_index = -1;
+ r->cache_info.signed_descriptor_body =
+ tor_strdup("123456789012345678901234567890123");
+ r->cache_info.signed_descriptor_len =
+ strlen(r->cache_info.signed_descriptor_body);
+ r->exit_policy = smartlist_new();
+ r->cache_info.published_on = ++published + time(NULL);
+ if (rs->has_bandwidth) {
+ /*
+ * Multiply by 1000 because the routerinfo_t and the routerstatus_t
+ * seem to use different units (*sigh*) and because we seem stuck on
+ * icky and perverse decimal kilobytes (*double sigh*) - see
+ * router_get_advertised_bandwidth_capped() of routerlist.c and
+ * routerstatus_format_entry() of dirserv.c.
+ */
+ r->bandwidthrate = rs->bandwidth_kb * 1000;
+ r->bandwidthcapacity = rs->bandwidth_kb * 1000;
+ }
+ return r;
+}
+
+/** Create routerstatuses and signed vote.
+ * Create routerstatuses using *vrs_gen* and add them to global routerlist.
+ * Next, create signed vote using *sign_skey* and *vote*, which should have
+ * predefined header fields.
+ * Setting *clear_rl* clears the global routerlist before adding the new
+ * routers.
+ * Return the signed vote, same as *vote_out*. Save the number of routers added
+ * in *n_vrs*.
+ */
+networkstatus_t *
+dir_common_add_rs_and_parse(networkstatus_t *vote, networkstatus_t **vote_out,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ crypto_pk_t *sign_skey, int *n_vrs, time_t now,
+ int clear_rl)
+{
+ vote_routerstatus_t *vrs;
+ char *v_text=NULL;
+ const char *msg=NULL;
+ int idx;
+ was_router_added_t router_added = -1;
+ *vote_out = NULL;
+
+ if (clear_rl) {
+ nodelist_free_all();
+ routerlist_free_all();
+ }
+
+ idx = 0;
+ do {
+ vrs = vrs_gen(idx, now);
+ if (vrs) {
+ smartlist_add(vote->routerstatus_list, vrs);
+ router_added =
+ router_add_to_routerlist(dir_common_generate_ri_from_rs(vrs),
+ &msg,0,0);
+ tt_assert(router_added >= 0);
+ ++idx;
+ }
+ } while (vrs);
+ *n_vrs = idx;
+
+ /* dump the vote and try to parse it. */
+ v_text = format_networkstatus_vote(sign_skey, vote);
+ tt_assert(v_text);
+ *vote_out = networkstatus_parse_vote_from_string(v_text, NULL, NS_TYPE_VOTE);
+
+ done:
+ if (v_text)
+ tor_free(v_text);
+
+ return *vote_out;
+}
+
+/** Create a fake *vote* where *cert* describes the signer, *sign_skey*
+ * is the signing key, and *vrs_gen* is the function we'll use to create the
+ * routers on which we're voting.
+ * We pass *vote_out*, *n_vrs*, and *clear_rl* directly to vrs_gen().
+ * Return 0 on success, return -1 on failure.
+ */
+int
+dir_common_construct_vote_1(networkstatus_t **vote, authority_cert_t *cert,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs,
+ time_t now, int clear_rl)
+{
+ networkstatus_voter_info_t *voter;
+
+ dir_common_setup_vote(vote, now);
+ (*vote)->valid_after = now+1000;
+ (*vote)->fresh_until = now+2000;
+ (*vote)->valid_until = now+3000;
+ (*vote)->vote_seconds = 100;
+ (*vote)->dist_seconds = 200;
+ smartlist_split_string((*vote)->supported_methods, "1 2 3", NULL, 0, -1);
+ (*vote)->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
+ (*vote)->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
+ smartlist_split_string((*vote)->known_flags,
+ "Authority Exit Fast Guard Running Stable V2Dir Valid",
+ 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
+ voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
+ voter->nickname = tor_strdup("Voter1");
+ voter->address = tor_strdup("1.2.3.4");
+ voter->addr = 0x01020304;
+ voter->dir_port = 80;
+ voter->or_port = 9000;
+ voter->contact = tor_strdup("voter@example.com");
+ crypto_pk_get_digest(cert->identity_key, voter->identity_digest);
+ /*
+ * Set up a vote; generate it; try to parse it.
+ */
+ smartlist_add((*vote)->voters, voter);
+ (*vote)->cert = authority_cert_dup(cert);
+ smartlist_split_string((*vote)->net_params, "circuitwindow=101 foo=990",
+ NULL, 0, 0);
+ *n_vrs = 0;
+ /* add routerstatuses */
+ if (!dir_common_add_rs_and_parse(*vote, vote_out, vrs_gen, sign_skey,
+ n_vrs, now, clear_rl))
+ return -1;
+
+ return 0;
+}
+
+/** See dir_common_construct_vote_1.
+ * Produces a vote with slightly different values.
+ */
+int
+dir_common_construct_vote_2(networkstatus_t **vote, authority_cert_t *cert,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs,
+ time_t now, int clear_rl)
+{
+ networkstatus_voter_info_t *voter;
+
+ dir_common_setup_vote(vote, now);
+ (*vote)->type = NS_TYPE_VOTE;
+ (*vote)->published += 1;
+ (*vote)->valid_after = now+1000;
+ (*vote)->fresh_until = now+3005;
+ (*vote)->valid_until = now+3000;
+ (*vote)->vote_seconds = 100;
+ (*vote)->dist_seconds = 300;
+ smartlist_split_string((*vote)->supported_methods, "1 2 3", NULL, 0, -1);
+ smartlist_split_string((*vote)->known_flags,
+ "Authority Exit Fast Guard MadeOfCheese MadeOfTin "
+ "Running Stable V2Dir Valid", 0,
+ SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
+ voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
+ voter->nickname = tor_strdup("Voter2");
+ voter->address = tor_strdup("2.3.4.5");
+ voter->addr = 0x02030405;
+ voter->dir_port = 80;
+ voter->or_port = 9000;
+ voter->contact = tor_strdup("voter@example.com");
+ crypto_pk_get_digest(cert->identity_key, voter->identity_digest);
+ /*
+ * Set up a vote; generate it; try to parse it.
+ */
+ smartlist_add((*vote)->voters, voter);
+ (*vote)->cert = authority_cert_dup(cert);
+ if (! (*vote)->net_params)
+ (*vote)->net_params = smartlist_new();
+ smartlist_split_string((*vote)->net_params,
+ "bar=2000000000 circuitwindow=20",
+ NULL, 0, 0);
+ /* add routerstatuses */
+ /* dump the vote and try to parse it. */
+ dir_common_add_rs_and_parse(*vote, vote_out, vrs_gen, sign_skey,
+ n_vrs, now, clear_rl);
+
+ return 0;
+}
+
+/** See dir_common_construct_vote_1.
+ * Produces a vote with slightly different values. Adds a legacy key.
+ */
+int
+dir_common_construct_vote_3(networkstatus_t **vote, authority_cert_t *cert,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs,
+ time_t now, int clear_rl)
+{
+ networkstatus_voter_info_t *voter;
+
+ dir_common_setup_vote(vote, now);
+ (*vote)->valid_after = now+1000;
+ (*vote)->fresh_until = now+2003;
+ (*vote)->valid_until = now+3000;
+ (*vote)->vote_seconds = 100;
+ (*vote)->dist_seconds = 250;
+ smartlist_split_string((*vote)->supported_methods, "1 2 3 4", NULL, 0, -1);
+ (*vote)->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
+ (*vote)->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
+ smartlist_split_string((*vote)->known_flags,
+ "Authority Exit Fast Guard Running Stable V2Dir Valid",
+ 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
+ voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
+ voter->nickname = tor_strdup("Voter2");
+ voter->address = tor_strdup("3.4.5.6");
+ voter->addr = 0x03040506;
+ voter->dir_port = 80;
+ voter->or_port = 9000;
+ voter->contact = tor_strdup("voter@example.com");
+ crypto_pk_get_digest(cert->identity_key, voter->identity_digest);
+ memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
+ /*
+ * Set up a vote; generate it; try to parse it.
+ */
+ smartlist_add((*vote)->voters, voter);
+ (*vote)->cert = authority_cert_dup(cert);
+ smartlist_split_string((*vote)->net_params, "circuitwindow=80 foo=660",
+ NULL, 0, 0);
+ /* add routerstatuses */
+ /* dump the vote and try to parse it. */
+ dir_common_add_rs_and_parse(*vote, vote_out, vrs_gen, sign_skey,
+ n_vrs, now, clear_rl);
+
+ return 0;
+}
+
diff --git a/src/test/test_dir_common.h b/src/test/test_dir_common.h
new file mode 100644
index 0000000000..9682b0db49
--- /dev/null
+++ b/src/test/test_dir_common.h
@@ -0,0 +1,52 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+#include "networkstatus.h"
+#include "routerparse.h"
+
+#define TEST_DIR_ROUTER_ID_1 3
+#define TEST_DIR_ROUTER_ID_2 5
+#define TEST_DIR_ROUTER_ID_3 33
+#define TEST_DIR_ROUTER_ID_4 34
+
+#define TEST_DIR_ROUTER_DD_1 78
+#define TEST_DIR_ROUTER_DD_2 77
+#define TEST_DIR_ROUTER_DD_3 79
+#define TEST_DIR_ROUTER_DD_4 44
+
+int dir_common_authority_pk_init(authority_cert_t **cert1,
+ authority_cert_t **cert2,
+ authority_cert_t **cert3,
+ crypto_pk_t **sign_skey_1,
+ crypto_pk_t **sign_skey_2,
+ crypto_pk_t **sign_skey_3);
+
+routerinfo_t * dir_common_generate_ri_from_rs(const vote_routerstatus_t *vrs);
+
+vote_routerstatus_t * dir_common_gen_routerstatus_for_v3ns(int idx,
+ time_t now);
+
+int dir_common_construct_vote_1(networkstatus_t **vote,
+ authority_cert_t *cert1,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs, time_t now,
+ int clear_rl);
+
+int dir_common_construct_vote_2(networkstatus_t **vote,
+ authority_cert_t *cert2,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs, time_t now,
+ int clear_rl);
+
+int dir_common_construct_vote_3(networkstatus_t **vote,
+ authority_cert_t *cert3,
+ crypto_pk_t *sign_skey,
+ vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
+ networkstatus_t **vote_out, int *n_vrs, time_t now,
+ int clear_rl);
+
diff --git a/src/test/test_dir_handle_get.c b/src/test/test_dir_handle_get.c
new file mode 100644
index 0000000000..05657ca452
--- /dev/null
+++ b/src/test/test_dir_handle_get.c
@@ -0,0 +1,2538 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define RENDCOMMON_PRIVATE
+#define GEOIP_PRIVATE
+#define CONNECTION_PRIVATE
+#define CONFIG_PRIVATE
+#define RENDCACHE_PRIVATE
+
+#include "or.h"
+#include "config.h"
+#include "connection.h"
+#include "directory.h"
+#include "test.h"
+#include "connection.h"
+#include "rendcommon.h"
+#include "rendcache.h"
+#include "router.h"
+#include "routerlist.h"
+#include "rend_test_helpers.h"
+#include "microdesc.h"
+#include "test_helpers.h"
+#include "nodelist.h"
+#include "entrynodes.h"
+#include "routerparse.h"
+#include "networkstatus.h"
+#include "geoip.h"
+#include "dirserv.h"
+#include "torgzip.h"
+#include "dirvote.h"
+
+#ifdef _WIN32
+/* For mkdir() */
+#include <direct.h>
+#else
+#include <dirent.h>
+#endif
+
+#include "vote_descriptors.inc"
+
+#define NS_MODULE dir_handle_get
+
+static void
+connection_write_to_buf_mock(const char *string, size_t len,
+ connection_t *conn, int zlib)
+{
+ (void) zlib;
+
+ tor_assert(string);
+ tor_assert(conn);
+
+ write_to_buf(string, len, conn->outbuf);
+}
+
+#define GET(path) "GET " path " HTTP/1.0\r\n\r\n"
+#define NOT_FOUND "HTTP/1.0 404 Not found\r\n\r\n"
+#define BAD_REQUEST "HTTP/1.0 400 Bad request\r\n\r\n"
+#define SERVER_BUSY "HTTP/1.0 503 Directory busy, try again later\r\n\r\n"
+#define NOT_ENOUGH_CONSENSUS_SIGNATURES "HTTP/1.0 404 " \
+ "Consensus not signed by sufficient number of requested authorities\r\n\r\n"
+
+static tor_addr_t MOCK_TOR_ADDR;
+
+static void
+test_dir_handle_get_bad_request(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(directory_handle_command_get(conn, "", NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(header, OP_EQ, BAD_REQUEST);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_v1_command_not_found(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ // no frontpage configured
+ tt_ptr_op(get_dirportfrontpage(), OP_EQ, NULL);
+
+ /* V1 path */
+ tt_int_op(directory_handle_command_get(conn, GET("/tor/"), NULL, 0),
+ OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static const char*
+mock_get_dirportfrontpage(void)
+{
+ return "HELLO FROM FRONTPAGE";
+}
+
+static void
+test_dir_handle_get_v1_command(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0, body_len = 0;
+ const char *exp_body = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ MOCK(get_dirportfrontpage, mock_get_dirportfrontpage);
+
+ exp_body = get_dirportfrontpage();
+ body_len = strlen(exp_body);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(directory_handle_command_get(conn, GET("/tor/"), NULL, 0),
+ OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, body_len+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/html\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 20\r\n"));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_str_op(body, OP_EQ, exp_body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ UNMOCK(get_dirportfrontpage);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_not_found(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ /* Unrecognized path */
+ tt_int_op(directory_handle_command_get(conn, GET("/anything"), NULL, 0),
+ OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_robots_txt(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ tt_int_op(directory_handle_command_get(conn, GET("/tor/robots.txt"),
+ NULL, 0), OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, 29, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 28\r\n"));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_str_op(body, OP_EQ, "User-agent: *\r\nDisallow: /\r\n");
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_bytes_txt(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0, body_len = 0;
+ char buff[30];
+ char *exp_body = NULL;
+ (void) data;
+
+ exp_body = directory_dump_request_log();
+ body_len = strlen(exp_body);
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ tt_int_op(directory_handle_command_get(conn, GET("/tor/bytes.txt"), NULL, 0),
+ OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, body_len+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Pragma: no-cache\r\n"));
+
+ tor_snprintf(buff, sizeof(buff), "Content-Length: %ld\r\n", (long) body_len);
+ tt_assert(strstr(header, buff));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_str_op(body, OP_EQ, exp_body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ tor_free(exp_body);
+}
+
+#define RENDEZVOUS2_GET(descid) GET("/tor/rendezvous2/" descid)
+static void
+test_dir_handle_get_rendezvous2_not_found_if_not_encrypted(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ // connection is not encrypted
+ tt_assert(!connection_dir_is_encrypted(conn))
+
+ tt_int_op(directory_handle_command_get(conn, RENDEZVOUS2_GET(), NULL, 0),
+ OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_rendezvous2_on_encrypted_conn_with_invalid_desc_id(
+ void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ // connection is encrypted
+ TO_CONN(conn)->linked = 1;
+ tt_assert(connection_dir_is_encrypted(conn));
+
+ tt_int_op(directory_handle_command_get(conn,
+ RENDEZVOUS2_GET("invalid-desc-id"), NULL, 0), OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(header, OP_EQ, BAD_REQUEST);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_rendezvous2_on_encrypted_conn_not_well_formed(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ // connection is encrypted
+ TO_CONN(conn)->linked = 1;
+ tt_assert(connection_dir_is_encrypted(conn));
+
+ //TODO: this cant be reached because rend_valid_descriptor_id() prevents this
+ //case to happen. This test is the same as
+ //test_dir_handle_get_rendezvous2_on_encrypted_conn_with_invalid_desc_id
+ //We should refactor to remove the case from the switch.
+
+ const char *req = RENDEZVOUS2_GET("1bababababababababababababababab");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(header, OP_EQ, BAD_REQUEST);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_rendezvous2_not_found(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ rend_cache_init();
+
+ // connection is encrypted
+ TO_CONN(conn)->linked = 1;
+ tt_assert(connection_dir_is_encrypted(conn));
+
+ const char *req = RENDEZVOUS2_GET("3xqunszqnaolrrfmtzgaki7mxelgvkje");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ rend_cache_free_all();
+}
+
+NS_DECL(const routerinfo_t *, router_get_my_routerinfo, (void));
+
+static routerinfo_t *mock_routerinfo;
+
+static const routerinfo_t *
+NS(router_get_my_routerinfo)(void)
+{
+ if (!mock_routerinfo) {
+ mock_routerinfo = tor_malloc_zero(sizeof(routerinfo_t));
+ }
+
+ return mock_routerinfo;
+}
+
+static void
+test_dir_handle_get_rendezvous2_on_encrypted_conn_success(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ char buff[30];
+ char req[70];
+ rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
+ char *service_id = NULL;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
+ size_t body_len = 0;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ NS_MOCK(router_get_my_routerinfo);
+
+ rend_cache_init();
+
+ /* create a valid rend service descriptor */
+ #define RECENT_TIME -10
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+
+ tt_int_op(rend_cache_store_v2_desc_as_dir(desc_holder->desc_str),
+ OP_EQ, 0);
+
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ // connection is encrypted
+ TO_CONN(conn)->linked = 1;
+ tt_assert(connection_dir_is_encrypted(conn));
+
+ sprintf(req, RENDEZVOUS2_GET("%s"), desc_id_base32);
+
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ body_len = strlen(desc_holder->desc_str);
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, body_len+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Pragma: no-cache\r\n"));
+ sprintf(buff, "Content-Length: %ld\r\n", (long) body_len);
+ tt_assert(strstr(header, buff));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_str_op(body, OP_EQ, desc_holder->desc_str);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ NS_UNMOCK(router_get_my_routerinfo);
+
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_cache_free_all();
+}
+
+#define MICRODESC_GET(digest) GET("/tor/micro/d/" digest)
+static void
+test_dir_handle_get_micro_d_not_found(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ #define B64_256_1 "8/Pz8/u7vz8/Pz+7vz8/Pz+7u/Pz8/P7u/Pz8/P7u78"
+ #define B64_256_2 "zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMw"
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = MICRODESC_GET(B64_256_1 "-" B64_256_2);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static or_options_t *mock_options = NULL;
+static void
+init_mock_options(void)
+{
+ mock_options = malloc(sizeof(or_options_t));
+ memset(mock_options, 0, sizeof(or_options_t));
+ mock_options->TestingTorNetwork = 1;
+}
+
+static const or_options_t *
+mock_get_options(void)
+{
+ tor_assert(mock_options);
+ return mock_options;
+}
+
+static const char microdesc[] =
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMjlHH/daN43cSVRaHBwgUfnszzAhg98EvivJ9Qxfv51mvQUxPjQ07es\n"
+ "gV/3n8fyh3Kqr/ehi9jxkdgSRfSnmF7giaHL1SLZ29kA7KtST+pBvmTpDtHa3ykX\n"
+ "Xorc7hJvIyTZoc1HU+5XSynj3gsBE5IGK1ZRzrNS688LnuZMVp1tAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n";
+
+static void
+test_dir_handle_get_micro_d(void *data)
+{
+ dir_connection_t *conn = NULL;
+ microdesc_cache_t *mc = NULL ;
+ smartlist_t *list = NULL;
+ char digest[DIGEST256_LEN];
+ char digest_base64[128];
+ char path[80];
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* SETUP */
+ init_mock_options();
+ const char *fn = get_fname("dir_handle_datadir_test1");
+ mock_options->DataDirectory = tor_strdup(fn);
+
+#ifdef _WIN32
+ tt_int_op(0, OP_EQ, mkdir(mock_options->DataDirectory));
+#else
+ tt_int_op(0, OP_EQ, mkdir(mock_options->DataDirectory, 0700));
+#endif
+
+ /* Add microdesc to cache */
+ crypto_digest256(digest, microdesc, strlen(microdesc), DIGEST_SHA256);
+ base64_encode_nopad(digest_base64, sizeof(digest_base64),
+ (uint8_t *) digest, DIGEST256_LEN);
+
+ mc = get_microdesc_cache();
+ list = microdescs_add_to_cache(mc, microdesc, NULL, SAVED_NOWHERE, 0,
+ time(NULL), NULL);
+ tt_int_op(1, OP_EQ, smartlist_len(list));
+
+ /* Make the request */
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ sprintf(path, MICRODESC_GET("%s"), digest_base64);
+ tt_int_op(directory_handle_command_get(conn, path, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(microdesc)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_str_op(body, OP_EQ, microdesc);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ smartlist_free(list);
+ microdesc_free_all();
+}
+
+static void
+test_dir_handle_get_micro_d_server_busy(void *data)
+{
+ dir_connection_t *conn = NULL;
+ microdesc_cache_t *mc = NULL ;
+ smartlist_t *list = NULL;
+ char digest[DIGEST256_LEN];
+ char digest_base64[128];
+ char path[80];
+ char *header = NULL;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* SETUP */
+ init_mock_options();
+ const char *fn = get_fname("dir_handle_datadir_test2");
+ mock_options->DataDirectory = tor_strdup(fn);
+
+#ifdef _WIN32
+ tt_int_op(0, OP_EQ, mkdir(mock_options->DataDirectory));
+#else
+ tt_int_op(0, OP_EQ, mkdir(mock_options->DataDirectory, 0700));
+#endif
+
+ /* Add microdesc to cache */
+ crypto_digest256(digest, microdesc, strlen(microdesc), DIGEST_SHA256);
+ base64_encode_nopad(digest_base64, sizeof(digest_base64),
+ (uint8_t *) digest, DIGEST256_LEN);
+
+ mc = get_microdesc_cache();
+ list = microdescs_add_to_cache(mc, microdesc, NULL, SAVED_NOWHERE, 0,
+ time(NULL), NULL);
+ tt_int_op(1, OP_EQ, smartlist_len(list));
+
+ //Make it busy
+ mock_options->CountPrivateBandwidth = 1;
+
+ /* Make the request */
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ sprintf(path, MICRODESC_GET("%s"), digest_base64);
+ tt_int_op(directory_handle_command_get(conn, path, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ smartlist_free(list);
+ microdesc_free_all();
+}
+
+#define BRIDGES_PATH "/tor/networkstatus-bridges"
+static void
+test_dir_handle_get_networkstatus_bridges_not_found_without_auth(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* SETUP */
+ init_mock_options();
+ mock_options->BridgeAuthoritativeDir = 1;
+ mock_options->BridgePassword_AuthDigest_ = tor_strdup("digest");
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ TO_CONN(conn)->linked = 1;
+
+ const char *req = GET(BRIDGES_PATH);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_networkstatus_bridges(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* SETUP */
+ init_mock_options();
+ mock_options->BridgeAuthoritativeDir = 1;
+ mock_options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
+ crypto_digest256(mock_options->BridgePassword_AuthDigest_,
+ "abcdefghijklm12345", 18, DIGEST_SHA256);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ TO_CONN(conn)->linked = 1;
+
+ const char *req = "GET " BRIDGES_PATH " HTTP/1.0\r\n"
+ "Authorization: Basic abcdefghijklm12345\r\n\r\n";
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 0\r\n"));
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_networkstatus_bridges_not_found_wrong_auth(void *data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* SETUP */
+ init_mock_options();
+ mock_options->BridgeAuthoritativeDir = 1;
+ mock_options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
+ crypto_digest256(mock_options->BridgePassword_AuthDigest_,
+ "abcdefghijklm12345", 18, DIGEST_SHA256);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ TO_CONN(conn)->linked = 1;
+
+ const char *req = "GET " BRIDGES_PATH " HTTP/1.0\r\n"
+ "Authorization: Basic NOTSAMEDIGEST\r\n\r\n";
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+#define SERVER_DESC_GET(id) GET("/tor/server/" id)
+static void
+test_dir_handle_get_server_descriptors_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = SERVER_DESC_GET("invalid");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_SERVER_BY_FP);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ or_options_free(mock_options); mock_options = NULL;
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_server_descriptors_all(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ //TODO: change to router_get_my_extrainfo when testing "extra" path
+ NS_MOCK(router_get_my_routerinfo);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ // We are one of the routers
+ routerlist_t *our_routerlist = router_get_routerlist();
+ tt_int_op(smartlist_len(our_routerlist->routers), OP_GE, 1);
+ mock_routerinfo = smartlist_get(our_routerlist->routers, 0);
+ set_server_identity_key(mock_routerinfo->identity_pkey);
+
+ /* Treat "all" requests as if they were unencrypted */
+ mock_routerinfo->cache_info.send_unencrypted = 1;
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = SERVER_DESC_GET("all");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ //TODO: Is this a BUG?
+ //It requires strlen(signed_descriptor_len)+1 as body_len but returns a body
+ //which is smaller than that by annotation_len bytes
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used,
+ mock_routerinfo->cache_info.signed_descriptor_len+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+
+ //TODO: Is this a BUG?
+ //This is what should be expected: tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_int_op(body_used, OP_EQ,
+ mock_routerinfo->cache_info.signed_descriptor_len);
+
+ tt_str_op(body, OP_EQ, mock_routerinfo->cache_info.signed_descriptor_body +
+ mock_routerinfo->cache_info.annotations_len);
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_NONE);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+
+ routerlist_free_all();
+ nodelist_free_all();
+ entry_guards_free_all();
+}
+
+static char
+TEST_DESCRIPTOR[] =
+"@uploaded-at 2014-06-08 19:20:11\n"
+"@source \"127.0.0.1\"\n"
+"router test000a 127.0.0.1 5000 0 7000\n"
+"platform Tor 0.2.5.3-alpha-dev on Linux\n"
+"protocols Link 1 2 Circuit 1\n"
+"published 2014-06-08 19:20:11\n"
+"fingerprint C7E7 CCB8 179F 8CC3 7F5C 8A04 2B3A 180B 934B 14BA\n"
+"uptime 0\n"
+"bandwidth 1073741824 1073741824 0\n"
+"extra-info-digest 67A152A4C7686FB07664F872620635F194D76D95\n"
+"caches-extra-info\n"
+"onion-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAOuBUIEBARMkkka/TGyaQNgUEDLP0KG7sy6KNQTNOlZHUresPr/vlVjo\n"
+"HPpLMfu9M2z18c51YX/muWwY9x4MyQooD56wI4+AqXQcJRwQfQlPn3Ay82uZViA9\n"
+"DpBajRieLlKKkl145KjArpD7F5BVsqccvjErgFYXvhhjSrx7BVLnAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBAN6NLnSxWQnFXxqZi5D3b0BMgV6y9NJLGjYQVP+eWtPZWgqyv4zeYsqv\n"
+"O9y6c5lvxyUxmNHfoAbe/s8f2Vf3/YaC17asAVSln4ktrr3e9iY74a9RMWHv1Gzk\n"
+"3042nMcqj3PEhRN0PoLkcOZNjjmNbaqki6qy9bWWZDNTdo+uI44dAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"hidden-service-dir\n"
+"contact auth0@test.test\n"
+"ntor-onion-key pK4bs08ERYN591jj7ca17Rn9Q02TIEfhnjR6hSq+fhU=\n"
+"reject *:*\n"
+"router-signature\n"
+"-----BEGIN SIGNATURE-----\n"
+"rx88DuM3Y7tODlHNDDEVzKpwh3csaG1or+T4l2Xs1oq3iHHyPEtB6QTLYrC60trG\n"
+"aAPsj3DEowGfjga1b248g2dtic8Ab+0exfjMm1RHXfDam5TXXZU3A0wMyoHjqHuf\n"
+"eChGPgFNUvEc+5YtD27qEDcUjcinYztTs7/dzxBT4PE=\n"
+"-----END SIGNATURE-----\n";
+
+static void
+test_dir_handle_get_server_descriptors_authority(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ crypto_pk_t *identity_pkey = pk_generate(0);
+ (void) data;
+
+ NS_MOCK(router_get_my_routerinfo);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* init mock */
+ router_get_my_routerinfo();
+ crypto_pk_get_digest(identity_pkey,
+ mock_routerinfo->cache_info.identity_digest);
+
+ // the digest is mine (the channel is unnecrypted, so we must allow sending)
+ set_server_identity_key(identity_pkey);
+ mock_routerinfo->cache_info.send_unencrypted = 1;
+
+ /* Setup descriptor */
+ long annotation_len = strstr(TEST_DESCRIPTOR, "router ") - TEST_DESCRIPTOR;
+ mock_routerinfo->cache_info.signed_descriptor_body =
+ tor_strdup(TEST_DESCRIPTOR);
+ mock_routerinfo->cache_info.signed_descriptor_len =
+ strlen(TEST_DESCRIPTOR) - annotation_len;;
+ mock_routerinfo->cache_info.annotations_len = annotation_len;
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = SERVER_DESC_GET("authority");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ //TODO: Is this a BUG?
+ //It requires strlen(TEST_DESCRIPTOR)+1 as body_len but returns a body which
+ //is smaller than that by annotation_len bytes
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_DESCRIPTOR)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+
+ tt_str_op(body, OP_EQ, TEST_DESCRIPTOR + annotation_len);
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_NONE);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ UNMOCK(connection_write_to_buf_impl_);
+ tor_free(mock_routerinfo->cache_info.signed_descriptor_body);
+ tor_free(mock_routerinfo);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ crypto_pk_free(identity_pkey);
+}
+
+static void
+test_dir_handle_get_server_descriptors_fp(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ crypto_pk_t *identity_pkey = pk_generate(0);
+ (void) data;
+
+ NS_MOCK(router_get_my_routerinfo);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* init mock */
+ router_get_my_routerinfo();
+ crypto_pk_get_digest(identity_pkey,
+ mock_routerinfo->cache_info.identity_digest);
+
+ // the digest is mine (the channel is unnecrypted, so we must allow sending)
+ set_server_identity_key(identity_pkey);
+ mock_routerinfo->cache_info.send_unencrypted = 1;
+
+ /* Setup descriptor */
+ long annotation_len = strstr(TEST_DESCRIPTOR, "router ") - TEST_DESCRIPTOR;
+ mock_routerinfo->cache_info.signed_descriptor_body =
+ tor_strdup(TEST_DESCRIPTOR);
+ mock_routerinfo->cache_info.signed_descriptor_len =
+ strlen(TEST_DESCRIPTOR) - annotation_len;
+ mock_routerinfo->cache_info.annotations_len = annotation_len;
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ #define HEX1 "Fe0daff89127389bc67558691231234551193EEE"
+ #define HEX2 "Deadbeef99999991111119999911111111f00ba4"
+ const char *hex_digest = hex_str(mock_routerinfo->cache_info.identity_digest,
+ DIGEST_LEN);
+
+ char req[155];
+ sprintf(req, SERVER_DESC_GET("fp/%s+" HEX1 "+" HEX2), hex_digest);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ //TODO: Is this a BUG?
+ //It requires strlen(TEST_DESCRIPTOR)+1 as body_len but returns a body which
+ //is smaller than that by annotation_len bytes
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_DESCRIPTOR)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+
+ tt_int_op(body_used, OP_EQ, strlen(body));
+
+ tt_str_op(body, OP_EQ, TEST_DESCRIPTOR + annotation_len);
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_NONE);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ UNMOCK(connection_write_to_buf_impl_);
+ tor_free(mock_routerinfo->cache_info.signed_descriptor_body);
+ tor_free(mock_routerinfo);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ crypto_pk_free(identity_pkey);
+}
+
+#define HEX1 "Fe0daff89127389bc67558691231234551193EEE"
+#define HEX2 "Deadbeef99999991111119999911111111f00ba4"
+
+static void
+test_dir_handle_get_server_descriptors_d(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ crypto_pk_t *identity_pkey = pk_generate(0);
+ (void) data;
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* Get one router's signed_descriptor_digest */
+ routerlist_t *our_routerlist = router_get_routerlist();
+ tt_int_op(smartlist_len(our_routerlist->routers), OP_GE, 1);
+ routerinfo_t *router = smartlist_get(our_routerlist->routers, 0);
+ const char *hex_digest = hex_str(router->cache_info.signed_descriptor_digest,
+ DIGEST_LEN);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ char req_header[155];
+ sprintf(req_header, SERVER_DESC_GET("d/%s+" HEX1 "+" HEX2), hex_digest);
+ tt_int_op(directory_handle_command_get(conn, req_header, NULL, 0), OP_EQ, 0);
+
+ //TODO: Is this a BUG?
+ //It requires strlen(signed_descriptor_len)+1 as body_len but returns a body
+ //which is smaller than that by annotation_len bytes
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used,
+ router->cache_info.signed_descriptor_len+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+
+ //TODO: Is this a BUG?
+ //This is what should be expected:
+ //tt_int_op(body_used, OP_EQ, strlen(body));
+ tt_int_op(body_used, OP_EQ, router->cache_info.signed_descriptor_len);
+
+ tt_str_op(body, OP_EQ, router->cache_info.signed_descriptor_body +
+ router->cache_info.annotations_len);
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_NONE);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ tor_free(mock_routerinfo);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ crypto_pk_free(identity_pkey);
+
+ routerlist_free_all();
+ nodelist_free_all();
+ entry_guards_free_all();
+}
+
+static void
+test_dir_handle_get_server_descriptors_busy(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ crypto_pk_t *identity_pkey = pk_generate(0);
+ (void) data;
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ //Make it busy
+ MOCK(get_options, mock_get_options);
+ init_mock_options();
+ mock_options->CountPrivateBandwidth = 1;
+
+ /* Get one router's signed_descriptor_digest */
+ routerlist_t *our_routerlist = router_get_routerlist();
+ tt_int_op(smartlist_len(our_routerlist->routers), OP_GE, 1);
+ routerinfo_t *router = smartlist_get(our_routerlist->routers, 0);
+ const char *hex_digest = hex_str(router->cache_info.signed_descriptor_digest,
+ DIGEST_LEN);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ #define HEX1 "Fe0daff89127389bc67558691231234551193EEE"
+ #define HEX2 "Deadbeef99999991111119999911111111f00ba4"
+ char req_header[155];
+ sprintf(req_header, SERVER_DESC_GET("d/%s+" HEX1 "+" HEX2), hex_digest);
+ tt_int_op(directory_handle_command_get(conn, req_header, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ tt_int_op(conn->dir_spool_src, OP_EQ, DIR_SPOOL_NONE);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+ tor_free(mock_routerinfo);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ crypto_pk_free(identity_pkey);
+
+ routerlist_free_all();
+ nodelist_free_all();
+ entry_guards_free_all();
+}
+
+static void
+test_dir_handle_get_server_keys_bad_req(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(BAD_REQUEST, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_server_keys_all_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/all");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+#define TEST_CERTIFICATE AUTHORITY_CERT_3
+#define TEST_SIGNING_KEY AUTHORITY_SIGNKEY_A_DIGEST
+extern const char AUTHORITY_CERT_3[];
+extern const char AUTHORITY_SIGNKEY_A_DIGEST[];
+
+static const char TEST_CERT_IDENT_KEY[] =
+ "D867ACF56A9D229B35C25F0090BC9867E906BE69";
+
+static void
+test_dir_handle_get_server_keys_all(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ const char digest[DIGEST_LEN] = "";
+
+ dir_server_t *ds = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/all");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_CERTIFICATE)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 1883\r\n"));
+
+ tt_str_op(TEST_CERTIFICATE, OP_EQ, body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static void
+test_dir_handle_get_server_keys_authority_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/authority");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static authority_cert_t * mock_cert = NULL;
+
+static authority_cert_t *
+get_my_v3_authority_cert_m(void)
+{
+ tor_assert(mock_cert);
+ return mock_cert;
+}
+
+static void
+test_dir_handle_get_server_keys_authority(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ mock_cert = authority_cert_parse_from_string(TEST_CERTIFICATE, NULL);
+
+ MOCK(get_my_v3_authority_cert, get_my_v3_authority_cert_m);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/authority");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_CERTIFICATE)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 1883\r\n"));
+
+ tt_str_op(TEST_CERTIFICATE, OP_EQ, body);
+
+ done:
+ UNMOCK(get_my_v3_authority_cert);
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ authority_cert_free(mock_cert); mock_cert = NULL;
+}
+
+static void
+test_dir_handle_get_server_keys_fp_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/fp/somehex");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_server_keys_fp(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ dir_server_t *ds = NULL;
+ const char digest[DIGEST_LEN] = "";
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ char req[71];
+ sprintf(req, GET("/tor/keys/fp/%s"), TEST_CERT_IDENT_KEY);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_CERTIFICATE)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 1883\r\n"));
+
+ tt_str_op(TEST_CERTIFICATE, OP_EQ, body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static void
+test_dir_handle_get_server_keys_sk_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/sk/somehex");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_server_keys_sk(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ mock_cert = authority_cert_parse_from_string(TEST_CERTIFICATE, NULL);
+ MOCK(get_my_v3_authority_cert, get_my_v3_authority_cert_m);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ char req[71];
+ sprintf(req, GET("/tor/keys/sk/%s"), TEST_SIGNING_KEY);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_CERTIFICATE)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 1883\r\n"));
+
+ tt_str_op(TEST_CERTIFICATE, OP_EQ, body);
+
+ done:
+ UNMOCK(get_my_v3_authority_cert);
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ authority_cert_free(mock_cert); mock_cert = NULL;
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_server_keys_fpsk_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ const char *req = GET("/tor/keys/fp-sk/somehex");
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_server_keys_fpsk(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ dir_server_t *ds = NULL;
+ const char digest[DIGEST_LEN] = "";
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+ dir_server_add(ds);
+
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ char req[115];
+ sprintf(req, GET("/tor/keys/fp-sk/%s-%s"),
+ TEST_CERT_IDENT_KEY, TEST_SIGNING_KEY);
+
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(TEST_CERTIFICATE)+1, 0);
+
+ tt_assert(header);
+ tt_assert(body);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 1883\r\n"));
+
+ tt_str_op(TEST_CERTIFICATE, OP_EQ, body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static void
+test_dir_handle_get_server_keys_busy(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ dir_server_t *ds = NULL;
+ const char digest[DIGEST_LEN] = "";
+ (void) data;
+
+ clear_dir_servers();
+ routerlist_free_all();
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+ dir_server_add(ds);
+
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* setup busy server */
+ init_mock_options();
+ mock_options->CountPrivateBandwidth = 1;
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ char req[71];
+ sprintf(req, GET("/tor/keys/fp/%s"), TEST_CERT_IDENT_KEY);
+ tt_int_op(directory_handle_command_get(conn, req, NULL, 0), OP_EQ, 0);
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ done:
+ UNMOCK(get_options);
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ or_options_free(mock_options); mock_options = NULL;
+
+ clear_dir_servers();
+ routerlist_free_all();
+}
+
+static networkstatus_t *mock_ns_val = NULL;
+static networkstatus_t *
+mock_ns_get_by_flavor(consensus_flavor_t f)
+{
+ (void)f;
+ return mock_ns_val;
+}
+
+static void
+test_dir_handle_get_status_vote_current_consensus_ns_not_enough_sigs(void* d)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *stats = NULL;
+ (void) d;
+
+ /* init mock */
+ mock_ns_val = tor_malloc_zero(sizeof(networkstatus_t));
+ mock_ns_val->flavor = FLAV_NS;
+ mock_ns_val->voters = smartlist_new();
+
+ /* init mock */
+ init_mock_options();
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+ MOCK(networkstatus_get_latest_consensus_by_flavor, mock_ns_get_by_flavor);
+
+ /* start gathering stats */
+ mock_options->DirReqStatistics = 1;
+ geoip_dirreq_stats_init(time(NULL));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/consensus-ns/" HEX1 "+" HEX2), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+
+ tt_assert(header);
+ tt_str_op(NOT_ENOUGH_CONSENSUS_SIGNATURES, OP_EQ, header);
+
+ stats = geoip_format_dirreq_stats(time(NULL));
+ tt_assert(stats);
+ tt_assert(strstr(stats, "not-enough-sigs=8"));
+
+ done:
+ UNMOCK(networkstatus_get_latest_consensus_by_flavor);
+ UNMOCK(connection_write_to_buf_impl_);
+ UNMOCK(get_options);
+
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(stats);
+ smartlist_free(mock_ns_val->voters);
+ tor_free(mock_ns_val);
+ or_options_free(mock_options); mock_options = NULL;
+}
+
+static void
+test_dir_handle_get_status_vote_current_consensus_ns_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ char *stats = NULL;
+ (void) data;
+
+ init_mock_options();
+
+ MOCK(get_options, mock_get_options);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ /* start gathering stats */
+ mock_options->DirReqStatistics = 1;
+ geoip_dirreq_stats_init(time(NULL));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/consensus-ns"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ stats = geoip_format_dirreq_stats(time(NULL));
+ tt_assert(stats);
+ tt_assert(strstr(stats, "not-found=8"));
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ UNMOCK(get_options);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(stats);
+ or_options_free(mock_options); mock_options = NULL;
+}
+
+NS_DECL(int, geoip_get_country_by_addr, (const tor_addr_t *addr));
+
+int
+NS(geoip_get_country_by_addr)(const tor_addr_t *addr)
+{
+ (void)addr;
+ CALLED(geoip_get_country_by_addr)++;
+ return 1;
+}
+
+static void
+status_vote_current_consensus_ns_test(char **header, char **body,
+ size_t *body_len)
+{
+ common_digests_t digests;
+ dir_connection_t *conn = NULL;
+
+ #define NETWORK_STATUS "some network status string"
+ dirserv_set_cached_consensus_networkstatus(NETWORK_STATUS, "ns", &digests,
+ time(NULL));
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ tt_assert(mock_options);
+ mock_options->DirReqStatistics = 1;
+ geoip_dirreq_stats_init(time(NULL));
+
+ /* init geoip database */
+ geoip_parse_entry("10,50,AB", AF_INET);
+ tt_str_op("ab", OP_EQ, geoip_get_country_name(1));
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ TO_CONN(conn)->address = tor_strdup("127.0.0.1");
+
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/consensus-ns"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, header, MAX_HEADERS_SIZE,
+ body, body_len, strlen(NETWORK_STATUS)+7, 0);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+}
+
+static void
+test_dir_handle_get_status_vote_current_consensus_ns(void* data)
+{
+ char *header = NULL;
+ char *body = NULL, *comp_body = NULL;
+ size_t body_used = 0, comp_body_used = 0;
+ char *stats = NULL, *hist = NULL;
+ (void) data;
+
+ dirserv_free_all();
+ clear_geoip_db();
+
+ NS_MOCK(geoip_get_country_by_addr);
+ MOCK(get_options, mock_get_options);
+
+ init_mock_options();
+
+ status_vote_current_consensus_ns_test(&header, &comp_body, &comp_body_used);
+ tt_assert(header);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Pragma: no-cache\r\n"));
+
+ compress_method_t compression = detect_compression_method(comp_body,
+ comp_body_used);
+ tt_int_op(ZLIB_METHOD, OP_EQ, compression);
+
+ tor_gzip_uncompress(&body, &body_used, comp_body, comp_body_used,
+ compression, 0, LOG_PROTOCOL_WARN);
+
+ tt_str_op(NETWORK_STATUS, OP_EQ, body);
+ tt_int_op(strlen(NETWORK_STATUS), OP_EQ, body_used);
+
+ stats = geoip_format_dirreq_stats(time(NULL));
+ tt_assert(stats);
+
+ tt_assert(strstr(stats, "ok=8"));
+ tt_assert(strstr(stats, "dirreq-v3-ips ab=8"));
+ tt_assert(strstr(stats, "dirreq-v3-reqs ab=8"));
+ tt_assert(strstr(stats, "dirreq-v3-direct-dl"
+ " complete=0,timeout=0,running=4"));
+
+ hist = geoip_get_request_history();
+ tt_assert(hist);
+ tt_str_op("ab=8", OP_EQ, hist);
+
+ done:
+ NS_UNMOCK(geoip_get_country_by_addr);
+ UNMOCK(get_options);
+ tor_free(header);
+ tor_free(comp_body);
+ tor_free(body);
+ tor_free(stats);
+ tor_free(hist);
+ or_options_free(mock_options); mock_options = NULL;
+
+ dirserv_free_all();
+ clear_geoip_db();
+}
+
+static void
+test_dir_handle_get_status_vote_current_consensus_ns_busy(void* data)
+{
+ char *header = NULL;
+ char *body = NULL;
+ size_t body_used = 0;
+ char *stats = NULL;
+ (void) data;
+
+ dirserv_free_all();
+ clear_geoip_db();
+
+ MOCK(get_options, mock_get_options);
+
+ // Make it busy
+ init_mock_options();
+ mock_options->CountPrivateBandwidth = 1;
+
+ status_vote_current_consensus_ns_test(&header, &body, &body_used);
+ tt_assert(header);
+
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ stats = geoip_format_dirreq_stats(time(NULL));
+ tt_assert(stats);
+ tt_assert(strstr(stats, "busy=8"));
+
+ done:
+ UNMOCK(get_options);
+ tor_free(header);
+ tor_free(body);
+ or_options_free(mock_options); mock_options = NULL;
+
+ tor_free(stats);
+ dirserv_free_all();
+ clear_geoip_db();
+}
+
+static void
+test_dir_handle_get_status_vote_current_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/" HEX1), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+#define VOTE_DIGEST "312A4890D4D832597ABBD3089C782DBBFB81E48D"
+
+static void
+status_vote_current_d_test(char **header, char **body, size_t *body_l)
+{
+ dir_connection_t *conn = NULL;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/d/" VOTE_DIGEST), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, header, MAX_HEADERS_SIZE,
+ body, body_l, strlen(VOTE_BODY_V3)+1, 0);
+ tt_assert(header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+}
+
+static void
+status_vote_next_d_test(char **header, char **body, size_t *body_l)
+{
+ dir_connection_t *conn = NULL;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/d/" VOTE_DIGEST), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, header, MAX_HEADERS_SIZE,
+ body, body_l, strlen(VOTE_BODY_V3)+1, 0);
+ tt_assert(header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+}
+
+static void
+test_dir_handle_get_status_vote_current_d_not_found(void* data)
+{
+ char *header = NULL;
+ (void) data;
+
+ status_vote_current_d_test(&header, NULL, NULL);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_status_vote_next_d_not_found(void* data)
+{
+ char *header = NULL;
+ (void) data;
+
+ status_vote_next_d_test(&header, NULL, NULL);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_status_vote_d(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used = 0;
+ dir_server_t *ds = NULL;
+ const char digest[DIGEST_LEN] = "";
+ (void) data;
+
+ clear_dir_servers();
+ dirvote_free_all();
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+
+ init_mock_options();
+ mock_options->AuthoritativeDir = 1;
+ mock_options->V3AuthoritativeDir = 1;
+ mock_options->TestingV3AuthVotingStartOffset = 0;
+ mock_options->TestingV3AuthInitialVotingInterval = 1;
+ mock_options->TestingV3AuthInitialVoteDelay = 1;
+ mock_options->TestingV3AuthInitialDistDelay = 1;
+
+ time_t now = 1441223455 -1;
+ dirvote_recalculate_timing(mock_options, now);
+
+ const char *msg_out = NULL;
+ int status_out = 0;
+ struct pending_vote_t *pv = dirvote_add_vote(VOTE_BODY_V3, &msg_out,
+ &status_out);
+ tt_assert(pv);
+
+ status_vote_current_d_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 4135\r\n"));
+
+ tt_str_op(VOTE_BODY_V3, OP_EQ, body);
+
+ tor_free(header);
+ tor_free(body);
+
+ status_vote_next_d_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 4135\r\n"));
+
+ tt_str_op(VOTE_BODY_V3, OP_EQ, body);
+
+ done:
+ tor_free(header);
+ tor_free(body);
+ or_options_free(mock_options); mock_options = NULL;
+
+ clear_dir_servers();
+ dirvote_free_all();
+}
+
+static void
+test_dir_handle_get_status_vote_next_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/" HEX1), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+status_vote_next_consensus_test(char **header, char **body, size_t *body_used)
+{
+ dir_connection_t *conn = NULL;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/consensus"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, header, MAX_HEADERS_SIZE,
+ body, body_used, 18, 0);
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus_not_found(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used;
+ (void) data;
+
+ status_vote_next_consensus_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_status_vote_current_authority_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/authority"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+static void
+test_dir_handle_get_status_vote_next_authority_not_found(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL;
+ (void) data;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/authority"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ NULL, NULL, 1, 0);
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+}
+
+NS_DECL(const char*,
+dirvote_get_pending_consensus, (consensus_flavor_t flav));
+
+const char*
+NS(dirvote_get_pending_consensus)(consensus_flavor_t flav)
+{
+ (void)flav;
+ return "pending consensus";
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ NS_MOCK(dirvote_get_pending_consensus);
+
+ status_vote_next_consensus_test(&header, &body, &body_used);
+ tt_assert(header);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 17\r\n"));
+
+ tt_str_op("pending consensus", OP_EQ, body);
+
+ done:
+ NS_UNMOCK(dirvote_get_pending_consensus);
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus_busy(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ MOCK(get_options, mock_get_options);
+ NS_MOCK(dirvote_get_pending_consensus);
+
+ //Make it busy
+ init_mock_options();
+ mock_options->CountPrivateBandwidth = 1;
+
+ status_vote_next_consensus_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ done:
+ NS_UNMOCK(dirvote_get_pending_consensus);
+ UNMOCK(get_options);
+ tor_free(header);
+ tor_free(body);
+ or_options_free(mock_options); mock_options = NULL;
+}
+
+static void
+status_vote_next_consensus_signatures_test(char **header, char **body,
+ size_t *body_used)
+{
+ dir_connection_t *conn = NULL;
+
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/consensus-signatures"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, header, MAX_HEADERS_SIZE,
+ body, body_used, 22, 0);
+
+ done:
+ connection_free_(TO_CONN(conn));
+ UNMOCK(connection_write_to_buf_impl_);
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus_signatures_not_found(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used;
+ (void) data;
+
+ status_vote_next_consensus_signatures_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_str_op(NOT_FOUND, OP_EQ, header);
+
+ done:
+ tor_free(header);
+ tor_free(body);
+}
+
+NS_DECL(const char*,
+dirvote_get_pending_detached_signatures, (void));
+
+const char*
+NS(dirvote_get_pending_detached_signatures)(void)
+{
+ return "pending detached sigs";
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus_signatures(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used = 0;
+ (void) data;
+
+ NS_MOCK(dirvote_get_pending_detached_signatures);
+
+ status_vote_next_consensus_signatures_test(&header, &body, &body_used);
+ tt_assert(header);
+
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 21\r\n"));
+
+ tt_str_op("pending detached sigs", OP_EQ, body);
+
+ done:
+ NS_UNMOCK(dirvote_get_pending_detached_signatures);
+ tor_free(header);
+ tor_free(body);
+}
+
+static void
+test_dir_handle_get_status_vote_next_consensus_signatures_busy(void* data)
+{
+ char *header = NULL, *body = NULL;
+ size_t body_used;
+ (void) data;
+
+ NS_MOCK(dirvote_get_pending_detached_signatures);
+ MOCK(get_options, mock_get_options);
+
+ //Make it busy
+ init_mock_options();
+ mock_options->CountPrivateBandwidth = 1;
+
+ status_vote_next_consensus_signatures_test(&header, &body, &body_used);
+
+ tt_assert(header);
+ tt_str_op(SERVER_BUSY, OP_EQ, header);
+
+ done:
+ UNMOCK(get_options);
+ NS_UNMOCK(dirvote_get_pending_detached_signatures);
+ tor_free(header);
+ tor_free(body);
+ or_options_free(mock_options); mock_options = NULL;
+}
+
+static void
+test_dir_handle_get_status_vote_next_authority(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL, *body = NULL;
+ const char *msg_out = NULL;
+ int status_out = 0;
+ size_t body_used = 0;
+ dir_server_t *ds = NULL;
+ const char digest[DIGEST_LEN] = "";
+ (void) data;
+
+ clear_dir_servers();
+ routerlist_free_all();
+ dirvote_free_all();
+
+ mock_cert = authority_cert_parse_from_string(TEST_CERTIFICATE, NULL);
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ init_mock_options();
+ mock_options->AuthoritativeDir = 1;
+ mock_options->V3AuthoritativeDir = 1;
+ mock_options->TestingV3AuthVotingStartOffset = 0;
+ mock_options->TestingV3AuthInitialVotingInterval = 1;
+ mock_options->TestingV3AuthInitialVoteDelay = 1;
+ mock_options->TestingV3AuthInitialDistDelay = 1;
+
+ time_t now = 1441223455 -1;
+ dirvote_recalculate_timing(mock_options, now);
+
+ struct pending_vote_t *vote = dirvote_add_vote(VOTE_BODY_V3, &msg_out,
+ &status_out);
+ tt_assert(vote);
+
+ MOCK(get_my_v3_authority_cert, get_my_v3_authority_cert_m);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/next/authority"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(VOTE_BODY_V3)+1, 0);
+
+ tt_assert(header);
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 4135\r\n"));
+
+ tt_str_op(VOTE_BODY_V3, OP_EQ, body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ UNMOCK(get_my_v3_authority_cert);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ authority_cert_free(mock_cert); mock_cert = NULL;
+ or_options_free(mock_options); mock_options = NULL;
+
+ clear_dir_servers();
+ routerlist_free_all();
+ dirvote_free_all();
+}
+
+static void
+test_dir_handle_get_status_vote_current_authority(void* data)
+{
+ dir_connection_t *conn = NULL;
+ char *header = NULL, *body = NULL;
+ const char *msg_out = NULL;
+ int status_out = 0;
+ size_t body_used = 0;
+ const char digest[DIGEST_LEN] = "";
+
+ dir_server_t *ds = NULL;
+ (void) data;
+
+ clear_dir_servers();
+ routerlist_free_all();
+ dirvote_free_all();
+
+ mock_cert = authority_cert_parse_from_string(TEST_CERTIFICATE, NULL);
+
+ /* create a trusted ds */
+ ds = trusted_dir_server_new("ds", "127.0.0.1", 9059, 9060, NULL, digest,
+ NULL, V3_DIRINFO, 1.0);
+ tt_assert(ds);
+ dir_server_add(ds);
+
+ /* ds v3_identity_digest is the certificate's identity_key */
+ base16_decode(ds->v3_identity_digest, DIGEST_LEN,
+ TEST_CERT_IDENT_KEY, HEX_DIGEST_LEN);
+
+ tt_int_op(0, OP_EQ, trusted_dirs_load_certs_from_string(TEST_CERTIFICATE,
+ TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST, 1));
+
+ init_mock_options();
+ mock_options->AuthoritativeDir = 1;
+ mock_options->V3AuthoritativeDir = 1;
+ mock_options->TestingV3AuthVotingStartOffset = 0;
+ mock_options->TestingV3AuthInitialVotingInterval = 1;
+ mock_options->TestingV3AuthInitialVoteDelay = 1;
+ mock_options->TestingV3AuthInitialDistDelay = 1;
+
+ time_t now = 1441223455;
+ dirvote_recalculate_timing(mock_options, now-1);
+
+ struct pending_vote_t *vote = dirvote_add_vote(VOTE_BODY_V3, &msg_out,
+ &status_out);
+ tt_assert(vote);
+
+ // move the pending vote to previous vote
+ dirvote_act(mock_options, now+1);
+
+ MOCK(get_my_v3_authority_cert, get_my_v3_authority_cert_m);
+ MOCK(connection_write_to_buf_impl_, connection_write_to_buf_mock);
+
+ conn = dir_connection_new(tor_addr_family(&MOCK_TOR_ADDR));
+ tt_int_op(0, OP_EQ, directory_handle_command_get(conn,
+ GET("/tor/status-vote/current/authority"), NULL, 0));
+
+ fetch_from_buf_http(TO_CONN(conn)->outbuf, &header, MAX_HEADERS_SIZE,
+ &body, &body_used, strlen(VOTE_BODY_V3)+1, 0);
+
+ tt_assert(header);
+ tt_ptr_op(strstr(header, "HTTP/1.0 200 OK\r\n"), OP_EQ, header);
+ tt_assert(strstr(header, "Content-Type: text/plain\r\n"));
+ tt_assert(strstr(header, "Content-Encoding: identity\r\n"));
+ tt_assert(strstr(header, "Content-Length: 4135\r\n"));
+
+ tt_str_op(VOTE_BODY_V3, OP_EQ, body);
+
+ done:
+ UNMOCK(connection_write_to_buf_impl_);
+ UNMOCK(get_my_v3_authority_cert);
+ connection_free_(TO_CONN(conn));
+ tor_free(header);
+ tor_free(body);
+ authority_cert_free(mock_cert); mock_cert = NULL;
+ or_options_free(mock_options); mock_options = NULL;
+
+ clear_dir_servers();
+ routerlist_free_all();
+ dirvote_free_all();
+}
+
+#define DIR_HANDLE_CMD(name,flags) \
+ { #name, test_dir_handle_get_##name, (flags), NULL, NULL }
+
+struct testcase_t dir_handle_get_tests[] = {
+ DIR_HANDLE_CMD(not_found, 0),
+ DIR_HANDLE_CMD(bad_request, 0),
+ DIR_HANDLE_CMD(v1_command_not_found, 0),
+ DIR_HANDLE_CMD(v1_command, 0),
+ DIR_HANDLE_CMD(robots_txt, 0),
+ DIR_HANDLE_CMD(bytes_txt, 0),
+ DIR_HANDLE_CMD(rendezvous2_not_found_if_not_encrypted, 0),
+ DIR_HANDLE_CMD(rendezvous2_not_found, 0),
+ DIR_HANDLE_CMD(rendezvous2_on_encrypted_conn_with_invalid_desc_id, 0),
+ DIR_HANDLE_CMD(rendezvous2_on_encrypted_conn_not_well_formed, 0),
+ DIR_HANDLE_CMD(rendezvous2_on_encrypted_conn_success, 0),
+ DIR_HANDLE_CMD(micro_d_not_found, 0),
+ DIR_HANDLE_CMD(micro_d_server_busy, 0),
+ DIR_HANDLE_CMD(micro_d, 0),
+ DIR_HANDLE_CMD(networkstatus_bridges_not_found_without_auth, 0),
+ DIR_HANDLE_CMD(networkstatus_bridges_not_found_wrong_auth, 0),
+ DIR_HANDLE_CMD(networkstatus_bridges, 0),
+ DIR_HANDLE_CMD(server_descriptors_not_found, 0),
+ DIR_HANDLE_CMD(server_descriptors_busy, TT_FORK),
+ DIR_HANDLE_CMD(server_descriptors_all, TT_FORK),
+ DIR_HANDLE_CMD(server_descriptors_authority, TT_FORK),
+ DIR_HANDLE_CMD(server_descriptors_fp, TT_FORK),
+ DIR_HANDLE_CMD(server_descriptors_d, TT_FORK),
+ DIR_HANDLE_CMD(server_keys_bad_req, 0),
+ DIR_HANDLE_CMD(server_keys_busy, 0),
+ DIR_HANDLE_CMD(server_keys_all_not_found, 0),
+ DIR_HANDLE_CMD(server_keys_all, 0),
+ DIR_HANDLE_CMD(server_keys_authority_not_found, 0),
+ DIR_HANDLE_CMD(server_keys_authority, 0),
+ DIR_HANDLE_CMD(server_keys_fp_not_found, 0),
+ DIR_HANDLE_CMD(server_keys_fp, 0),
+ DIR_HANDLE_CMD(server_keys_sk_not_found, 0),
+ DIR_HANDLE_CMD(server_keys_sk, 0),
+ DIR_HANDLE_CMD(server_keys_fpsk_not_found, 0),
+ DIR_HANDLE_CMD(server_keys_fpsk, 0),
+ DIR_HANDLE_CMD(status_vote_current_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_next_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_current_authority_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_current_authority, 0),
+ DIR_HANDLE_CMD(status_vote_next_authority_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_next_authority, 0),
+ DIR_HANDLE_CMD(status_vote_current_consensus_ns_not_enough_sigs, 0),
+ DIR_HANDLE_CMD(status_vote_current_consensus_ns_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_current_consensus_ns_busy, 0),
+ DIR_HANDLE_CMD(status_vote_current_consensus_ns, 0),
+ DIR_HANDLE_CMD(status_vote_current_d_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_next_d_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_d, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus_busy, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus_signatures_not_found, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus_signatures_busy, 0),
+ DIR_HANDLE_CMD(status_vote_next_consensus_signatures, 0),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_dns.c b/src/test/test_dns.c
new file mode 100644
index 0000000000..5289ca58ff
--- /dev/null
+++ b/src/test/test_dns.c
@@ -0,0 +1,765 @@
+#include "or.h"
+#include "test.h"
+
+#define DNS_PRIVATE
+
+#include "dns.h"
+#include "connection.h"
+#include "router.h"
+
+#define NS_MODULE dns
+
+#define NS_SUBMODULE clip_ttl
+
+static void
+NS(test_main)(void *arg)
+{
+ (void)arg;
+
+ uint32_t ttl_mid = MIN_DNS_TTL / 2 + MAX_DNS_TTL / 2;
+
+ tt_int_op(dns_clip_ttl(MIN_DNS_TTL - 1),==,MIN_DNS_TTL);
+ tt_int_op(dns_clip_ttl(ttl_mid),==,ttl_mid);
+ tt_int_op(dns_clip_ttl(MAX_DNS_TTL + 1),==,MAX_DNS_TTL);
+
+ done:
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE expiry_ttl
+
+static void
+NS(test_main)(void *arg)
+{
+ (void)arg;
+
+ uint32_t ttl_mid = MIN_DNS_TTL / 2 + MAX_DNS_ENTRY_AGE / 2;
+
+ tt_int_op(dns_get_expiry_ttl(MIN_DNS_TTL - 1),==,MIN_DNS_TTL);
+ tt_int_op(dns_get_expiry_ttl(ttl_mid),==,ttl_mid);
+ tt_int_op(dns_get_expiry_ttl(MAX_DNS_ENTRY_AGE + 1),==,MAX_DNS_ENTRY_AGE);
+
+ done:
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE resolve
+
+static int resolve_retval = 0;
+static int resolve_made_conn_pending = 0;
+static char *resolved_name = NULL;
+static cached_resolve_t *cache_entry = NULL;
+
+static int n_fake_impl = 0;
+
+NS_DECL(int, dns_resolve_impl, (edge_connection_t *exitconn, int is_resolve,
+ or_circuit_t *oncirc, char **hostname_out,
+ int *made_connection_pending_out,
+ cached_resolve_t **resolve_out));
+
+/** This will be our configurable substitute for <b>dns_resolve_impl</b> in
+ * dns.c. It will return <b>resolve_retval</b>,
+ * and set <b>resolve_made_conn_pending</b> to
+ * <b>made_connection_pending_out</b>. It will set <b>hostname_out</b>
+ * to a duplicate of <b>resolved_name</b> and it will set <b>resolve_out</b>
+ * to <b>cache_entry</b>. Lastly, it will increment <b>n_fake_impl</b< by
+ * 1.
+ */
+static int
+NS(dns_resolve_impl)(edge_connection_t *exitconn, int is_resolve,
+ or_circuit_t *oncirc, char **hostname_out,
+ int *made_connection_pending_out,
+ cached_resolve_t **resolve_out)
+{
+ (void)oncirc;
+ (void)exitconn;
+ (void)is_resolve;
+
+ if (made_connection_pending_out)
+ *made_connection_pending_out = resolve_made_conn_pending;
+
+ if (hostname_out && resolved_name)
+ *hostname_out = tor_strdup(resolved_name);
+
+ if (resolve_out && cache_entry)
+ *resolve_out = cache_entry;
+
+ n_fake_impl++;
+
+ return resolve_retval;
+}
+
+static edge_connection_t *conn_for_resolved_cell = NULL;
+
+static int n_send_resolved_cell_replacement = 0;
+static uint8_t last_answer_type = 0;
+static cached_resolve_t *last_resolved;
+
+static void
+NS(send_resolved_cell)(edge_connection_t *conn, uint8_t answer_type,
+ const cached_resolve_t *resolved)
+{
+ conn_for_resolved_cell = conn;
+
+ last_answer_type = answer_type;
+ last_resolved = (cached_resolve_t *)resolved;
+
+ n_send_resolved_cell_replacement++;
+}
+
+static int n_send_resolved_hostname_cell_replacement = 0;
+
+static char *last_resolved_hostname = NULL;
+
+static void
+NS(send_resolved_hostname_cell)(edge_connection_t *conn,
+ const char *hostname)
+{
+ conn_for_resolved_cell = conn;
+
+ tor_free(last_resolved_hostname);
+ last_resolved_hostname = tor_strdup(hostname);
+
+ n_send_resolved_hostname_cell_replacement++;
+}
+
+static int n_dns_cancel_pending_resolve_replacement = 0;
+
+static void
+NS(dns_cancel_pending_resolve)(const char *address)
+{
+ (void) address;
+ n_dns_cancel_pending_resolve_replacement++;
+}
+
+static int n_connection_free = 0;
+static connection_t *last_freed_conn = NULL;
+
+static void
+NS(connection_free)(connection_t *conn)
+{
+ n_connection_free++;
+
+ last_freed_conn = conn;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ (void) arg;
+ int retval;
+ int prev_n_send_resolved_hostname_cell_replacement;
+ int prev_n_send_resolved_cell_replacement;
+ int prev_n_connection_free;
+ cached_resolve_t *fake_resolved = tor_malloc(sizeof(cached_resolve_t));
+ edge_connection_t *exitconn = tor_malloc(sizeof(edge_connection_t));
+ edge_connection_t *nextconn = tor_malloc(sizeof(edge_connection_t));
+
+ or_circuit_t *on_circuit = tor_malloc(sizeof(or_circuit_t));
+ memset(on_circuit,0,sizeof(or_circuit_t));
+ on_circuit->base_.magic = OR_CIRCUIT_MAGIC;
+
+ memset(fake_resolved,0,sizeof(cached_resolve_t));
+ memset(exitconn,0,sizeof(edge_connection_t));
+ memset(nextconn,0,sizeof(edge_connection_t));
+
+ NS_MOCK(dns_resolve_impl);
+ NS_MOCK(send_resolved_cell);
+ NS_MOCK(send_resolved_hostname_cell);
+
+ /*
+ * CASE 1: dns_resolve_impl returns 1 and sets a hostname. purpose is
+ * EXIT_PURPOSE_RESOLVE.
+ *
+ * We want dns_resolve() to call send_resolved_hostname_cell() for a
+ * given exit connection (represented by edge_connection_t object)
+ * with a hostname it received from _impl.
+ */
+
+ prev_n_send_resolved_hostname_cell_replacement =
+ n_send_resolved_hostname_cell_replacement;
+
+ exitconn->base_.purpose = EXIT_PURPOSE_RESOLVE;
+ exitconn->on_circuit = &(on_circuit->base_);
+
+ resolve_retval = 1;
+ resolved_name = tor_strdup("www.torproject.org");
+
+ retval = dns_resolve(exitconn);
+
+ tt_int_op(retval,==,1);
+ tt_str_op(resolved_name,==,last_resolved_hostname);
+ tt_assert(conn_for_resolved_cell == exitconn);
+ tt_int_op(n_send_resolved_hostname_cell_replacement,==,
+ prev_n_send_resolved_hostname_cell_replacement + 1);
+ tt_assert(exitconn->on_circuit == NULL);
+
+ tor_free(last_resolved_hostname);
+ // implies last_resolved_hostname = NULL;
+
+ /* CASE 2: dns_resolve_impl returns 1, but does not set hostname.
+ * Instead, it yields cached_resolve_t object.
+ *
+ * We want dns_resolve to call send_resolved_cell on exitconn with
+ * RESOLVED_TYPE_AUTO and the cached_resolve_t object from _impl.
+ */
+
+ tor_free(resolved_name);
+ resolved_name = NULL;
+
+ exitconn->on_circuit = &(on_circuit->base_);
+
+ cache_entry = fake_resolved;
+
+ prev_n_send_resolved_cell_replacement =
+ n_send_resolved_cell_replacement;
+
+ retval = dns_resolve(exitconn);
+
+ tt_int_op(retval,==,1);
+ tt_assert(conn_for_resolved_cell == exitconn);
+ tt_int_op(n_send_resolved_cell_replacement,==,
+ prev_n_send_resolved_cell_replacement + 1);
+ tt_assert(last_resolved == fake_resolved);
+ tt_int_op(last_answer_type,==,0xff);
+ tt_assert(exitconn->on_circuit == NULL);
+
+ /* CASE 3: The purpose of exit connection is not EXIT_PURPOSE_RESOLVE
+ * and _impl returns 1.
+ *
+ * We want dns_resolve to prepend exitconn to n_streams linked list.
+ * We don't want it to send any cells about hostname being resolved.
+ */
+
+ exitconn->base_.purpose = EXIT_PURPOSE_CONNECT;
+ exitconn->on_circuit = &(on_circuit->base_);
+
+ on_circuit->n_streams = nextconn;
+
+ prev_n_send_resolved_cell_replacement =
+ n_send_resolved_cell_replacement;
+
+ prev_n_send_resolved_hostname_cell_replacement =
+ n_send_resolved_hostname_cell_replacement;
+
+ retval = dns_resolve(exitconn);
+
+ tt_int_op(retval,==,1);
+ tt_assert(on_circuit->n_streams == exitconn);
+ tt_assert(exitconn->next_stream == nextconn);
+ tt_int_op(prev_n_send_resolved_cell_replacement,==,
+ n_send_resolved_cell_replacement);
+ tt_int_op(prev_n_send_resolved_hostname_cell_replacement,==,
+ n_send_resolved_hostname_cell_replacement);
+
+ /* CASE 4: _impl returns 0.
+ *
+ * We want dns_resolve() to set exitconn state to
+ * EXIT_CONN_STATE_RESOLVING and prepend exitconn to resolving_streams
+ * linked list.
+ */
+
+ exitconn->on_circuit = &(on_circuit->base_);
+
+ resolve_retval = 0;
+
+ exitconn->next_stream = NULL;
+ on_circuit->resolving_streams = nextconn;
+
+ retval = dns_resolve(exitconn);
+
+ tt_int_op(retval,==,0);
+ tt_int_op(exitconn->base_.state,==,EXIT_CONN_STATE_RESOLVING);
+ tt_assert(on_circuit->resolving_streams == exitconn);
+ tt_assert(exitconn->next_stream == nextconn);
+
+ /* CASE 5: _impl returns -1 when purpose of exitconn is
+ * EXIT_PURPOSE_RESOLVE. We want dns_resolve to call send_resolved_cell
+ * on exitconn with type being RESOLVED_TYPE_ERROR.
+ */
+
+ NS_MOCK(dns_cancel_pending_resolve);
+ NS_MOCK(connection_free);
+
+ exitconn->on_circuit = &(on_circuit->base_);
+ exitconn->base_.purpose = EXIT_PURPOSE_RESOLVE;
+
+ resolve_retval = -1;
+
+ prev_n_send_resolved_cell_replacement =
+ n_send_resolved_cell_replacement;
+
+ prev_n_connection_free = n_connection_free;
+
+ retval = dns_resolve(exitconn);
+
+ tt_int_op(retval,==,-1);
+ tt_int_op(n_send_resolved_cell_replacement,==,
+ prev_n_send_resolved_cell_replacement + 1);
+ tt_int_op(last_answer_type,==,RESOLVED_TYPE_ERROR);
+ tt_int_op(n_dns_cancel_pending_resolve_replacement,==,1);
+ tt_int_op(n_connection_free,==,prev_n_connection_free + 1);
+ tt_assert(last_freed_conn == TO_CONN(exitconn));
+
+ done:
+ NS_UNMOCK(dns_resolve_impl);
+ NS_UNMOCK(send_resolved_cell);
+ NS_UNMOCK(send_resolved_hostname_cell);
+ NS_UNMOCK(dns_cancel_pending_resolve);
+ NS_UNMOCK(connection_free);
+ tor_free(on_circuit);
+ tor_free(exitconn);
+ tor_free(nextconn);
+ tor_free(resolved_name);
+ tor_free(fake_resolved);
+ tor_free(last_resolved_hostname);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+/** Create an <b>edge_connection_t</b> instance that is considered a
+ * valid exit connection by asserts in dns_resolve_impl.
+ */
+static edge_connection_t *
+create_valid_exitconn(void)
+{
+ edge_connection_t *exitconn = tor_malloc_zero(sizeof(edge_connection_t));
+ TO_CONN(exitconn)->type = CONN_TYPE_EXIT;
+ TO_CONN(exitconn)->magic = EDGE_CONNECTION_MAGIC;
+ TO_CONN(exitconn)->purpose = EXIT_PURPOSE_RESOLVE;
+ TO_CONN(exitconn)->state = EXIT_CONN_STATE_RESOLVING;
+ exitconn->base_.s = TOR_INVALID_SOCKET;
+
+ return exitconn;
+}
+
+#define NS_SUBMODULE ASPECT(resolve_impl, addr_is_ip_no_need_to_resolve)
+
+/*
+ * Given that <b>exitconn->base_.address</b> is IP address string, we
+ * want dns_resolve_impl() to parse it and store in
+ * <b>exitconn->base_.addr</b>. We expect dns_resolve_impl to return 1.
+ * Lastly, we want it to set the TTL value to default one for DNS queries.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending;
+ const tor_addr_t *resolved_addr;
+ tor_addr_t addr_to_compare;
+
+ (void)arg;
+
+ tor_addr_parse(&addr_to_compare, "8.8.8.8");
+
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+
+ TO_CONN(exitconn)->address = tor_strdup("8.8.8.8");
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ resolved_addr = &(exitconn->base_.addr);
+
+ tt_int_op(retval,==,1);
+ tt_assert(tor_addr_eq(resolved_addr, (const tor_addr_t *)&addr_to_compare));
+ tt_int_op(exitconn->address_ttl,==,DEFAULT_DNS_TTL);
+
+ done:
+ tor_free(on_circ);
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(exitconn);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, non_exit)
+
+/** Given that Tor instance is not configured as an exit node, we want
+ * dns_resolve_impl() to fail with return value -1.
+ */
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 1;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ (void)arg;
+
+ TO_CONN(exitconn)->address = tor_strdup("torproject.org");
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,-1);
+
+ done:
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(exitconn);
+ tor_free(on_circ);
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, addr_is_invalid_dest)
+
+/** Given that address is not a valid destination (as judged by
+ * address_is_invalid_destination() function), we want dns_resolve_impl()
+ * function to fail with return value -1.
+ */
+
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 0;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ (void)arg;
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+
+ TO_CONN(exitconn)->address = tor_strdup("invalid#@!.org");
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,-1);
+
+ done:
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(exitconn);
+ tor_free(on_circ);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, malformed_ptr)
+
+/** Given that address is a malformed PTR name, we want dns_resolve_impl to
+ * fail.
+ */
+
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 0;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ (void)arg;
+
+ TO_CONN(exitconn)->address = tor_strdup("1.0.0.127.in-addr.arpa");
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,-1);
+
+ tor_free(TO_CONN(exitconn)->address);
+
+ TO_CONN(exitconn)->address =
+ tor_strdup("z01234567890123456789.in-addr.arpa");
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,-1);
+
+ done:
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(exitconn);
+ tor_free(on_circ);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, cache_hit_pending)
+
+/* Given that there is already a pending resolve for the given address,
+ * we want dns_resolve_impl to append our exit connection to list
+ * of pending connections for the pending DNS request and return 0.
+ */
+
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 0;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending = 0;
+
+ pending_connection_t *pending_conn = NULL;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ cached_resolve_t *cache_entry = tor_malloc_zero(sizeof(cached_resolve_t));
+ cache_entry->magic = CACHED_RESOLVE_MAGIC;
+ cache_entry->state = CACHE_STATE_PENDING;
+ cache_entry->minheap_idx = -1;
+ cache_entry->expire = time(NULL) + 60 * 60;
+
+ (void)arg;
+
+ TO_CONN(exitconn)->address = tor_strdup("torproject.org");
+
+ strlcpy(cache_entry->address, TO_CONN(exitconn)->address,
+ sizeof(cache_entry->address));
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+
+ dns_init();
+
+ dns_insert_cache_entry(cache_entry);
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,0);
+ tt_int_op(made_pending,==,1);
+
+ pending_conn = cache_entry->pending_connections;
+
+ tt_assert(pending_conn != NULL);
+ tt_assert(pending_conn->conn == exitconn);
+
+ done:
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ tor_free(on_circ);
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(cache_entry->pending_connections);
+ tor_free(cache_entry);
+ tor_free(exitconn);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, cache_hit_cached)
+
+/* Given that a finished DNS resolve is available in our cache, we want
+ * dns_resolve_impl() return it to called via resolve_out and pass the
+ * handling to set_exitconn_info_from_resolve function.
+ */
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 0;
+}
+
+static edge_connection_t *last_exitconn = NULL;
+static cached_resolve_t *last_resolve = NULL;
+
+static int
+NS(set_exitconn_info_from_resolve)(edge_connection_t *exitconn,
+ const cached_resolve_t *resolve,
+ char **hostname_out)
+{
+ last_exitconn = exitconn;
+ last_resolve = (cached_resolve_t *)resolve;
+
+ (void)hostname_out;
+
+ return 0;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending = 0;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ cached_resolve_t *resolve_out = NULL;
+
+ cached_resolve_t *cache_entry = tor_malloc_zero(sizeof(cached_resolve_t));
+ cache_entry->magic = CACHED_RESOLVE_MAGIC;
+ cache_entry->state = CACHE_STATE_CACHED;
+ cache_entry->minheap_idx = -1;
+ cache_entry->expire = time(NULL) + 60 * 60;
+
+ (void)arg;
+
+ TO_CONN(exitconn)->address = tor_strdup("torproject.org");
+
+ strlcpy(cache_entry->address, TO_CONN(exitconn)->address,
+ sizeof(cache_entry->address));
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+ NS_MOCK(set_exitconn_info_from_resolve);
+
+ dns_init();
+
+ dns_insert_cache_entry(cache_entry);
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ &resolve_out);
+
+ tt_int_op(retval,==,0);
+ tt_int_op(made_pending,==,0);
+ tt_assert(resolve_out == cache_entry);
+
+ tt_assert(last_exitconn == exitconn);
+ tt_assert(last_resolve == cache_entry);
+
+ done:
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ NS_UNMOCK(set_exitconn_info_from_resolve);
+ tor_free(on_circ);
+ tor_free(TO_CONN(exitconn)->address);
+ tor_free(cache_entry->pending_connections);
+ tor_free(cache_entry);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE ASPECT(resolve_impl, cache_miss)
+
+/* Given that there are neither pending nor pre-cached resolve for a given
+ * address, we want dns_resolve_impl() to create a new cached_resolve_t
+ * object, mark it as pending, insert it into the cache, attach the exit
+ * connection to list of pending connections and call launch_resolve()
+ * with the cached_resolve_t object it created.
+ */
+static int
+NS(router_my_exit_policy_is_reject_star)(void)
+{
+ return 0;
+}
+
+static cached_resolve_t *last_launched_resolve = NULL;
+
+static int
+NS(launch_resolve)(cached_resolve_t *resolve)
+{
+ last_launched_resolve = resolve;
+
+ return 0;
+}
+
+static void
+NS(test_main)(void *arg)
+{
+ int retval;
+ int made_pending = 0;
+
+ pending_connection_t *pending_conn = NULL;
+
+ edge_connection_t *exitconn = create_valid_exitconn();
+ or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));
+
+ cached_resolve_t *cache_entry = NULL;
+ cached_resolve_t query;
+
+ (void)arg;
+
+ TO_CONN(exitconn)->address = tor_strdup("torproject.org");
+
+ strlcpy(query.address, TO_CONN(exitconn)->address, sizeof(query.address));
+
+ NS_MOCK(router_my_exit_policy_is_reject_star);
+ NS_MOCK(launch_resolve);
+
+ dns_init();
+
+ retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
+ NULL);
+
+ tt_int_op(retval,==,0);
+ tt_int_op(made_pending,==,1);
+
+ cache_entry = dns_get_cache_entry(&query);
+
+ tt_assert(cache_entry);
+
+ pending_conn = cache_entry->pending_connections;
+
+ tt_assert(pending_conn != NULL);
+ tt_assert(pending_conn->conn == exitconn);
+
+ tt_assert(last_launched_resolve == cache_entry);
+ tt_str_op(cache_entry->address,==,TO_CONN(exitconn)->address);
+
+ done:
+ NS_UNMOCK(router_my_exit_policy_is_reject_star);
+ NS_UNMOCK(launch_resolve);
+ tor_free(on_circ);
+ tor_free(TO_CONN(exitconn)->address);
+ if (cache_entry)
+ tor_free(cache_entry->pending_connections);
+ tor_free(cache_entry);
+ tor_free(exitconn);
+ return;
+}
+
+#undef NS_SUBMODULE
+
+struct testcase_t dns_tests[] = {
+ TEST_CASE(clip_ttl),
+ TEST_CASE(expiry_ttl),
+ TEST_CASE(resolve),
+ TEST_CASE_ASPECT(resolve_impl, addr_is_ip_no_need_to_resolve),
+ TEST_CASE_ASPECT(resolve_impl, non_exit),
+ TEST_CASE_ASPECT(resolve_impl, addr_is_invalid_dest),
+ TEST_CASE_ASPECT(resolve_impl, malformed_ptr),
+ TEST_CASE_ASPECT(resolve_impl, cache_hit_pending),
+ TEST_CASE_ASPECT(resolve_impl, cache_hit_cached),
+ TEST_CASE_ASPECT(resolve_impl, cache_miss),
+ END_OF_TESTCASES
+};
+
+#undef NS_MODULE
+
diff --git a/src/test/test_entryconn.c b/src/test/test_entryconn.c
new file mode 100644
index 0000000000..9580a1fd3f
--- /dev/null
+++ b/src/test/test_entryconn.c
@@ -0,0 +1,769 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+
+#define CONNECTION_PRIVATE
+#define CONNECTION_EDGE_PRIVATE
+
+#include "or.h"
+#include "test.h"
+
+#include "addressmap.h"
+#include "config.h"
+#include "confparse.h"
+#include "connection.h"
+#include "connection_edge.h"
+
+static void *
+entryconn_rewrite_setup(const struct testcase_t *tc)
+{
+ (void)tc;
+ entry_connection_t *ec = entry_connection_new(CONN_TYPE_AP, AF_INET);
+ addressmap_init();
+ return ec;
+}
+
+static int
+entryconn_rewrite_teardown(const struct testcase_t *tc, void *arg)
+{
+ (void)tc;
+ entry_connection_t *ec = arg;
+ if (ec)
+ connection_free_(ENTRY_TO_CONN(ec));
+ addressmap_free_all();
+ return 1;
+}
+
+static struct testcase_setup_t test_rewrite_setup = {
+ entryconn_rewrite_setup, entryconn_rewrite_teardown
+};
+
+/* Simple rewrite: no changes needed */
+static void
+test_entryconn_rewrite_basic(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+
+ tt_assert(ec->socks_request);
+ strlcpy(ec->socks_request->address, "www.TORproject.org",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.torproject.org");
+ tt_str_op(ec->socks_request->address, OP_EQ, "www.torproject.org");
+ tt_str_op(ec->original_dest_address, OP_EQ, "www.torproject.org");
+
+ done:
+ ;
+}
+
+/* Rewrite but reject because of disallowed .exit */
+static void
+test_entryconn_rewrite_bad_dotexit(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+
+ get_options_mutable()->AllowDotExit = 0;
+ tt_assert(ec->socks_request);
+ strlcpy(ec->socks_request->address, "www.TORproject.org.foo.exit",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 1);
+ tt_int_op(rr.end_reason, OP_EQ, END_STREAM_REASON_TORPROTOCOL);
+
+ done:
+ ;
+}
+
+/* Automap on resolve, connect to automapped address, resolve again and get
+ * same answer. (IPv4) */
+static void
+test_entryconn_rewrite_automap_ipv4(void *arg)
+{
+ entry_connection_t *ec = arg;
+ entry_connection_t *ec2=NULL, *ec3=NULL;
+ rewrite_result_t rr;
+ char *msg = NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+ ec3 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes, tor_strdup("."));
+ parse_virtual_addr_network("127.202.0.0/16", AF_INET, 0, &msg);
+
+ /* Automap this on resolve. */
+ strlcpy(ec->socks_request->address, "WWW.MIT.EDU",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.mit.edu");
+ tt_str_op(ec->original_dest_address, OP_EQ, "www.mit.edu");
+
+ tt_assert(!strcmpstart(ec->socks_request->address,"127.202."));
+
+ /* Connect to it and make sure we get the original address back. */
+ strlcpy(ec2->socks_request->address, ec->socks_request->address,
+ sizeof(ec2->socks_request->address));
+
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->original_dest_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->socks_request->address, OP_EQ, "www.mit.edu");
+
+ /* Resolve it again, make sure the answer is the same. */
+ strlcpy(ec3->socks_request->address, "www.MIT.EDU",
+ sizeof(ec3->socks_request->address));
+ ec3->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec3, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.mit.edu");
+ tt_str_op(ec3->original_dest_address, OP_EQ, "www.mit.edu");
+
+ tt_str_op(ec3->socks_request->address, OP_EQ,
+ ec->socks_request->address);
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+ connection_free_(ENTRY_TO_CONN(ec3));
+}
+
+/* Automap on resolve, connect to automapped address, resolve again and get
+ * same answer. (IPv6) */
+static void
+test_entryconn_rewrite_automap_ipv6(void *arg)
+{
+ (void)arg;
+ entry_connection_t *ec =NULL;
+ entry_connection_t *ec2=NULL, *ec3=NULL;
+ rewrite_result_t rr;
+ char *msg = NULL;
+
+ ec = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+ ec3 = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes, tor_strdup("."));
+ parse_virtual_addr_network("FE80::/32", AF_INET6, 0, &msg);
+
+ /* Automap this on resolve. */
+ strlcpy(ec->socks_request->address, "WWW.MIT.EDU",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.mit.edu");
+ tt_str_op(ec->original_dest_address, OP_EQ, "www.mit.edu");
+
+ /* Yes, this [ should be here. */
+ tt_assert(!strcmpstart(ec->socks_request->address,"[fe80:"));
+
+ /* Connect to it and make sure we get the original address back. */
+ strlcpy(ec2->socks_request->address, ec->socks_request->address,
+ sizeof(ec2->socks_request->address));
+
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->original_dest_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->socks_request->address, OP_EQ, "www.mit.edu");
+
+ /* Resolve it again, make sure the answer is the same. */
+ strlcpy(ec3->socks_request->address, "www.MIT.EDU",
+ sizeof(ec3->socks_request->address));
+ ec3->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec3, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.mit.edu");
+ tt_str_op(ec3->original_dest_address, OP_EQ, "www.mit.edu");
+
+ tt_str_op(ec3->socks_request->address, OP_EQ,
+ ec->socks_request->address);
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec));
+ connection_free_(ENTRY_TO_CONN(ec2));
+ connection_free_(ENTRY_TO_CONN(ec3));
+}
+
+#if 0
+/* FFFF not actually supported. */
+/* automap on resolve, reverse lookup. */
+static void
+test_entryconn_rewrite_automap_reverse(void *arg)
+{
+ entry_connection_t *ec = arg;
+ entry_connection_t *ec2=NULL;
+ rewrite_result_t rr;
+ char *msg = NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ get_options_mutable()->SafeLogging_ = SAFELOG_SCRUB_NONE;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes,
+ tor_strdup(".bloom"));
+ parse_virtual_addr_network("127.80.0.0/16", AF_INET, 0, &msg);
+
+ /* Automap this on resolve. */
+ strlcpy(ec->socks_request->address, "www.poldy.BLOOM",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.poldy.bloom");
+ tt_str_op(ec->original_dest_address, OP_EQ, "www.poldy.bloom");
+
+ tt_assert(!strcmpstart(ec->socks_request->address,"127.80."));
+
+ strlcpy(ec2->socks_request->address, ec->socks_request->address,
+ sizeof(ec2->socks_request->address));
+ ec2->socks_request->command = SOCKS_COMMAND_RESOLVE_PTR;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 1);
+ tt_int_op(rr.end_reason, OP_EQ,
+ END_STREAM_REASON_DONE|END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+}
+#endif
+
+/* Rewrite because of cached DNS entry. */
+static void
+test_entryconn_rewrite_cached_dns_ipv4(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+ time_t expires = time(NULL) + 3600;
+ entry_connection_t *ec2=NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ addressmap_register("www.friendly.example.com",
+ tor_strdup("240.240.241.241"),
+ expires,
+ ADDRMAPSRC_DNS,
+ 0, 0);
+
+ strlcpy(ec->socks_request->address, "www.friendly.example.com",
+ sizeof(ec->socks_request->address));
+ strlcpy(ec2->socks_request->address, "www.friendly.example.com",
+ sizeof(ec2->socks_request->address));
+
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+
+ ec2->entry_cfg.use_cached_ipv4_answers = 1; /* only ec2 gets this flag */
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.friendly.example.com");
+ tt_str_op(ec->socks_request->address, OP_EQ, "www.friendly.example.com");
+
+ connection_ap_handshake_rewrite(ec2, &rr);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, expires);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.friendly.example.com");
+ tt_str_op(ec2->socks_request->address, OP_EQ, "240.240.241.241");
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+}
+
+/* Rewrite because of cached DNS entry. */
+static void
+test_entryconn_rewrite_cached_dns_ipv6(void *arg)
+{
+ entry_connection_t *ec = NULL;
+ rewrite_result_t rr;
+ time_t expires = time(NULL) + 3600;
+ entry_connection_t *ec2=NULL;
+
+ (void)arg;
+
+ ec = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+
+ addressmap_register("www.friendly.example.com",
+ tor_strdup("[::f00f]"),
+ expires,
+ ADDRMAPSRC_DNS,
+ 0, 0);
+
+ strlcpy(ec->socks_request->address, "www.friendly.example.com",
+ sizeof(ec->socks_request->address));
+ strlcpy(ec2->socks_request->address, "www.friendly.example.com",
+ sizeof(ec2->socks_request->address));
+
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+
+ ec2->entry_cfg.use_cached_ipv6_answers = 1; /* only ec2 gets this flag */
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.friendly.example.com");
+ tt_str_op(ec->socks_request->address, OP_EQ, "www.friendly.example.com");
+
+ connection_ap_handshake_rewrite(ec2, &rr);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, expires);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "www.friendly.example.com");
+ tt_str_op(ec2->socks_request->address, OP_EQ, "[::f00f]");
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec));
+ connection_free_(ENTRY_TO_CONN(ec2));
+}
+
+/* Fail to connect to unmapped address in virtual range. */
+static void
+test_entryconn_rewrite_unmapped_virtual(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+ entry_connection_t *ec2 = NULL;
+ char *msg = NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET6);
+
+ parse_virtual_addr_network("18.202.0.0/16", AF_INET, 0, &msg);
+ parse_virtual_addr_network("[ABCD::]/16", AF_INET6, 0, &msg);
+
+ strlcpy(ec->socks_request->address, "18.202.5.5",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 1);
+ tt_int_op(rr.end_reason, OP_EQ, END_STREAM_REASON_INTERNAL);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+
+ strlcpy(ec2->socks_request->address, "[ABCD:9::5314:9543]",
+ sizeof(ec2->socks_request->address));
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 1);
+ tt_int_op(rr.end_reason, OP_EQ, END_STREAM_REASON_INTERNAL);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+}
+
+/* Rewrite because of mapaddress option */
+static void
+test_entryconn_rewrite_mapaddress(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+
+ config_line_append(&get_options_mutable()->AddressMap,
+ "MapAddress", "meta metaobjects.example");
+ config_register_addressmaps(get_options());
+
+ strlcpy(ec->socks_request->address, "meta",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(ec->socks_request->address, OP_EQ, "metaobjects.example");
+
+ done:
+ ;
+}
+
+/* Reject reverse lookups of internal address. */
+static void
+test_entryconn_rewrite_reject_internal_reverse(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+
+ strlcpy(ec->socks_request->address, "10.0.0.1",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_RESOLVE_PTR;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.should_close, OP_EQ, 1);
+ tt_int_op(rr.end_reason, OP_EQ, END_STREAM_REASON_SOCKSPROTOCOL |
+ END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+
+ done:
+ ;
+}
+
+/* Rewrite into .exit because of virtual address mapping */
+static void
+test_entryconn_rewrite_automap_exit(void *arg)
+{
+ entry_connection_t *ec = arg;
+ entry_connection_t *ec2=NULL;
+ rewrite_result_t rr;
+ char *msg = NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ get_options_mutable()->AllowDotExit = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes,
+ tor_strdup(".EXIT"));
+ parse_virtual_addr_network("127.1.0.0/16", AF_INET, 0, &msg);
+
+ /* Automap this on resolve. */
+ strlcpy(ec->socks_request->address, "website.example.exit",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "website.example.exit");
+ tt_str_op(ec->original_dest_address, OP_EQ, "website.example.exit");
+
+ tt_assert(!strcmpstart(ec->socks_request->address,"127.1."));
+
+ /* Connect to it and make sure we get the original address back. */
+ strlcpy(ec2->socks_request->address, ec->socks_request->address,
+ sizeof(ec2->socks_request->address));
+
+ ec2->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_AUTOMAP);
+ tt_str_op(rr.orig_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->original_dest_address, OP_EQ, ec->socks_request->address);
+ tt_str_op(ec2->socks_request->address, OP_EQ, "website.example.exit");
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+}
+
+/* Rewrite into .exit because of mapaddress */
+static void
+test_entryconn_rewrite_mapaddress_exit(void *arg)
+{
+ entry_connection_t *ec = arg;
+ rewrite_result_t rr;
+
+ config_line_append(&get_options_mutable()->AddressMap,
+ "MapAddress", "*.example.com *.example.com.abc.exit");
+ config_register_addressmaps(get_options());
+
+ /* Automap this on resolve. */
+ strlcpy(ec->socks_request->address, "abc.example.com",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_TORRC);
+ tt_str_op(rr.orig_address, OP_EQ, "abc.example.com");
+ tt_str_op(ec->socks_request->address, OP_EQ, "abc.example.com.abc.exit");
+ done:
+ ;
+}
+
+/* Map foo.onion to longthing.onion, and also automap. */
+static void
+test_entryconn_rewrite_mapaddress_automap_onion(void *arg)
+{
+ entry_connection_t *ec = arg;
+ entry_connection_t *ec2 = NULL;
+ entry_connection_t *ec3 = NULL;
+ entry_connection_t *ec4 = NULL;
+ rewrite_result_t rr;
+ char *msg = NULL;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+ ec3 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+ ec4 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ get_options_mutable()->AllowDotExit = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes,
+ tor_strdup(".onion"));
+ parse_virtual_addr_network("192.168.0.0/16", AF_INET, 0, &msg);
+ config_line_append(&get_options_mutable()->AddressMap,
+ "MapAddress", "foo.onion abcdefghijklmnop.onion");
+ config_register_addressmaps(get_options());
+
+ /* Connect to foo.onion. */
+ strlcpy(ec->socks_request->address, "foo.onion",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "foo.onion");
+ tt_str_op(ec->socks_request->address, OP_EQ, "abcdefghijklmnop.onion");
+
+ /* Okay, resolve foo.onion */
+ strlcpy(ec2->socks_request->address, "foo.onion",
+ sizeof(ec2->socks_request->address));
+ ec2->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "foo.onion");
+ tt_assert(!strcmpstart(ec2->socks_request->address, "192.168."));
+
+ /* Now connect */
+ strlcpy(ec3->socks_request->address, ec2->socks_request->address,
+ sizeof(ec3->socks_request->address));
+ ec3->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec3, &rr);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_assert(!strcmpstart(ec3->socks_request->address,
+ "abcdefghijklmnop.onion"));
+
+ /* Now resolve abcefghijklmnop.onion. */
+ strlcpy(ec4->socks_request->address, "abcdefghijklmnop.onion",
+ sizeof(ec4->socks_request->address));
+ ec4->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec4, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 1);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "abcdefghijklmnop.onion");
+ tt_assert(!strcmpstart(ec4->socks_request->address, "192.168."));
+ /* XXXX doesn't work
+ tt_str_op(ec4->socks_request->address, OP_EQ, ec2->socks_request->address);
+ */
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+ connection_free_(ENTRY_TO_CONN(ec3));
+ connection_free_(ENTRY_TO_CONN(ec4));
+}
+
+static void
+test_entryconn_rewrite_mapaddress_automap_onion_common(entry_connection_t *ec,
+ int map_to_onion,
+ int map_to_address)
+{
+ entry_connection_t *ec2 = NULL;
+ entry_connection_t *ec3 = NULL;
+ rewrite_result_t rr;
+
+ ec2 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+ ec3 = entry_connection_new(CONN_TYPE_AP, AF_INET);
+
+ /* Connect to irc.example.com */
+ strlcpy(ec->socks_request->address, "irc.example.com",
+ sizeof(ec->socks_request->address));
+ ec->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "irc.example.com");
+ tt_str_op(ec->socks_request->address, OP_EQ,
+ map_to_onion ? "abcdefghijklmnop.onion" : "irc.example.com");
+
+ /* Okay, resolve irc.example.com */
+ strlcpy(ec2->socks_request->address, "irc.example.com",
+ sizeof(ec2->socks_request->address));
+ ec2->socks_request->command = SOCKS_COMMAND_RESOLVE;
+ connection_ap_handshake_rewrite(ec2, &rr);
+
+ tt_int_op(rr.automap, OP_EQ, map_to_onion && map_to_address);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ tt_i64_op(rr.map_expires, OP_EQ, TIME_MAX);
+ tt_int_op(rr.exit_source, OP_EQ, ADDRMAPSRC_NONE);
+ tt_str_op(rr.orig_address, OP_EQ, "irc.example.com");
+ if (map_to_onion && map_to_address)
+ tt_assert(!strcmpstart(ec2->socks_request->address, "192.168."));
+
+ /* Now connect */
+ strlcpy(ec3->socks_request->address, ec2->socks_request->address,
+ sizeof(ec3->socks_request->address));
+ ec3->socks_request->command = SOCKS_COMMAND_CONNECT;
+ connection_ap_handshake_rewrite(ec3, &rr);
+ tt_int_op(rr.automap, OP_EQ, 0);
+ tt_int_op(rr.should_close, OP_EQ, 0);
+ tt_int_op(rr.end_reason, OP_EQ, 0);
+ if (map_to_onion)
+ tt_assert(!strcmpstart(ec3->socks_request->address,
+ "abcdefghijklmnop.onion"));
+
+ done:
+ connection_free_(ENTRY_TO_CONN(ec2));
+ connection_free_(ENTRY_TO_CONN(ec3));
+}
+
+/* This time is the same, but we start with a mapping from a non-onion
+ * address. */
+static void
+test_entryconn_rewrite_mapaddress_automap_onion2(void *arg)
+{
+ char *msg = NULL;
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes,
+ tor_strdup(".onion"));
+ parse_virtual_addr_network("192.168.0.0/16", AF_INET, 0, &msg);
+ config_line_append(&get_options_mutable()->AddressMap,
+ "MapAddress", "irc.example.com abcdefghijklmnop.onion");
+ config_register_addressmaps(get_options());
+
+ test_entryconn_rewrite_mapaddress_automap_onion_common(arg, 1, 1);
+}
+
+/* Same as above, with automapped turned off */
+static void
+test_entryconn_rewrite_mapaddress_automap_onion3(void *arg)
+{
+ config_line_append(&get_options_mutable()->AddressMap,
+ "MapAddress", "irc.example.com abcdefghijklmnop.onion");
+ config_register_addressmaps(get_options());
+
+ test_entryconn_rewrite_mapaddress_automap_onion_common(arg, 1, 0);
+}
+
+/* As above, with no mapping. */
+static void
+test_entryconn_rewrite_mapaddress_automap_onion4(void *arg)
+{
+ char *msg = NULL;
+ get_options_mutable()->AutomapHostsOnResolve = 1;
+ smartlist_add(get_options_mutable()->AutomapHostsSuffixes,
+ tor_strdup(".onion"));
+ parse_virtual_addr_network("192.168.0.0/16", AF_INET, 0, &msg);
+
+ test_entryconn_rewrite_mapaddress_automap_onion_common(arg, 0, 1);
+}
+
+#define REWRITE(name) \
+ { #name, test_entryconn_##name, TT_FORK, &test_rewrite_setup, NULL }
+
+struct testcase_t entryconn_tests[] = {
+ REWRITE(rewrite_basic),
+ REWRITE(rewrite_bad_dotexit),
+ REWRITE(rewrite_automap_ipv4),
+ REWRITE(rewrite_automap_ipv6),
+ // REWRITE(rewrite_automap_reverse),
+ REWRITE(rewrite_cached_dns_ipv4),
+ REWRITE(rewrite_cached_dns_ipv6),
+ REWRITE(rewrite_unmapped_virtual),
+ REWRITE(rewrite_mapaddress),
+ REWRITE(rewrite_reject_internal_reverse),
+ REWRITE(rewrite_automap_exit),
+ REWRITE(rewrite_mapaddress_exit),
+ REWRITE(rewrite_mapaddress_automap_onion),
+ REWRITE(rewrite_mapaddress_automap_onion2),
+ REWRITE(rewrite_mapaddress_automap_onion3),
+ REWRITE(rewrite_mapaddress_automap_onion4),
+
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_entrynodes.c b/src/test/test_entrynodes.c
new file mode 100644
index 0000000000..b1c3accfab
--- /dev/null
+++ b/src/test/test_entrynodes.c
@@ -0,0 +1,875 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+
+#define STATEFILE_PRIVATE
+#define ENTRYNODES_PRIVATE
+#define ROUTERLIST_PRIVATE
+
+#include "or.h"
+#include "test.h"
+
+#include "config.h"
+#include "entrynodes.h"
+#include "nodelist.h"
+#include "policies.h"
+#include "routerlist.h"
+#include "routerparse.h"
+#include "routerset.h"
+#include "statefile.h"
+#include "util.h"
+
+#include "test_helpers.h"
+
+/* TODO:
+ * choose_random_entry() test with state set.
+ *
+ * parse_state() tests with more than one guards.
+ *
+ * More tests for set_from_config(): Multiple nodes, use fingerprints,
+ * use country codes.
+ */
+
+/** Dummy Tor state used in unittests. */
+static or_state_t *dummy_state = NULL;
+static or_state_t *
+get_or_state_replacement(void)
+{
+ return dummy_state;
+}
+
+/* Unittest cleanup function: Cleanup the fake network. */
+static int
+fake_network_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ (void) testcase;
+ (void) ptr;
+
+ routerlist_free_all();
+ nodelist_free_all();
+ entry_guards_free_all();
+ or_state_free(dummy_state);
+
+ return 1; /* NOP */
+}
+
+/* Unittest setup function: Setup a fake network. */
+static void *
+fake_network_setup(const struct testcase_t *testcase)
+{
+ (void) testcase;
+
+ /* Setup fake state */
+ dummy_state = tor_malloc_zero(sizeof(or_state_t));
+ MOCK(get_or_state,
+ get_or_state_replacement);
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ /* Return anything but NULL (it's interpreted as test fail) */
+ return dummy_state;
+}
+
+static or_options_t mocked_options;
+
+static const or_options_t *
+mock_get_options(void)
+{
+ return &mocked_options;
+}
+
+/** Test choose_random_entry() with none of our routers being guard nodes. */
+static void
+test_choose_random_entry_no_guards(void *arg)
+{
+ const node_t *chosen_entry = NULL;
+
+ (void) arg;
+
+ MOCK(get_options, mock_get_options);
+
+ /* Check that we get a guard if it passes preferred
+ * address settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientPreferIPv6ORPort = 0;
+
+ /* Try to pick an entry even though none of our routers are guards. */
+ chosen_entry = choose_random_entry(NULL);
+
+ /* Unintuitively, we actually pick a random node as our entry,
+ because router_choose_random_node() relaxes its constraints if it
+ can't find a proper entry guard. */
+ tt_assert(chosen_entry);
+
+ /* And with the other IP version active */
+ mocked_options.ClientUseIPv6 = 1;
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ /* And with the preference on auto */
+ mocked_options.ClientPreferIPv6ORPort = -1;
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ /* Check that we don't get a guard if it doesn't pass mandatory address
+ * settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 0;
+ mocked_options.ClientPreferIPv6ORPort = 0;
+
+ chosen_entry = choose_random_entry(NULL);
+
+ /* If we don't allow IPv4 at all, we don't get a guard*/
+ tt_assert(!chosen_entry);
+
+ /* Check that we get a guard if it passes allowed but not preferred address
+ * settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientUseIPv6 = 1;
+ mocked_options.ClientPreferIPv6ORPort = 1;
+
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ /* Check that we get a guard if it passes preferred address settings when
+ * they're auto */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientPreferIPv6ORPort = -1;
+
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ /* And with IPv6 active */
+ mocked_options.ClientUseIPv6 = 1;
+
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ done:
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ UNMOCK(get_options);
+}
+
+/** Test choose_random_entry() with only one of our routers being a
+ guard node. */
+static void
+test_choose_random_entry_one_possible_guard(void *arg)
+{
+ const node_t *chosen_entry = NULL;
+ node_t *the_guard = NULL;
+ smartlist_t *our_nodelist = NULL;
+
+ (void) arg;
+
+ MOCK(get_options, mock_get_options);
+
+ /* Set one of the nodes to be a guard. */
+ our_nodelist = nodelist_get_list();
+ the_guard = smartlist_get(our_nodelist, 4); /* chosen by fair dice roll */
+ the_guard->is_possible_guard = 1;
+
+ /* Check that we get the guard if it passes preferred
+ * address settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientPreferIPv6ORPort = 0;
+
+ /* Pick an entry. Make sure we pick the node we marked as guard. */
+ chosen_entry = choose_random_entry(NULL);
+ tt_ptr_op(chosen_entry, OP_EQ, the_guard);
+
+ /* And with the other IP version active */
+ mocked_options.ClientUseIPv6 = 1;
+ chosen_entry = choose_random_entry(NULL);
+ tt_ptr_op(chosen_entry, OP_EQ, the_guard);
+
+ /* And with the preference on auto */
+ mocked_options.ClientPreferIPv6ORPort = -1;
+ chosen_entry = choose_random_entry(NULL);
+ tt_ptr_op(chosen_entry, OP_EQ, the_guard);
+
+ /* Check that we don't get a guard if it doesn't pass mandatory address
+ * settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 0;
+ mocked_options.ClientPreferIPv6ORPort = 0;
+
+ chosen_entry = choose_random_entry(NULL);
+
+ /* If we don't allow IPv4 at all, we don't get a guard*/
+ tt_assert(!chosen_entry);
+
+ /* Check that we get a node if it passes allowed but not preferred
+ * address settings */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientUseIPv6 = 1;
+ mocked_options.ClientPreferIPv6ORPort = 1;
+
+ chosen_entry = choose_random_entry(NULL);
+
+ /* We disable the guard check and the preferred address check at the same
+ * time, so we can't be sure we get the guard */
+ tt_assert(chosen_entry);
+
+ /* Check that we get a node if it is allowed but not preferred when settings
+ * are auto */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientPreferIPv6ORPort = -1;
+
+ chosen_entry = choose_random_entry(NULL);
+
+ /* We disable the guard check and the preferred address check at the same
+ * time, so we can't be sure we get the guard */
+ tt_assert(chosen_entry);
+
+ /* and with IPv6 active */
+ mocked_options.ClientUseIPv6 = 1;
+
+ chosen_entry = choose_random_entry(NULL);
+ tt_assert(chosen_entry);
+
+ done:
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ UNMOCK(get_options);
+}
+
+/** Helper to conduct tests for populate_live_entry_guards().
+
+ This test adds some entry guards to our list, and then tests
+ populate_live_entry_guards() to mke sure it filters them correctly.
+
+ <b>num_needed</b> is the number of guard nodes we support. It's
+ configurable to make sure we function properly with 1 or 3 guard
+ nodes configured.
+*/
+static void
+populate_live_entry_guards_test_helper(int num_needed)
+{
+ smartlist_t *our_nodelist = NULL;
+ smartlist_t *live_entry_guards = smartlist_new();
+ const smartlist_t *all_entry_guards = get_entry_guards();
+ or_options_t *options = get_options_mutable();
+ int retval;
+
+ /* Set NumEntryGuards to the provided number. */
+ options->NumEntryGuards = num_needed;
+ tt_int_op(num_needed, OP_EQ, decide_num_guards(options, 0));
+
+ /* The global entry guards smartlist should be empty now. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 0);
+
+ /* Walk the nodelist and add all nodes as entry guards. */
+ our_nodelist = nodelist_get_list();
+ tt_int_op(smartlist_len(our_nodelist), OP_EQ, HELPER_NUMBER_OF_DESCRIPTORS);
+
+ SMARTLIST_FOREACH_BEGIN(our_nodelist, const node_t *, node) {
+ const node_t *node_tmp;
+ node_tmp = add_an_entry_guard(node, 0, 1, 0, 0);
+ tt_assert(node_tmp);
+ } SMARTLIST_FOREACH_END(node);
+
+ /* Make sure the nodes were added as entry guards. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ,
+ HELPER_NUMBER_OF_DESCRIPTORS);
+
+ /* Ensure that all the possible entry guards are enough to satisfy us. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_GE, num_needed);
+
+ /* Walk the entry guard list for some sanity checking */
+ SMARTLIST_FOREACH_BEGIN(all_entry_guards, const entry_guard_t *, entry) {
+ /* Since we called add_an_entry_guard() with 'for_discovery' being
+ False, all guards should have made_contact enabled. */
+ tt_int_op(entry->made_contact, OP_EQ, 1);
+
+ } SMARTLIST_FOREACH_END(entry);
+
+ /* First, try to get some fast guards. This should fail. */
+ retval = populate_live_entry_guards(live_entry_guards,
+ all_entry_guards,
+ NULL,
+ NO_DIRINFO, /* Don't care about DIRINFO*/
+ 0, 0,
+ 1); /* We want fast guard! */
+ tt_int_op(retval, OP_EQ, 0);
+ tt_int_op(smartlist_len(live_entry_guards), OP_EQ, 0);
+
+ /* Now try to get some stable guards. This should fail too. */
+ retval = populate_live_entry_guards(live_entry_guards,
+ all_entry_guards,
+ NULL,
+ NO_DIRINFO,
+ 0,
+ 1, /* We want stable guard! */
+ 0);
+ tt_int_op(retval, OP_EQ, 0);
+ tt_int_op(smartlist_len(live_entry_guards), OP_EQ, 0);
+
+ /* Now try to get any guard we can find. This should succeed. */
+ retval = populate_live_entry_guards(live_entry_guards,
+ all_entry_guards,
+ NULL,
+ NO_DIRINFO,
+ 0, 0, 0); /* No restrictions! */
+
+ /* Since we had more than enough guards in 'all_entry_guards', we
+ should have added 'num_needed' of them to live_entry_guards.
+ 'retval' should be 1 since we now have enough live entry guards
+ to pick one. */
+ tt_int_op(retval, OP_EQ, 1);
+ tt_int_op(smartlist_len(live_entry_guards), OP_EQ, num_needed);
+
+ done:
+ smartlist_free(live_entry_guards);
+}
+
+/* Test populate_live_entry_guards() for 1 guard node. */
+static void
+test_populate_live_entry_guards_1guard(void *arg)
+{
+ (void) arg;
+
+ populate_live_entry_guards_test_helper(1);
+}
+
+/* Test populate_live_entry_guards() for 3 guard nodes. */
+static void
+test_populate_live_entry_guards_3guards(void *arg)
+{
+ (void) arg;
+
+ populate_live_entry_guards_test_helper(3);
+}
+
+/** Append some EntryGuard lines to the Tor state at <b>state</b>.
+
+ <b>entry_guard_lines</b> is a smartlist containing 2-tuple
+ smartlists that carry the key and values of the statefile.
+ As an example:
+ entry_guard_lines =
+ (("EntryGuard", "name 67E72FF33D7D41BF11C569646A0A7B4B188340DF DirCache"),
+ ("EntryGuardDownSince", "2014-06-07 16:02:46 2014-06-07 16:02:46"))
+*/
+static void
+state_insert_entry_guard_helper(or_state_t *state,
+ smartlist_t *entry_guard_lines)
+{
+ config_line_t **next, *line;
+
+ next = &state->EntryGuards;
+ *next = NULL;
+
+ /* Loop over all the state lines in the smartlist */
+ SMARTLIST_FOREACH_BEGIN(entry_guard_lines, const smartlist_t *,state_lines) {
+ /* Get key and value for each line */
+ const char *state_key = smartlist_get(state_lines, 0);
+ const char *state_value = smartlist_get(state_lines, 1);
+
+ *next = line = tor_malloc_zero(sizeof(config_line_t));
+ line->key = tor_strdup(state_key);
+ tor_asprintf(&line->value, "%s", state_value);
+ next = &(line->next);
+ } SMARTLIST_FOREACH_END(state_lines);
+}
+
+/** Free memory occupied by <b>entry_guard_lines</b>. */
+static void
+state_lines_free(smartlist_t *entry_guard_lines)
+{
+ SMARTLIST_FOREACH_BEGIN(entry_guard_lines, smartlist_t *, state_lines) {
+ char *state_key = smartlist_get(state_lines, 0);
+ char *state_value = smartlist_get(state_lines, 1);
+
+ tor_free(state_key);
+ tor_free(state_value);
+ smartlist_free(state_lines);
+ } SMARTLIST_FOREACH_END(state_lines);
+
+ smartlist_free(entry_guard_lines);
+}
+
+/* Tests entry_guards_parse_state(). It creates a fake Tor state with
+ a saved entry guard and makes sure that Tor can parse it and
+ creates the right entry node out of it.
+*/
+static void
+test_entry_guards_parse_state_simple(void *arg)
+{
+ or_state_t *state = or_state_new();
+ const smartlist_t *all_entry_guards = get_entry_guards();
+ smartlist_t *entry_state_lines = smartlist_new();
+ char *msg = NULL;
+ int retval;
+
+ /* Details of our fake guard node */
+ const char *nickname = "hagbard";
+ const char *fpr = "B29D536DD1752D542E1FBB3C9CE4449D51298212";
+ const char *tor_version = "0.2.5.3-alpha-dev";
+ const char *added_at = get_yesterday_date_str();
+ const char *unlisted_since = "2014-06-08 16:16:50";
+
+ (void) arg;
+
+ /* The global entry guards smartlist should be empty now. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 0);
+
+ { /* Prepare the state entry */
+
+ /* Prepare the smartlist to hold the key/value of each line */
+ smartlist_t *state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuard");
+ smartlist_add_asprintf(state_line, "%s %s %s", nickname, fpr, "DirCache");
+ smartlist_add(entry_state_lines, state_line);
+
+ state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuardAddedBy");
+ smartlist_add_asprintf(state_line, "%s %s %s", fpr, tor_version, added_at);
+ smartlist_add(entry_state_lines, state_line);
+
+ state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuardUnlistedSince");
+ smartlist_add_asprintf(state_line, "%s", unlisted_since);
+ smartlist_add(entry_state_lines, state_line);
+ }
+
+ /* Inject our lines in the state */
+ state_insert_entry_guard_helper(state, entry_state_lines);
+
+ /* Parse state */
+ retval = entry_guards_parse_state(state, 1, &msg);
+ tt_int_op(retval, OP_GE, 0);
+
+ /* Test that the guard was registered.
+ We need to re-get the entry guard list since its pointer was
+ overwritten in entry_guards_parse_state(). */
+ all_entry_guards = get_entry_guards();
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 1);
+
+ { /* Test the entry guard structure */
+ char hex_digest[1024];
+ char str_time[1024];
+
+ const entry_guard_t *e = smartlist_get(all_entry_guards, 0);
+ tt_str_op(e->nickname, OP_EQ, nickname); /* Verify nickname */
+
+ base16_encode(hex_digest, sizeof(hex_digest),
+ e->identity, DIGEST_LEN);
+ tt_str_op(hex_digest, OP_EQ, fpr); /* Verify fingerprint */
+
+ tt_assert(e->is_dir_cache); /* Verify dirness */
+
+ tt_str_op(e->chosen_by_version, OP_EQ, tor_version); /* Verify version */
+
+ tt_assert(e->made_contact); /* All saved guards have been contacted */
+
+ tt_assert(e->bad_since); /* Verify bad_since timestamp */
+ format_iso_time(str_time, e->bad_since);
+ tt_str_op(str_time, OP_EQ, unlisted_since);
+
+ /* The rest should be unset */
+ tt_assert(!e->unreachable_since);
+ tt_assert(!e->can_retry);
+ tt_assert(!e->path_bias_noticed);
+ tt_assert(!e->path_bias_warned);
+ tt_assert(!e->path_bias_extreme);
+ tt_assert(!e->path_bias_disabled);
+ tt_assert(!e->path_bias_use_noticed);
+ tt_assert(!e->path_bias_use_extreme);
+ tt_assert(!e->last_attempted);
+ }
+
+ done:
+ state_lines_free(entry_state_lines);
+ or_state_free(state);
+ tor_free(msg);
+}
+
+/** Similar to test_entry_guards_parse_state_simple() but aims to test
+ the PathBias-related details of the entry guard. */
+static void
+test_entry_guards_parse_state_pathbias(void *arg)
+{
+ or_state_t *state = or_state_new();
+ const smartlist_t *all_entry_guards = get_entry_guards();
+ char *msg = NULL;
+ int retval;
+ smartlist_t *entry_state_lines = smartlist_new();
+
+ /* Path bias details of the fake guard */
+ const double circ_attempts = 9;
+ const double circ_successes = 8;
+ const double successful_closed = 4;
+ const double collapsed = 2;
+ const double unusable = 0;
+ const double timeouts = 1;
+
+ (void) arg;
+
+ /* The global entry guards smartlist should be empty now. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 0);
+
+ { /* Prepare the state entry */
+
+ /* Prepare the smartlist to hold the key/value of each line */
+ smartlist_t *state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuard");
+ smartlist_add_asprintf(state_line,
+ "givethanks B29D536DD1752D542E1FBB3C9CE4449D51298212 NoDirCache");
+ smartlist_add(entry_state_lines, state_line);
+
+ state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuardAddedBy");
+ smartlist_add_asprintf(state_line,
+ "B29D536DD1752D542E1FBB3C9CE4449D51298212 0.2.5.3-alpha-dev "
+ "%s", get_yesterday_date_str());
+ smartlist_add(entry_state_lines, state_line);
+
+ state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuardUnlistedSince");
+ smartlist_add_asprintf(state_line, "2014-06-08 16:16:50");
+ smartlist_add(entry_state_lines, state_line);
+
+ state_line = smartlist_new();
+ smartlist_add_asprintf(state_line, "EntryGuardPathBias");
+ smartlist_add_asprintf(state_line, "%f %f %f %f %f %f",
+ circ_attempts, circ_successes, successful_closed,
+ collapsed, unusable, timeouts);
+ smartlist_add(entry_state_lines, state_line);
+ }
+
+ /* Inject our lines in the state */
+ state_insert_entry_guard_helper(state, entry_state_lines);
+
+ /* Parse state */
+ retval = entry_guards_parse_state(state, 1, &msg);
+ tt_int_op(retval, OP_GE, 0);
+
+ /* Test that the guard was registered */
+ all_entry_guards = get_entry_guards();
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 1);
+
+ { /* Test the path bias of this guard */
+ const entry_guard_t *e = smartlist_get(all_entry_guards, 0);
+
+ tt_assert(!e->is_dir_cache);
+ tt_assert(!e->can_retry);
+
+ /* XXX tt_double_op doesn't support equality. Cast to int for now. */
+ tt_int_op((int)e->circ_attempts, OP_EQ, (int)circ_attempts);
+ tt_int_op((int)e->circ_successes, OP_EQ, (int)circ_successes);
+ tt_int_op((int)e->successful_circuits_closed, OP_EQ,
+ (int)successful_closed);
+ tt_int_op((int)e->timeouts, OP_EQ, (int)timeouts);
+ tt_int_op((int)e->collapsed_circuits, OP_EQ, (int)collapsed);
+ tt_int_op((int)e->unusable_circuits, OP_EQ, (int)unusable);
+ }
+
+ done:
+ or_state_free(state);
+ state_lines_free(entry_state_lines);
+ tor_free(msg);
+}
+
+/* Simple test of entry_guards_set_from_config() by specifying a
+ particular EntryNode and making sure it gets picked. */
+static void
+test_entry_guards_set_from_config(void *arg)
+{
+ or_options_t *options = get_options_mutable();
+ const smartlist_t *all_entry_guards = get_entry_guards();
+ const char *entrynodes_str = "test003r";
+ const node_t *chosen_entry = NULL;
+ int retval;
+
+ (void) arg;
+
+ /* Prase EntryNodes as a routerset. */
+ options->EntryNodes = routerset_new();
+ retval = routerset_parse(options->EntryNodes,
+ entrynodes_str,
+ "test_entrynodes");
+ tt_int_op(retval, OP_GE, 0);
+
+ /* Read nodes from EntryNodes */
+ entry_guards_set_from_config(options);
+
+ /* Test that only one guard was added. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 1);
+
+ /* Make sure it was the guard we specified. */
+ chosen_entry = choose_random_entry(NULL);
+ tt_str_op(chosen_entry->ri->nickname, OP_EQ, entrynodes_str);
+
+ done:
+ routerset_free(options->EntryNodes);
+}
+
+static void
+test_entry_is_time_to_retry(void *arg)
+{
+ entry_guard_t *test_guard;
+ time_t now;
+ int retval;
+ (void)arg;
+
+ now = time(NULL);
+
+ test_guard = tor_malloc_zero(sizeof(entry_guard_t));
+
+ test_guard->last_attempted = now - 10;
+ test_guard->unreachable_since = now - 1;
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->unreachable_since = now - (6*60*60 - 1);
+ test_guard->last_attempted = now - (60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->last_attempted = now - (60*60 - 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,0);
+
+ test_guard->unreachable_since = now - (6*60*60 + 1);
+ test_guard->last_attempted = now - (4*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->unreachable_since = now - (3*24*60*60 - 1);
+ test_guard->last_attempted = now - (4*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->unreachable_since = now - (3*24*60*60 + 1);
+ test_guard->last_attempted = now - (18*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->unreachable_since = now - (7*24*60*60 - 1);
+ test_guard->last_attempted = now - (18*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->last_attempted = now - (18*60*60 - 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,0);
+
+ test_guard->unreachable_since = now - (7*24*60*60 + 1);
+ test_guard->last_attempted = now - (36*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ test_guard->unreachable_since = now - (7*24*60*60 + 1);
+ test_guard->last_attempted = now - (36*60*60 + 1);
+
+ retval = entry_is_time_to_retry(test_guard,now);
+ tt_int_op(retval,OP_EQ,1);
+
+ done:
+ tor_free(test_guard);
+}
+
+/** XXX Do some tests that entry_is_live() */
+static void
+test_entry_is_live(void *arg)
+{
+ smartlist_t *our_nodelist = NULL;
+ const smartlist_t *all_entry_guards = get_entry_guards();
+ const node_t *test_node = NULL;
+ const entry_guard_t *test_entry = NULL;
+ const char *msg;
+ int which_node;
+
+ (void) arg;
+
+ /* The global entry guards smartlist should be empty now. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ, 0);
+
+ /* Walk the nodelist and add all nodes as entry guards. */
+ our_nodelist = nodelist_get_list();
+ tt_int_op(smartlist_len(our_nodelist), OP_EQ, HELPER_NUMBER_OF_DESCRIPTORS);
+
+ SMARTLIST_FOREACH_BEGIN(our_nodelist, const node_t *, node) {
+ const node_t *node_tmp;
+ node_tmp = add_an_entry_guard(node, 0, 1, 0, 0);
+ tt_assert(node_tmp);
+
+ tt_int_op(node->is_stable, OP_EQ, 0);
+ tt_int_op(node->is_fast, OP_EQ, 0);
+ } SMARTLIST_FOREACH_END(node);
+
+ /* Make sure the nodes were added as entry guards. */
+ tt_int_op(smartlist_len(all_entry_guards), OP_EQ,
+ HELPER_NUMBER_OF_DESCRIPTORS);
+
+ /* Now get a random test entry that we will use for this unit test. */
+ which_node = 3; /* (chosen by fair dice roll) */
+ test_entry = smartlist_get(all_entry_guards, which_node);
+
+ /* Let's do some entry_is_live() tests! */
+
+ /* Require the node to be stable, but it's not. Should fail.
+ Also enable 'assume_reachable' because why not. */
+ test_node = entry_is_live(test_entry,
+ ENTRY_NEED_UPTIME | ENTRY_ASSUME_REACHABLE,
+ &msg);
+ tt_assert(!test_node);
+
+ /* Require the node to be fast, but it's not. Should fail. */
+ test_node = entry_is_live(test_entry,
+ ENTRY_NEED_CAPACITY | ENTRY_ASSUME_REACHABLE,
+ &msg);
+ tt_assert(!test_node);
+
+ /* Don't impose any restrictions on the node. Should succeed. */
+ test_node = entry_is_live(test_entry, 0, &msg);
+ tt_assert(test_node);
+ tt_ptr_op(test_node, OP_EQ, node_get_by_id(test_entry->identity));
+
+ /* Require descriptor for this node. It has one so it should succeed. */
+ test_node = entry_is_live(test_entry, ENTRY_NEED_DESCRIPTOR, &msg);
+ tt_assert(test_node);
+ tt_ptr_op(test_node, OP_EQ, node_get_by_id(test_entry->identity));
+
+ done:
+ ; /* XXX */
+}
+
+#define TEST_IPV4_ADDR "123.45.67.89"
+#define TEST_IPV6_ADDR "[1234:5678:90ab:cdef::]"
+
+static void
+test_node_preferred_orport(void *arg)
+{
+ (void)arg;
+ tor_addr_t ipv4_addr;
+ const uint16_t ipv4_port = 4444;
+ tor_addr_t ipv6_addr;
+ const uint16_t ipv6_port = 6666;
+ routerinfo_t node_ri;
+ node_t node;
+ tor_addr_port_t ap;
+
+ /* Setup options */
+ memset(&mocked_options, 0, sizeof(mocked_options));
+ /* We don't test ClientPreferIPv6ORPort here, because it's used in
+ * nodelist_set_consensus to setup node.ipv6_preferred, which we set
+ * directly. */
+ MOCK(get_options, mock_get_options);
+
+ /* Setup IP addresses */
+ tor_addr_parse(&ipv4_addr, TEST_IPV4_ADDR);
+ tor_addr_parse(&ipv6_addr, TEST_IPV6_ADDR);
+
+ /* Setup node_ri */
+ memset(&node_ri, 0, sizeof(node_ri));
+ node_ri.addr = tor_addr_to_ipv4h(&ipv4_addr);
+ node_ri.or_port = ipv4_port;
+ tor_addr_copy(&node_ri.ipv6_addr, &ipv6_addr);
+ node_ri.ipv6_orport = ipv6_port;
+
+ /* Setup node */
+ memset(&node, 0, sizeof(node));
+ node.ri = &node_ri;
+
+ /* Check the preferred address is IPv4 if we're only using IPv4, regardless
+ * of whether we prefer it or not */
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientUseIPv6 = 0;
+ node.ipv6_preferred = 0;
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
+ tt_assert(ap.port == ipv4_port);
+
+ node.ipv6_preferred = 1;
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
+ tt_assert(ap.port == ipv4_port);
+
+ /* Check the preferred address is IPv4 if we're using IPv4 and IPv6, but
+ * don't prefer the IPv6 address */
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientUseIPv6 = 1;
+ node.ipv6_preferred = 0;
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
+ tt_assert(ap.port == ipv4_port);
+
+ /* Check the preferred address is IPv6 if we prefer it and
+ * ClientUseIPv6 is 1, regardless of ClientUseIPv4 */
+ mocked_options.ClientUseIPv4 = 1;
+ mocked_options.ClientUseIPv6 = 1;
+ node.ipv6_preferred = 1;
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
+ tt_assert(ap.port == ipv6_port);
+
+ mocked_options.ClientUseIPv4 = 0;
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
+ tt_assert(ap.port == ipv6_port);
+
+ /* Check the preferred address is IPv6 if we don't prefer it, but
+ * ClientUseIPv4 is 0 */
+ mocked_options.ClientUseIPv4 = 0;
+ mocked_options.ClientUseIPv6 = 1;
+ node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(&mocked_options);
+ node_get_pref_orport(&node, &ap);
+ tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
+ tt_assert(ap.port == ipv6_port);
+
+ done:
+ UNMOCK(get_options);
+}
+
+static const struct testcase_setup_t fake_network = {
+ fake_network_setup, fake_network_cleanup
+};
+
+struct testcase_t entrynodes_tests[] = {
+ { "entry_is_time_to_retry", test_entry_is_time_to_retry,
+ TT_FORK, NULL, NULL },
+ { "choose_random_entry_no_guards", test_choose_random_entry_no_guards,
+ TT_FORK, &fake_network, NULL },
+ { "choose_random_entry_one_possibleguard",
+ test_choose_random_entry_one_possible_guard,
+ TT_FORK, &fake_network, NULL },
+ { "populate_live_entry_guards_1guard",
+ test_populate_live_entry_guards_1guard,
+ TT_FORK, &fake_network, NULL },
+ { "populate_live_entry_guards_3guards",
+ test_populate_live_entry_guards_3guards,
+ TT_FORK, &fake_network, NULL },
+ { "entry_guards_parse_state_simple",
+ test_entry_guards_parse_state_simple,
+ TT_FORK, &fake_network, NULL },
+ { "entry_guards_parse_state_pathbias",
+ test_entry_guards_parse_state_pathbias,
+ TT_FORK, &fake_network, NULL },
+ { "entry_guards_set_from_config",
+ test_entry_guards_set_from_config,
+ TT_FORK, &fake_network, NULL },
+ { "entry_is_live",
+ test_entry_is_live,
+ TT_FORK, &fake_network, NULL },
+ { "node_preferred_orport",
+ test_node_preferred_orport,
+ 0, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_extorport.c b/src/test/test_extorport.c
index 93c8f77d5b..1f92780177 100644
--- a/src/test/test_extorport.c
+++ b/src/test/test_extorport.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define CONNECTION_PRIVATE
@@ -24,35 +24,37 @@ test_ext_or_id_map(void *arg)
(void)arg;
/* pre-initialization */
- tt_ptr_op(NULL, ==, connection_or_get_by_ext_or_id("xxxxxxxxxxxxxxxxxxxx"));
+ tt_ptr_op(NULL, OP_EQ,
+ connection_or_get_by_ext_or_id("xxxxxxxxxxxxxxxxxxxx"));
c1 = or_connection_new(CONN_TYPE_EXT_OR, AF_INET);
c2 = or_connection_new(CONN_TYPE_EXT_OR, AF_INET);
c3 = or_connection_new(CONN_TYPE_OR, AF_INET);
- tt_ptr_op(c1->ext_or_conn_id, !=, NULL);
- tt_ptr_op(c2->ext_or_conn_id, !=, NULL);
- tt_ptr_op(c3->ext_or_conn_id, ==, NULL);
+ tt_ptr_op(c1->ext_or_conn_id, OP_NE, NULL);
+ tt_ptr_op(c2->ext_or_conn_id, OP_NE, NULL);
+ tt_ptr_op(c3->ext_or_conn_id, OP_EQ, NULL);
- tt_ptr_op(c1, ==, connection_or_get_by_ext_or_id(c1->ext_or_conn_id));
- tt_ptr_op(c2, ==, connection_or_get_by_ext_or_id(c2->ext_or_conn_id));
- tt_ptr_op(NULL, ==, connection_or_get_by_ext_or_id("xxxxxxxxxxxxxxxxxxxx"));
+ tt_ptr_op(c1, OP_EQ, connection_or_get_by_ext_or_id(c1->ext_or_conn_id));
+ tt_ptr_op(c2, OP_EQ, connection_or_get_by_ext_or_id(c2->ext_or_conn_id));
+ tt_ptr_op(NULL, OP_EQ,
+ connection_or_get_by_ext_or_id("xxxxxxxxxxxxxxxxxxxx"));
idp = tor_memdup(c2->ext_or_conn_id, EXT_OR_CONN_ID_LEN);
/* Give c2 a new ID. */
connection_or_set_ext_or_identifier(c2);
- test_mem_op(idp, !=, c2->ext_or_conn_id, EXT_OR_CONN_ID_LEN);
+ tt_mem_op(idp, OP_NE, c2->ext_or_conn_id, EXT_OR_CONN_ID_LEN);
idp2 = tor_memdup(c2->ext_or_conn_id, EXT_OR_CONN_ID_LEN);
tt_assert(!tor_digest_is_zero(idp2));
- tt_ptr_op(NULL, ==, connection_or_get_by_ext_or_id(idp));
- tt_ptr_op(c2, ==, connection_or_get_by_ext_or_id(idp2));
+ tt_ptr_op(NULL, OP_EQ, connection_or_get_by_ext_or_id(idp));
+ tt_ptr_op(c2, OP_EQ, connection_or_get_by_ext_or_id(idp2));
/* Now remove it. */
connection_or_remove_from_ext_or_id_map(c2);
- tt_ptr_op(NULL, ==, connection_or_get_by_ext_or_id(idp));
- tt_ptr_op(NULL, ==, connection_or_get_by_ext_or_id(idp2));
+ tt_ptr_op(NULL, OP_EQ, connection_or_get_by_ext_or_id(idp));
+ tt_ptr_op(NULL, OP_EQ, connection_or_get_by_ext_or_id(idp2));
done:
if (c1)
@@ -112,33 +114,33 @@ test_ext_or_write_command(void *arg)
/* Length too long */
tt_int_op(connection_write_ext_or_command(TO_CONN(c1), 100, "X", 100000),
- <, 0);
+ OP_LT, 0);
/* Empty command */
tt_int_op(connection_write_ext_or_command(TO_CONN(c1), 0x99, NULL, 0),
- ==, 0);
+ OP_EQ, 0);
cp = buf_get_contents(TO_CONN(c1)->outbuf, &sz);
- tt_int_op(sz, ==, 4);
- test_mem_op(cp, ==, "\x00\x99\x00\x00", 4);
+ tt_int_op(sz, OP_EQ, 4);
+ tt_mem_op(cp, OP_EQ, "\x00\x99\x00\x00", 4);
tor_free(cp);
/* Medium command. */
tt_int_op(connection_write_ext_or_command(TO_CONN(c1), 0x99,
- "Wai\0Hello", 9), ==, 0);
+ "Wai\0Hello", 9), OP_EQ, 0);
cp = buf_get_contents(TO_CONN(c1)->outbuf, &sz);
- tt_int_op(sz, ==, 13);
- test_mem_op(cp, ==, "\x00\x99\x00\x09Wai\x00Hello", 13);
+ tt_int_op(sz, OP_EQ, 13);
+ tt_mem_op(cp, OP_EQ, "\x00\x99\x00\x09Wai\x00Hello", 13);
tor_free(cp);
/* Long command */
buf = tor_malloc(65535);
memset(buf, 'x', 65535);
tt_int_op(connection_write_ext_or_command(TO_CONN(c1), 0xf00d,
- buf, 65535), ==, 0);
+ buf, 65535), OP_EQ, 0);
cp = buf_get_contents(TO_CONN(c1)->outbuf, &sz);
- tt_int_op(sz, ==, 65539);
- test_mem_op(cp, ==, "\xf0\x0d\xff\xff", 4);
- test_mem_op(cp+4, ==, buf, 65535);
+ tt_int_op(sz, OP_EQ, 65539);
+ tt_mem_op(cp, OP_EQ, "\xf0\x0d\xff\xff", 4);
+ tt_mem_op(cp+4, OP_EQ, buf, 65535);
tor_free(cp);
done:
@@ -175,42 +177,42 @@ test_ext_or_init_auth(void *arg)
tor_free(options->DataDirectory);
options->DataDirectory = tor_strdup("foo");
cp = get_ext_or_auth_cookie_file_name();
- tt_str_op(cp, ==, "foo"PATH_SEPARATOR"extended_orport_auth_cookie");
+ tt_str_op(cp, OP_EQ, "foo"PATH_SEPARATOR"extended_orport_auth_cookie");
tor_free(cp);
/* Shouldn't be initialized already, or our tests will be a bit
* meaningless */
ext_or_auth_cookie = tor_malloc_zero(32);
- test_assert(tor_mem_is_zero((char*)ext_or_auth_cookie, 32));
+ tt_assert(tor_mem_is_zero((char*)ext_or_auth_cookie, 32));
/* Now make sure we use a temporary file */
fn = get_fname("ext_cookie_file");
options->ExtORPortCookieAuthFile = tor_strdup(fn);
cp = get_ext_or_auth_cookie_file_name();
- tt_str_op(cp, ==, fn);
+ tt_str_op(cp, OP_EQ, fn);
tor_free(cp);
/* Test the initialization function with a broken
write_bytes_to_file(). See if the problem is handled properly. */
MOCK(write_bytes_to_file, write_bytes_to_file_fail);
- tt_int_op(-1, ==, init_ext_or_cookie_authentication(1));
- tt_int_op(ext_or_auth_cookie_is_set, ==, 0);
+ tt_int_op(-1, OP_EQ, init_ext_or_cookie_authentication(1));
+ tt_int_op(ext_or_auth_cookie_is_set, OP_EQ, 0);
UNMOCK(write_bytes_to_file);
/* Now do the actual initialization. */
- tt_int_op(0, ==, init_ext_or_cookie_authentication(1));
- tt_int_op(ext_or_auth_cookie_is_set, ==, 1);
+ tt_int_op(0, OP_EQ, init_ext_or_cookie_authentication(1));
+ tt_int_op(ext_or_auth_cookie_is_set, OP_EQ, 1);
cp = read_file_to_str(fn, RFTS_BIN, &st);
- tt_ptr_op(cp, !=, NULL);
- tt_u64_op((uint64_t)st.st_size, ==, 64);
- test_memeq(cp, "! Extended ORPort Auth Cookie !\x0a", 32);
- test_memeq(cp+32, ext_or_auth_cookie, 32);
+ tt_ptr_op(cp, OP_NE, NULL);
+ tt_u64_op((uint64_t)st.st_size, OP_EQ, 64);
+ tt_mem_op(cp,OP_EQ, "! Extended ORPort Auth Cookie !\x0a", 32);
+ tt_mem_op(cp+32,OP_EQ, ext_or_auth_cookie, 32);
memcpy(cookie0, ext_or_auth_cookie, 32);
- test_assert(!tor_mem_is_zero((char*)ext_or_auth_cookie, 32));
+ tt_assert(!tor_mem_is_zero((char*)ext_or_auth_cookie, 32));
/* Operation should be idempotent. */
- tt_int_op(0, ==, init_ext_or_cookie_authentication(1));
- test_memeq(cookie0, ext_or_auth_cookie, 32);
+ tt_int_op(0, OP_EQ, init_ext_or_cookie_authentication(1));
+ tt_mem_op(cookie0,OP_EQ, ext_or_auth_cookie, 32);
done:
tor_free(cp);
@@ -237,8 +239,8 @@ test_ext_or_cookie_auth(void *arg)
(void)arg;
- tt_int_op(strlen(client_hash_input), ==, 46+32+32);
- tt_int_op(strlen(server_hash_input), ==, 46+32+32);
+ tt_int_op(strlen(client_hash_input), OP_EQ, 46+32+32);
+ tt_int_op(strlen(server_hash_input), OP_EQ, 46+32+32);
ext_or_auth_cookie = tor_malloc_zero(32);
memcpy(ext_or_auth_cookie, "s beside you? When I count, ther", 32);
@@ -258,20 +260,20 @@ test_ext_or_cookie_auth(void *arg)
*/
/* Wrong length */
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
handle_client_auth_nonce(client_nonce, 33, &client_hash, &reply,
&reply_len));
- tt_int_op(-1, ==,
+ tt_int_op(-1, OP_EQ,
handle_client_auth_nonce(client_nonce, 31, &client_hash, &reply,
&reply_len));
/* Now let's try this for real! */
- tt_int_op(0, ==,
+ tt_int_op(0, OP_EQ,
handle_client_auth_nonce(client_nonce, 32, &client_hash, &reply,
&reply_len));
- tt_int_op(reply_len, ==, 64);
- tt_ptr_op(reply, !=, NULL);
- tt_ptr_op(client_hash, !=, NULL);
+ tt_int_op(reply_len, OP_EQ, 64);
+ tt_ptr_op(reply, OP_NE, NULL);
+ tt_ptr_op(client_hash, OP_NE, NULL);
/* Fill in the server nonce into the hash inputs... */
memcpy(server_hash_input+46+32, reply+32, 32);
memcpy(client_hash_input+46+32, reply+32, 32);
@@ -280,15 +282,15 @@ test_ext_or_cookie_auth(void *arg)
46+32+32);
crypto_hmac_sha256(hmac2, (char*)ext_or_auth_cookie, 32, client_hash_input,
46+32+32);
- test_memeq(hmac1, reply, 32);
- test_memeq(hmac2, client_hash, 32);
+ tt_mem_op(hmac1,OP_EQ, reply, 32);
+ tt_mem_op(hmac2,OP_EQ, client_hash, 32);
/* Now do it again and make sure that the results are *different* */
- tt_int_op(0, ==,
+ tt_int_op(0, OP_EQ,
handle_client_auth_nonce(client_nonce, 32, &client_hash2, &reply2,
&reply_len));
- test_memneq(reply2, reply, reply_len);
- test_memneq(client_hash2, client_hash, 32);
+ tt_mem_op(reply2,OP_NE, reply, reply_len);
+ tt_mem_op(client_hash2,OP_NE, client_hash, 32);
/* But that this one checks out too. */
memcpy(server_hash_input+46+32, reply2+32, 32);
memcpy(client_hash_input+46+32, reply2+32, 32);
@@ -297,8 +299,8 @@ test_ext_or_cookie_auth(void *arg)
46+32+32);
crypto_hmac_sha256(hmac2, (char*)ext_or_auth_cookie, 32, client_hash_input,
46+32+32);
- test_memeq(hmac1, reply2, 32);
- test_memeq(hmac2, client_hash2, 32);
+ tt_mem_op(hmac1,OP_EQ, reply2, 32);
+ tt_mem_op(hmac2,OP_EQ, client_hash2, 32);
done:
tor_free(reply);
@@ -307,15 +309,14 @@ test_ext_or_cookie_auth(void *arg)
tor_free(client_hash2);
}
-static int
+static void
crypto_rand_return_tse_str(char *to, size_t n)
{
if (n != 32) {
TT_FAIL(("Asked for %d bytes, not 32", (int)n));
- return -1;
+ return;
}
memcpy(to, "te road There is always another ", 32);
- return 0;
}
static void
@@ -334,12 +335,12 @@ test_ext_or_cookie_auth_testvec(void *arg)
MOCK(crypto_rand, crypto_rand_return_tse_str);
- tt_int_op(0, ==,
+ tt_int_op(0, OP_EQ,
handle_client_auth_nonce(client_nonce, 32, &client_hash, &reply,
&reply_len));
- tt_ptr_op(reply, !=, NULL );
- tt_uint_op(reply_len, ==, 64);
- test_memeq(reply+32, "te road There is always another ", 32);
+ tt_ptr_op(reply, OP_NE, NULL );
+ tt_uint_op(reply_len, OP_EQ, 64);
+ tt_mem_op(reply+32,OP_EQ, "te road There is always another ", 32);
/* HMACSHA256("Gliding wrapt in a brown mantle,"
* "ExtORPort authentication server-to-client hash"
* "But when I look ahead up the write road There is always another ");
@@ -402,11 +403,11 @@ handshake_start(or_connection_t *conn, int receiving)
} while (0)
#define CONTAINS(s,n) \
do { \
- tt_int_op((n), <=, sizeof(b)); \
- tt_int_op(buf_datalen(TO_CONN(conn)->outbuf), ==, (n)); \
+ tt_int_op((n), OP_LE, sizeof(b)); \
+ tt_int_op(buf_datalen(TO_CONN(conn)->outbuf), OP_EQ, (n)); \
if ((n)) { \
fetch_from_buf(b, (n), TO_CONN(conn)->outbuf); \
- test_memeq(b, (s), (n)); \
+ tt_mem_op(b, OP_EQ, (s), (n)); \
} \
} while (0)
@@ -416,14 +417,15 @@ do_ext_or_handshake(or_connection_t *conn)
{
char b[256];
- tt_int_op(0, ==, connection_ext_or_start_auth(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_start_auth(conn));
CONTAINS("\x01\x00", 2);
WRITE("\x01", 1);
WRITE("But when I look ahead up the whi", 32);
MOCK(crypto_rand, crypto_rand_return_tse_str);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
UNMOCK(crypto_rand);
- tt_int_op(TO_CONN(conn)->state, ==, EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH);
+ tt_int_op(TO_CONN(conn)->state, OP_EQ,
+ EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH);
CONTAINS("\xec\x80\xed\x6e\x54\x6d\x3b\x36\xfd\xfc\x22\xfe\x13\x15\x41\x6b"
"\x02\x9f\x1a\xde\x76\x10\xd9\x10\x87\x8b\x62\xee\xb7\x40\x38\x21"
"te road There is always another ", 64);
@@ -431,10 +433,10 @@ do_ext_or_handshake(or_connection_t *conn)
WRITE("\xab\x39\x17\x32\xdd\x2e\xd9\x68\xcd\x40\xc0\x87\xd1\xb1\xf2\x5b"
"\x33\xb3\xcd\x77\xff\x79\xbd\x80\xc2\x07\x4b\xbf\x43\x81\x19\xa2",
32);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("\x01", 1);
tt_assert(! TO_CONN(conn)->marked_for_close);
- tt_int_op(TO_CONN(conn)->state, ==, EXT_OR_CONN_STATE_OPEN);
+ tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_OPEN);
done: ;
}
@@ -456,14 +458,14 @@ test_ext_or_handshake(void *arg)
init_connection_lists();
conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET);
- tt_int_op(0, ==, connection_ext_or_start_auth(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_start_auth(conn));
/* The server starts by telling us about the one supported authtype. */
CONTAINS("\x01\x00", 2);
/* Say the client hasn't responded yet. */
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
/* Let's say the client replies badly. */
WRITE("\x99", 1);
- tt_int_op(-1, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
tt_assert(TO_CONN(conn)->marked_for_close);
close_closeable_connections();
@@ -471,23 +473,23 @@ test_ext_or_handshake(void *arg)
/* Okay, try again. */
conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET);
- tt_int_op(0, ==, connection_ext_or_start_auth(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_start_auth(conn));
CONTAINS("\x01\x00", 2);
/* Let's say the client replies sensibly this time. "Yes, AUTHTYPE_COOKIE
* sounds delicious. Let's have some of that!" */
WRITE("\x01", 1);
/* Let's say that the client also sends part of a nonce. */
WRITE("But when I look ", 16);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
- tt_int_op(TO_CONN(conn)->state, ==,
+ tt_int_op(TO_CONN(conn)->state, OP_EQ,
EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE);
/* Pump it again. Nothing should happen. */
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
/* send the rest of the nonce. */
WRITE("ahead up the whi", 16);
MOCK(crypto_rand, crypto_rand_return_tse_str);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
UNMOCK(crypto_rand);
/* We should get the right reply from the server. */
CONTAINS("\xec\x80\xed\x6e\x54\x6d\x3b\x36\xfd\xfc\x22\xfe\x13\x15\x41\x6b"
@@ -496,7 +498,7 @@ test_ext_or_handshake(void *arg)
/* Send the wrong response. */
WRITE("not with a bang but a whimper...", 32);
MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem);
- tt_int_op(-1, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("\x00", 1);
tt_assert(TO_CONN(conn)->marked_for_close);
/* XXXX Hold-open-until-flushed. */
@@ -515,32 +517,32 @@ test_ext_or_handshake(void *arg)
/* Now let's run through some messages. */
/* First let's send some junk and make sure it's ignored. */
WRITE("\xff\xf0\x00\x03""ABC", 7);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
/* Now let's send a USERADDR command. */
WRITE("\x00\x01\x00\x0c""1.2.3.4:5678", 16);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
- tt_int_op(TO_CONN(conn)->port, ==, 5678);
- tt_int_op(tor_addr_to_ipv4h(&TO_CONN(conn)->addr), ==, 0x01020304);
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
+ tt_int_op(TO_CONN(conn)->port, OP_EQ, 5678);
+ tt_int_op(tor_addr_to_ipv4h(&TO_CONN(conn)->addr), OP_EQ, 0x01020304);
/* Now let's send a TRANSPORT command. */
WRITE("\x00\x02\x00\x07""rfc1149", 11);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
- tt_ptr_op(NULL, !=, conn->ext_or_transport);
- tt_str_op("rfc1149", ==, conn->ext_or_transport);
- tt_int_op(is_reading,==,1);
- tt_int_op(TO_CONN(conn)->state, ==, EXT_OR_CONN_STATE_OPEN);
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
+ tt_ptr_op(NULL, OP_NE, conn->ext_or_transport);
+ tt_str_op("rfc1149", OP_EQ, conn->ext_or_transport);
+ tt_int_op(is_reading,OP_EQ,1);
+ tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_OPEN);
/* DONE */
WRITE("\x00\x00\x00\x00", 4);
- tt_int_op(0, ==, connection_ext_or_process_inbuf(conn));
- tt_int_op(TO_CONN(conn)->state, ==, EXT_OR_CONN_STATE_FLUSHING);
- tt_int_op(is_reading,==,0);
+ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn));
+ tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_FLUSHING);
+ tt_int_op(is_reading,OP_EQ,0);
CONTAINS("\x10\x00\x00\x00", 4);
- tt_int_op(handshake_start_called,==,0);
- tt_int_op(0, ==, connection_ext_or_finished_flushing(conn));
- tt_int_op(is_reading,==,1);
- tt_int_op(handshake_start_called,==,1);
- tt_int_op(TO_CONN(conn)->type, ==, CONN_TYPE_OR);
- tt_int_op(TO_CONN(conn)->state, ==, 0);
+ tt_int_op(handshake_start_called,OP_EQ,0);
+ tt_int_op(0, OP_EQ, connection_ext_or_finished_flushing(conn));
+ tt_int_op(is_reading,OP_EQ,1);
+ tt_int_op(handshake_start_called,OP_EQ,1);
+ tt_int_op(TO_CONN(conn)->type, OP_EQ, CONN_TYPE_OR);
+ tt_int_op(TO_CONN(conn)->state, OP_EQ, 0);
close_closeable_connections();
conn = NULL;
@@ -551,7 +553,7 @@ test_ext_or_handshake(void *arg)
/* USERADDR command with an extra NUL byte */
WRITE("\x00\x01\x00\x0d""1.2.3.4:5678\x00", 17);
MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem);
- tt_int_op(-1, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
tt_assert(TO_CONN(conn)->marked_for_close);
close_closeable_connections();
@@ -564,7 +566,7 @@ test_ext_or_handshake(void *arg)
/* TRANSPORT command with an extra NUL byte */
WRITE("\x00\x02\x00\x08""rfc1149\x00", 12);
MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem);
- tt_int_op(-1, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
tt_assert(TO_CONN(conn)->marked_for_close);
close_closeable_connections();
@@ -578,7 +580,7 @@ test_ext_or_handshake(void *arg)
C-identifier) */
WRITE("\x00\x02\x00\x07""rf*1149", 11);
MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem);
- tt_int_op(-1, ==, connection_ext_or_process_inbuf(conn));
+ tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn));
CONTAINS("", 0);
tt_assert(TO_CONN(conn)->marked_for_close);
close_closeable_connections();
diff --git a/src/test/test_guardfraction.c b/src/test/test_guardfraction.c
new file mode 100644
index 0000000000..300590a3d9
--- /dev/null
+++ b/src/test/test_guardfraction.c
@@ -0,0 +1,418 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define DIRSERV_PRIVATE
+#define ROUTERPARSE_PRIVATE
+#define NETWORKSTATUS_PRIVATE
+
+#include "orconfig.h"
+#include "or.h"
+#include "config.h"
+#include "dirserv.h"
+#include "container.h"
+#include "entrynodes.h"
+#include "util.h"
+#include "routerparse.h"
+#include "networkstatus.h"
+
+#include "test.h"
+#include "test_helpers.h"
+
+/** Generate a vote_routerstatus_t for a router with identity digest
+ * <b>digest_in_hex</b>. */
+static vote_routerstatus_t *
+gen_vote_routerstatus_for_tests(const char *digest_in_hex, int is_guard)
+{
+ int retval;
+ vote_routerstatus_t *vrs = NULL;
+ routerstatus_t *rs;
+
+ vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
+ rs = &vrs->status;
+
+ { /* Useful information for tests */
+ char digest_tmp[DIGEST_LEN];
+
+ /* Guard or not? */
+ rs->is_possible_guard = is_guard;
+
+ /* Fill in the fpr */
+ tt_int_op(strlen(digest_in_hex), ==, HEX_DIGEST_LEN);
+ retval = base16_decode(digest_tmp, sizeof(digest_tmp),
+ digest_in_hex, HEX_DIGEST_LEN);
+ tt_int_op(retval, ==, 0);
+ memcpy(rs->identity_digest, digest_tmp, DIGEST_LEN);
+ }
+
+ { /* Misc info (maybe not used in tests) */
+ vrs->version = tor_strdup("0.1.2.14");
+ strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
+ memset(rs->descriptor_digest, 78, DIGEST_LEN);
+ rs->addr = 0x99008801;
+ rs->or_port = 443;
+ rs->dir_port = 8000;
+ /* all flags but running cleared */
+ rs->is_flagged_running = 1;
+ vrs->has_measured_bw = 1;
+ rs->has_bandwidth = 1;
+ }
+
+ return vrs;
+
+ done:
+ vote_routerstatus_free(vrs);
+
+ return NULL;
+}
+
+/** Make sure our parsers reject corrupted guardfraction files. */
+static void
+test_parse_guardfraction_file_bad(void *arg)
+{
+ int retval;
+ char *guardfraction_bad = NULL;
+ const char *yesterday_date_str = get_yesterday_date_str();
+
+ (void) arg;
+
+ /* Start parsing all those corrupted guardfraction files! */
+
+ /* Guardfraction file version is not a number! */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version nan\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 100 420\n"
+ "guard-seen 07B5547026DF3E229806E135CFA8552D56AFBABC 5 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, -1);
+ tor_free(guardfraction_bad);
+
+ /* This one does not have a date! Parsing should fail. */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at not_date\n"
+ "n-inputs 420 3\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 100 420\n"
+ "guard-seen 07B5547026DF3E229806E135CFA8552D56AFBABC 5 420\n");
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, -1);
+ tor_free(guardfraction_bad);
+
+ /* This one has an incomplete n-inputs line, but parsing should
+ still continue. */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs biggie\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 100 420\n"
+ "guard-seen 07B5547026DF3E229806E135CFA8552D56AFBABC 5 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, 2);
+ tor_free(guardfraction_bad);
+
+ /* This one does not have a fingerprint in the guard line! */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen not_a_fingerprint 100 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, 0);
+ tor_free(guardfraction_bad);
+
+ /* This one does not even have an integer guardfraction value. */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 NaN 420\n"
+ "guard-seen 07B5547026DF3E229806E135CFA8552D56AFBABC 5 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, 1);
+ tor_free(guardfraction_bad);
+
+ /* This one is not a percentage (not in [0, 100]) */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 666 420\n"
+ "guard-seen 07B5547026DF3E229806E135CFA8552D56AFBABC 5 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, 1);
+ tor_free(guardfraction_bad);
+
+ /* This one is not a percentage either (not in [0, 100]) */
+ tor_asprintf(&guardfraction_bad,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777 -3 420\n",
+ yesterday_date_str);
+
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_bad, NULL);
+ tt_int_op(retval, ==, 0);
+
+ done:
+ tor_free(guardfraction_bad);
+}
+
+/** Make sure that our test guardfraction file gets parsed properly, and
+ * its information are applied properly to our routerstatuses. */
+static void
+test_parse_guardfraction_file_good(void *arg)
+{
+ int retval;
+ vote_routerstatus_t *vrs_guard = NULL;
+ vote_routerstatus_t *vrs_dummy = NULL;
+ char *guardfraction_good = NULL;
+ const char *yesterday_date_str = get_yesterday_date_str();
+ smartlist_t *routerstatuses = smartlist_new();
+
+ /* Some test values that we need to validate later */
+ const char fpr_guard[] = "D0EDB47BEAD32D26D0A837F7D5357EC3AD3B8777";
+ const char fpr_unlisted[] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+ const int guardfraction_value = 42;
+
+ (void) arg;
+
+ {
+ /* Populate the smartlist with some fake routerstatuses, so that
+ after parsing the guardfraction file we can check that their
+ elements got filled properly. */
+
+ /* This one is a guard */
+ vrs_guard = gen_vote_routerstatus_for_tests(fpr_guard, 1);
+ tt_assert(vrs_guard);
+ smartlist_add(routerstatuses, vrs_guard);
+
+ /* This one is a guard but it's not in the guardfraction file */
+ vrs_dummy = gen_vote_routerstatus_for_tests(fpr_unlisted, 1);
+ tt_assert(vrs_dummy);
+ smartlist_add(routerstatuses, vrs_dummy);
+ }
+
+ tor_asprintf(&guardfraction_good,
+ "guardfraction-file-version 1\n"
+ "written-at %s\n"
+ "n-inputs 420 3\n"
+ "guard-seen %s %d 420\n",
+ yesterday_date_str,
+ fpr_guard, guardfraction_value);
+
+ /* Read the guardfraction file */
+ retval = dirserv_read_guardfraction_file_from_str(guardfraction_good,
+ routerstatuses);
+ tt_int_op(retval, ==, 1);
+
+ { /* Test that routerstatus fields got filled properly */
+
+ /* The guardfraction fields of the guard should be filled. */
+ tt_assert(vrs_guard->status.has_guardfraction);
+ tt_int_op(vrs_guard->status.guardfraction_percentage,
+ ==,
+ guardfraction_value);
+
+ /* The guard that was not in the guardfraction file should not have
+ been touched either. */
+ tt_assert(!vrs_dummy->status.has_guardfraction);
+ }
+
+ done:
+ vote_routerstatus_free(vrs_guard);
+ vote_routerstatus_free(vrs_dummy);
+ smartlist_free(routerstatuses);
+ tor_free(guardfraction_good);
+}
+
+/** Make sure that the guardfraction bandwidths get calculated properly. */
+static void
+test_get_guardfraction_bandwidth(void *arg)
+{
+ guardfraction_bandwidth_t gf_bw;
+ const int orig_bw = 1000;
+
+ (void) arg;
+
+ /* A guard with bandwidth 1000 and GuardFraction 0.25, should have
+ bandwidth 250 as a guard and bandwidth 750 as a non-guard. */
+ guard_get_guardfraction_bandwidth(&gf_bw,
+ orig_bw, 25);
+
+ tt_int_op(gf_bw.guard_bw, ==, 250);
+ tt_int_op(gf_bw.non_guard_bw, ==, 750);
+
+ /* Also check the 'guard_bw + non_guard_bw == original_bw'
+ * invariant. */
+ tt_int_op(gf_bw.non_guard_bw + gf_bw.guard_bw, ==, orig_bw);
+
+ done:
+ ;
+}
+
+/** Parse the GuardFraction element of the consensus, and make sure it
+ * gets parsed correctly. */
+static void
+test_parse_guardfraction_consensus(void *arg)
+{
+ int retval;
+ or_options_t *options = get_options_mutable();
+
+ const char *guardfraction_str_good = "GuardFraction=66";
+ routerstatus_t rs_good;
+ routerstatus_t rs_no_guard;
+
+ const char *guardfraction_str_bad1 = "GuardFraction="; /* no value */
+ routerstatus_t rs_bad1;
+
+ const char *guardfraction_str_bad2 = "GuardFraction=166"; /* no percentage */
+ routerstatus_t rs_bad2;
+
+ (void) arg;
+
+ /* GuardFraction use is currently disabled by default. So we need to
+ manually enable it. */
+ options->UseGuardFraction = 1;
+
+ { /* Properly formatted GuardFraction. Check that it gets applied
+ correctly. */
+ memset(&rs_good, 0, sizeof(routerstatus_t));
+ rs_good.is_possible_guard = 1;
+
+ retval = routerstatus_parse_guardfraction(guardfraction_str_good,
+ NULL, NULL,
+ &rs_good);
+ tt_int_op(retval, ==, 0);
+ tt_assert(rs_good.has_guardfraction);
+ tt_int_op(rs_good.guardfraction_percentage, ==, 66);
+ }
+
+ { /* Properly formatted GuardFraction but router is not a
+ guard. GuardFraction should not get applied. */
+ memset(&rs_no_guard, 0, sizeof(routerstatus_t));
+ tt_assert(!rs_no_guard.is_possible_guard);
+
+ retval = routerstatus_parse_guardfraction(guardfraction_str_good,
+ NULL, NULL,
+ &rs_no_guard);
+ tt_int_op(retval, ==, 0);
+ tt_assert(!rs_no_guard.has_guardfraction);
+ }
+
+ { /* Bad GuardFraction. Function should fail and not apply. */
+ memset(&rs_bad1, 0, sizeof(routerstatus_t));
+ rs_bad1.is_possible_guard = 1;
+
+ retval = routerstatus_parse_guardfraction(guardfraction_str_bad1,
+ NULL, NULL,
+ &rs_bad1);
+ tt_int_op(retval, ==, -1);
+ tt_assert(!rs_bad1.has_guardfraction);
+ }
+
+ { /* Bad GuardFraction. Function should fail and not apply. */
+ memset(&rs_bad2, 0, sizeof(routerstatus_t));
+ rs_bad2.is_possible_guard = 1;
+
+ retval = routerstatus_parse_guardfraction(guardfraction_str_bad2,
+ NULL, NULL,
+ &rs_bad2);
+ tt_int_op(retval, ==, -1);
+ tt_assert(!rs_bad2.has_guardfraction);
+ }
+
+ done:
+ ;
+}
+
+/** Make sure that we use GuardFraction information when we should,
+ * according to the torrc option and consensus parameter. */
+static void
+test_should_apply_guardfraction(void *arg)
+{
+ networkstatus_t vote_enabled, vote_disabled, vote_missing;
+ or_options_t *options = get_options_mutable();
+
+ (void) arg;
+
+ { /* Fill the votes for later */
+ /* This one suggests enabled GuardFraction. */
+ memset(&vote_enabled, 0, sizeof(vote_enabled));
+ vote_enabled.net_params = smartlist_new();
+ smartlist_split_string(vote_enabled.net_params,
+ "UseGuardFraction=1", NULL, 0, 0);
+
+ /* This one suggests disabled GuardFraction. */
+ memset(&vote_disabled, 0, sizeof(vote_disabled));
+ vote_disabled.net_params = smartlist_new();
+ smartlist_split_string(vote_disabled.net_params,
+ "UseGuardFraction=0", NULL, 0, 0);
+
+ /* This one doesn't have GuardFraction at all. */
+ memset(&vote_missing, 0, sizeof(vote_missing));
+ vote_missing.net_params = smartlist_new();
+ smartlist_split_string(vote_missing.net_params,
+ "leon=trout", NULL, 0, 0);
+ }
+
+ /* If torrc option is set to yes, we should always use
+ * guardfraction.*/
+ options->UseGuardFraction = 1;
+ tt_int_op(should_apply_guardfraction(&vote_disabled), ==, 1);
+
+ /* If torrc option is set to no, we should never use
+ * guardfraction.*/
+ options->UseGuardFraction = 0;
+ tt_int_op(should_apply_guardfraction(&vote_enabled), ==, 0);
+
+ /* Now let's test torrc option set to auto. */
+ options->UseGuardFraction = -1;
+
+ /* If torrc option is set to auto, and consensus parameter is set to
+ * yes, we should use guardfraction. */
+ tt_int_op(should_apply_guardfraction(&vote_enabled), ==, 1);
+
+ /* If torrc option is set to auto, and consensus parameter is set to
+ * no, we should use guardfraction. */
+ tt_int_op(should_apply_guardfraction(&vote_disabled), ==, 0);
+
+ /* If torrc option is set to auto, and consensus parameter is not
+ * set, we should fallback to "no". */
+ tt_int_op(should_apply_guardfraction(&vote_missing), ==, 0);
+
+ done:
+ SMARTLIST_FOREACH(vote_enabled.net_params, char *, cp, tor_free(cp));
+ SMARTLIST_FOREACH(vote_disabled.net_params, char *, cp, tor_free(cp));
+ SMARTLIST_FOREACH(vote_missing.net_params, char *, cp, tor_free(cp));
+ smartlist_free(vote_enabled.net_params);
+ smartlist_free(vote_disabled.net_params);
+ smartlist_free(vote_missing.net_params);
+}
+
+struct testcase_t guardfraction_tests[] = {
+ { "parse_guardfraction_file_bad", test_parse_guardfraction_file_bad,
+ TT_FORK, NULL, NULL },
+ { "parse_guardfraction_file_good", test_parse_guardfraction_file_good,
+ TT_FORK, NULL, NULL },
+ { "parse_guardfraction_consensus", test_parse_guardfraction_consensus,
+ TT_FORK, NULL, NULL },
+ { "get_guardfraction_bandwidth", test_get_guardfraction_bandwidth,
+ TT_FORK, NULL, NULL },
+ { "should_apply_guardfraction", test_should_apply_guardfraction,
+ TT_FORK, NULL, NULL },
+
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_helpers.c b/src/test/test_helpers.c
new file mode 100644
index 0000000000..c6daaf220a
--- /dev/null
+++ b/src/test/test_helpers.c
@@ -0,0 +1,86 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file test_helpers.c
+ * \brief Some helper functions to avoid code duplication in unit tests.
+ */
+
+#define ROUTERLIST_PRIVATE
+#include "orconfig.h"
+#include "or.h"
+
+#include "routerlist.h"
+#include "nodelist.h"
+
+#include "test.h"
+#include "test_helpers.h"
+
+#include "test_descriptors.inc"
+
+/* Return a statically allocated string representing yesterday's date
+ * in ISO format. We use it so that state file items are not found to
+ * be outdated. */
+const char *
+get_yesterday_date_str(void)
+{
+ static char buf[ISO_TIME_LEN+1];
+
+ time_t yesterday = time(NULL) - 24*60*60;
+ format_iso_time(buf, yesterday);
+ return buf;
+}
+
+/* NOP replacement for router_descriptor_is_older_than() */
+static int
+router_descriptor_is_older_than_replacement(const routerinfo_t *router,
+ int seconds)
+{
+ (void) router;
+ (void) seconds;
+ return 0;
+}
+
+/** Parse a file containing router descriptors and load them to our
+ routerlist. This function is used to setup an artificial network
+ so that we can conduct tests on it. */
+void
+helper_setup_fake_routerlist(void)
+{
+ int retval;
+ routerlist_t *our_routerlist = NULL;
+ smartlist_t *our_nodelist = NULL;
+
+ /* Read the file that contains our test descriptors. */
+
+ /* We need to mock this function otherwise the descriptors will not
+ accepted as they are too old. */
+ MOCK(router_descriptor_is_older_than,
+ router_descriptor_is_older_than_replacement);
+
+ /* Load all the test descriptors to the routerlist. */
+ retval = router_load_routers_from_string(TEST_DESCRIPTORS,
+ NULL, SAVED_IN_JOURNAL,
+ NULL, 0, NULL);
+ tt_int_op(retval, ==, HELPER_NUMBER_OF_DESCRIPTORS);
+
+ /* Sanity checking of routerlist and nodelist. */
+ our_routerlist = router_get_routerlist();
+ tt_int_op(smartlist_len(our_routerlist->routers), ==,
+ HELPER_NUMBER_OF_DESCRIPTORS);
+ routerlist_assert_ok(our_routerlist);
+
+ our_nodelist = nodelist_get_list();
+ tt_int_op(smartlist_len(our_nodelist), ==, HELPER_NUMBER_OF_DESCRIPTORS);
+
+ /* Mark all routers as non-guards but up and running! */
+ SMARTLIST_FOREACH_BEGIN(our_nodelist, node_t *, node) {
+ node->is_running = 1;
+ node->is_valid = 1;
+ node->is_possible_guard = 0;
+ } SMARTLIST_FOREACH_END(node);
+
+ done:
+ UNMOCK(router_descriptor_is_older_than);
+}
+
diff --git a/src/test/test_helpers.h b/src/test/test_helpers.h
new file mode 100644
index 0000000000..684375e1b1
--- /dev/null
+++ b/src/test/test_helpers.h
@@ -0,0 +1,17 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TOR_TEST_HELPERS_H
+#define TOR_TEST_HELPERS_H
+
+const char *get_yesterday_date_str(void);
+
+/* Number of descriptors contained in test_descriptors.txt. */
+#define HELPER_NUMBER_OF_DESCRIPTORS 8
+
+void helper_setup_fake_routerlist(void);
+
+extern const char TEST_DESCRIPTORS[];
+
+#endif
+
diff --git a/src/test/test_hs.c b/src/test/test_hs.c
index 99ef7dd570..49939a53cf 100644
--- a/src/test/test_hs.c
+++ b/src/test/test_hs.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2007-2013, The Tor Project, Inc. */
+/* Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
@@ -7,9 +7,16 @@
**/
#define CONTROL_PRIVATE
+#define CIRCUITBUILD_PRIVATE
+
#include "or.h"
#include "test.h"
#include "control.h"
+#include "config.h"
+#include "rendcommon.h"
+#include "routerset.h"
+#include "circuitbuild.h"
+#include "test_helpers.h"
/* mock ID digest and longname for node that's in nodelist */
#define HSDIR_EXIST_ID "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" \
@@ -22,6 +29,68 @@
#define STR_HSDIR_NONE_EXIST_LONGNAME \
"$BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+/* DuckDuckGo descriptor as an example. */
+static const char *hs_desc_content = "\
+rendezvous-service-descriptor g5ojobzupf275beh5ra72uyhb3dkpxwg\r\n\
+version 2\r\n\
+permanent-key\r\n\
+-----BEGIN RSA PUBLIC KEY-----\r\n\
+MIGJAoGBAJ/SzzgrXPxTlFrKVhXh3buCWv2QfcNgncUpDpKouLn3AtPH5Ocys0jE\r\n\
+aZSKdvaiQ62md2gOwj4x61cFNdi05tdQjS+2thHKEm/KsB9BGLSLBNJYY356bupg\r\n\
+I5gQozM65ENelfxYlysBjJ52xSDBd8C4f/p9umdzaaaCmzXG/nhzAgMBAAE=\r\n\
+-----END RSA PUBLIC KEY-----\r\n\
+secret-id-part anmjoxxwiupreyajjt5yasimfmwcnxlf\r\n\
+publication-time 2015-03-11 19:00:00\r\n\
+protocol-versions 2,3\r\n\
+introduction-points\r\n\
+-----BEGIN MESSAGE-----\r\n\
+aW50cm9kdWN0aW9uLXBvaW50IDd1bnd4cmg2dG5kNGh6eWt1Z3EzaGZzdHduc2ll\r\n\
+cmhyCmlwLWFkZHJlc3MgMTg4LjEzOC4xMjEuMTE4Cm9uaW9uLXBvcnQgOTAwMQpv\r\n\
+bmlvbi1rZXkKLS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1JR0pBb0dC\r\n\
+QUxGRVVyeVpDbk9ROEhURmV5cDVjMTRObWVqL1BhekFLTTBxRENTNElKUWh0Y3g1\r\n\
+NXpRSFdOVWIKQ2hHZ0JqR1RjV3ZGRnA0N3FkdGF6WUZhVXE2c0lQKzVqeWZ5b0Q4\r\n\
+UmJ1bzBwQmFWclJjMmNhYUptWWM0RDh6Vgpuby9sZnhzOVVaQnZ1cWY4eHIrMDB2\r\n\
+S0JJNmFSMlA2OE1WeDhrMExqcUpUU2RKOE9idm9yQWdNQkFBRT0KLS0tLS1FTkQg\r\n\
+UlNBIFBVQkxJQyBLRVktLS0tLQpzZXJ2aWNlLWtleQotLS0tLUJFR0lOIFJTQSBQ\r\n\
+VUJMSUMgS0VZLS0tLS0KTUlHSkFvR0JBTnJHb0ozeTlHNXQzN2F2ekI1cTlwN1hG\r\n\
+VUplRUVYMUNOaExnWmJXWGJhVk5OcXpoZFhyL0xTUQppM1Z6dW5OaUs3cndUVnE2\r\n\
+K2QyZ1lRckhMMmIvMXBBY3ZKWjJiNSs0bTRRc0NibFpjRENXTktRbHJnRWN5WXRJ\r\n\
+CkdscXJTbFFEaXA0ZnNrUFMvNDVkWTI0QmJsQ3NGU1k3RzVLVkxJck4zZFpGbmJr\r\n\
+NEZIS1hBZ01CQUFFPQotLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0tCmludHJv\r\n\
+ZHVjdGlvbi1wb2ludCBiNGM3enlxNXNheGZzN2prNXFibG1wN3I1b3pwdHRvagpp\r\n\
+cC1hZGRyZXNzIDEwOS4xNjkuNDUuMjI2Cm9uaW9uLXBvcnQgOTAwMQpvbmlvbi1r\r\n\
+ZXkKLS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1JR0pBb0dCQU8xSXpw\r\n\
+WFFUTUY3RXZUb1NEUXpzVnZiRVFRQUQrcGZ6NzczMVRXZzVaUEJZY1EyUkRaeVp4\r\n\
+OEQKNUVQSU1FeUE1RE83cGd0ak5LaXJvYXJGMC8yempjMkRXTUlSaXZyU29YUWVZ\r\n\
+ZXlMM1pzKzFIajJhMDlCdkYxZAp6MEswblRFdVhoNVR5V3lyMHdsbGI1SFBnTlI0\r\n\
+MS9oYkprZzkwZitPVCtIeGhKL1duUml2QWdNQkFBRT0KLS0tLS1FTkQgUlNBIFBV\r\n\
+QkxJQyBLRVktLS0tLQpzZXJ2aWNlLWtleQotLS0tLUJFR0lOIFJTQSBQVUJMSUMg\r\n\
+S0VZLS0tLS0KTUlHSkFvR0JBSzNWZEJ2ajFtQllLL3JrcHNwcm9Ub0llNUtHVmth\r\n\
+QkxvMW1tK1I2YUVJek1VZFE1SjkwNGtyRwpCd3k5NC8rV0lGNFpGYXh5Z2phejl1\r\n\
+N2pKY1k3ZGJhd1pFeG1hYXFCRlRwL2h2ZG9rcHQ4a1ByRVk4OTJPRHJ1CmJORUox\r\n\
+N1FPSmVMTVZZZk5Kcjl4TWZCQ3JQai8zOGh2RUdrbWVRNmRVWElvbVFNaUJGOVRB\r\n\
+Z01CQUFFPQotLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0tCmludHJvZHVjdGlv\r\n\
+bi1wb2ludCBhdjVtcWl0Y2Q3cjJkandsYmN0c2Jlc2R3eGt0ZWtvegppcC1hZGRy\r\n\
+ZXNzIDE0NC43Ni44LjczCm9uaW9uLXBvcnQgNDQzCm9uaW9uLWtleQotLS0tLUJF\r\n\
+R0lOIFJTQSBQVUJMSUMgS0VZLS0tLS0KTUlHSkFvR0JBTzVweVZzQmpZQmNmMXBE\r\n\
+dklHUlpmWXUzQ05nNldka0ZLMGlvdTBXTGZtejZRVDN0NWhzd3cyVwpjejlHMXhx\r\n\
+MmN0Nkd6VWkrNnVkTDlITTRVOUdHTi9BbW8wRG9GV1hKWHpBQkFXd2YyMVdsd1lW\r\n\
+eFJQMHRydi9WCkN6UDkzcHc5OG5vSmdGUGRUZ05iMjdKYmVUZENLVFBrTEtscXFt\r\n\
+b3NveUN2RitRa25vUS9BZ01CQUFFPQotLS0tLUVORCBSU0EgUFVCTElDIEtFWS0t\r\n\
+LS0tCnNlcnZpY2Uta2V5Ci0tLS0tQkVHSU4gUlNBIFBVQkxJQyBLRVktLS0tLQpN\r\n\
+SUdKQW9HQkFMVjNKSmtWN3lTNU9jc1lHMHNFYzFQOTVRclFRR3ZzbGJ6Wi9zRGxl\r\n\
+RlpKYXFSOUYvYjRUVERNClNGcFMxcU1GbldkZDgxVmRGMEdYRmN2WVpLamRJdHU2\r\n\
+SndBaTRJeEhxeXZtdTRKdUxrcXNaTEFLaXRLVkx4eGsKeERlMjlDNzRWMmJrOTRJ\r\n\
+MEgybTNKS2tzTHVwc3VxWWRVUmhOVXN0SElKZmgyZmNIalF0bEFnTUJBQUU9Ci0t\r\n\
+LS0tRU5EIFJTQSBQVUJMSUMgS0VZLS0tLS0KCg==\r\n\
+-----END MESSAGE-----\r\n\
+signature\r\n\
+-----BEGIN SIGNATURE-----\r\n\
+d4OuCE5OLAOnRB6cQN6WyMEmg/BHem144Vec+eYgeWoKwx3MxXFplUjFxgnMlmwN\r\n\
+PcftsZf2ztN0sbNCtPgDL3d0PqvxY3iHTQAI8EbaGq/IAJUZ8U4y963dD5+Bn6JQ\r\n\
+myE3ctmh0vy5+QxSiRjmQBkuEpCyks7LvWvHYrhnmcg=\r\n\
+-----END SIGNATURE-----";
+
/* Helper global variable for hidden service descriptor event test.
* It's used as a pointer to dynamically created message buffer in
* send_control_event_string_replacement function, which mocks
@@ -33,13 +102,11 @@ static char *received_msg = NULL;
/** Mock function for send_control_event_string
*/
static void
-send_control_event_string_replacement(uint16_t event, event_format_t which,
- const char *msg)
+queue_control_event_string_replacement(uint16_t event, char *msg)
{
(void) event;
- (void) which;
tor_free(received_msg);
- received_msg = tor_strdup(msg);
+ received_msg = msg;
}
/** Mock function for node_describe_longname_by_id, it returns either
@@ -63,67 +130,321 @@ static void
test_hs_desc_event(void *arg)
{
#define STR_HS_ADDR "ajhb7kljbiru65qo"
- #define STR_HS_ID "b3oeducbhjmbqmgw2i3jtz4fekkrinwj"
+ #define STR_HS_CONTENT_DESC_ID "g5ojobzupf275beh5ra72uyhb3dkpxwg"
+ #define STR_DESC_ID_BASE32 "hba3gmcgpfivzfhx5rtfqkfdhv65yrj3"
+ int ret;
rend_data_t rend_query;
const char *expected_msg;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
(void) arg;
- MOCK(send_control_event_string,
- send_control_event_string_replacement);
+ MOCK(queue_control_event_string,
+ queue_control_event_string_replacement);
MOCK(node_describe_longname_by_id,
node_describe_longname_by_id_replacement);
/* setup rend_query struct */
+ memset(&rend_query, 0, sizeof(rend_query));
strncpy(rend_query.onion_address, STR_HS_ADDR,
REND_SERVICE_ID_LEN_BASE32+1);
- rend_query.auth_type = 0;
+ rend_query.auth_type = REND_NO_AUTH;
+ rend_query.hsdirs_fp = smartlist_new();
+ smartlist_add(rend_query.hsdirs_fp, tor_memdup(HSDIR_EXIST_ID,
+ DIGEST_LEN));
+
+ /* Compute descriptor ID for replica 0, should be STR_DESC_ID_BASE32. */
+ ret = rend_compute_v2_desc_id(rend_query.descriptor_id[0],
+ rend_query.onion_address,
+ NULL, 0, 0);
+ tt_int_op(ret, ==, 0);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32),
+ rend_query.descriptor_id[0], DIGEST_LEN);
+ /* Make sure rend_compute_v2_desc_id works properly. */
+ tt_mem_op(desc_id_base32, OP_EQ, STR_DESC_ID_BASE32,
+ sizeof(desc_id_base32));
/* test request event */
control_event_hs_descriptor_requested(&rend_query, HSDIR_EXIST_ID,
- STR_HS_ID);
+ STR_DESC_ID_BASE32);
expected_msg = "650 HS_DESC REQUESTED "STR_HS_ADDR" NO_AUTH "\
- STR_HSDIR_EXIST_LONGNAME" "STR_HS_ID"\r\n";
- test_assert(received_msg);
- test_streq(received_msg, expected_msg);
+ STR_HSDIR_EXIST_LONGNAME " " STR_DESC_ID_BASE32 "\r\n";
+ tt_assert(received_msg);
+ tt_str_op(received_msg,OP_EQ, expected_msg);
tor_free(received_msg);
/* test received event */
- rend_query.auth_type = 1;
- control_event_hs_descriptor_received(&rend_query, HSDIR_EXIST_ID);
+ rend_query.auth_type = REND_BASIC_AUTH;
+ control_event_hs_descriptor_received(rend_query.onion_address,
+ &rend_query, HSDIR_EXIST_ID);
expected_msg = "650 HS_DESC RECEIVED "STR_HS_ADDR" BASIC_AUTH "\
- STR_HSDIR_EXIST_LONGNAME"\r\n";
- test_assert(received_msg);
- test_streq(received_msg, expected_msg);
+ STR_HSDIR_EXIST_LONGNAME " " STR_DESC_ID_BASE32"\r\n";
+ tt_assert(received_msg);
+ tt_str_op(received_msg,OP_EQ, expected_msg);
tor_free(received_msg);
/* test failed event */
- rend_query.auth_type = 2;
- control_event_hs_descriptor_failed(&rend_query, HSDIR_NONE_EXIST_ID);
+ rend_query.auth_type = REND_STEALTH_AUTH;
+ control_event_hs_descriptor_failed(&rend_query,
+ HSDIR_NONE_EXIST_ID,
+ "QUERY_REJECTED");
expected_msg = "650 HS_DESC FAILED "STR_HS_ADDR" STEALTH_AUTH "\
- STR_HSDIR_NONE_EXIST_LONGNAME"\r\n";
- test_assert(received_msg);
- test_streq(received_msg, expected_msg);
+ STR_HSDIR_NONE_EXIST_LONGNAME" REASON=QUERY_REJECTED\r\n";
+ tt_assert(received_msg);
+ tt_str_op(received_msg,OP_EQ, expected_msg);
tor_free(received_msg);
/* test invalid auth type */
rend_query.auth_type = 999;
- control_event_hs_descriptor_failed(&rend_query, HSDIR_EXIST_ID);
+ control_event_hs_descriptor_failed(&rend_query,
+ HSDIR_EXIST_ID,
+ "QUERY_REJECTED");
expected_msg = "650 HS_DESC FAILED "STR_HS_ADDR" UNKNOWN "\
- STR_HSDIR_EXIST_LONGNAME"\r\n";
- test_assert(received_msg);
- test_streq(received_msg, expected_msg);
+ STR_HSDIR_EXIST_LONGNAME " " STR_DESC_ID_BASE32\
+ " REASON=QUERY_REJECTED\r\n";
+ tt_assert(received_msg);
+ tt_str_op(received_msg,OP_EQ, expected_msg);
tor_free(received_msg);
+ /* test valid content. */
+ char *exp_msg;
+ control_event_hs_descriptor_content(rend_query.onion_address,
+ STR_HS_CONTENT_DESC_ID, HSDIR_EXIST_ID,
+ hs_desc_content);
+ tor_asprintf(&exp_msg, "650+HS_DESC_CONTENT " STR_HS_ADDR " "\
+ STR_HS_CONTENT_DESC_ID " " STR_HSDIR_EXIST_LONGNAME\
+ "\r\n%s\r\n.\r\n650 OK\r\n", hs_desc_content);
+
+ tt_assert(received_msg);
+ tt_str_op(received_msg, OP_EQ, exp_msg);
+ tor_free(received_msg);
+ tor_free(exp_msg);
+ SMARTLIST_FOREACH(rend_query.hsdirs_fp, char *, d, tor_free(d));
+ smartlist_free(rend_query.hsdirs_fp);
+
done:
- UNMOCK(send_control_event_string);
+ UNMOCK(queue_control_event_string);
UNMOCK(node_describe_longname_by_id);
tor_free(received_msg);
}
+/* Make sure we always pick the right RP, given a well formatted
+ * Tor2webRendezvousPoints value. */
+static void
+test_pick_tor2web_rendezvous_node(void *arg)
+{
+ or_options_t *options = get_options_mutable();
+ const node_t *chosen_rp = NULL;
+ router_crn_flags_t flags = CRN_NEED_DESC;
+ int retval, i;
+ const char *tor2web_rendezvous_str = "test003r";
+
+ (void) arg;
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ /* Parse Tor2webRendezvousPoints as a routerset. */
+ options->Tor2webRendezvousPoints = routerset_new();
+ retval = routerset_parse(options->Tor2webRendezvousPoints,
+ tor2web_rendezvous_str,
+ "test_tor2web_rp");
+ tt_int_op(retval, >=, 0);
+
+ /* Pick rendezvous point. Make sure the correct one is
+ picked. Repeat many times to make sure it works properly. */
+ for (i = 0; i < 50 ; i++) {
+ chosen_rp = pick_tor2web_rendezvous_node(flags, options);
+ tt_assert(chosen_rp);
+ tt_str_op(chosen_rp->ri->nickname, ==, tor2web_rendezvous_str);
+ }
+
+ done:
+ routerset_free(options->Tor2webRendezvousPoints);
+}
+
+/* Make sure we never pick an RP if Tor2webRendezvousPoints doesn't
+ * correspond to an actual node. */
+static void
+test_pick_bad_tor2web_rendezvous_node(void *arg)
+{
+ or_options_t *options = get_options_mutable();
+ const node_t *chosen_rp = NULL;
+ router_crn_flags_t flags = CRN_NEED_DESC;
+ int retval, i;
+ const char *tor2web_rendezvous_str = "dummy";
+
+ (void) arg;
+
+ /* Setup fake routerlist. */
+ helper_setup_fake_routerlist();
+
+ /* Parse Tor2webRendezvousPoints as a routerset. */
+ options->Tor2webRendezvousPoints = routerset_new();
+ retval = routerset_parse(options->Tor2webRendezvousPoints,
+ tor2web_rendezvous_str,
+ "test_tor2web_rp");
+ tt_int_op(retval, >=, 0);
+
+ /* Pick rendezvous point. Since Tor2webRendezvousPoints was set to a
+ dummy value, we shouldn't find any eligible RPs. */
+ for (i = 0; i < 50 ; i++) {
+ chosen_rp = pick_tor2web_rendezvous_node(flags, options);
+ tt_assert(!chosen_rp);
+ }
+
+ done:
+ routerset_free(options->Tor2webRendezvousPoints);
+}
+
+/* Make sure rend_data_t is valid at creation, destruction and when
+ * duplicated. */
+static void
+test_hs_rend_data(void *arg)
+{
+ int rep;
+ rend_data_t *client = NULL, *client_dup = NULL;
+ /* Binary format of a descriptor ID. */
+ char desc_id[DIGEST_LEN];
+ char client_cookie[REND_DESC_COOKIE_LEN];
+ time_t now = time(NULL);
+ rend_data_t *service_dup = NULL;
+ rend_data_t *service = NULL;
+
+ (void)arg;
+
+ base32_decode(desc_id, sizeof(desc_id), STR_DESC_ID_BASE32,
+ REND_DESC_ID_V2_LEN_BASE32);
+ memset(client_cookie, 'e', sizeof(client_cookie));
+
+ client = rend_data_client_create(STR_HS_ADDR, desc_id, client_cookie,
+ REND_NO_AUTH);
+ tt_assert(client);
+ tt_int_op(client->auth_type, ==, REND_NO_AUTH);
+ tt_str_op(client->onion_address, OP_EQ, STR_HS_ADDR);
+ tt_mem_op(client->desc_id_fetch, OP_EQ, desc_id, sizeof(desc_id));
+ tt_mem_op(client->descriptor_cookie, OP_EQ, client_cookie,
+ sizeof(client_cookie));
+ tt_assert(client->hsdirs_fp);
+ tt_int_op(smartlist_len(client->hsdirs_fp), ==, 0);
+ for (rep = 0; rep < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; rep++) {
+ int ret = rend_compute_v2_desc_id(desc_id, client->onion_address,
+ client->descriptor_cookie, now, rep);
+ /* That shouldn't never fail. */
+ tt_int_op(ret, ==, 0);
+ tt_mem_op(client->descriptor_id[rep], OP_EQ, desc_id, sizeof(desc_id));
+ }
+ /* The rest should be zeroed because this is a client request. */
+ tt_int_op(tor_digest_is_zero(client->rend_pk_digest), ==, 1);
+ tt_int_op(tor_digest_is_zero(client->rend_cookie), ==, 1);
+
+ /* Test dup(). */
+ client_dup = rend_data_dup(client);
+ tt_assert(client_dup);
+ tt_int_op(client_dup->auth_type, ==, client->auth_type);
+ tt_str_op(client_dup->onion_address, OP_EQ, client->onion_address);
+ tt_mem_op(client_dup->desc_id_fetch, OP_EQ, client->desc_id_fetch,
+ sizeof(client_dup->desc_id_fetch));
+ tt_mem_op(client_dup->descriptor_cookie, OP_EQ, client->descriptor_cookie,
+ sizeof(client_dup->descriptor_cookie));
+
+ tt_assert(client_dup->hsdirs_fp);
+ tt_int_op(smartlist_len(client_dup->hsdirs_fp), ==, 0);
+ for (rep = 0; rep < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; rep++) {
+ tt_mem_op(client_dup->descriptor_id[rep], OP_EQ,
+ client->descriptor_id[rep], DIGEST_LEN);
+ }
+ /* The rest should be zeroed because this is a client request. */
+ tt_int_op(tor_digest_is_zero(client_dup->rend_pk_digest), ==, 1);
+ tt_int_op(tor_digest_is_zero(client_dup->rend_cookie), ==, 1);
+ rend_data_free(client);
+ client = NULL;
+ rend_data_free(client_dup);
+ client_dup = NULL;
+
+ /* Reset state. */
+ base32_decode(desc_id, sizeof(desc_id), STR_DESC_ID_BASE32,
+ REND_DESC_ID_V2_LEN_BASE32);
+ memset(client_cookie, 'e', sizeof(client_cookie));
+
+ /* Try with different parameters here for which some content should be
+ * zeroed out. */
+ client = rend_data_client_create(NULL, desc_id, NULL, REND_BASIC_AUTH);
+ tt_assert(client);
+ tt_int_op(client->auth_type, ==, REND_BASIC_AUTH);
+ tt_int_op(strlen(client->onion_address), ==, 0);
+ tt_mem_op(client->desc_id_fetch, OP_EQ, desc_id, sizeof(desc_id));
+ tt_int_op(tor_mem_is_zero(client->descriptor_cookie,
+ sizeof(client->descriptor_cookie)), ==, 1);
+ tt_assert(client->hsdirs_fp);
+ tt_int_op(smartlist_len(client->hsdirs_fp), ==, 0);
+ for (rep = 0; rep < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; rep++) {
+ tt_int_op(tor_digest_is_zero(client->descriptor_id[rep]), ==, 1);
+ }
+ /* The rest should be zeroed because this is a client request. */
+ tt_int_op(tor_digest_is_zero(client->rend_pk_digest), ==, 1);
+ tt_int_op(tor_digest_is_zero(client->rend_cookie), ==, 1);
+ rend_data_free(client);
+ client = NULL;
+
+ /* Let's test the service object now. */
+ char rend_pk_digest[DIGEST_LEN];
+ uint8_t rend_cookie[DIGEST_LEN];
+ memset(rend_pk_digest, 'f', sizeof(rend_pk_digest));
+ memset(rend_cookie, 'g', sizeof(rend_cookie));
+
+ service = rend_data_service_create(STR_HS_ADDR, rend_pk_digest,
+ rend_cookie, REND_NO_AUTH);
+ tt_assert(service);
+ tt_int_op(service->auth_type, ==, REND_NO_AUTH);
+ tt_str_op(service->onion_address, OP_EQ, STR_HS_ADDR);
+ tt_mem_op(service->rend_pk_digest, OP_EQ, rend_pk_digest,
+ sizeof(rend_pk_digest));
+ tt_mem_op(service->rend_cookie, OP_EQ, rend_cookie, sizeof(rend_cookie));
+ tt_assert(service->hsdirs_fp);
+ tt_int_op(smartlist_len(service->hsdirs_fp), ==, 0);
+ for (rep = 0; rep < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; rep++) {
+ tt_int_op(tor_digest_is_zero(service->descriptor_id[rep]), ==, 1);
+ }
+ /* The rest should be zeroed because this is a service request. */
+ tt_int_op(tor_digest_is_zero(service->descriptor_cookie), ==, 1);
+ tt_int_op(tor_digest_is_zero(service->desc_id_fetch), ==, 1);
+
+ /* Test dup(). */
+ service_dup = rend_data_dup(service);
+ tt_assert(service_dup);
+ tt_int_op(service_dup->auth_type, ==, service->auth_type);
+ tt_str_op(service_dup->onion_address, OP_EQ, service->onion_address);
+ tt_mem_op(service_dup->rend_pk_digest, OP_EQ, service->rend_pk_digest,
+ sizeof(service_dup->rend_pk_digest));
+ tt_mem_op(service_dup->rend_cookie, OP_EQ, service->rend_cookie,
+ sizeof(service_dup->rend_cookie));
+ tt_assert(service_dup->hsdirs_fp);
+ tt_int_op(smartlist_len(service_dup->hsdirs_fp), ==, 0);
+ for (rep = 0; rep < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; rep++) {
+ tt_int_op(tor_digest_is_zero(service_dup->descriptor_id[rep]), ==, 1);
+ }
+ /* The rest should be zeroed because this is a service request. */
+ tt_int_op(tor_digest_is_zero(service_dup->descriptor_cookie), ==, 1);
+ tt_int_op(tor_digest_is_zero(service_dup->desc_id_fetch), ==, 1);
+
+ done:
+ rend_data_free(service);
+ rend_data_free(service_dup);
+ rend_data_free(client);
+ rend_data_free(client_dup);
+}
+
struct testcase_t hs_tests[] = {
+ { "hs_rend_data", test_hs_rend_data, TT_FORK,
+ NULL, NULL },
{ "hs_desc_event", test_hs_desc_event, TT_FORK,
NULL, NULL },
+ { "pick_tor2web_rendezvous_node", test_pick_tor2web_rendezvous_node, TT_FORK,
+ NULL, NULL },
+ { "pick_bad_tor2web_rendezvous_node",
+ test_pick_bad_tor2web_rendezvous_node, TT_FORK,
+ NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_introduce.c b/src/test/test_introduce.c
index 69c1152229..9c7a86da66 100644
--- a/src/test/test_introduce.c
+++ b/src/test/test_introduce.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2012-2013, The Tor Project, Inc. */
+/* Copyright (c) 2012-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -290,48 +290,48 @@ do_parse_test(uint8_t *plaintext, size_t plaintext_len, int phase)
/* Get a key */
k = crypto_pk_new();
- test_assert(k);
+ tt_assert(k);
r = crypto_pk_read_private_key_from_string(k, AUTHORITY_SIGNKEY_1, -1);
- test_assert(!r);
+ tt_assert(!r);
/* Get digest for future comparison */
r = crypto_pk_get_digest(k, digest);
- test_assert(r >= 0);
+ tt_assert(r >= 0);
/* Make a cell out of it */
r = make_intro_from_plaintext(
plaintext, plaintext_len,
k, (void **)(&cell));
- test_assert(r > 0);
- test_assert(cell);
+ tt_assert(r > 0);
+ tt_assert(cell);
cell_len = r;
/* Do early parsing */
parsed_req = rend_service_begin_parse_intro(cell, cell_len, 2, &err_msg);
- test_assert(parsed_req);
- test_assert(!err_msg);
- test_memeq(parsed_req->pk, digest, DIGEST_LEN);
- test_assert(parsed_req->ciphertext);
- test_assert(parsed_req->ciphertext_len > 0);
+ tt_assert(parsed_req);
+ tt_assert(!err_msg);
+ tt_mem_op(parsed_req->pk,OP_EQ, digest, DIGEST_LEN);
+ tt_assert(parsed_req->ciphertext);
+ tt_assert(parsed_req->ciphertext_len > 0);
if (phase == EARLY_PARSE_ONLY)
goto done;
/* Do decryption */
r = rend_service_decrypt_intro(parsed_req, k, &err_msg);
- test_assert(!r);
- test_assert(!err_msg);
- test_assert(parsed_req->plaintext);
- test_assert(parsed_req->plaintext_len > 0);
+ tt_assert(!r);
+ tt_assert(!err_msg);
+ tt_assert(parsed_req->plaintext);
+ tt_assert(parsed_req->plaintext_len > 0);
if (phase == DECRYPT_ONLY)
goto done;
/* Do late parsing */
r = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
- test_assert(!r);
- test_assert(!err_msg);
- test_assert(parsed_req->parsed);
+ tt_assert(!r);
+ tt_assert(!err_msg);
+ tt_assert(parsed_req->parsed);
done:
tor_free(cell);
@@ -371,14 +371,14 @@ make_intro_from_plaintext(
/* Compute key digest (will be first DIGEST_LEN octets of cell) */
r = crypto_pk_get_digest(key, cell);
- test_assert(r >= 0);
+ tt_assert(r >= 0);
/* Do encryption */
r = crypto_pk_public_hybrid_encrypt(
key, cell + DIGEST_LEN, ciphertext_size,
buf, len,
PK_PKCS1_OAEP_PADDING, 0);
- test_assert(r >= 0);
+ tt_assert(r >= 0);
/* Figure out cell length */
cell_len = DIGEST_LEN + r;
@@ -394,8 +394,9 @@ make_intro_from_plaintext(
*/
static void
-test_introduce_decrypt_v0(void)
+test_introduce_decrypt_v0(void *arg)
{
+ (void)arg;
do_decrypt_test(v0_test_plaintext, sizeof(v0_test_plaintext));
}
@@ -403,8 +404,9 @@ test_introduce_decrypt_v0(void)
*/
static void
-test_introduce_decrypt_v1(void)
+test_introduce_decrypt_v1(void *arg)
{
+ (void)arg;
do_decrypt_test(v1_test_plaintext, sizeof(v1_test_plaintext));
}
@@ -412,8 +414,9 @@ test_introduce_decrypt_v1(void)
*/
static void
-test_introduce_decrypt_v2(void)
+test_introduce_decrypt_v2(void *arg)
{
+ (void)arg;
do_decrypt_test(v2_test_plaintext, sizeof(v2_test_plaintext));
}
@@ -421,8 +424,9 @@ test_introduce_decrypt_v2(void)
*/
static void
-test_introduce_decrypt_v3(void)
+test_introduce_decrypt_v3(void *arg)
{
+ (void)arg;
do_decrypt_test(
v3_no_auth_test_plaintext, sizeof(v3_no_auth_test_plaintext));
do_decrypt_test(
@@ -433,8 +437,9 @@ test_introduce_decrypt_v3(void)
*/
static void
-test_introduce_early_parse_v0(void)
+test_introduce_early_parse_v0(void *arg)
{
+ (void)arg;
do_early_parse_test(v0_test_plaintext, sizeof(v0_test_plaintext));
}
@@ -442,8 +447,9 @@ test_introduce_early_parse_v0(void)
*/
static void
-test_introduce_early_parse_v1(void)
+test_introduce_early_parse_v1(void *arg)
{
+ (void)arg;
do_early_parse_test(v1_test_plaintext, sizeof(v1_test_plaintext));
}
@@ -451,8 +457,9 @@ test_introduce_early_parse_v1(void)
*/
static void
-test_introduce_early_parse_v2(void)
+test_introduce_early_parse_v2(void *arg)
{
+ (void)arg;
do_early_parse_test(v2_test_plaintext, sizeof(v2_test_plaintext));
}
@@ -460,8 +467,9 @@ test_introduce_early_parse_v2(void)
*/
static void
-test_introduce_early_parse_v3(void)
+test_introduce_early_parse_v3(void *arg)
{
+ (void)arg;
do_early_parse_test(
v3_no_auth_test_plaintext, sizeof(v3_no_auth_test_plaintext));
do_early_parse_test(
@@ -472,8 +480,9 @@ test_introduce_early_parse_v3(void)
*/
static void
-test_introduce_late_parse_v0(void)
+test_introduce_late_parse_v0(void *arg)
{
+ (void)arg;
do_late_parse_test(v0_test_plaintext, sizeof(v0_test_plaintext));
}
@@ -481,8 +490,9 @@ test_introduce_late_parse_v0(void)
*/
static void
-test_introduce_late_parse_v1(void)
+test_introduce_late_parse_v1(void *arg)
{
+ (void)arg;
do_late_parse_test(v1_test_plaintext, sizeof(v1_test_plaintext));
}
@@ -490,8 +500,9 @@ test_introduce_late_parse_v1(void)
*/
static void
-test_introduce_late_parse_v2(void)
+test_introduce_late_parse_v2(void *arg)
{
+ (void)arg;
do_late_parse_test(v2_test_plaintext, sizeof(v2_test_plaintext));
}
@@ -499,8 +510,9 @@ test_introduce_late_parse_v2(void)
*/
static void
-test_introduce_late_parse_v3(void)
+test_introduce_late_parse_v3(void *arg)
{
+ (void)arg;
do_late_parse_test(
v3_no_auth_test_plaintext, sizeof(v3_no_auth_test_plaintext));
do_late_parse_test(
@@ -508,7 +520,7 @@ test_introduce_late_parse_v3(void)
}
#define INTRODUCE_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_introduce_ ## name }
+ { #name, test_introduce_ ## name , 0, NULL, NULL }
struct testcase_t introduce_tests[] = {
INTRODUCE_LEGACY(early_parse_v0),
diff --git a/src/test/test_keygen.sh b/src/test/test_keygen.sh
new file mode 100755
index 0000000000..87012cd283
--- /dev/null
+++ b/src/test/test_keygen.sh
@@ -0,0 +1,368 @@
+#!/bin/sh
+
+# Note: some of this code is lifted from zero_length_keys.sh, and could be
+# unified.
+
+umask 077
+set -e
+
+if [ $# -eq 0 ] || [ ! -f ${1} ] || [ ! -x ${1} ]; then
+ if [ "$TESTING_TOR_BINARY" = "" ] ; then
+ echo "Usage: ${0} PATH_TO_TOR [case-number]"
+ exit 1
+ fi
+fi
+
+if [ $# -ge 1 ]; then
+ TOR_BINARY="${1}"
+ shift
+else
+ TOR_BINARY="${TESTING_TOR_BINARY}"
+fi
+
+
+
+ if [ $# -ge 1 ]; then
+ dflt=0
+ else
+ dflt=1
+ fi
+
+ CASE2A=$dflt
+ CASE2B=$dflt
+ CASE3A=$dflt
+ CASE3B=$dflt
+ CASE3C=$dflt
+ CASE4=$dflt
+ CASE5=$dflt
+ CASE6=$dflt
+ CASE7=$dflt
+ CASE8=$dflt
+ CASE9=$dflt
+ CASE10=$dflt
+
+ if [ $# -ge 1 ]; then
+ eval "CASE${1}"=1
+ fi
+
+
+dump() { xxd -p "$1" | tr -d '\n '; }
+die() { echo "$1" >&2 ; exit 5; }
+check_dir() { [ -d "$1" ] || die "$1 did not exist"; }
+check_file() { [ -e "$1" ] || die "$1 did not exist"; }
+check_no_file() { [ -e "$1" ] && die "$1 was not supposed to exist" || true; }
+check_files_eq() { cmp "$1" "$2" || die "$1 and $2 did not match: `dump $1` vs `dump $2`"; }
+check_keys_eq() { check_files_eq "${SRC}/keys/${1}" "${ME}/keys/${1}"; }
+
+DATA_DIR=`mktemp -d -t tor_keygen_tests.XXXXXX`
+if [ -z "$DATA_DIR" ]; then
+ echo "Failure: mktemp invocation returned empty string" >&2
+ exit 3
+fi
+if [ ! -d "$DATA_DIR" ]; then
+ echo "Failure: mktemp invocation result doesn't point to directory" >&2
+ exit 3
+fi
+trap "rm -rf '$DATA_DIR'" 0
+
+# Use an absolute path for this or Tor will complain
+DATA_DIR=`cd "${DATA_DIR}" && pwd`
+
+touch "${DATA_DIR}/empty_torrc"
+
+QUIETLY="--hush"
+SILENTLY="--quiet"
+TOR="${TOR_BINARY} ${QUIETLY} --DisableNetwork 1 --ShutdownWaitLength 0 --ORPort 12345 --ExitRelay 0 -f ${DATA_DIR}/empty_torrc"
+
+##### SETUP
+#
+# Here we create three sets of keys: one using "tor", one using "tor
+# --keygen", and one using "tor --keygen" and encryption. We'll be
+# copying them into different keys directories in order to simulate
+# different kinds of configuration problems/issues.
+
+# Step 1: Start Tor with --list-fingerprint --quiet. Make sure everything is there.
+mkdir "${DATA_DIR}/orig"
+${TOR} --DataDirectory "${DATA_DIR}/orig" --list-fingerprint ${SILENTLY} > /dev/null
+
+check_dir "${DATA_DIR}/orig/keys"
+check_file "${DATA_DIR}/orig/keys/ed25519_master_id_public_key"
+check_file "${DATA_DIR}/orig/keys/ed25519_master_id_secret_key"
+check_file "${DATA_DIR}/orig/keys/ed25519_signing_cert"
+check_file "${DATA_DIR}/orig/keys/ed25519_signing_secret_key"
+
+# Step 2: Start Tor with --keygen. Make sure everything is there.
+mkdir "${DATA_DIR}/keygen"
+${TOR} --DataDirectory "${DATA_DIR}/keygen" --keygen --no-passphrase 2>"${DATA_DIR}/keygen/stderr"
+grep "Not encrypting the secret key" "${DATA_DIR}/keygen/stderr" >/dev/null || die "Tor didn't declare that there would be no encryption"
+
+check_dir "${DATA_DIR}/keygen/keys"
+check_file "${DATA_DIR}/keygen/keys/ed25519_master_id_public_key"
+check_file "${DATA_DIR}/keygen/keys/ed25519_master_id_secret_key"
+check_file "${DATA_DIR}/keygen/keys/ed25519_signing_cert"
+check_file "${DATA_DIR}/keygen/keys/ed25519_signing_secret_key"
+
+# Step 3: Start Tor with --keygen and a passphrase.
+# Make sure everything is there.
+mkdir "${DATA_DIR}/encrypted"
+echo "passphrase" | ${TOR} --DataDirectory "${DATA_DIR}/encrypted" --keygen --passphrase-fd 0
+
+check_dir "${DATA_DIR}/encrypted/keys"
+check_file "${DATA_DIR}/encrypted/keys/ed25519_master_id_public_key"
+check_file "${DATA_DIR}/encrypted/keys/ed25519_master_id_secret_key_encrypted"
+check_file "${DATA_DIR}/encrypted/keys/ed25519_signing_cert"
+check_file "${DATA_DIR}/encrypted/keys/ed25519_signing_secret_key"
+
+
+echo "=== Starting keygen tests."
+
+#
+# The "case X" numbers below come from s7r's email on
+# https://lists.torproject.org/pipermail/tor-dev/2015-August/009204.html
+
+
+# Case 2a: Missing secret key, public key exists, start tor.
+
+if [ "$CASE2A" = 1 ]; then
+
+ME="${DATA_DIR}/case2a"
+SRC="${DATA_DIR}/orig"
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint > "${ME}/stdout" && die "Somehow succeeded when missing secret key, certs: `cat ${ME}/stdout`" || true
+check_files_eq "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/ed25519_master_id_public_key"
+
+grep "We needed to load a secret key.*but couldn't find it" "${ME}/stdout" >/dev/null || die "Tor didn't declare that it was missing a secret key"
+
+echo "==== Case 2A ok"
+fi
+
+# Case 2b: Encrypted secret key, public key exists, start tor.
+
+if [ "$CASE2B" = 1 ]; then
+
+ME="${DATA_DIR}/case2b"
+SRC="${DATA_DIR}/encrypted"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_master_id_secret_key_encrypted" "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint > "${ME}/stdout" && dir "Somehow succeeded with encrypted secret key, missing certs"
+
+check_files_eq "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/ed25519_master_id_public_key"
+check_files_eq "${SRC}/keys/ed25519_master_id_secret_key_encrypted" "${ME}/keys/ed25519_master_id_secret_key_encrypted"
+
+grep "We needed to load a secret key.*but it was encrypted.*--keygen" "${ME}/stdout" >/dev/null || die "Tor didn't declare that it was missing a secret key and suggest --keygen."
+
+echo "==== Case 2B ok"
+
+fi
+
+# Case 3a: Start Tor with only master key.
+
+if [ "$CASE3A" = 1 ]; then
+
+ME="${DATA_DIR}/case3a"
+SRC="${DATA_DIR}/orig"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_"* "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} >/dev/null || die "Tor failed when starting with only master key"
+check_files_eq "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/ed25519_master_id_public_key"
+check_files_eq "${SRC}/keys/ed25519_master_id_secret_key" "${ME}/keys/ed25519_master_id_secret_key"
+check_file "${ME}/keys/ed25519_signing_cert"
+check_file "${ME}/keys/ed25519_signing_secret_key"
+
+echo "==== Case 3A ok"
+
+fi
+
+# Case 3b: Call keygen with only unencrypted master key.
+
+if [ "$CASE3B" = 1 ]; then
+
+ME="${DATA_DIR}/case3b"
+SRC="${DATA_DIR}/orig"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_"* "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --keygen || die "Keygen failed with only master key"
+check_files_eq "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/ed25519_master_id_public_key"
+check_files_eq "${SRC}/keys/ed25519_master_id_secret_key" "${ME}/keys/ed25519_master_id_secret_key"
+check_file "${ME}/keys/ed25519_signing_cert"
+check_file "${ME}/keys/ed25519_signing_secret_key"
+
+echo "==== Case 3B ok"
+
+fi
+
+# Case 3c: Call keygen with only encrypted master key.
+
+if [ "$CASE3C" = 1 ]; then
+
+ME="${DATA_DIR}/case3c"
+SRC="${DATA_DIR}/encrypted"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_"* "${ME}/keys/"
+echo "passphrase" | ${TOR} --DataDirectory "${ME}" --keygen --passphrase-fd 0 || die "Keygen failed with only encrypted master key"
+check_files_eq "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/ed25519_master_id_public_key"
+check_files_eq "${SRC}/keys/ed25519_master_id_secret_key_encrypted" "${ME}/keys/ed25519_master_id_secret_key_encrypted"
+check_file "${ME}/keys/ed25519_signing_cert"
+check_file "${ME}/keys/ed25519_signing_secret_key"
+
+echo "==== Case 3C ok"
+
+fi
+
+# Case 4: Make a new data directory with only an unencrypted secret key.
+# Then start tor. The rest should become correct.
+
+if [ "$CASE4" = 1 ]; then
+
+ME="${DATA_DIR}/case4"
+SRC="${DATA_DIR}/orig"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_secret_key" "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} > "${ME}/fp1" || die "Tor wouldn't start with only unencrypted secret key"
+check_file "${ME}/keys/ed25519_master_id_public_key"
+check_file "${ME}/keys/ed25519_signing_cert"
+check_file "${ME}/keys/ed25519_signing_secret_key"
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} > "${ME}/fp2" || die "Tor wouldn't start again after starting once with only unencrypted secret key."
+
+check_files_eq "${ME}/fp1" "${ME}/fp2"
+
+echo "==== Case 4 ok"
+
+fi
+
+# Case 5: Make a new data directory with only an encrypted secret key.
+
+if [ "$CASE5" = 1 ]; then
+
+ME="${DATA_DIR}/case5"
+SRC="${DATA_DIR}/encrypted"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_secret_key_encrypted" "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint >"${ME}/stdout" && die "Tor started with only encrypted secret key!"
+check_no_file "${ME}/keys/ed25519_master_id_public_key"
+check_no_file "${ME}/keys/ed25519_master_id_public_key"
+
+grep "but not public key file" "${ME}/stdout" >/dev/null || die "Tor didn't declare it couldn't find a public key."
+
+echo "==== Case 5 ok"
+
+fi
+
+# Case 6: Make a new data directory with encrypted secret key and public key
+
+if [ "$CASE6" = 1 ]; then
+
+ME="${DATA_DIR}/case6"
+SRC="${DATA_DIR}/encrypted"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_secret_key_encrypted" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/"
+${TOR} --DataDirectory "${ME}" --list-fingerprint > "${ME}/stdout" && die "Tor started with encrypted secret key and no certs" || true
+check_no_file "${ME}/keys/ed25519_signing_cert"
+check_no_file "${ME}/keys/ed25519_signing_secret_key"
+
+grep "but it was encrypted" "${ME}/stdout" >/dev/null || die "Tor didn't declare that the secret key was encrypted."
+
+echo "==== Case 6 ok"
+
+fi
+
+# Case 7: Make a new data directory with unencrypted secret key and
+# certificates; missing master public.
+
+if [ "$CASE7" = 1 ]; then
+
+ME="${DATA_DIR}/case7"
+SRC="${DATA_DIR}/keygen"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_secret_key" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_signing_cert" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_signing_secret_key" "${ME}/keys/"
+
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} >/dev/null || die "Failed when starting with missing public key"
+check_keys_eq ed25519_master_id_secret_key
+check_keys_eq ed25519_master_id_public_key
+check_keys_eq ed25519_signing_secret_key
+check_keys_eq ed25519_signing_cert
+
+echo "==== Case 7 ok"
+
+fi
+
+# Case 8: offline master secret key.
+
+if [ "$CASE8" = 1 ]; then
+
+ME="${DATA_DIR}/case8"
+SRC="${DATA_DIR}/keygen"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_signing_cert" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_signing_secret_key" "${ME}/keys/"
+
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} >/dev/null || die "Failed when starting with offline secret key"
+check_no_file "${ME}/keys/ed25519_master_id_secret_key"
+check_keys_eq ed25519_master_id_public_key
+check_keys_eq ed25519_signing_secret_key
+check_keys_eq ed25519_signing_cert
+
+echo "==== Case 8 ok"
+
+fi
+
+# Case 9: signing cert and secret key provided; could infer master key.
+
+if [ "$CASE9" = 1 ]; then
+
+ME="${DATA_DIR}/case9"
+SRC="${DATA_DIR}/keygen"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_signing_cert" "${ME}/keys/"
+cp "${SRC}/keys/ed25519_signing_secret_key" "${ME}/keys/"
+
+${TOR} --DataDirectory "${ME}" --list-fingerprint ${SILENTLY} >/dev/null || die "Failed when starting with only signing material"
+check_no_file "${ME}/keys/ed25519_master_id_secret_key"
+check_file "${ME}/keys/ed25519_master_id_public_key"
+check_keys_eq ed25519_signing_secret_key
+check_keys_eq ed25519_signing_cert
+
+echo "==== Case 9 ok"
+
+fi
+
+
+# Case 10: master key mismatch.
+
+if [ "$CASE10" = 1 ]; then
+
+ME="${DATA_DIR}/case10"
+SRC="${DATA_DIR}/keygen"
+OTHER="${DATA_DIR}/orig"
+
+mkdir -p "${ME}/keys"
+cp "${SRC}/keys/ed25519_master_id_public_key" "${ME}/keys/"
+cp "${OTHER}/keys/ed25519_master_id_secret_key" "${ME}/keys/"
+
+${TOR} --DataDirectory "${ME}" --list-fingerprint >"${ME}/stdout" && die "Successfully started with mismatched keys!?" || true
+
+grep "public_key does not match.*secret_key" "${ME}/stdout" >/dev/null || die "Tor didn't declare that there was a key mismatch"
+
+echo "==== Case 10 ok"
+
+fi
+
+
+# Check cert-only.
+
diff --git a/src/test/test_keypin.c b/src/test/test_keypin.c
new file mode 100644
index 0000000000..95657349c6
--- /dev/null
+++ b/src/test/test_keypin.c
@@ -0,0 +1,256 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#define KEYPIN_PRIVATE
+#include "or.h"
+#include "keypin.h"
+#include "util.h"
+
+#include "test.h"
+
+static void
+test_keypin_parse_line(void *arg)
+{
+ (void)arg;
+ keypin_ent_t *ent = NULL;
+
+ /* Good line */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(ent);
+ tt_mem_op(ent->rsa_id, ==, "here is a good sha1!", 20);
+ tt_mem_op(ent->ed25519_key, ==, "This ed25519 scoffs at the sha1.", 32);
+ tor_free(ent); ent = NULL;
+
+ /* Good line with extra stuff we will ignore. */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4helloworld");
+ tt_assert(ent);
+ tt_mem_op(ent->rsa_id, ==, "here is a good sha1!", 20);
+ tt_mem_op(ent->ed25519_key, ==, "This ed25519 scoffs at the sha1.", 32);
+ tor_free(ent); ent = NULL;
+
+ /* Bad line: no space in the middle. */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE?"
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ /* Bad line: bad base64 in RSA ID */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdv!2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ /* Bad line: bad base64 in Ed25519 */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyB!dCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ done:
+ tor_free(ent);
+}
+
+static smartlist_t *mock_addent_got = NULL;
+static void
+mock_addent(keypin_ent_t *ent)
+{
+ smartlist_add(mock_addent_got, ent);
+ keypin_add_entry_to_map__real(ent);
+}
+
+static void
+test_keypin_parse_file(void *arg)
+{
+ (void)arg;
+
+ mock_addent_got = smartlist_new();
+ MOCK(keypin_add_entry_to_map, mock_addent);
+
+ /* Simple, minimal, correct example. */
+ const char data1[] =
+"PT09PT09PT09PT09PT09PT09PT0 PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0\n"
+"TG9yYXggaXBzdW0gZ3J1dnZ1bHU cyB0aG5lZWQgYW1ldCwgc25lcmdlbGx5IG9uY2UtbGU\n"
+"ciBsZXJraW0sIHNlZCBkbyBiYXI YmFsb290IHRlbXBvciBnbHVwcGl0dXMgdXQgbGFib3I\n"
+"ZSBldCB0cnVmZnVsYSBtYWduYSA YWxpcXVhLiBVdCBlbmltIGFkIGdyaWNrbGUtZ3Jhc3M\n"
+"dmVuaWFtLCBxdWlzIG1pZmYtbXU ZmZlcmVkIGdhLXp1bXBjbyBsYWJvcmlzIG5pc2kgdXQ\n"
+"Y3J1ZmZ1bHVzIGV4IGVhIHNjaGw b3BwaXR5IGNvbnNlcXVhdC4gRHVpcyBhdXRlIHNuYXI\n"
+"Z2dsZSBpbiBzd29tZWVzd2FucyA aW4gdm9sdXB0YXRlIGF4ZS1oYWNrZXIgZXNzZSByaXA\n"
+"cHVsdXMgY3J1bW1paSBldSBtb28 ZiBudWxsYSBzbnV2di5QTFVHSFBMT1ZFUlhZWlpZLi4\n";
+
+ tt_int_op(0, ==, keypin_load_journal_impl(data1, strlen(data1)));
+ tt_int_op(8, ==, smartlist_len(mock_addent_got));
+ keypin_ent_t *ent = smartlist_get(mock_addent_got, 2);
+ tt_mem_op(ent->rsa_id, ==, "r lerkim, sed do bar", 20);
+ tt_mem_op(ent->ed25519_key, ==, "baloot tempor gluppitus ut labor", 32);
+
+ /* More complex example: weird lines, bogus lines,
+ duplicate/conflicting lines */
+ const char data2[] =
+ "PT09PT09PT09PT09PT09PT09PT0 PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0\n"
+ "# This is a comment.\n"
+ " \n"
+ "QXQgdGhlIGVuZCBvZiB0aGUgeWU YXIgS3VycmVta2FybWVycnVrIHNhaWQgdG8gaGltLCA\n"
+ "IllvdSBoYXZlIG1hZGUgYSBnb28 ZCBiZWdpbm5pbmcuIiBCdXQgbm8gbW9yZS4gV2l6YXI\n"
+ "\n"
+ "ZHMgc3BlYWsgdHJ1dGgsIGFuZCA aXQgd2FzIHRydWUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ "@reserved for a future extension \n"
+ "eSBvZiBOYW1lcyB0aGF0IEdlZCA aGFkIHRvaWxlZCbyB3aW4gdGhhdCB5ZWFyIHdhcyA\n"
+ "eSBvZiBOYW1lcyB0aGF0IEdlZCA aGFkIHRvaWxlZCbyB3aW4gdGhhdCB5ZWFyIHdhcy"
+ "A line too long\n"
+ "dGhlIG1lcmUgc3RhcnQgb2Ygd2g YXQgaGUgbXVzdCBnbyBvb!BsZWFybmluZy4uLi4uLi4\n"
+ "ZHMgc3BlYWsgdaJ1dGgsIGFuZCA aXQgd2FzIHRydWUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ "ZHMgc3BlYWsgdHJ1dGgsIGFuZCA aXQgd2FzIHRydaUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ ;
+
+ tt_int_op(0, ==, keypin_load_journal_impl(data2, strlen(data2)));
+ tt_int_op(13, ==, smartlist_len(mock_addent_got));
+ ent = smartlist_get(mock_addent_got, 9);
+ tt_mem_op(ent->rsa_id, ==, "\"You have made a goo", 20);
+ tt_mem_op(ent->ed25519_key, ==, "d beginning.\" But no more. Wizar", 32);
+
+ ent = smartlist_get(mock_addent_got, 12);
+ tt_mem_op(ent->rsa_id, ==, "ds speak truth, and ", 20);
+ tt_mem_op(ent->ed25519_key, ==, "it was tru\xa5 that all the master\n", 32);
+
+ /* File truncated before NL */
+ const char data3[] =
+ "Tm8gZHJhZ29uIGNhbiByZXNpc3Q IHRoZSBmYXNjaW5hdGlvbiBvZiByaWRkbGluZyB0YWw";
+ tt_int_op(0, ==, keypin_load_journal_impl(data3, strlen(data3)));
+ tt_int_op(14, ==, smartlist_len(mock_addent_got));
+ ent = smartlist_get(mock_addent_got, 13);
+ tt_mem_op(ent->rsa_id, ==, "No dragon can resist", 20);
+ tt_mem_op(ent->ed25519_key, ==, " the fascination of riddling tal", 32);
+
+ done:
+ keypin_clear();
+ smartlist_free(mock_addent_got);
+}
+
+#define ADD(a,b) keypin_check_and_add((const uint8_t*)(a),\
+ (const uint8_t*)(b),0)
+#define LONE_RSA(a) keypin_check_lone_rsa((const uint8_t*)(a))
+
+static void
+test_keypin_add_entry(void *arg)
+{
+ (void)arg;
+ keypin_clear();
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_FOUND, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("Johnnies-come-lately",
+ "run-of-the-mill root-mean-square"));
+
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("gentleman-adventurer",
+ "hypersentimental closefistedness"));
+
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("disestablismentarian",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_FOUND, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_NOT_FOUND, ==, LONE_RSA("Llanfairpwllgwyngyll"));
+ tt_int_op(KEYPIN_MISMATCH, ==, LONE_RSA("Johnnies-come-lately"));
+
+ done:
+ keypin_clear();
+}
+
+static void
+test_keypin_journal(void *arg)
+{
+ (void)arg;
+ char *contents = NULL;
+ const char *fname = get_fname("keypin-journal");
+
+ tt_int_op(0, ==, keypin_load_journal(fname)); /* ENOENT is okay */
+ update_approx_time(1217709000);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("king-of-the-herrings",
+ "good-for-nothing attorney-at-law"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ keypin_close_journal();
+ keypin_clear();
+
+ tt_int_op(0, ==, keypin_load_journal(fname));
+ update_approx_time(1231041600);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("theatre-in-the-round",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("no-deposit-no-return",
+ "across-the-board will-o-the-wisp"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("intellectualizations",
+ "salt-and-pepper high-muck-a-muck"));
+ keypin_close_journal();
+ keypin_clear();
+
+ tt_int_op(0, ==, keypin_load_journal(fname));
+ update_approx_time(1412278354);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("intellectualizations",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("theatre-in-the-round",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("counterrevolutionary",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("no-deposit-no-return",
+ "floccinaucinihilipilificationism"));
+ keypin_close_journal();
+
+ contents = read_file_to_str(fname, RFTS_BIN, NULL);
+ tt_assert(contents);
+ tt_str_op(contents,==,
+ "\n"
+ "@opened-at 2008-08-02 20:30:00\n"
+ "a2luZy1vZi10aGUtaGVycmluZ3M Z29vZC1mb3Itbm90aGluZyBhdHRvcm5leS1hdC1sYXc\n"
+ "eWVsbG93aXNoLXJlZC15ZWxsb3c c2FsdC1hbmQtcGVwcGVyIGhpZ2gtbXVjay1hLW11Y2s\n"
+ "\n"
+ "@opened-at 2009-01-04 04:00:00\n"
+ "dGhlYXRyZS1pbi10aGUtcm91bmQ aG9saWVyLXRoYW4tdGhvdSBqYWNrLWluLXRoZS1ib3g\n"
+ "bm8tZGVwb3NpdC1uby1yZXR1cm4 YWNyb3NzLXRoZS1ib2FyZCB3aWxsLW8tdGhlLXdpc3A\n"
+ "\n"
+ "@opened-at 2014-10-02 19:32:34\n");
+
+ done:
+ tor_free(contents);
+ keypin_clear();
+}
+
+#undef ADD
+#undef LONE_RSA
+
+#define TEST(name, flags) \
+ { #name , test_keypin_ ## name, (flags), NULL, NULL }
+
+struct testcase_t keypin_tests[] = {
+ TEST( parse_line, 0 ),
+ TEST( parse_file, TT_FORK ),
+ TEST( add_entry, TT_FORK ),
+ TEST( journal, TT_FORK ),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_link_handshake.c b/src/test/test_link_handshake.c
new file mode 100644
index 0000000000..e8856c60de
--- /dev/null
+++ b/src/test/test_link_handshake.c
@@ -0,0 +1,928 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+
+#define CHANNELTLS_PRIVATE
+#define CONNECTION_PRIVATE
+#define TOR_CHANNEL_INTERNAL_
+#include "or.h"
+#include "config.h"
+#include "connection.h"
+#include "connection_or.h"
+#include "channeltls.h"
+#include "link_handshake.h"
+#include "scheduler.h"
+
+#include "test.h"
+
+var_cell_t *mock_got_var_cell = NULL;
+
+static void
+mock_write_var_cell(const var_cell_t *vc, or_connection_t *conn)
+{
+ (void)conn;
+
+ var_cell_t *newcell = var_cell_new(vc->payload_len);
+ memcpy(newcell, vc, sizeof(var_cell_t));
+ memcpy(newcell->payload, vc->payload, vc->payload_len);
+
+ mock_got_var_cell = newcell;
+}
+static int
+mock_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert)
+{
+ (void) tls;
+ (void) cert; // XXXX look at this.
+ return 1;
+}
+
+static int mock_send_netinfo_called = 0;
+static int
+mock_send_netinfo(or_connection_t *conn)
+{
+ (void) conn;
+ ++mock_send_netinfo_called;// XXX check_this
+ return 0;
+}
+
+static int mock_close_called = 0;
+static void
+mock_close_for_err(or_connection_t *orconn, int flush)
+{
+ (void)orconn;
+ (void)flush;
+ ++mock_close_called;
+}
+
+static int mock_send_authenticate_called = 0;
+static int
+mock_send_authenticate(or_connection_t *conn, int type)
+{
+ (void) conn;
+ (void) type;
+ ++mock_send_authenticate_called;// XXX check_this
+ return 0;
+}
+
+/* Test good certs cells */
+static void
+test_link_handshake_certs_ok(void *arg)
+{
+ (void) arg;
+
+ or_connection_t *c1 = or_connection_new(CONN_TYPE_OR, AF_INET);
+ or_connection_t *c2 = or_connection_new(CONN_TYPE_OR, AF_INET);
+ var_cell_t *cell1 = NULL, *cell2 = NULL;
+ certs_cell_t *cc1 = NULL, *cc2 = NULL;
+ channel_tls_t *chan1 = NULL, *chan2 = NULL;
+ crypto_pk_t *key1 = NULL, *key2 = NULL;
+
+ scheduler_init();
+
+ MOCK(tor_tls_cert_matches_key, mock_tls_cert_matches_key);
+ MOCK(connection_or_write_var_cell_to_buf, mock_write_var_cell);
+ MOCK(connection_or_send_netinfo, mock_send_netinfo);
+
+ key1 = pk_generate(2);
+ key2 = pk_generate(3);
+
+ /* We need to make sure that our TLS certificates are set up before we can
+ * actually generate a CERTS cell.
+ */
+ tt_int_op(tor_tls_context_init(TOR_TLS_CTX_IS_PUBLIC_SERVER,
+ key1, key2, 86400), ==, 0);
+
+ c1->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ c1->link_proto = 3;
+ tt_int_op(connection_init_or_handshake_state(c1, 1), ==, 0);
+
+ c2->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ c2->link_proto = 3;
+ tt_int_op(connection_init_or_handshake_state(c2, 0), ==, 0);
+
+ tt_int_op(0, ==, connection_or_send_certs_cell(c1));
+ tt_assert(mock_got_var_cell);
+ cell1 = mock_got_var_cell;
+
+ tt_int_op(0, ==, connection_or_send_certs_cell(c2));
+ tt_assert(mock_got_var_cell);
+ cell2 = mock_got_var_cell;
+
+ tt_int_op(cell1->command, ==, CELL_CERTS);
+ tt_int_op(cell1->payload_len, >, 1);
+
+ tt_int_op(cell2->command, ==, CELL_CERTS);
+ tt_int_op(cell2->payload_len, >, 1);
+
+ tt_int_op(cell1->payload_len, ==,
+ certs_cell_parse(&cc1, cell1->payload, cell1->payload_len));
+ tt_int_op(cell2->payload_len, ==,
+ certs_cell_parse(&cc2, cell2->payload, cell2->payload_len));
+
+ tt_int_op(2, ==, cc1->n_certs);
+ tt_int_op(2, ==, cc2->n_certs);
+
+ tt_int_op(certs_cell_get_certs(cc1, 0)->cert_type, ==,
+ CERTTYPE_RSA1024_ID_AUTH);
+ tt_int_op(certs_cell_get_certs(cc1, 1)->cert_type, ==,
+ CERTTYPE_RSA1024_ID_ID);
+
+ tt_int_op(certs_cell_get_certs(cc2, 0)->cert_type, ==,
+ CERTTYPE_RSA1024_ID_LINK);
+ tt_int_op(certs_cell_get_certs(cc2, 1)->cert_type, ==,
+ CERTTYPE_RSA1024_ID_ID);
+
+ chan1 = tor_malloc_zero(sizeof(*chan1));
+ channel_tls_common_init(chan1);
+ c1->chan = chan1;
+ chan1->conn = c1;
+ c1->base_.address = tor_strdup("C1");
+ c1->tls = tor_tls_new(-1, 0);
+ c1->link_proto = 4;
+ c1->base_.conn_array_index = -1;
+ crypto_pk_get_digest(key2, c1->identity_digest);
+
+ channel_tls_process_certs_cell(cell2, chan1);
+
+ tt_assert(c1->handshake_state->received_certs_cell);
+ tt_assert(c1->handshake_state->auth_cert == NULL);
+ tt_assert(c1->handshake_state->id_cert);
+ tt_assert(! tor_mem_is_zero(
+ (char*)c1->handshake_state->authenticated_peer_id, 20));
+
+ chan2 = tor_malloc_zero(sizeof(*chan2));
+ channel_tls_common_init(chan2);
+ c2->chan = chan2;
+ chan2->conn = c2;
+ c2->base_.address = tor_strdup("C2");
+ c2->tls = tor_tls_new(-1, 1);
+ c2->link_proto = 4;
+ c2->base_.conn_array_index = -1;
+ crypto_pk_get_digest(key1, c2->identity_digest);
+
+ channel_tls_process_certs_cell(cell1, chan2);
+
+ tt_assert(c2->handshake_state->received_certs_cell);
+ tt_assert(c2->handshake_state->auth_cert);
+ tt_assert(c2->handshake_state->id_cert);
+ tt_assert(tor_mem_is_zero(
+ (char*)c2->handshake_state->authenticated_peer_id, 20));
+
+ done:
+ UNMOCK(tor_tls_cert_matches_key);
+ UNMOCK(connection_or_write_var_cell_to_buf);
+ UNMOCK(connection_or_send_netinfo);
+ connection_free_(TO_CONN(c1));
+ connection_free_(TO_CONN(c2));
+ tor_free(cell1);
+ tor_free(cell2);
+ certs_cell_free(cc1);
+ certs_cell_free(cc2);
+ if (chan1)
+ circuitmux_free(chan1->base_.cmux);
+ tor_free(chan1);
+ if (chan2)
+ circuitmux_free(chan2->base_.cmux);
+ tor_free(chan2);
+ crypto_pk_free(key1);
+ crypto_pk_free(key2);
+}
+
+typedef struct certs_data_s {
+ or_connection_t *c;
+ channel_tls_t *chan;
+ certs_cell_t *ccell;
+ var_cell_t *cell;
+ crypto_pk_t *key1, *key2;
+} certs_data_t;
+
+static int
+recv_certs_cleanup(const struct testcase_t *test, void *obj)
+{
+ (void)test;
+ certs_data_t *d = obj;
+ UNMOCK(tor_tls_cert_matches_key);
+ UNMOCK(connection_or_send_netinfo);
+ UNMOCK(connection_or_close_for_error);
+
+ if (d) {
+ tor_free(d->cell);
+ certs_cell_free(d->ccell);
+ connection_free_(TO_CONN(d->c));
+ circuitmux_free(d->chan->base_.cmux);
+ tor_free(d->chan);
+ crypto_pk_free(d->key1);
+ crypto_pk_free(d->key2);
+ tor_free(d);
+ }
+ return 1;
+}
+
+static void *
+recv_certs_setup(const struct testcase_t *test)
+{
+ (void)test;
+ certs_data_t *d = tor_malloc_zero(sizeof(*d));
+ certs_cell_cert_t *ccc1 = NULL;
+ certs_cell_cert_t *ccc2 = NULL;
+ ssize_t n;
+
+ d->c = or_connection_new(CONN_TYPE_OR, AF_INET);
+ d->chan = tor_malloc_zero(sizeof(*d->chan));
+ d->c->chan = d->chan;
+ d->c->base_.address = tor_strdup("HaveAnAddress");
+ d->c->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ d->chan->conn = d->c;
+ tt_int_op(connection_init_or_handshake_state(d->c, 1), ==, 0);
+ d->c->link_proto = 4;
+
+ d->key1 = pk_generate(2);
+ d->key2 = pk_generate(3);
+
+ tt_int_op(tor_tls_context_init(TOR_TLS_CTX_IS_PUBLIC_SERVER,
+ d->key1, d->key2, 86400), ==, 0);
+ d->ccell = certs_cell_new();
+ ccc1 = certs_cell_cert_new();
+ certs_cell_add_certs(d->ccell, ccc1);
+ ccc2 = certs_cell_cert_new();
+ certs_cell_add_certs(d->ccell, ccc2);
+ d->ccell->n_certs = 2;
+ ccc1->cert_type = 1;
+ ccc2->cert_type = 2;
+
+ const tor_x509_cert_t *a,*b;
+ const uint8_t *enca, *encb;
+ size_t lena, lenb;
+ tor_tls_get_my_certs(1, &a, &b);
+ tor_x509_cert_get_der(a, &enca, &lena);
+ tor_x509_cert_get_der(b, &encb, &lenb);
+ certs_cell_cert_setlen_body(ccc1, lena);
+ ccc1->cert_len = lena;
+ certs_cell_cert_setlen_body(ccc2, lenb);
+ ccc2->cert_len = lenb;
+
+ memcpy(certs_cell_cert_getarray_body(ccc1), enca, lena);
+ memcpy(certs_cell_cert_getarray_body(ccc2), encb, lenb);
+
+ d->cell = var_cell_new(4096);
+ d->cell->command = CELL_CERTS;
+
+ n = certs_cell_encode(d->cell->payload, 4096, d->ccell);
+ tt_int_op(n, >, 0);
+ d->cell->payload_len = n;
+
+ MOCK(tor_tls_cert_matches_key, mock_tls_cert_matches_key);
+ MOCK(connection_or_send_netinfo, mock_send_netinfo);
+ MOCK(connection_or_close_for_error, mock_close_for_err);
+
+ tt_int_op(0, ==, d->c->handshake_state->received_certs_cell);
+ tt_int_op(0, ==, mock_send_authenticate_called);
+ tt_int_op(0, ==, mock_send_netinfo_called);
+
+ return d;
+ done:
+ recv_certs_cleanup(test, d);
+ return NULL;
+}
+
+static struct testcase_setup_t setup_recv_certs = {
+ .setup_fn = recv_certs_setup,
+ .cleanup_fn = recv_certs_cleanup
+};
+
+static void
+test_link_handshake_recv_certs_ok(void *arg)
+{
+ certs_data_t *d = arg;
+ channel_tls_process_certs_cell(d->cell, d->chan);
+ tt_int_op(0, ==, mock_close_called);
+ tt_int_op(d->c->handshake_state->authenticated, ==, 1);
+ tt_int_op(d->c->handshake_state->received_certs_cell, ==, 1);
+ tt_assert(d->c->handshake_state->id_cert != NULL);
+ tt_assert(d->c->handshake_state->auth_cert == NULL);
+
+ done:
+ ;
+}
+
+static void
+test_link_handshake_recv_certs_ok_server(void *arg)
+{
+ certs_data_t *d = arg;
+ d->c->handshake_state->started_here = 0;
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 3;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 2;
+ ssize_t n = certs_cell_encode(d->cell->payload, 2048, d->ccell);
+ tt_int_op(n, >, 0);
+ d->cell->payload_len = n;
+ channel_tls_process_certs_cell(d->cell, d->chan);
+ tt_int_op(0, ==, mock_close_called);
+ tt_int_op(d->c->handshake_state->authenticated, ==, 0);
+ tt_int_op(d->c->handshake_state->received_certs_cell, ==, 1);
+ tt_assert(d->c->handshake_state->id_cert != NULL);
+ tt_assert(d->c->handshake_state->auth_cert != NULL);
+
+ done:
+ ;
+}
+
+#define CERTS_FAIL(name, code) \
+ static void \
+ test_link_handshake_recv_certs_ ## name(void *arg) \
+ { \
+ certs_data_t *d = arg; \
+ { code ; } \
+ channel_tls_process_certs_cell(d->cell, d->chan); \
+ tt_int_op(1, ==, mock_close_called); \
+ tt_int_op(0, ==, mock_send_authenticate_called); \
+ tt_int_op(0, ==, mock_send_netinfo_called); \
+ done: \
+ ; \
+ }
+
+CERTS_FAIL(badstate, d->c->base_.state = OR_CONN_STATE_CONNECTING)
+CERTS_FAIL(badproto, d->c->link_proto = 2)
+CERTS_FAIL(duplicate, d->c->handshake_state->received_certs_cell = 1)
+CERTS_FAIL(already_authenticated,
+ d->c->handshake_state->authenticated = 1)
+CERTS_FAIL(empty, d->cell->payload_len = 0)
+CERTS_FAIL(bad_circid, d->cell->circ_id = 1)
+CERTS_FAIL(truncated_1, d->cell->payload[0] = 5)
+CERTS_FAIL(truncated_2,
+ {
+ d->cell->payload_len = 4;
+ memcpy(d->cell->payload, "\x01\x01\x00\x05", 4);
+ })
+CERTS_FAIL(truncated_3,
+ {
+ d->cell->payload_len = 7;
+ memcpy(d->cell->payload, "\x01\x01\x00\x05""abc", 7);
+ })
+#define REENCODE() do { \
+ ssize_t n = certs_cell_encode(d->cell->payload, 4096, d->ccell); \
+ tt_int_op(n, >, 0); \
+ d->cell->payload_len = n; \
+ } while (0)
+
+CERTS_FAIL(not_x509,
+ {
+ certs_cell_cert_setlen_body(certs_cell_get_certs(d->ccell, 0), 3);
+ certs_cell_get_certs(d->ccell, 0)->cert_len = 3;
+ REENCODE();
+ })
+CERTS_FAIL(both_link,
+ {
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 1;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 1;
+ REENCODE();
+ })
+CERTS_FAIL(both_id_rsa,
+ {
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 2;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 2;
+ REENCODE();
+ })
+CERTS_FAIL(both_auth,
+ {
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 3;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 3;
+ REENCODE();
+ })
+CERTS_FAIL(wrong_labels_1,
+ {
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 2;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 1;
+ REENCODE();
+ })
+CERTS_FAIL(wrong_labels_2,
+ {
+ const tor_x509_cert_t *a;
+ const tor_x509_cert_t *b;
+ const uint8_t *enca;
+ size_t lena;
+ tor_tls_get_my_certs(1, &a, &b);
+ tor_x509_cert_get_der(a, &enca, &lena);
+ certs_cell_cert_setlen_body(certs_cell_get_certs(d->ccell, 1), lena);
+ memcpy(certs_cell_cert_getarray_body(certs_cell_get_certs(d->ccell, 1)),
+ enca, lena);
+ certs_cell_get_certs(d->ccell, 1)->cert_len = lena;
+ REENCODE();
+ })
+CERTS_FAIL(wrong_labels_3,
+ {
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 2;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 3;
+ REENCODE();
+ })
+CERTS_FAIL(server_missing_certs,
+ {
+ d->c->handshake_state->started_here = 0;
+ })
+CERTS_FAIL(server_wrong_labels_1,
+ {
+ d->c->handshake_state->started_here = 0;
+ certs_cell_get_certs(d->ccell, 0)->cert_type = 2;
+ certs_cell_get_certs(d->ccell, 1)->cert_type = 3;
+ REENCODE();
+ })
+
+static void
+test_link_handshake_send_authchallenge(void *arg)
+{
+ (void)arg;
+
+ or_connection_t *c1 = or_connection_new(CONN_TYPE_OR, AF_INET);
+ var_cell_t *cell1=NULL, *cell2=NULL;
+
+ MOCK(connection_or_write_var_cell_to_buf, mock_write_var_cell);
+
+ tt_int_op(connection_init_or_handshake_state(c1, 0), ==, 0);
+ c1->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ tt_assert(! mock_got_var_cell);
+ tt_int_op(0, ==, connection_or_send_auth_challenge_cell(c1));
+ cell1 = mock_got_var_cell;
+ tt_int_op(0, ==, connection_or_send_auth_challenge_cell(c1));
+ cell2 = mock_got_var_cell;
+ tt_int_op(36, ==, cell1->payload_len);
+ tt_int_op(36, ==, cell2->payload_len);
+ tt_int_op(0, ==, cell1->circ_id);
+ tt_int_op(0, ==, cell2->circ_id);
+ tt_int_op(CELL_AUTH_CHALLENGE, ==, cell1->command);
+ tt_int_op(CELL_AUTH_CHALLENGE, ==, cell2->command);
+
+ tt_mem_op("\x00\x01\x00\x01", ==, cell1->payload + 32, 4);
+ tt_mem_op("\x00\x01\x00\x01", ==, cell2->payload + 32, 4);
+ tt_mem_op(cell1->payload, !=, cell2->payload, 32);
+
+ done:
+ UNMOCK(connection_or_write_var_cell_to_buf);
+ connection_free_(TO_CONN(c1));
+ tor_free(cell1);
+ tor_free(cell2);
+}
+
+typedef struct authchallenge_data_s {
+ or_connection_t *c;
+ channel_tls_t *chan;
+ var_cell_t *cell;
+} authchallenge_data_t;
+
+static int
+recv_authchallenge_cleanup(const struct testcase_t *test, void *obj)
+{
+ (void)test;
+ authchallenge_data_t *d = obj;
+
+ UNMOCK(connection_or_send_netinfo);
+ UNMOCK(connection_or_close_for_error);
+ UNMOCK(connection_or_send_authenticate_cell);
+
+ if (d) {
+ tor_free(d->cell);
+ connection_free_(TO_CONN(d->c));
+ circuitmux_free(d->chan->base_.cmux);
+ tor_free(d->chan);
+ tor_free(d);
+ }
+ return 1;
+}
+
+static void *
+recv_authchallenge_setup(const struct testcase_t *test)
+{
+ (void)test;
+ authchallenge_data_t *d = tor_malloc_zero(sizeof(*d));
+ d->c = or_connection_new(CONN_TYPE_OR, AF_INET);
+ d->chan = tor_malloc_zero(sizeof(*d->chan));
+ d->c->chan = d->chan;
+ d->c->base_.address = tor_strdup("HaveAnAddress");
+ d->c->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ d->chan->conn = d->c;
+ tt_int_op(connection_init_or_handshake_state(d->c, 1), ==, 0);
+ d->c->link_proto = 4;
+ d->c->handshake_state->received_certs_cell = 1;
+ d->cell = var_cell_new(128);
+ d->cell->payload_len = 38;
+ d->cell->payload[33] = 2;
+ d->cell->payload[35] = 7;
+ d->cell->payload[37] = 1;
+ d->cell->command = CELL_AUTH_CHALLENGE;
+
+ get_options_mutable()->ORPort_set = 1;
+
+ MOCK(connection_or_close_for_error, mock_close_for_err);
+ MOCK(connection_or_send_netinfo, mock_send_netinfo);
+ MOCK(connection_or_send_authenticate_cell, mock_send_authenticate);
+
+ tt_int_op(0, ==, d->c->handshake_state->received_auth_challenge);
+ tt_int_op(0, ==, mock_send_authenticate_called);
+ tt_int_op(0, ==, mock_send_netinfo_called);
+
+ return d;
+ done:
+ recv_authchallenge_cleanup(test, d);
+ return NULL;
+}
+
+static struct testcase_setup_t setup_recv_authchallenge = {
+ .setup_fn = recv_authchallenge_setup,
+ .cleanup_fn = recv_authchallenge_cleanup
+};
+
+static void
+test_link_handshake_recv_authchallenge_ok(void *arg)
+{
+ authchallenge_data_t *d = arg;
+
+ channel_tls_process_auth_challenge_cell(d->cell, d->chan);
+ tt_int_op(0, ==, mock_close_called);
+ tt_int_op(1, ==, d->c->handshake_state->received_auth_challenge);
+ tt_int_op(1, ==, mock_send_authenticate_called);
+ tt_int_op(1, ==, mock_send_netinfo_called);
+ done:
+ ;
+}
+
+static void
+test_link_handshake_recv_authchallenge_ok_noserver(void *arg)
+{
+ authchallenge_data_t *d = arg;
+ get_options_mutable()->ORPort_set = 0;
+
+ channel_tls_process_auth_challenge_cell(d->cell, d->chan);
+ tt_int_op(0, ==, mock_close_called);
+ tt_int_op(1, ==, d->c->handshake_state->received_auth_challenge);
+ tt_int_op(0, ==, mock_send_authenticate_called);
+ tt_int_op(0, ==, mock_send_netinfo_called);
+ done:
+ ;
+}
+
+static void
+test_link_handshake_recv_authchallenge_ok_unrecognized(void *arg)
+{
+ authchallenge_data_t *d = arg;
+ d->cell->payload[37] = 99;
+
+ channel_tls_process_auth_challenge_cell(d->cell, d->chan);
+ tt_int_op(0, ==, mock_close_called);
+ tt_int_op(1, ==, d->c->handshake_state->received_auth_challenge);
+ tt_int_op(0, ==, mock_send_authenticate_called);
+ tt_int_op(1, ==, mock_send_netinfo_called);
+ done:
+ ;
+}
+
+#define AUTHCHALLENGE_FAIL(name, code) \
+ static void \
+ test_link_handshake_recv_authchallenge_ ## name(void *arg) \
+ { \
+ authchallenge_data_t *d = arg; \
+ { code ; } \
+ channel_tls_process_auth_challenge_cell(d->cell, d->chan); \
+ tt_int_op(1, ==, mock_close_called); \
+ tt_int_op(0, ==, mock_send_authenticate_called); \
+ tt_int_op(0, ==, mock_send_netinfo_called); \
+ done: \
+ ; \
+ }
+
+AUTHCHALLENGE_FAIL(badstate,
+ d->c->base_.state = OR_CONN_STATE_CONNECTING)
+AUTHCHALLENGE_FAIL(badproto,
+ d->c->link_proto = 2)
+AUTHCHALLENGE_FAIL(as_server,
+ d->c->handshake_state->started_here = 0;)
+AUTHCHALLENGE_FAIL(duplicate,
+ d->c->handshake_state->received_auth_challenge = 1)
+AUTHCHALLENGE_FAIL(nocerts,
+ d->c->handshake_state->received_certs_cell = 0)
+AUTHCHALLENGE_FAIL(tooshort,
+ d->cell->payload_len = 33)
+AUTHCHALLENGE_FAIL(truncated,
+ d->cell->payload_len = 34)
+AUTHCHALLENGE_FAIL(nonzero_circid,
+ d->cell->circ_id = 1337)
+
+static tor_x509_cert_t *mock_peer_cert = NULL;
+static tor_x509_cert_t *
+mock_get_peer_cert(tor_tls_t *tls)
+{
+ (void)tls;
+ return mock_peer_cert;
+}
+
+static int
+mock_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
+{
+ (void)tls;
+ memcpy(secrets_out, "int getRandomNumber(){return 4;}", 32);
+ return 0;
+}
+
+static void
+mock_set_circid_type(channel_t *chan,
+ crypto_pk_t *identity_rcvd,
+ int consider_identity)
+{
+ (void) chan;
+ (void) identity_rcvd;
+ (void) consider_identity;
+}
+
+typedef struct authenticate_data_s {
+ or_connection_t *c1, *c2;
+ channel_tls_t *chan2;
+ var_cell_t *cell;
+ crypto_pk_t *key1, *key2;
+} authenticate_data_t;
+
+static int
+authenticate_data_cleanup(const struct testcase_t *test, void *arg)
+{
+ (void) test;
+ UNMOCK(connection_or_write_var_cell_to_buf);
+ UNMOCK(tor_tls_get_peer_cert);
+ UNMOCK(tor_tls_get_tlssecrets);
+ UNMOCK(connection_or_close_for_error);
+ UNMOCK(channel_set_circid_type);
+ authenticate_data_t *d = arg;
+ if (d) {
+ tor_free(d->cell);
+ connection_free_(TO_CONN(d->c1));
+ connection_free_(TO_CONN(d->c2));
+ circuitmux_free(d->chan2->base_.cmux);
+ tor_free(d->chan2);
+ crypto_pk_free(d->key1);
+ crypto_pk_free(d->key2);
+ tor_free(d);
+ }
+ mock_peer_cert = NULL;
+
+ return 1;
+}
+
+static void *
+authenticate_data_setup(const struct testcase_t *test)
+{
+ authenticate_data_t *d = tor_malloc_zero(sizeof(*d));
+
+ scheduler_init();
+
+ MOCK(connection_or_write_var_cell_to_buf, mock_write_var_cell);
+ MOCK(tor_tls_get_peer_cert, mock_get_peer_cert);
+ MOCK(tor_tls_get_tlssecrets, mock_get_tlssecrets);
+ MOCK(connection_or_close_for_error, mock_close_for_err);
+ MOCK(channel_set_circid_type, mock_set_circid_type);
+ d->c1 = or_connection_new(CONN_TYPE_OR, AF_INET);
+ d->c2 = or_connection_new(CONN_TYPE_OR, AF_INET);
+
+ d->key1 = pk_generate(2);
+ d->key2 = pk_generate(3);
+ tt_int_op(tor_tls_context_init(TOR_TLS_CTX_IS_PUBLIC_SERVER,
+ d->key1, d->key2, 86400), ==, 0);
+
+ d->c1->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ d->c1->link_proto = 3;
+ tt_int_op(connection_init_or_handshake_state(d->c1, 1), ==, 0);
+
+ d->c2->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
+ d->c2->link_proto = 3;
+ tt_int_op(connection_init_or_handshake_state(d->c2, 0), ==, 0);
+ var_cell_t *cell = var_cell_new(16);
+ cell->command = CELL_CERTS;
+ or_handshake_state_record_var_cell(d->c1, d->c1->handshake_state, cell, 1);
+ or_handshake_state_record_var_cell(d->c2, d->c2->handshake_state, cell, 0);
+ memset(cell->payload, 0xf0, 16);
+ or_handshake_state_record_var_cell(d->c1, d->c1->handshake_state, cell, 0);
+ or_handshake_state_record_var_cell(d->c2, d->c2->handshake_state, cell, 1);
+ tor_free(cell);
+
+ d->chan2 = tor_malloc_zero(sizeof(*d->chan2));
+ channel_tls_common_init(d->chan2);
+ d->c2->chan = d->chan2;
+ d->chan2->conn = d->c2;
+ d->c2->base_.address = tor_strdup("C2");
+ d->c2->tls = tor_tls_new(-1, 1);
+ d->c2->handshake_state->received_certs_cell = 1;
+
+ const tor_x509_cert_t *id_cert=NULL, *link_cert=NULL, *auth_cert=NULL;
+ tt_assert(! tor_tls_get_my_certs(1, &link_cert, &id_cert));
+
+ const uint8_t *der;
+ size_t sz;
+ tor_x509_cert_get_der(id_cert, &der, &sz);
+ d->c1->handshake_state->id_cert = tor_x509_cert_decode(der, sz);
+ d->c2->handshake_state->id_cert = tor_x509_cert_decode(der, sz);
+
+ tor_x509_cert_get_der(link_cert, &der, &sz);
+ mock_peer_cert = tor_x509_cert_decode(der, sz);
+ tt_assert(mock_peer_cert);
+ tt_assert(! tor_tls_get_my_certs(0, &auth_cert, &id_cert));
+ tor_x509_cert_get_der(auth_cert, &der, &sz);
+ d->c2->handshake_state->auth_cert = tor_x509_cert_decode(der, sz);
+
+ /* Make an authenticate cell ... */
+ tt_int_op(0, ==, connection_or_send_authenticate_cell(d->c1,
+ AUTHTYPE_RSA_SHA256_TLSSECRET));
+ tt_assert(mock_got_var_cell);
+ d->cell = mock_got_var_cell;
+ mock_got_var_cell = NULL;
+
+ return d;
+ done:
+ authenticate_data_cleanup(test, d);
+ return NULL;
+}
+
+static struct testcase_setup_t setup_authenticate = {
+ .setup_fn = authenticate_data_setup,
+ .cleanup_fn = authenticate_data_cleanup
+};
+
+static void
+test_link_handshake_auth_cell(void *arg)
+{
+ authenticate_data_t *d = arg;
+ auth1_t *auth1 = NULL;
+ crypto_pk_t *auth_pubkey = NULL;
+
+ /* Is the cell well-formed on the outer layer? */
+ tt_int_op(d->cell->command, ==, CELL_AUTHENTICATE);
+ tt_int_op(d->cell->payload[0], ==, 0);
+ tt_int_op(d->cell->payload[1], ==, 1);
+ tt_int_op(ntohs(get_uint16(d->cell->payload + 2)), ==,
+ d->cell->payload_len - 4);
+
+ /* Check it out for plausibility... */
+ auth_ctx_t ctx;
+ ctx.is_ed = 0;
+ tt_int_op(d->cell->payload_len-4, ==, auth1_parse(&auth1,
+ d->cell->payload+4,
+ d->cell->payload_len - 4, &ctx));
+ tt_assert(auth1);
+
+ tt_mem_op(auth1->type, ==, "AUTH0001", 8);
+ tt_mem_op(auth1->tlssecrets, ==, "int getRandomNumber(){return 4;}", 32);
+ tt_int_op(auth1_getlen_sig(auth1), >, 120);
+
+ /* Is the signature okay? */
+ uint8_t sig[128];
+ uint8_t digest[32];
+
+ auth_pubkey = tor_tls_cert_get_key(d->c2->handshake_state->auth_cert);
+ int n = crypto_pk_public_checksig(
+ auth_pubkey,
+ (char*)sig, sizeof(sig), (char*)auth1_getarray_sig(auth1),
+ auth1_getlen_sig(auth1));
+ tt_int_op(n, ==, 32);
+ const uint8_t *start = d->cell->payload+4, *end = auth1->end_of_signed;
+ crypto_digest256((char*)digest,
+ (const char*)start, end-start, DIGEST_SHA256);
+ tt_mem_op(sig, ==, digest, 32);
+
+ /* Then feed it to c2. */
+ tt_int_op(d->c2->handshake_state->authenticated, ==, 0);
+ channel_tls_process_authenticate_cell(d->cell, d->chan2);
+ tt_int_op(mock_close_called, ==, 0);
+ tt_int_op(d->c2->handshake_state->authenticated, ==, 1);
+
+ done:
+ auth1_free(auth1);
+ crypto_pk_free(auth_pubkey);
+}
+
+#define AUTHENTICATE_FAIL(name, code) \
+ static void \
+ test_link_handshake_auth_ ## name(void *arg) \
+ { \
+ authenticate_data_t *d = arg; \
+ { code ; } \
+ tt_int_op(d->c2->handshake_state->authenticated, ==, 0); \
+ channel_tls_process_authenticate_cell(d->cell, d->chan2); \
+ tt_int_op(mock_close_called, ==, 1); \
+ tt_int_op(d->c2->handshake_state->authenticated, ==, 0); \
+ done: \
+ ; \
+ }
+
+AUTHENTICATE_FAIL(badstate,
+ d->c2->base_.state = OR_CONN_STATE_CONNECTING)
+AUTHENTICATE_FAIL(badproto,
+ d->c2->link_proto = 2)
+AUTHENTICATE_FAIL(atclient,
+ d->c2->handshake_state->started_here = 1)
+AUTHENTICATE_FAIL(duplicate,
+ d->c2->handshake_state->received_authenticate = 1)
+static void
+test_link_handshake_auth_already_authenticated(void *arg)
+{
+ authenticate_data_t *d = arg;
+ d->c2->handshake_state->authenticated = 1;
+ channel_tls_process_authenticate_cell(d->cell, d->chan2);
+ tt_int_op(mock_close_called, ==, 1);
+ tt_int_op(d->c2->handshake_state->authenticated, ==, 1);
+ done:
+ ;
+}
+AUTHENTICATE_FAIL(nocerts,
+ d->c2->handshake_state->received_certs_cell = 0)
+AUTHENTICATE_FAIL(noidcert,
+ tor_x509_cert_free(d->c2->handshake_state->id_cert);
+ d->c2->handshake_state->id_cert = NULL)
+AUTHENTICATE_FAIL(noauthcert,
+ tor_x509_cert_free(d->c2->handshake_state->auth_cert);
+ d->c2->handshake_state->auth_cert = NULL)
+AUTHENTICATE_FAIL(tooshort,
+ d->cell->payload_len = 3)
+AUTHENTICATE_FAIL(badtype,
+ d->cell->payload[0] = 0xff)
+AUTHENTICATE_FAIL(truncated_1,
+ d->cell->payload[2]++)
+AUTHENTICATE_FAIL(truncated_2,
+ d->cell->payload[3]++)
+AUTHENTICATE_FAIL(tooshort_1,
+ tt_int_op(d->cell->payload_len, >=, 260);
+ d->cell->payload[2] -= 1;
+ d->cell->payload_len -= 256;)
+AUTHENTICATE_FAIL(badcontent,
+ d->cell->payload[10] ^= 0xff)
+AUTHENTICATE_FAIL(badsig_1,
+ d->cell->payload[d->cell->payload_len - 5] ^= 0xff)
+
+#define TEST(name, flags) \
+ { #name , test_link_handshake_ ## name, (flags), NULL, NULL }
+
+#define TEST_RCV_AUTHCHALLENGE(name) \
+ { "recv_authchallenge/" #name , \
+ test_link_handshake_recv_authchallenge_ ## name, TT_FORK, \
+ &setup_recv_authchallenge, NULL }
+
+#define TEST_RCV_CERTS(name) \
+ { "recv_certs/" #name , \
+ test_link_handshake_recv_certs_ ## name, TT_FORK, \
+ &setup_recv_certs, NULL }
+
+#define TEST_AUTHENTICATE(name) \
+ { "authenticate/" #name , test_link_handshake_auth_ ## name, TT_FORK, \
+ &setup_authenticate, NULL }
+
+struct testcase_t link_handshake_tests[] = {
+ TEST(certs_ok, TT_FORK),
+ //TEST(certs_bad, TT_FORK),
+ TEST_RCV_CERTS(ok),
+ TEST_RCV_CERTS(ok_server),
+ TEST_RCV_CERTS(badstate),
+ TEST_RCV_CERTS(badproto),
+ TEST_RCV_CERTS(duplicate),
+ TEST_RCV_CERTS(already_authenticated),
+ TEST_RCV_CERTS(empty),
+ TEST_RCV_CERTS(bad_circid),
+ TEST_RCV_CERTS(truncated_1),
+ TEST_RCV_CERTS(truncated_2),
+ TEST_RCV_CERTS(truncated_3),
+ TEST_RCV_CERTS(not_x509),
+ TEST_RCV_CERTS(both_link),
+ TEST_RCV_CERTS(both_id_rsa),
+ TEST_RCV_CERTS(both_auth),
+ TEST_RCV_CERTS(wrong_labels_1),
+ TEST_RCV_CERTS(wrong_labels_2),
+ TEST_RCV_CERTS(wrong_labels_3),
+ TEST_RCV_CERTS(server_missing_certs),
+ TEST_RCV_CERTS(server_wrong_labels_1),
+
+ TEST(send_authchallenge, TT_FORK),
+ TEST_RCV_AUTHCHALLENGE(ok),
+ TEST_RCV_AUTHCHALLENGE(ok_noserver),
+ TEST_RCV_AUTHCHALLENGE(ok_unrecognized),
+ TEST_RCV_AUTHCHALLENGE(badstate),
+ TEST_RCV_AUTHCHALLENGE(badproto),
+ TEST_RCV_AUTHCHALLENGE(as_server),
+ TEST_RCV_AUTHCHALLENGE(duplicate),
+ TEST_RCV_AUTHCHALLENGE(nocerts),
+ TEST_RCV_AUTHCHALLENGE(tooshort),
+ TEST_RCV_AUTHCHALLENGE(truncated),
+ TEST_RCV_AUTHCHALLENGE(nonzero_circid),
+
+ TEST_AUTHENTICATE(cell),
+ TEST_AUTHENTICATE(badstate),
+ TEST_AUTHENTICATE(badproto),
+ TEST_AUTHENTICATE(atclient),
+ TEST_AUTHENTICATE(duplicate),
+ TEST_AUTHENTICATE(already_authenticated),
+ TEST_AUTHENTICATE(nocerts),
+ TEST_AUTHENTICATE(noidcert),
+ TEST_AUTHENTICATE(noauthcert),
+ TEST_AUTHENTICATE(tooshort),
+ TEST_AUTHENTICATE(badtype),
+ TEST_AUTHENTICATE(truncated_1),
+ TEST_AUTHENTICATE(truncated_2),
+ TEST_AUTHENTICATE(tooshort_1),
+ TEST_AUTHENTICATE(badcontent),
+ TEST_AUTHENTICATE(badsig_1),
+ //TEST_AUTHENTICATE(),
+
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_logging.c b/src/test/test_logging.c
index 7e558f83b1..eb294fe6f8 100644
--- a/src/test/test_logging.c
+++ b/src/test/test_logging.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -19,11 +19,11 @@ test_get_sigsafe_err_fds(void *arg)
int n;
log_severity_list_t include_bug, no_bug, no_bug2;
(void) arg;
- init_logging();
+ init_logging(1);
n = tor_log_get_sigsafe_err_fds(&fds);
- tt_int_op(n, ==, 1);
- tt_int_op(fds[0], ==, STDERR_FILENO);
+ tt_int_op(n, OP_EQ, 1);
+ tt_int_op(fds[0], OP_EQ, STDERR_FILENO);
set_log_severity_config(LOG_WARN, LOG_ERR, &include_bug);
set_log_severity_config(LOG_WARN, LOG_ERR, &no_bug);
@@ -40,26 +40,26 @@ test_get_sigsafe_err_fds(void *arg)
tor_log_update_sigsafe_err_fds();
n = tor_log_get_sigsafe_err_fds(&fds);
- tt_int_op(n, ==, 2);
- tt_int_op(fds[0], ==, STDERR_FILENO);
- tt_int_op(fds[1], ==, 3);
+ tt_int_op(n, OP_EQ, 2);
+ tt_int_op(fds[0], OP_EQ, STDERR_FILENO);
+ tt_int_op(fds[1], OP_EQ, 3);
/* Allow STDOUT to replace STDERR. */
add_stream_log(&include_bug, "dummy-4", STDOUT_FILENO);
tor_log_update_sigsafe_err_fds();
n = tor_log_get_sigsafe_err_fds(&fds);
- tt_int_op(n, ==, 2);
- tt_int_op(fds[0], ==, 3);
- tt_int_op(fds[1], ==, STDOUT_FILENO);
+ tt_int_op(n, OP_EQ, 2);
+ tt_int_op(fds[0], OP_EQ, 3);
+ tt_int_op(fds[1], OP_EQ, STDOUT_FILENO);
/* But don't allow it to replace explicit STDERR. */
add_stream_log(&include_bug, "dummy-5", STDERR_FILENO);
tor_log_update_sigsafe_err_fds();
n = tor_log_get_sigsafe_err_fds(&fds);
- tt_int_op(n, ==, 3);
- tt_int_op(fds[0], ==, STDERR_FILENO);
- tt_int_op(fds[1], ==, STDOUT_FILENO);
- tt_int_op(fds[2], ==, 3);
+ tt_int_op(n, OP_EQ, 3);
+ tt_int_op(fds[0], OP_EQ, STDERR_FILENO);
+ tt_int_op(fds[1], OP_EQ, STDOUT_FILENO);
+ tt_int_op(fds[2], OP_EQ, 3);
/* Don't overflow the array. */
{
@@ -70,7 +70,7 @@ test_get_sigsafe_err_fds(void *arg)
}
tor_log_update_sigsafe_err_fds();
n = tor_log_get_sigsafe_err_fds(&fds);
- tt_int_op(n, ==, 8);
+ tt_int_op(n, OP_EQ, 8);
done:
;
@@ -87,9 +87,9 @@ test_sigsafe_err(void *arg)
set_log_severity_config(LOG_WARN, LOG_ERR, &include_bug);
- init_logging();
+ init_logging(1);
mark_logs_temp();
- add_file_log(&include_bug, fn);
+ add_file_log(&include_bug, fn, 0);
tor_log_update_sigsafe_err_fds();
close_temp_logs();
@@ -109,7 +109,7 @@ test_sigsafe_err(void *arg)
tt_assert(content != NULL);
tor_split_lines(lines, content, (int)strlen(content));
- tt_int_op(smartlist_len(lines), >=, 5);
+ tt_int_op(smartlist_len(lines), OP_GE, 5);
if (strstr(smartlist_get(lines, 0), "opening new log file"))
smartlist_del_keeporder(lines, 0);
@@ -119,7 +119,7 @@ test_sigsafe_err(void *arg)
tt_assert(!strcmpstart(smartlist_get(lines, 2), "Minimal."));
/* Next line is blank. */
tt_assert(!strcmpstart(smartlist_get(lines, 3), "=============="));
- tt_str_op(smartlist_get(lines, 4), ==,
+ tt_str_op(smartlist_get(lines, 4), OP_EQ,
"Testing any attempt to manually log from a signal.");
done:
diff --git a/src/test/test_microdesc.c b/src/test/test_microdesc.c
index 78f4823b87..dbd1e5ac48 100644
--- a/src/test/test_microdesc.c
+++ b/src/test/test_microdesc.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2010-2013, The Tor Project, Inc. */
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -7,11 +7,38 @@
#include "config.h"
#include "dirvote.h"
#include "microdesc.h"
+#include "networkstatus.h"
#include "routerlist.h"
#include "routerparse.h"
+#include "torcert.h"
#include "test.h"
+#ifdef __GNUC__
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#endif
+
+#if __GNUC__ && GCC_VERSION >= 402
+#if GCC_VERSION >= 406
+#pragma GCC diagnostic push
+#endif
+/* Some versions of OpenSSL declare X509_STORE_CTX_set_verify_cb twice.
+ * Suppress the GCC warning so we can build with -Wredundant-decl. */
+#pragma GCC diagnostic ignored "-Wredundant-decls"
+#endif
+
+#include <openssl/rsa.h>
+#include <openssl/bn.h>
+#include <openssl/pem.h>
+
+#if __GNUC__ && GCC_VERSION >= 402
+#if GCC_VERSION >= 406
+#pragma GCC diagnostic pop
+#else
+#pragma GCC diagnostic warning "-Wredundant-decls"
+#endif
+#endif
+
#ifdef _WIN32
/* For mkdir() */
#include <direct.h>
@@ -70,9 +97,9 @@ test_md_cache(void *data)
tor_free(options->DataDirectory);
options->DataDirectory = tor_strdup(get_fname("md_datadir_test"));
#ifdef _WIN32
- tt_int_op(0, ==, mkdir(options->DataDirectory));
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory));
#else
- tt_int_op(0, ==, mkdir(options->DataDirectory, 0700));
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory, 0700));
#endif
tt_assert(!strcmpstart(test_md3_noannotation, "onion-key"));
@@ -86,7 +113,7 @@ test_md_cache(void *data)
added = microdescs_add_to_cache(mc, test_md1, NULL, SAVED_NOWHERE, 0,
time1, NULL);
- tt_int_op(1, ==, smartlist_len(added));
+ tt_int_op(1, OP_EQ, smartlist_len(added));
md1 = smartlist_get(added, 0);
smartlist_free(added);
added = NULL;
@@ -95,7 +122,7 @@ test_md_cache(void *data)
added = microdescs_add_to_cache(mc, test_md2, NULL, SAVED_NOWHERE, 0,
time2, wanted);
/* Should fail, since we didn't list test_md2's digest in wanted */
- tt_int_op(0, ==, smartlist_len(added));
+ tt_int_op(0, OP_EQ, smartlist_len(added));
smartlist_free(added);
added = NULL;
@@ -104,75 +131,75 @@ test_md_cache(void *data)
added = microdescs_add_to_cache(mc, test_md2, NULL, SAVED_NOWHERE, 0,
time2, wanted);
/* Now it can work. md2 should have been added */
- tt_int_op(1, ==, smartlist_len(added));
+ tt_int_op(1, OP_EQ, smartlist_len(added));
md2 = smartlist_get(added, 0);
/* And it should have gotten removed from 'wanted' */
- tt_int_op(smartlist_len(wanted), ==, 1);
- test_mem_op(smartlist_get(wanted, 0), ==, d3, DIGEST256_LEN);
+ tt_int_op(smartlist_len(wanted), OP_EQ, 1);
+ tt_mem_op(smartlist_get(wanted, 0), OP_EQ, d3, DIGEST256_LEN);
smartlist_free(added);
added = NULL;
added = microdescs_add_to_cache(mc, test_md3, NULL,
SAVED_NOWHERE, 0, -1, NULL);
/* Must fail, since SAVED_NOWHERE precludes annotations */
- tt_int_op(0, ==, smartlist_len(added));
+ tt_int_op(0, OP_EQ, smartlist_len(added));
smartlist_free(added);
added = NULL;
added = microdescs_add_to_cache(mc, test_md3_noannotation, NULL,
SAVED_NOWHERE, 0, time3, NULL);
/* Now it can work */
- tt_int_op(1, ==, smartlist_len(added));
+ tt_int_op(1, OP_EQ, smartlist_len(added));
md3 = smartlist_get(added, 0);
smartlist_free(added);
added = NULL;
/* Okay. We added 1...3. Let's poke them to see how they look, and make
* sure they're really in the journal. */
- tt_ptr_op(md1, ==, microdesc_cache_lookup_by_digest256(mc, d1));
- tt_ptr_op(md2, ==, microdesc_cache_lookup_by_digest256(mc, d2));
- tt_ptr_op(md3, ==, microdesc_cache_lookup_by_digest256(mc, d3));
-
- tt_int_op(md1->last_listed, ==, time1);
- tt_int_op(md2->last_listed, ==, time2);
- tt_int_op(md3->last_listed, ==, time3);
-
- tt_int_op(md1->saved_location, ==, SAVED_IN_JOURNAL);
- tt_int_op(md2->saved_location, ==, SAVED_IN_JOURNAL);
- tt_int_op(md3->saved_location, ==, SAVED_IN_JOURNAL);
-
- tt_int_op(md1->bodylen, ==, strlen(test_md1));
- tt_int_op(md2->bodylen, ==, strlen(test_md2));
- tt_int_op(md3->bodylen, ==, strlen(test_md3_noannotation));
- test_mem_op(md1->body, ==, test_md1, strlen(test_md1));
- test_mem_op(md2->body, ==, test_md2, strlen(test_md2));
- test_mem_op(md3->body, ==, test_md3_noannotation,
+ tt_ptr_op(md1, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d1));
+ tt_ptr_op(md2, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d2));
+ tt_ptr_op(md3, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d3));
+
+ tt_int_op(md1->last_listed, OP_EQ, time1);
+ tt_int_op(md2->last_listed, OP_EQ, time2);
+ tt_int_op(md3->last_listed, OP_EQ, time3);
+
+ tt_int_op(md1->saved_location, OP_EQ, SAVED_IN_JOURNAL);
+ tt_int_op(md2->saved_location, OP_EQ, SAVED_IN_JOURNAL);
+ tt_int_op(md3->saved_location, OP_EQ, SAVED_IN_JOURNAL);
+
+ tt_int_op(md1->bodylen, OP_EQ, strlen(test_md1));
+ tt_int_op(md2->bodylen, OP_EQ, strlen(test_md2));
+ tt_int_op(md3->bodylen, OP_EQ, strlen(test_md3_noannotation));
+ tt_mem_op(md1->body, OP_EQ, test_md1, strlen(test_md1));
+ tt_mem_op(md2->body, OP_EQ, test_md2, strlen(test_md2));
+ tt_mem_op(md3->body, OP_EQ, test_md3_noannotation,
strlen(test_md3_noannotation));
tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-microdescs.new",
options->DataDirectory);
s = read_file_to_str(fn, RFTS_BIN, NULL);
tt_assert(s);
- test_mem_op(md1->body, ==, s + md1->off, md1->bodylen);
- test_mem_op(md2->body, ==, s + md2->off, md2->bodylen);
- test_mem_op(md3->body, ==, s + md3->off, md3->bodylen);
+ tt_mem_op(md1->body, OP_EQ, s + md1->off, md1->bodylen);
+ tt_mem_op(md2->body, OP_EQ, s + md2->off, md2->bodylen);
+ tt_mem_op(md3->body, OP_EQ, s + md3->off, md3->bodylen);
- tt_ptr_op(md1->family, ==, NULL);
- tt_ptr_op(md3->family, !=, NULL);
- tt_int_op(smartlist_len(md3->family), ==, 3);
- tt_str_op(smartlist_get(md3->family, 0), ==, "nodeX");
+ tt_ptr_op(md1->family, OP_EQ, NULL);
+ tt_ptr_op(md3->family, OP_NE, NULL);
+ tt_int_op(smartlist_len(md3->family), OP_EQ, 3);
+ tt_str_op(smartlist_get(md3->family, 0), OP_EQ, "nodeX");
/* Now rebuild the cache! */
- tt_int_op(microdesc_cache_rebuild(mc, 1), ==, 0);
+ tt_int_op(microdesc_cache_rebuild(mc, 1), OP_EQ, 0);
- tt_int_op(md1->saved_location, ==, SAVED_IN_CACHE);
- tt_int_op(md2->saved_location, ==, SAVED_IN_CACHE);
- tt_int_op(md3->saved_location, ==, SAVED_IN_CACHE);
+ tt_int_op(md1->saved_location, OP_EQ, SAVED_IN_CACHE);
+ tt_int_op(md2->saved_location, OP_EQ, SAVED_IN_CACHE);
+ tt_int_op(md3->saved_location, OP_EQ, SAVED_IN_CACHE);
/* The journal should be empty now */
tor_free(s);
s = read_file_to_str(fn, RFTS_BIN, NULL);
- tt_str_op(s, ==, "");
+ tt_str_op(s, OP_EQ, "");
tor_free(s);
tor_free(fn);
@@ -180,9 +207,9 @@ test_md_cache(void *data)
tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-microdescs",
options->DataDirectory);
s = read_file_to_str(fn, RFTS_BIN, NULL);
- test_mem_op(md1->body, ==, s + md1->off, strlen(test_md1));
- test_mem_op(md2->body, ==, s + md2->off, strlen(test_md2));
- test_mem_op(md3->body, ==, s + md3->off, strlen(test_md3_noannotation));
+ tt_mem_op(md1->body, OP_EQ, s + md1->off, strlen(test_md1));
+ tt_mem_op(md2->body, OP_EQ, s + md2->off, strlen(test_md2));
+ tt_mem_op(md3->body, OP_EQ, s + md3->off, strlen(test_md3_noannotation));
/* Okay, now we are going to forget about the cache entirely, and reload it
* from the disk. */
@@ -191,44 +218,44 @@ test_md_cache(void *data)
md1 = microdesc_cache_lookup_by_digest256(mc, d1);
md2 = microdesc_cache_lookup_by_digest256(mc, d2);
md3 = microdesc_cache_lookup_by_digest256(mc, d3);
- test_assert(md1);
- test_assert(md2);
- test_assert(md3);
- test_mem_op(md1->body, ==, s + md1->off, strlen(test_md1));
- test_mem_op(md2->body, ==, s + md2->off, strlen(test_md2));
- test_mem_op(md3->body, ==, s + md3->off, strlen(test_md3_noannotation));
+ tt_assert(md1);
+ tt_assert(md2);
+ tt_assert(md3);
+ tt_mem_op(md1->body, OP_EQ, s + md1->off, strlen(test_md1));
+ tt_mem_op(md2->body, OP_EQ, s + md2->off, strlen(test_md2));
+ tt_mem_op(md3->body, OP_EQ, s + md3->off, strlen(test_md3_noannotation));
- tt_int_op(md1->last_listed, ==, time1);
- tt_int_op(md2->last_listed, ==, time2);
- tt_int_op(md3->last_listed, ==, time3);
+ tt_int_op(md1->last_listed, OP_EQ, time1);
+ tt_int_op(md2->last_listed, OP_EQ, time2);
+ tt_int_op(md3->last_listed, OP_EQ, time3);
/* Okay, now we are going to clear out everything older than a week old.
* In practice, that means md3 */
microdesc_cache_clean(mc, time(NULL)-7*24*60*60, 1/*force*/);
- tt_ptr_op(md1, ==, microdesc_cache_lookup_by_digest256(mc, d1));
- tt_ptr_op(md2, ==, microdesc_cache_lookup_by_digest256(mc, d2));
- tt_ptr_op(NULL, ==, microdesc_cache_lookup_by_digest256(mc, d3));
+ tt_ptr_op(md1, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d1));
+ tt_ptr_op(md2, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d2));
+ tt_ptr_op(NULL, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d3));
md3 = NULL; /* it's history now! */
/* rebuild again, make sure it stays gone. */
- tt_int_op(microdesc_cache_rebuild(mc, 1), ==, 0);
- tt_ptr_op(md1, ==, microdesc_cache_lookup_by_digest256(mc, d1));
- tt_ptr_op(md2, ==, microdesc_cache_lookup_by_digest256(mc, d2));
- tt_ptr_op(NULL, ==, microdesc_cache_lookup_by_digest256(mc, d3));
+ tt_int_op(microdesc_cache_rebuild(mc, 1), OP_EQ, 0);
+ tt_ptr_op(md1, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d1));
+ tt_ptr_op(md2, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d2));
+ tt_ptr_op(NULL, OP_EQ, microdesc_cache_lookup_by_digest256(mc, d3));
/* Re-add md3, and make sure we can rebuild the cache. */
added = microdescs_add_to_cache(mc, test_md3_noannotation, NULL,
SAVED_NOWHERE, 0, time3, NULL);
- tt_int_op(1, ==, smartlist_len(added));
+ tt_int_op(1, OP_EQ, smartlist_len(added));
md3 = smartlist_get(added, 0);
smartlist_free(added);
added = NULL;
- tt_int_op(md1->saved_location, ==, SAVED_IN_CACHE);
- tt_int_op(md2->saved_location, ==, SAVED_IN_CACHE);
- tt_int_op(md3->saved_location, ==, SAVED_IN_JOURNAL);
+ tt_int_op(md1->saved_location, OP_EQ, SAVED_IN_CACHE);
+ tt_int_op(md2->saved_location, OP_EQ, SAVED_IN_CACHE);
+ tt_int_op(md3->saved_location, OP_EQ, SAVED_IN_JOURNAL);
- tt_int_op(microdesc_cache_rebuild(mc, 1), ==, 0);
- tt_int_op(md3->saved_location, ==, SAVED_IN_CACHE);
+ tt_int_op(microdesc_cache_rebuild(mc, 1), OP_EQ, 0);
+ tt_int_op(md3->saved_location, OP_EQ, SAVED_IN_CACHE);
done:
if (options)
@@ -268,9 +295,9 @@ test_md_cache_broken(void *data)
options->DataDirectory = tor_strdup(get_fname("md_datadir_test2"));
#ifdef _WIN32
- tt_int_op(0, ==, mkdir(options->DataDirectory));
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory));
#else
- tt_int_op(0, ==, mkdir(options->DataDirectory, 0700));
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory, 0700));
#endif
tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-microdescs",
@@ -330,6 +357,59 @@ static const char test_ri[] =
"t0xkIE39ss/EwmQr7iIgkdVH4oRIMsjYnFFJBG26nYY=\n"
"-----END SIGNATURE-----\n";
+static const char test_ri2[] =
+ "router test001a 127.0.0.1 5001 0 7001\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf/FAf5iDuKCZP2VxnAaQWdklilAh6kaEeFX4z8261Yx2T1/AQAgBADCp8vO\n"
+ "B8K1F9g2DzwuwvVCnPFLSK1qknVqPpNucHLH9DY7fuIYogBAdz4zHv1qC7RKaMNG\n"
+ "Jux/tMO2tzPcm62Ky5PjClMQplKUOnZNQ+RIpA3wYCIfUDy/cQnY7XWgNQ0=\n"
+ "-----END ED25519 CERT-----\n"
+ "platform Tor 0.2.6.0-alpha-dev on Darwin\n"
+ "protocols Link 1 2 Circuit 1\n"
+ "published 2014-10-08 12:58:04\n"
+ "fingerprint B7E2 7F10 4213 C36F 13E7 E982 9182 845E 4959 97A0\n"
+ "uptime 0\n"
+ "bandwidth 1073741824 1073741824 0\n"
+ "extra-info-digest 568F27331B6D8C73E7024F1EF5D097B90DFC7CDB\n"
+ "caches-extra-info\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAN8+78KUVlgHXdMMkYJxcwh1Zv2y+Gb5eWUyltUaQRajhrT9ij2T5JZs\n"
+ "M0g85xTcuM3jNVVpV79+33hiTohdC6UZ+Bk4USQ7WBFzRbVFSXoVKLBJFkCOIexg\n"
+ "SMGNd5WEDtHWrXl58mizmPFu1eG6ZxHzt7RuLSol5cwBvawXPNkFAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "ETFDzU49bvNfoZnKK1j6JeBP2gDirgj6bBCgWpUYs663OO9ypbZRO0JwWANssKl6\n"
+ "oaq9vKTsKGRsaNnqnz/JGMhehymakjjNtqg7crWwsahe8+7Pw9GKmW+YjFtcOkUf\n"
+ "KfOn2bmKBa1FoJb4yW3oXzHcdlLSRuCciKqPn+Hky5o=\n"
+ "-----END CROSSCERT-----\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf2dAcKny84HwrUX2DYPPC7C9UKc8UtIrWqSdWo+k25wcsf0AFohutG+xI06\n"
+ "Ef21c5Zl1j8Hw6DzHDjYyJevXLFuOneaL3zcH2Ldn4sjrG3kc5UuVvRfTvV120UO\n"
+ "xk4f5s5LGwY=\n"
+ "-----END ED25519 CERT-----\n"
+ "hidden-service-dir\n"
+ "contact auth1@test.test\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "reject *:*\n"
+ "router-sig-ed25519 5aQXyTif7PExIuL2di37UvktmJECKnils2OWz2vDi"
+ "hFxi+5TTAAPxYkS5clhc/Pjvw34itfjGmTKFic/8httAQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "BaUB+aFPQbb3BwtdzKsKqV3+6cRlSqJF5bI3UTmwRoJk+Z5Pz+W5NWokNI0xArHM\n"
+ "T4T5FZCCP9350jXsUCIvzyIyktU6aVRCGFt76rFlo1OETpN8GWkMnQU0w18cxvgS\n"
+ "cf34GXHv61XReJF3AlzNHFpbrPOYmowmhrTULKyMqow=\n"
+ "-----END SIGNATURE-----\n";
+
static const char test_md_8[] =
"onion-key\n"
"-----BEGIN RSA PUBLIC KEY-----\n"
@@ -360,6 +440,26 @@ static const char test_md_18[] =
"p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999\n"
"id rsa1024 Cd47okjCHD83YGzThGBDptXs9Z4\n";
+static const char test_md2_18[] =
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "id rsa1024 t+J/EEITw28T5+mCkYKEXklZl6A\n";
+
+static const char test_md2_21[] =
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "id ed25519 wqfLzgfCtRfYNg88LsL1QpzxS0itapJ1aj6TbnByx/Q\n";
+
static void
test_md_generate(void *arg)
{
@@ -367,10 +467,10 @@ test_md_generate(void *arg)
microdesc_t *md = NULL;
(void)arg;
- ri = router_parse_entry_from_string(test_ri, NULL, 0, 0, NULL);
+ ri = router_parse_entry_from_string(test_ri, NULL, 0, 0, NULL, NULL);
tt_assert(ri);
md = dirvote_create_microdescriptor(ri, 8);
- tt_str_op(md->body, ==, test_md_8);
+ tt_str_op(md->body, OP_EQ, test_md_8);
/* XXXX test family lines. */
/* XXXX test method 14 for A lines. */
@@ -379,22 +479,395 @@ test_md_generate(void *arg)
microdesc_free(md);
md = NULL;
md = dirvote_create_microdescriptor(ri, 16);
- tt_str_op(md->body, ==, test_md_16);
+ tt_str_op(md->body, OP_EQ, test_md_16);
microdesc_free(md);
md = NULL;
md = dirvote_create_microdescriptor(ri, 18);
+ tt_str_op(md->body, OP_EQ, test_md_18);
+
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 21);
tt_str_op(md->body, ==, test_md_18);
+ routerinfo_free(ri);
+ ri = router_parse_entry_from_string(test_ri2, NULL, 0, 0, NULL, NULL);
+
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 18);
+ tt_str_op(md->body, ==, test_md2_18);
+
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 21);
+ tt_str_op(md->body, ==, test_md2_21);
+ tt_assert(ed25519_pubkey_eq(md->ed25519_identity_pkey,
+ &ri->cache_info.signing_key_cert->signing_key));
+
done:
microdesc_free(md);
routerinfo_free(ri);
}
+/* Taken at random from my ~/.tor/cached-microdescs file and then
+ * hand-munged */
+static const char MD_PARSE_TEST_DATA[] =
+ /* Good 0 */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANsKd1GRfOuSR1MkcwKqs6SVy4Gi/JXplt/bHDkIGm6Q96TeJ5uyVgUL\n"
+ "DBr/ij6+JqgVFeriuiMzHKREytzjdaTuKsKBFFpLwb+Ppcjr5nMIH/AR6/aHO8hW\n"
+ "T3B9lx5T6Kl7CqZ4yqXxYRHzn50EPTIZuz0y9se4J4gi9mLmL+pHAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "p accept 20-23,43,53,79-81,88,110,143,194,220,443,464,531,543-544\n"
+ "id rsa1024 GEo59/iR1GWSIWZDzXTd5QxtqnU\n"
+ /* Bad 0: I've messed with the onion-key in the second one. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMr4o/pflVwscx11vC1AKEADlKEqnhpvCIjAEzNEenMhvGQHRlA0EXLC\n"
+ "7G7O5bhnCwEHqK8Pvg8cuX/fD8v08TF1EVPhwPa0UI6ab8KnPP2F!!!!!!b92DG7EQIk3q\n"
+ "d68Uxp7E9/t3v1WWZjzDqvEe0par6ul+DKW6HMlTGebFo5Q4e8R1AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key 761Dmm27via7lXygNHM3l+oJLrYU2Nye0Uz4pkpipyY=\n"
+ "p accept 53\n"
+ "id rsa1024 3Y4fwXhtgkdGDZ5ef5mtb6TJRQQ\n"
+ /* Good 1 */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANsMSjVi3EX8ZHfm/dvPF6KdVR66k1tVul7Jp+dDbDajBYNhgKRzVCxy\n"
+ "Yac1CBuQjOqK89tKap9PQBnhF087eDrfaZDqYTLwB2W2sBJncVej15WEPXPRBifo\n"
+ "iFZ8337kgczkaY+IOfSuhtbOUyDOoDpRJheIKBNq0ZiTqtLbbadVAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key ncfiHJjSgdDEW/gc6q6/7idac7j+x7ejQrRm6i75pGA=\n"
+ "p accept 443,6660-6669,6697,7000-7001\n"
+ "id rsa1024 XXuLzw3mfBELEq3veXoNhdehwD4\n"
+ /* Good 2 */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANQfBlrHrh9F/CAOytrNFgi0ikWMW/HZxuoszF9X+AQ+MudR8bcxxOGl\n"
+ "1RFwb74s8E3uuzrCkNFvSw9Ar1L02F2DOX0gLsxEGuYC4Ave9NUteGqSqDyEJQUJ\n"
+ "KlfxCPn2qC9nvNT7wR/Dg2WRvAEKnJmkpb57N3+WSAOPLjKOFEz3AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key AppBt6CSeb1kKid/36ototmFA24ddfW5JpjWPLuoJgs=\n"
+ "id rsa1024 6y60AEI9a1PUUlRPO0YQT9WzrjI\n"
+ /* Bad 1: Here I've messed with the ntor key */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAPjy2HacU3jDNO5nTOFGSwNa0qKCNn4yhtrDVcAJ5alIQeBWZZGJLZ0q\n"
+ "Cqylw1vYqxu8E09g+QXXFbAgBv1U9TICaATxrIJhIJzc8TJPhqJemp1kq0DvHLDx\n"
+ "mxwlkNnCD/P5NS+JYB3EjOlU9EnSKUWNU61+Co344m2JqhEau40vAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key 4i2Fp9JHTUr1uQs0pxD5j5spl4/RG56S2P0gQxU=\n"
+ "id rsa1024 nMRmNEGysA0NmlALVaUmI7D5jLU\n"
+ /* Good 3: I've added a weird token in this one. This shouldn't prevent
+ * it parsing */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKmosxudyNA/yJNz3S890VqV/ebylzoD11Sc0b/d5tyNNaNZjcYy5vRD\n"
+ "kwyxFRMbP2TLZQ1zRfNwY7IDnYjU2SbW0pxuM6M8WRtsmx/YOE3kHMVAFJNrTUqU\n"
+ "6D1zB3IiRDS5q5+NoRxwqo+hYUck60O3WTwEoqb+l3lvXeu7z9rFAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "flux-capacitor 1.21 GW\n"
+ "ntor-onion-key MWBoEkl+RlBiGX44XKIvTSqbznTNZStOmUYtcYRQQyY=\n"
+ "id rsa1024 R+A5O9qRvRac4FT3C4L2QnFyxsc\n"
+ /* Good 4: Here I've made the 'id rsa' token odd. It should still parse
+ * just fine. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAOh+WMkdNe/Pkjb8UjQyfLOlFgpuVFrxAIGnJsmWWx0yBE97DQxGyh2n\n"
+ "h8G5OJZHRarJQyCIf7vpZQAi0oP0OkGGaCaDQsM+D8TnqhnU++RWGnMqY/cXxPrL\n"
+ "MEq+n6aGiLmzkO7ah8yorZpoREk4GqLUIN89/tHHGOhJL3c4CPGjAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999\n"
+ "id rsa1234 jlqAKFD2E7uMKv+8TmKSeo7NBho\n"
+ /* Good 5: Extra id type. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAMdgPPc5uaw4y/q+SUTN/I8Y+Gvdx9kKgWV4dmDGJ0mxsVZmo1v6+v3F\n"
+ "12M2f9m99G3WB8F8now29C+9XyEv8MBHj1lHRdUFHSQes3YTFvDNlgj+FjLqO5TJ\n"
+ "adOOmfu4DCUUtUEDyQKbNVL4EkMTXY73omTVsjcH3xxFjTx5wixhAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key AAVnWZcnDbxasdZwKqb4fL6O9sZV+XsRNHTpNd1YMz8=\n"
+ "id rsa1024 72EfBL11QuwX2vU8y+p9ExGfGEg\n"
+ "id expolding hedgehog 0+A5O9qRvRac4FT3C4L2QnFyxsc\n"
+ /* Good 6: I've given this a bogus policy. It should parse. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALNuufwhPMF8BooxYMNvhYJMPqUB8hQDt8wGmPKphJcD1sVD1i4gAZM2\n"
+ "HIo+zUBlljDrRWL5NzVzd1yxUJAiQxvXS5dRRFY3B70M7wTVpXw53xe0/BM5t1AX\n"
+ "n0MFk7Jl6XIKMlzRalZvmMvE/odtyWXkP4Nd1MyZ1QcIwrQ2iwyrAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "p condone 1-10\n"
+ "ntor-onion-key 2/nMJ+L4dd/2GpMyTYjz3zC59MvQy4MIzJZhdzKHekg=\n"
+ "id rsa1024 FHyh10glEMA6MCmBb5R9Y+X/MhQ\n"
+ /* Good 7: I've given this one another sort of odd policy. Should parse. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAKcd3FmQ8iAADghyvX8eca0ePqtJ2w1IDdUdTlf5Y/8+OMdp//sD01yC\n"
+ "YmiX45LK5ge1O3AzcakYCO6fb3pyIqvXdvm24OjyYZELQ40cmKSLjdhcSf4Fr/N9\n"
+ "uR/CkknR9cEePu1wZ5WBIGmGdXI6s7t3LB+e7XFyBYAx6wMGlnX7AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "p accept frogs-mice\n"
+ "ntor-onion-key AMxvhaQ1Qg7jBJFoyHuPRgETvLbFmJ194hExV24FuAI=\n"
+ "family $D8CFEA0D996F5D1473D2063C041B7910DB23981E\n"
+ "id rsa1024 d0VVZC/cHh1P3y4MMbfKlQHFycc\n"
+ /* Good 8: This one has the ntor-onion-key without terminating =. That's
+ * allowed. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL438YfjrJE2SPqkkXeQwICygu8KNO54Juj6sjqk5hgsiazIWMOBgbaX\n"
+ "LIRqPNGaiSq01xSqwjwCBCfwZYT/nSdDBqj1h9aoR8rnjxZjyQ+m3rWpdDqeCDMx\n"
+ "I3NgZ5w4bNX4poRb42lrV6NmQiFdjzpqszVbv5Lpn2CSKu32CwKVAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key UKL6Dnj2KwYsFlkCvOkXVatxvOPB4MaxqwPQQgZMTwI\n"
+ "id rsa1024 FPIXc6k++JnKCtSKWUxaR6oXEKs\n"
+ /* Good 9: Another totally normal one.*/
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBANNGIKRd8PFNXkJ2JPV1ohDMFNbJwKbwybeieaQFjtU9KWedHCbr+QD4\n"
+ "B6zNY5ysguNjHNnlq2f6D09+uhnfDBON8tAz0mPQH/6JqnOXm+EiUn+8bN0E8Nke\n"
+ "/i3GEgDeaxJJMNQcpsJvmmSmKFOlYy9Fy7ejAjTGqtAnqOte7BnTAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key gUsq3e5iYgsQQvyxINtLzBpHxmIt5rtuFlEbKfI4gFk=\n"
+ "id rsa1024 jv+LdatDzsMfEW6pLBeL/5uzwCc\n"
+ /* Bad 2: RSA key has bad exponent of 3. */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGHAoGBAMMTWtvPxYnUNJ5Y7B+XENcpxzPoGstrdiUszCBS+/42xvluLJ+JDSdR\n"
+ "qJaMD6ax8vKAeLS5C6O17MNdG2VldlPRbtgl41MXsOoUqEJ+nY9e3WG9Snjp47xC\n"
+ "zmWIfeduXSavIsb3a43/MLIz/9qO0TkgAAiuQr79JlwKhLdzCqTLAgED\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key NkRB4wTUFogiVp5jYmjGORe2ffb/y5Kk8Itw8jdzMjA=\n"
+ "p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999\n"
+ "id rsa1024 fKvYjP7TAjCC1FzYee5bYAwYkoDg\n"
+ /* Bad 3: Bogus annotation */
+ "@last-listed with strange aeons\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBALcRBFNCZtpd2TFJysU77/fJMFzKisRQEBOtDGtTZ2Bg4aEGosssa0Id\n"
+ "YtUagRLYle08QVGvGB+EHBI5qf6Ah2yPH7k5QiN2a3Sq+nyh85dXKPazBGBBbM+C\n"
+ "DOfDauV02CAnADNMLJEf1voY3oBVvYyIsmHxn5i1R19ZYIiR8NX5AgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key m4xcFXMWMjCvZDXq8FT3XmS0EHYseGOeu+fV+6FYDlk=\n"
+ "p accept 20-23,43,53,79-81,88,110,143,194,220,389,443,464,531,543-544\n"
+ "id rsa1024 SSbfNE9vmaiwRKH+eqNAkiKQhds\n"
+ /* Good 10: Normal, with added ipv6 address and added other address */
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAM7uUtq5F6h63QNYIvC+4NcWaD0DjtnrOORZMkdpJhinXUOwce3cD5Dj\n"
+ "sgdN1wJpWpTQMXJ2DssfSgmOVXETP7qJuZyRprxalQhaEATMDNJA/66Ml1jSO9mZ\n"
+ "+8Xb7m/4q778lNtkSbsvMaYD2Dq6k2QQ3kMhr9z8oUtX0XA23+pfAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "a [::1:2:3:4]:9090\n"
+ "a 18.0.0.1:9999\n"
+ "ntor-onion-key k2yFqTU2vzMCQDEiE/j9UcEHxKrXMLpB3IL0or09sik=\n"
+ "id rsa1024 2A8wYpHxnkKJ92orocvIQBzeHlE\n"
+ "p6 allow 80\n"
+ ;
+
+/** More tests for parsing different kinds of microdescriptors, and getting
+ * invalid digests trackd from them. */
+static void
+test_md_parse(void *arg)
+{
+ (void) arg;
+ char *mem_op_hex_tmp = NULL;
+ smartlist_t *invalid = smartlist_new();
+
+ smartlist_t *mds = microdescs_parse_from_string(MD_PARSE_TEST_DATA,
+ NULL, 1, SAVED_NOWHERE,
+ invalid);
+ tt_int_op(smartlist_len(mds), OP_EQ, 11);
+ tt_int_op(smartlist_len(invalid), OP_EQ, 4);
+
+ test_memeq_hex(smartlist_get(invalid,0),
+ "5d76bf1c6614e885614a1e0ad074e1ab"
+ "4ea14655ebeefb1736a71b5ed8a15a51");
+ test_memeq_hex(smartlist_get(invalid,1),
+ "2fde0ee3343669c2444cd9d53cbd39c6"
+ "a7d1fc0513513e840ca7f6e68864b36c");
+ test_memeq_hex(smartlist_get(invalid,2),
+ "20d1576c5ab11bbcff0dedb1db4a3cfc"
+ "c8bc8dd839d8cbfef92d00a1a7d7b294");
+ test_memeq_hex(smartlist_get(invalid,3),
+ "074770f394c73dbde7b44412e9692add"
+ "691a478d4727f9804b77646c95420a96");
+
+ /* Spot-check the valid ones. */
+ const microdesc_t *md = smartlist_get(mds, 5);
+ test_memeq_hex(md->digest,
+ "54bb6d733ddeb375d2456c79ae103961"
+ "da0cae29620375ac4cf13d54da4d92b3");
+ tt_int_op(md->last_listed, OP_EQ, 0);
+ tt_int_op(md->saved_location, OP_EQ, SAVED_NOWHERE);
+ tt_int_op(md->no_save, OP_EQ, 0);
+ tt_uint_op(md->held_in_map, OP_EQ, 0);
+ tt_uint_op(md->held_by_nodes, OP_EQ, 0);
+ tt_assert(md->onion_curve25519_pkey);
+
+ md = smartlist_get(mds, 6);
+ test_memeq_hex(md->digest,
+ "53f740bd222ab37f19f604b1d3759aa6"
+ "5eff1fbce9ac254bd0fa50d4af9b1bae");
+ tt_assert(! md->exit_policy);
+
+ md = smartlist_get(mds, 8);
+ test_memeq_hex(md->digest,
+ "a0a155562d8093d8fd0feb7b93b7226e"
+ "17f056c2142aab7a4ea8c5867a0376d5");
+ tt_assert(md->onion_curve25519_pkey);
+
+ md = smartlist_get(mds, 10);
+ test_memeq_hex(md->digest,
+ "409ebd87d23925a2732bd467a92813c9"
+ "21ca378fcb9ca193d354c51550b6d5e9");
+ tt_assert(tor_addr_family(&md->ipv6_addr) == AF_INET6);
+ tt_int_op(md->ipv6_orport, OP_EQ, 9090);
+
+ done:
+ SMARTLIST_FOREACH(mds, microdesc_t *, md, microdesc_free(md));
+ smartlist_free(mds);
+ SMARTLIST_FOREACH(invalid, char *, cp, tor_free(cp));
+ smartlist_free(invalid);
+ tor_free(mem_op_hex_tmp);
+}
+
+static int mock_rgsbd_called = 0;
+static routerstatus_t *mock_rgsbd_val_a = NULL;
+static routerstatus_t *mock_rgsbd_val_b = NULL;
+static routerstatus_t *
+mock_router_get_status_by_digest(networkstatus_t *c, const char *d)
+{
+ (void) c;
+ ++mock_rgsbd_called;
+
+ if (fast_memeq(d, "\x5d\x76", 2)) {
+ memcpy(mock_rgsbd_val_a->descriptor_digest, d, 32);
+ return mock_rgsbd_val_a;
+ } else if (fast_memeq(d, "\x20\xd1", 2)) {
+ memcpy(mock_rgsbd_val_b->descriptor_digest, d, 32);
+ return mock_rgsbd_val_b;
+ } else {
+ return NULL;
+ }
+}
+
+static networkstatus_t *mock_ns_val = NULL;
+static networkstatus_t *
+mock_ns_get_by_flavor(consensus_flavor_t f)
+{
+ (void)f;
+ return mock_ns_val;
+}
+
+static void
+test_md_reject_cache(void *arg)
+{
+ (void) arg;
+ microdesc_cache_t *mc = NULL ;
+ smartlist_t *added = NULL, *wanted = smartlist_new();
+ or_options_t *options = get_options_mutable();
+ char buf[DIGEST256_LEN];
+
+ tor_free(options->DataDirectory);
+ options->DataDirectory = tor_strdup(get_fname("md_datadir_test_rej"));
+ mock_rgsbd_val_a = tor_malloc_zero(sizeof(routerstatus_t));
+ mock_rgsbd_val_b = tor_malloc_zero(sizeof(routerstatus_t));
+ mock_ns_val = tor_malloc_zero(sizeof(networkstatus_t));
+
+ mock_ns_val->valid_after = time(NULL) - 86400;
+ mock_ns_val->valid_until = time(NULL) + 86400;
+ mock_ns_val->flavor = FLAV_MICRODESC;
+
+#ifdef _WIN32
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory));
+#else
+ tt_int_op(0, OP_EQ, mkdir(options->DataDirectory, 0700));
+#endif
+
+ MOCK(router_get_mutable_consensus_status_by_descriptor_digest,
+ mock_router_get_status_by_digest);
+ MOCK(networkstatus_get_latest_consensus_by_flavor, mock_ns_get_by_flavor);
+
+ mc = get_microdesc_cache();
+#define ADD(hex) \
+ do { \
+ tt_int_op(0,OP_EQ,base16_decode(buf,sizeof(buf),hex,strlen(hex))); \
+ smartlist_add(wanted, tor_memdup(buf, DIGEST256_LEN)); \
+ } while (0)
+
+ /* invalid,0 */
+ ADD("5d76bf1c6614e885614a1e0ad074e1ab4ea14655ebeefb1736a71b5ed8a15a51");
+ /* invalid,2 */
+ ADD("20d1576c5ab11bbcff0dedb1db4a3cfcc8bc8dd839d8cbfef92d00a1a7d7b294");
+ /* valid, 6 */
+ ADD("53f740bd222ab37f19f604b1d3759aa65eff1fbce9ac254bd0fa50d4af9b1bae");
+ /* valid, 8 */
+ ADD("a0a155562d8093d8fd0feb7b93b7226e17f056c2142aab7a4ea8c5867a0376d5");
+
+ added = microdescs_add_to_cache(mc, MD_PARSE_TEST_DATA, NULL,
+ SAVED_NOWHERE, 0, time(NULL), wanted);
+
+ tt_int_op(smartlist_len(added), OP_EQ, 2);
+ tt_int_op(mock_rgsbd_called, OP_EQ, 2);
+ tt_int_op(mock_rgsbd_val_a->dl_status.n_download_failures, OP_EQ, 255);
+ tt_int_op(mock_rgsbd_val_b->dl_status.n_download_failures, OP_EQ, 255);
+
+ done:
+ UNMOCK(networkstatus_get_latest_consensus_by_flavor);
+ UNMOCK(router_get_mutable_consensus_status_by_descriptor_digest);
+ tor_free(options->DataDirectory);
+ microdesc_free_all();
+ smartlist_free(added);
+ SMARTLIST_FOREACH(wanted, char *, cp, tor_free(cp));
+ smartlist_free(wanted);
+ tor_free(mock_rgsbd_val_a);
+ tor_free(mock_rgsbd_val_b);
+ tor_free(mock_ns_val);
+}
+
+static void
+test_md_corrupt_desc(void *arg)
+{
+ char *cp = NULL;
+ smartlist_t *sl = NULL;
+ (void) arg;
+
+ sl = microdescs_add_to_cache(get_microdesc_cache(),
+ "@last-listed 2015-06-22 10:00:00\n"
+ "onion-k\n",
+ NULL, SAVED_IN_JOURNAL, 0, time(NULL), NULL);
+ tt_int_op(smartlist_len(sl), ==, 0);
+ smartlist_free(sl);
+
+ sl = microdescs_add_to_cache(get_microdesc_cache(),
+ "@last-listed 2015-06-22 10:00:00\n"
+ "wiggly\n",
+ NULL, SAVED_IN_JOURNAL, 0, time(NULL), NULL);
+ tt_int_op(smartlist_len(sl), ==, 0);
+ smartlist_free(sl);
+
+ tor_asprintf(&cp, "%s\n%s", test_md1, "@foobar\nonion-wobble\n");
+
+ sl = microdescs_add_to_cache(get_microdesc_cache(),
+ cp, cp+strlen(cp),
+ SAVED_IN_JOURNAL, 0, time(NULL), NULL);
+ tt_int_op(smartlist_len(sl), ==, 0);
+
+ done:
+ tor_free(cp);
+ smartlist_free(sl);
+}
+
struct testcase_t microdesc_tests[] = {
{ "cache", test_md_cache, TT_FORK, NULL, NULL },
{ "broken_cache", test_md_cache_broken, TT_FORK, NULL, NULL },
{ "generate", test_md_generate, 0, NULL, NULL },
+ { "parse", test_md_parse, 0, NULL, NULL },
+ { "reject_cache", test_md_reject_cache, TT_FORK, NULL, NULL },
+ { "corrupt_desc", test_md_corrupt_desc, TT_FORK, NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_nodelist.c b/src/test/test_nodelist.c
index 600e6a89d4..d58f8a7fca 100644
--- a/src/test/test_nodelist.c
+++ b/src/test/test_nodelist.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2007-2013, The Tor Project, Inc. */
+/* Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
@@ -10,7 +10,7 @@
#include "nodelist.h"
#include "test.h"
-/** Tese the case when node_get_by_id() returns NULL,
+/** Test the case when node_get_by_id() returns NULL,
* node_get_verbose_nickname_by_id should return the base 16 encoding
* of the id.
*/
@@ -23,9 +23,9 @@ test_nodelist_node_get_verbose_nickname_by_id_null_node(void *arg)
(void) arg;
/* make sure node_get_by_id returns NULL */
- test_assert(!node_get_by_id(ID));
+ tt_assert(!node_get_by_id(ID));
node_get_verbose_nickname_by_id(ID, vname);
- test_streq(vname, "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
+ tt_str_op(vname,OP_EQ, "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
done:
return;
}
@@ -54,7 +54,47 @@ test_nodelist_node_get_verbose_nickname_not_named(void *arg)
"\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA",
DIGEST_LEN);
node_get_verbose_nickname(&mock_node, vname);
- test_streq(vname, "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~TestOR");
+ tt_str_op(vname,OP_EQ, "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~TestOR");
+
+ done:
+ return;
+}
+
+/** A node should be considered a directory server if it has an open dirport
+ * of it accepts tunnelled directory requests.
+ */
+static void
+test_nodelist_node_is_dir(void *arg)
+{
+ (void)arg;
+
+ routerstatus_t rs;
+ routerinfo_t ri;
+ node_t node;
+ memset(&node, 0, sizeof(node_t));
+ memset(&rs, 0, sizeof(routerstatus_t));
+ memset(&ri, 0, sizeof(routerinfo_t));
+
+ tt_assert(!node_is_dir(&node));
+
+ node.rs = &rs;
+ tt_assert(!node_is_dir(&node));
+
+ rs.is_v2_dir = 1;
+ tt_assert(node_is_dir(&node));
+
+ rs.is_v2_dir = 0;
+ rs.dir_port = 1;
+ tt_assert(! node_is_dir(&node));
+
+ node.rs = NULL;
+ tt_assert(!node_is_dir(&node));
+ node.ri = &ri;
+ ri.supports_tunnelled_dir_requests = 1;
+ tt_assert(node_is_dir(&node));
+ ri.supports_tunnelled_dir_requests = 0;
+ ri.dir_port = 1;
+ tt_assert(! node_is_dir(&node));
done:
return;
@@ -66,6 +106,7 @@ test_nodelist_node_get_verbose_nickname_not_named(void *arg)
struct testcase_t nodelist_tests[] = {
NODE(node_get_verbose_nickname_by_id_null_node, TT_FORK),
NODE(node_get_verbose_nickname_not_named, TT_FORK),
+ NODE(node_is_dir, TT_FORK),
END_OF_TESTCASES
};
diff --git a/src/test/test_ntor.sh b/src/test/test_ntor.sh
new file mode 100755
index 0000000000..5081dabc54
--- /dev/null
+++ b/src/test/test_ntor.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+# Validate Tor's ntor implementation.
+
+exitcode=0
+
+"${PYTHON:-python}" "${abs_top_srcdir:-.}/src/test/ntor_ref.py" test-tor || exitcode=1
+"${PYTHON:-python}" "${abs_top_srcdir:-.}/src/test/ntor_ref.py" self-test || exitcode=1
+
+exit ${exitcode}
diff --git a/src/test/test_ntor_cl.c b/src/test/test_ntor_cl.c
index f2b7a72ad5..6df123162e 100644
--- a/src/test/test_ntor_cl.c
+++ b/src/test/test_ntor_cl.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2012-2013, The Tor Project, Inc. */
+/* Copyright (c) 2012-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -13,10 +13,6 @@
#include "crypto_curve25519.h"
#include "onion_ntor.h"
-#ifndef CURVE25519_ENABLED
-#error "This isn't going to work without curve25519."
-#endif
-
#define N_ARGS(n) STMT_BEGIN { \
if (argc < (n)) { \
fprintf(stderr, "%s needs %d arguments.\n",argv[1],n); \
@@ -110,6 +106,7 @@ server1(int argc, char **argv)
done:
tor_free(keys);
tor_free(hexkeys);
+ dimap_free(keymap, NULL);
return result;
}
@@ -130,7 +127,7 @@ client2(int argc, char **argv)
keys = tor_malloc(keybytes);
hexkeys = tor_malloc(keybytes*2+1);
- if (onion_skin_ntor_client_handshake(&state, msg, keys, keybytes)<0) {
+ if (onion_skin_ntor_client_handshake(&state, msg, keys, keybytes, NULL)<0) {
fprintf(stderr, "handshake failed");
result = 2;
goto done;
diff --git a/src/test/test_oom.c b/src/test/test_oom.c
index 2726056b80..2569b6e00f 100644
--- a/src/test/test_oom.c
+++ b/src/test/test_oom.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2014, The Tor Project, Inc. */
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/* Unit tests for OOM handling logic */
@@ -13,9 +13,6 @@
#include "compat_libevent.h"
#include "connection.h"
#include "config.h"
-#ifdef ENABLE_MEMPOOLS
-#include "mempool.h"
-#endif
#include "relay.h"
#include "test.h"
@@ -143,17 +140,13 @@ test_oom_circbuf(void *arg)
MOCK(circuit_mark_for_close_, circuit_mark_for_close_dummy_);
-#ifdef ENABLE_MEMPOOLS
- init_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
-
/* Far too low for real life. */
options->MaxMemInQueues = 256*packed_cell_mem_cost();
options->CellStatistics = 0;
- tt_int_op(cell_queues_check_size(), ==, 0); /* We don't start out OOM. */
- tt_int_op(cell_queues_get_total_allocation(), ==, 0);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(cell_queues_check_size(), OP_EQ, 0); /* We don't start out OOM. */
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
/* Now we're going to fake up some circuits and get them added to the global
circuit list. */
@@ -164,22 +157,17 @@ test_oom_circbuf(void *arg)
tor_gettimeofday_cache_set(&tv);
c2 = dummy_or_circuit_new(20, 20);
-#ifdef ENABLE_MEMPOOLS
- tt_int_op(packed_cell_mem_cost(), ==,
- sizeof(packed_cell_t) + MP_POOL_ITEM_OVERHEAD);
-#else
- tt_int_op(packed_cell_mem_cost(), ==,
+ tt_int_op(packed_cell_mem_cost(), OP_EQ,
sizeof(packed_cell_t));
-#endif /* ENABLE_MEMPOOLS */
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 70);
- tt_int_op(cell_queues_check_size(), ==, 0); /* We are still not OOM */
+ tt_int_op(cell_queues_check_size(), OP_EQ, 0); /* We are still not OOM */
tv.tv_usec = 20*1000;
tor_gettimeofday_cache_set(&tv);
c3 = dummy_or_circuit_new(100, 85);
- tt_int_op(cell_queues_check_size(), ==, 0); /* We are still not OOM */
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_check_size(), OP_EQ, 0); /* We are still not OOM */
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 255);
tv.tv_usec = 30*1000;
@@ -187,17 +175,17 @@ test_oom_circbuf(void *arg)
/* Adding this cell will trigger our OOM handler. */
c4 = dummy_or_circuit_new(2, 0);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 257);
- tt_int_op(cell_queues_check_size(), ==, 1); /* We are now OOM */
+ tt_int_op(cell_queues_check_size(), OP_EQ, 1); /* We are now OOM */
tt_assert(c1->marked_for_close);
tt_assert(! c2->marked_for_close);
tt_assert(! c3->marked_for_close);
tt_assert(! c4->marked_for_close);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * (257 - 30));
circuit_free(c1);
@@ -208,14 +196,14 @@ test_oom_circbuf(void *arg)
tv.tv_usec = 40*1000; /* go back to the future */
tor_gettimeofday_cache_set(&tv);
- tt_int_op(cell_queues_check_size(), ==, 1); /* We are now OOM */
+ tt_int_op(cell_queues_check_size(), OP_EQ, 1); /* We are now OOM */
tt_assert(c1->marked_for_close);
tt_assert(! c2->marked_for_close);
tt_assert(! c3->marked_for_close);
tt_assert(! c4->marked_for_close);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * (257 - 30));
done:
@@ -242,17 +230,13 @@ test_oom_streambuf(void *arg)
MOCK(circuit_mark_for_close_, circuit_mark_for_close_dummy_);
-#ifdef ENABLE_MEMPOOLS
- init_cell_pool();
-#endif /* ENABLE_MEMPOOLS */
-
/* Far too low for real life. */
options->MaxMemInQueues = 81*packed_cell_mem_cost() + 4096 * 34;
options->CellStatistics = 0;
- tt_int_op(cell_queues_check_size(), ==, 0); /* We don't start out OOM. */
- tt_int_op(cell_queues_get_total_allocation(), ==, 0);
- tt_int_op(buf_get_total_allocation(), ==, 0);
+ tt_int_op(cell_queues_check_size(), OP_EQ, 0); /* We don't start out OOM. */
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ, 0);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 0);
/* Start all circuits with a bit of data queued in cells */
tv.tv_usec = 500*1000; /* go halfway into the second. */
@@ -267,7 +251,7 @@ test_oom_streambuf(void *arg)
tv.tv_usec = 530*1000;
tor_gettimeofday_cache_set(&tv);
c4 = dummy_or_circuit_new(0,0);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 80);
tv.tv_usec = 600*1000;
@@ -303,24 +287,24 @@ test_oom_streambuf(void *arg)
tv.tv_usec = 0;
tvms = (uint32_t) tv_to_msec(&tv);
- tt_int_op(circuit_max_queued_cell_age(c1, tvms), ==, 500);
- tt_int_op(circuit_max_queued_cell_age(c2, tvms), ==, 490);
- tt_int_op(circuit_max_queued_cell_age(c3, tvms), ==, 480);
- tt_int_op(circuit_max_queued_cell_age(c4, tvms), ==, 0);
+ tt_int_op(circuit_max_queued_cell_age(c1, tvms), OP_EQ, 500);
+ tt_int_op(circuit_max_queued_cell_age(c2, tvms), OP_EQ, 490);
+ tt_int_op(circuit_max_queued_cell_age(c3, tvms), OP_EQ, 480);
+ tt_int_op(circuit_max_queued_cell_age(c4, tvms), OP_EQ, 0);
- tt_int_op(circuit_max_queued_data_age(c1, tvms), ==, 390);
- tt_int_op(circuit_max_queued_data_age(c2, tvms), ==, 380);
- tt_int_op(circuit_max_queued_data_age(c3, tvms), ==, 0);
- tt_int_op(circuit_max_queued_data_age(c4, tvms), ==, 370);
+ tt_int_op(circuit_max_queued_data_age(c1, tvms), OP_EQ, 390);
+ tt_int_op(circuit_max_queued_data_age(c2, tvms), OP_EQ, 380);
+ tt_int_op(circuit_max_queued_data_age(c3, tvms), OP_EQ, 0);
+ tt_int_op(circuit_max_queued_data_age(c4, tvms), OP_EQ, 370);
- tt_int_op(circuit_max_queued_item_age(c1, tvms), ==, 500);
- tt_int_op(circuit_max_queued_item_age(c2, tvms), ==, 490);
- tt_int_op(circuit_max_queued_item_age(c3, tvms), ==, 480);
- tt_int_op(circuit_max_queued_item_age(c4, tvms), ==, 370);
+ tt_int_op(circuit_max_queued_item_age(c1, tvms), OP_EQ, 500);
+ tt_int_op(circuit_max_queued_item_age(c2, tvms), OP_EQ, 490);
+ tt_int_op(circuit_max_queued_item_age(c3, tvms), OP_EQ, 480);
+ tt_int_op(circuit_max_queued_item_age(c4, tvms), OP_EQ, 370);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 80);
- tt_int_op(buf_get_total_allocation(), ==, 4096*16*2);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 4096*16*2);
/* Now give c4 a very old buffer of modest size */
{
@@ -332,21 +316,21 @@ test_oom_streambuf(void *arg)
tt_assert(ec);
smartlist_add(edgeconns, ec);
}
- tt_int_op(buf_get_total_allocation(), ==, 4096*17*2);
- tt_int_op(circuit_max_queued_item_age(c4, tvms), ==, 1000);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 4096*17*2);
+ tt_int_op(circuit_max_queued_item_age(c4, tvms), OP_EQ, 1000);
- tt_int_op(cell_queues_check_size(), ==, 0);
+ tt_int_op(cell_queues_check_size(), OP_EQ, 0);
/* And run over the limit. */
tv.tv_usec = 800*1000;
tor_gettimeofday_cache_set(&tv);
c5 = dummy_or_circuit_new(0,5);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 85);
- tt_int_op(buf_get_total_allocation(), ==, 4096*17*2);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 4096*17*2);
- tt_int_op(cell_queues_check_size(), ==, 1); /* We are now OOM */
+ tt_int_op(cell_queues_check_size(), OP_EQ, 1); /* We are now OOM */
/* C4 should have died. */
tt_assert(! c1->marked_for_close);
@@ -355,9 +339,9 @@ test_oom_streambuf(void *arg)
tt_assert(c4->marked_for_close);
tt_assert(! c5->marked_for_close);
- tt_int_op(cell_queues_get_total_allocation(), ==,
+ tt_int_op(cell_queues_get_total_allocation(), OP_EQ,
packed_cell_mem_cost() * 85);
- tt_int_op(buf_get_total_allocation(), ==, 4096*8*2);
+ tt_int_op(buf_get_total_allocation(), OP_EQ, 4096*8*2);
done:
circuit_free(c1);
diff --git a/src/test/test_options.c b/src/test/test_options.c
index 737f658e2c..4f24757a85 100644
--- a/src/test/test_options.c
+++ b/src/test/test_options.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define CONFIG_PRIVATE
@@ -8,6 +8,18 @@
#include "confparse.h"
#include "config.h"
#include "test.h"
+#include "geoip.h"
+
+#define ROUTERSET_PRIVATE
+#include "routerset.h"
+
+#include "log_test_helpers.h"
+
+#include "sandbox.h"
+#include "memarea.h"
+#include "policies.h"
+
+#define NS_MODULE test_options
typedef struct {
int severity;
@@ -38,6 +50,7 @@ setup_log_callback(void)
lst.masks[LOG_WARN - LOG_ERR] = ~0;
lst.masks[LOG_NOTICE - LOG_ERR] = ~0;
add_callback_log(&lst, log_cback);
+ mark_logs_temp();
}
static char *
@@ -69,28 +82,47 @@ clear_log_messages(void)
messages = NULL;
}
+#define setup_options(opt,dflt) \
+ do { \
+ opt = options_new(); \
+ opt->command = CMD_RUN_TOR; \
+ options_init(opt); \
+ \
+ dflt = config_dup(&options_format, opt); \
+ clear_log_messages(); \
+ } while (0)
+
+#define VALID_DIR_AUTH "DirAuthority dizum orport=443 v3ident=E8A9C45" \
+ "EDE6D711294FADF8E7951F4DE6CA56B58 194.109.206.212:80 7EA6 EAD6 FD83" \
+ " 083C 538F 4403 8BBF A077 587D D755\n"
+#define VALID_ALT_BRIDGE_AUTH \
+ "AlternateBridgeAuthority dizum orport=443 v3ident=E8A9C45" \
+ "EDE6D711294FADF8E7951F4DE6CA56B58 194.109.206.212:80 7EA6 EAD6 FD83" \
+ " 083C 538F 4403 8BBF A077 587D D755\n"
+#define VALID_ALT_DIR_AUTH \
+ "AlternateDirAuthority dizum orport=443 v3ident=E8A9C45" \
+ "EDE6D711294FADF8E7951F4DE6CA56B58 194.109.206.212:80 7EA6 EAD6 FD83" \
+ " 083C 538F 4403 8BBF A077 587D D755\n"
+
static void
test_options_validate_impl(const char *configuration,
const char *expect_errmsg,
int expect_log_severity,
const char *expect_log)
{
- or_options_t *opt = options_new();
+ or_options_t *opt=NULL;
or_options_t *dflt;
config_line_t *cl=NULL;
char *msg=NULL;
int r;
- opt->command = CMD_RUN_TOR;
- options_init(opt);
- dflt = config_dup(&options_format, opt);
- clear_log_messages();
+ setup_options(opt, dflt);
r = config_get_lines(configuration, &cl, 1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
r = config_assign(&options_format, opt, cl, 0, 0, &msg);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
r = options_validate(NULL, opt, dflt, 0, &msg);
if (expect_errmsg && !msg) {
@@ -103,7 +135,7 @@ test_options_validate_impl(const char *configuration,
TT_DIE(("Expected no error message from <%s> but got <%s>.",
configuration, msg));
}
- tt_int_op((r == 0), ==, (msg == NULL));
+ tt_int_op((r == 0), OP_EQ, (msg == NULL));
if (expect_log) {
int found = 0;
@@ -126,6 +158,8 @@ test_options_validate_impl(const char *configuration,
}
done:
+ escaped(NULL);
+ policies_free_all();
config_free_lines(cl);
or_options_free(opt);
or_options_free(dflt);
@@ -147,6 +181,7 @@ test_options_validate(void *arg)
{
(void)arg;
setup_log_callback();
+ sandbox_disable_getaddrinfo_cache();
WANT_ERR("ExtORPort 500000", "Invalid ExtORPort");
@@ -159,12 +194,4205 @@ test_options_validate(void *arg)
"ServerTransportOptions did not parse",
LOG_WARN, "\"slingsnappy\" is not a k=v");
+ WANT_ERR("DirPort 8080\nDirCache 0",
+ "DirPort configured but DirCache disabled.");
+ WANT_ERR("BridgeRelay 1\nDirCache 0",
+ "We're a bridge but DirCache is disabled.");
+
+ close_temp_logs();
+ clear_log_messages();
+ return;
+}
+
+#define MEGABYTEIFY(mb) (U64_LITERAL(mb) << 20)
+static void
+test_have_enough_mem_for_dircache(void *arg)
+{
+ (void)arg;
+ or_options_t *opt=NULL;
+ or_options_t *dflt=NULL;
+ config_line_t *cl=NULL;
+ char *msg=NULL;;
+ int r;
+ const char *configuration = "ORPort 8080\nDirCache 1", *expect_errmsg;
+
+ setup_options(opt, dflt);
+ setup_log_callback();
+ (void)dflt;
+
+ r = config_get_lines(configuration, &cl, 1);
+ tt_int_op(r, OP_EQ, 0);
+
+ r = config_assign(&options_format, opt, cl, 0, 0, &msg);
+ tt_int_op(r, OP_EQ, 0);
+
+ /* 300 MB RAM available, DirCache enabled */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(300), &msg);
+ tt_int_op(r, OP_EQ, 0);
+ tt_assert(!msg);
+
+ /* 200 MB RAM available, DirCache enabled */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(200), &msg);
+ tt_int_op(r, OP_EQ, -1);
+ expect_errmsg = "Being a directory cache (default) with less than ";
+ if (!strstr(msg, expect_errmsg)) {
+ TT_DIE(("Expected error message <%s> from <%s>, but got <%s>.",
+ expect_errmsg, configuration, msg));
+ }
+ tor_free(msg);
+
+ config_free_lines(cl); cl = NULL;
+ configuration = "ORPort 8080\nDirCache 1\nBridgeRelay 1";
+ r = config_get_lines(configuration, &cl, 1);
+ tt_int_op(r, OP_EQ, 0);
+
+ r = config_assign(&options_format, opt, cl, 0, 0, &msg);
+ tt_int_op(r, OP_EQ, 0);
+
+ /* 300 MB RAM available, DirCache enabled, Bridge */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(300), &msg);
+ tt_int_op(r, OP_EQ, 0);
+ tt_assert(!msg);
+
+ /* 200 MB RAM available, DirCache enabled, Bridge */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(200), &msg);
+ tt_int_op(r, OP_EQ, -1);
+ expect_errmsg = "Running a Bridge with less than ";
+ if (!strstr(msg, expect_errmsg)) {
+ TT_DIE(("Expected error message <%s> from <%s>, but got <%s>.",
+ expect_errmsg, configuration, msg));
+ }
+ tor_free(msg);
+
+ config_free_lines(cl); cl = NULL;
+ configuration = "ORPort 8080\nDirCache 0";
+ r = config_get_lines(configuration, &cl, 1);
+ tt_int_op(r, OP_EQ, 0);
+
+ r = config_assign(&options_format, opt, cl, 0, 0, &msg);
+ tt_int_op(r, OP_EQ, 0);
+
+ /* 200 MB RAM available, DirCache disabled */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(200), &msg);
+ tt_int_op(r, OP_EQ, 0);
+ tt_assert(!msg);
+
+ /* 300 MB RAM available, DirCache disabled */
+ r = have_enough_mem_for_dircache(opt, MEGABYTEIFY(300), &msg);
+ tt_int_op(r, OP_EQ, -1);
+ expect_errmsg = "DirCache is disabled and we are configured as a ";
+ if (!strstr(msg, expect_errmsg)) {
+ TT_DIE(("Expected error message <%s> from <%s>, but got <%s>.",
+ expect_errmsg, configuration, msg));
+ }
+ tor_free(msg);
+
clear_log_messages();
+
+ done:
+ if (msg)
+ tor_free(msg);
+ or_options_free(dflt);
+ or_options_free(opt);
+ config_free_lines(cl);
return;
}
+static const char *fixed_get_uname_result = NULL;
+
+static const char *
+fixed_get_uname(void)
+{
+ return fixed_get_uname_result;
+}
+
+#define TEST_OPTIONS_OLD_VALUES "TestingV3AuthInitialVotingInterval 1800\n" \
+ "ClientBootstrapConsensusMaxDownloadTries 7\n" \
+ "ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries 4\n" \
+ "ClientBootstrapConsensusMaxInProgressTries 3\n" \
+ "TestingV3AuthInitialVoteDelay 300\n" \
+ "TestingV3AuthInitialDistDelay 300\n" \
+ "TestingClientMaxIntervalWithoutRequest 600\n" \
+ "TestingDirConnectionMaxStall 600\n" \
+ "TestingConsensusMaxDownloadTries 8\n" \
+ "TestingDescriptorMaxDownloadTries 8\n" \
+ "TestingMicrodescMaxDownloadTries 8\n" \
+ "TestingCertMaxDownloadTries 8\n"
+
+#define TEST_OPTIONS_DEFAULT_VALUES TEST_OPTIONS_OLD_VALUES \
+ "MaxClientCircuitsPending 1\n" \
+ "RendPostPeriod 1000\n" \
+ "KeepAlivePeriod 1\n" \
+ "ConnLimit 1\n" \
+ "V3AuthVotingInterval 300\n" \
+ "V3AuthVoteDelay 20\n" \
+ "V3AuthDistDelay 20\n" \
+ "V3AuthNIntervalsValid 3\n" \
+ "ClientUseIPv4 1\n" \
+ "VirtualAddrNetworkIPv4 127.192.0.0/10\n" \
+ "VirtualAddrNetworkIPv6 [FE80::]/10\n" \
+ "SchedulerHighWaterMark__ 42\n" \
+ "SchedulerLowWaterMark__ 10\n"
+
+typedef struct {
+ or_options_t *old_opt;
+ or_options_t *opt;
+ or_options_t *def_opt;
+} options_test_data_t;
+
+static void free_options_test_data(options_test_data_t *td);
+
+static options_test_data_t *
+get_options_test_data(const char *conf)
+{
+ int rv = -1;
+ char *msg = NULL;
+ config_line_t *cl=NULL;
+ options_test_data_t *result = tor_malloc(sizeof(options_test_data_t));
+ result->opt = options_new();
+ result->old_opt = options_new();
+ result->def_opt = options_new();
+ rv = config_get_lines(conf, &cl, 1);
+ tt_assert(rv == 0);
+ rv = config_assign(&options_format, result->opt, cl, 0, 0, &msg);
+ if (msg) {
+ /* Display the parse error message by comparing it with an empty string */
+ tt_str_op(msg, OP_EQ, "");
+ }
+ tt_assert(rv == 0);
+ config_free_lines(cl);
+ result->opt->LogTimeGranularity = 1;
+ result->opt->TokenBucketRefillInterval = 1;
+ rv = config_get_lines(TEST_OPTIONS_OLD_VALUES, &cl, 1);
+ tt_assert(rv == 0);
+ rv = config_assign(&options_format, result->def_opt, cl, 0, 0, &msg);
+ if (msg) {
+ /* Display the parse error message by comparing it with an empty string */
+ tt_str_op(msg, OP_EQ, "");
+ }
+ tt_assert(rv == 0);
+
+ done:
+ config_free_lines(cl);
+ if (rv != 0) {
+ free_options_test_data(result);
+ result = NULL;
+ /* Callers expect a non-NULL result, so just die if we can't provide one.
+ */
+ tor_assert(0);
+ }
+ return result;
+}
+
+static void
+free_options_test_data(options_test_data_t *td)
+{
+ if (!td) return;
+ or_options_free(td->old_opt);
+ or_options_free(td->opt);
+ or_options_free(td->def_opt);
+ tor_free(td);
+}
+
+#define expect_log_msg(str) \
+ tt_assert_msg(mock_saved_log_has_message(str), \
+ "expected log to contain " # str);
+
+#define expect_no_log_msg(str) \
+ tt_assert_msg(!mock_saved_log_has_message(str), \
+ "expected log to not contain " # str);
+
+static void
+test_options_validate__uname_for_server(void *ignored)
+{
+ (void)ignored;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "ORListenAddress 127.0.0.1:5555");
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ MOCK(get_uname, fixed_get_uname);
+ fixed_get_uname_result = "Windows 95";
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("Tor is running as a server, but you"
+ " are running Windows 95; this probably won't work. See https://www"
+ ".torproject.org/docs/faq.html#BestOSForRelay for details.\n");
+ tor_free(msg);
+
+ fixed_get_uname_result = "Windows 98";
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("Tor is running as a server, but you"
+ " are running Windows 98; this probably won't work. See https://www"
+ ".torproject.org/docs/faq.html#BestOSForRelay for details.\n");
+ tor_free(msg);
+
+ fixed_get_uname_result = "Windows Me";
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("Tor is running as a server, but you"
+ " are running Windows Me; this probably won't work. See https://www"
+ ".torproject.org/docs/faq.html#BestOSForRelay for details.\n");
+ tor_free(msg);
+
+ fixed_get_uname_result = "Windows 2000";
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_entry();
+ tor_free(msg);
+
+ done:
+ UNMOCK(get_uname);
+ free_options_test_data(tdata);
+ tor_free(msg);
+ teardown_capture_of_logs(previous_log);
+}
+
+static void
+test_options_validate__outbound_addresses(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "OutboundBindAddress xxyy!!!sdfaf");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__data_directory(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "DataDirectory longreallyl"
+ "ongLONGLONGlongreallylong"
+ "LONGLONGlongreallylongLON"
+ "GLONGlongreallylongLONGLO"
+ "NGlongreallylongLONGLONGl"
+ "ongreallylongLONGLONGlong"
+ "reallylongLONGLONGlongrea"
+ "llylongLONGLONGlongreally"
+ "longLONGLONGlongreallylon"
+ "gLONGLONGlongreallylongLO"
+ "NGLONGlongreallylongLONGL"
+ "ONGlongreallylongLONGLONG"
+ "longreallylongLONGLONGlon"
+ "greallylongLONGLONGlongre"
+ "allylongLONGLONGlongreall"
+ "ylongLONGLONGlongreallylo"
+ "ngLONGLONGlongreallylongL"
+ "ONGLONGlongreallylongLONG"
+ "LONG"); // 440 characters
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Invalid DataDirectory");
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__nickname(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "Nickname ThisNickNameIsABitTooLong");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Nickname 'ThisNickNameIsABitTooLong' is wrong length or"
+ " contains illegal characters.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("Nickname AMoreValidNick");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("DataDirectory /tmp/somewhere");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__contactinfo(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "ORListenAddress 127.0.0.1:5555\nORPort 955");
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+ tdata->opt->ContactInfo = NULL;
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg(
+ "Your ContactInfo config option is not"
+ " set. Please consider setting it, so we can contact you if your"
+ " server is misconfigured or something else goes wrong.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ORListenAddress 127.0.0.1:5555\nORPort 955\n"
+ "ContactInfo hella@example.org");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_no_log_msg(
+ "Your ContactInfo config option is not"
+ " set. Please consider setting it, so we can contact you if your"
+ " server is misconfigured or something else goes wrong.\n");
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+extern int quiet_level;
+
+static void
+test_options_validate__logs(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ (void)ret;
+ char *msg;
+ int orig_quiet_level = quiet_level;
+ options_test_data_t *tdata = get_options_test_data("");
+ tdata->opt->Logs = NULL;
+ tdata->opt->RunAsDaemon = 0;
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(tdata->opt->Logs->key, OP_EQ, "Log");
+ tt_str_op(tdata->opt->Logs->value, OP_EQ, "notice stdout");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("");
+ tdata->opt->Logs = NULL;
+ tdata->opt->RunAsDaemon = 0;
+ quiet_level = 1;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(tdata->opt->Logs->key, OP_EQ, "Log");
+ tt_str_op(tdata->opt->Logs->value, OP_EQ, "warn stdout");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("");
+ tdata->opt->Logs = NULL;
+ tdata->opt->RunAsDaemon = 0;
+ quiet_level = 2;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_assert(!tdata->opt->Logs);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("");
+ tdata->opt->Logs = NULL;
+ tdata->opt->RunAsDaemon = 0;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 1, &msg);
+ tt_assert(!tdata->opt->Logs);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("");
+ tdata->opt->Logs = NULL;
+ tdata->opt->RunAsDaemon = 1;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_assert(!tdata->opt->Logs);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("");
+ tdata->opt->RunAsDaemon = 0;
+ config_line_t *cl=NULL;
+ config_get_lines("Log foo", &cl, 1);
+ tdata->opt->Logs = cl;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op((intptr_t)tdata->opt->Logs, OP_EQ, (intptr_t)cl);
+
+ done:
+ quiet_level = orig_quiet_level;
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+/* static config_line_t * */
+/* mock_config_line(const char *key, const char *val) */
+/* { */
+/* config_line_t *config_line = tor_malloc(sizeof(config_line_t)); */
+/* memset(config_line, 0, sizeof(config_line_t)); */
+/* config_line->key = tor_strdup(key); */
+/* config_line->value = tor_strdup(val); */
+/* return config_line; */
+/* } */
+
+static void
+test_options_validate__authdir(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_INFO);
+ options_test_data_t *tdata = get_options_test_data(
+ "AuthoritativeDirectory 1\n"
+ "Address this.should.not_exist.example.org");
+
+ sandbox_disable_getaddrinfo_cache();
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Failed to resolve/guess local address. See logs for"
+ " details.");
+ expect_log_msg("Could not resolve local Address "
+ "'this.should.not_exist.example.org'. Failing.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Authoritative directory servers must set ContactInfo");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "TestingTorNetwork 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "AuthoritativeDir is set, but none of (Bridge/V3)"
+ "AuthoritativeDir is set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "AuthoritativeDir is set, but none of (Bridge/V3)"
+ "AuthoritativeDir is set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "RecommendedVersions 1.2, 3.14\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(tdata->opt->RecommendedClientVersions->value, OP_EQ, "1.2, 3.14");
+ tt_str_op(tdata->opt->RecommendedServerVersions->value, OP_EQ, "1.2, 3.14");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "RecommendedVersions 1.2, 3.14\n"
+ "RecommendedClientVersions 25\n"
+ "RecommendedServerVersions 4.18\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(tdata->opt->RecommendedClientVersions->value, OP_EQ, "25");
+ tt_str_op(tdata->opt->RecommendedServerVersions->value, OP_EQ, "4.18");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "VersioningAuthoritativeDirectory 1\n"
+ "RecommendedVersions 1.2, 3.14\n"
+ "RecommendedClientVersions 25\n"
+ "RecommendedServerVersions 4.18\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ, "AuthoritativeDir is set, but none of (Bridge/V3)"
+ "AuthoritativeDir is set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "VersioningAuthoritativeDirectory 1\n"
+ "RecommendedServerVersions 4.18\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ, "Versioning authoritative dir servers must set "
+ "Recommended*Versions.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "VersioningAuthoritativeDirectory 1\n"
+ "RecommendedClientVersions 4.18\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ, "Versioning authoritative dir servers must set "
+ "Recommended*Versions.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "UseEntryGuards 1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("Authoritative directory servers "
+ "can't set UseEntryGuards. Disabling.\n");
+ tt_int_op(tdata->opt->UseEntryGuards, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "V3AuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("Authoritative directories always try"
+ " to download extra-info documents. Setting DownloadExtraInfo.\n");
+ tt_int_op(tdata->opt->DownloadExtraInfo, OP_EQ, 1);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "DownloadExtraInfo 1\n"
+ "V3AuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_no_log_msg("Authoritative directories always try"
+ " to download extra-info documents. Setting DownloadExtraInfo.\n");
+ tt_int_op(tdata->opt->DownloadExtraInfo, OP_EQ, 1);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ, "AuthoritativeDir is set, but none of (Bridge/V3)"
+ "AuthoritativeDir is set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "V3BandwidthsFile non-existant-file\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no DirPort set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "V3BandwidthsFile non-existant-file\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(NULL, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no DirPort set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "GuardfractionFile non-existant-file\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no DirPort set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "GuardfractionFile non-existant-file\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ options_validate(NULL, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no DirPort set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no DirPort set.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AuthoritativeDirectory 1\n"
+ "Address 100.200.10.1\n"
+ "DirPort 999\n"
+ "BridgeAuthoritativeDir 1\n"
+ "ContactInfo hello@hello.com\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Running as authoritative directory, but no ORPort set.");
+ tor_free(msg);
+
+ // TODO: This case can't be reached, since clientonly is used to
+ // check when parsing port lines as well.
+ /* free_options_test_data(tdata); */
+ /* tdata = get_options_test_data("AuthoritativeDirectory 1\n" */
+ /* "Address 100.200.10.1\n" */
+ /* "DirPort 999\n" */
+ /* "ORPort 888\n" */
+ /* "ClientOnly 1\n" */
+ /* "BridgeAuthoritativeDir 1\n" */
+ /* "ContactInfo hello@hello.com\n" */
+ /* "SchedulerHighWaterMark__ 42\n" */
+ /* "SchedulerLowWaterMark__ 10\n"); */
+ /* mock_clean_saved_logs(); */
+ /* ret = options_validate(tdata->old_opt, tdata->opt, */
+ /* tdata->def_opt, 0, &msg); */
+ /* tt_int_op(ret, OP_EQ, -1); */
+ /* tt_str_op(msg, OP_EQ, "Running as authoritative directory, " */
+ /* "but ClientOnly also set."); */
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ // sandbox_free_getaddrinfo_cache();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__relay_with_hidden_services(void *ignored)
+{
+ (void)ignored;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+ options_test_data_t *tdata = get_options_test_data(
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "HiddenServiceDir "
+ "/Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ );
+
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg(
+ "Tor is currently configured as a relay and a hidden service. "
+ "That's not very secure: you should probably run your hidden servi"
+ "ce in a separate Tor process, at least -- see "
+ "https://trac.torproject.org/8742\n");
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+// TODO: it doesn't seem possible to hit the case of having no port lines at
+// all, since there will be a default created for SocksPort
+/* static void */
+/* test_options_validate__ports(void *ignored) */
+/* { */
+/* (void)ignored; */
+/* int ret; */
+/* char *msg; */
+/* int previous_log = setup_capture_of_logs(LOG_WARN); */
+/* options_test_data_t *tdata = get_options_test_data(""); */
+/* ret = options_validate(tdata->old_opt, tdata->opt, */
+/* tdata->def_opt, 0, &msg); */
+/* expect_log_msg("SocksPort, TransPort, NATDPort, DNSPort, and ORPort " */
+/* "are all undefined, and there aren't any hidden services " */
+/* "configured. " */
+/* " Tor will still run, but probably won't do anything.\n"); */
+/* done: */
+/* teardown_capture_of_logs(previous_log); */
+/* free_options_test_data(tdata); */
+/* tor_free(msg); */
+/* } */
+
+static void
+test_options_validate__transproxy(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata;
+
+#ifdef USE_TRANSPARENT
+ // Test default trans proxy
+ tdata = get_options_test_data("TransProxyType default\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->TransProxyType_parsed, OP_EQ, TPT_DEFAULT);
+ tor_free(msg);
+
+ // Test pf-divert trans proxy
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TransProxyType pf-divert\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+
+#if !defined(__OpenBSD__) && !defined( DARWIN )
+ tt_str_op(msg, OP_EQ,
+ "pf-divert is a OpenBSD-specific and OS X/Darwin-specific feature.");
+#else
+ tt_int_op(tdata->opt->TransProxyType_parsed, OP_EQ, TPT_PF_DIVERT);
+ tt_str_op(msg, OP_EQ, "Cannot use TransProxyType without "
+ "any valid TransPort or TransListenAddress.");
+#endif
+ tor_free(msg);
+
+ // Test tproxy trans proxy
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TransProxyType tproxy\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+
+#if !defined(__linux__)
+ tt_str_op(msg, OP_EQ, "TPROXY is a Linux-specific feature.");
+#else
+ tt_int_op(tdata->opt->TransProxyType_parsed, OP_EQ, TPT_TPROXY);
+ tt_str_op(msg, OP_EQ, "Cannot use TransProxyType without any valid "
+ "TransPort or TransListenAddress.");
+#endif
+ tor_free(msg);
+
+ // Test ipfw trans proxy
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TransProxyType ipfw\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+
+#ifndef KERNEL_MAY_SUPPORT_IPFW
+ tt_str_op(msg, OP_EQ, "ipfw is a FreeBSD-specificand OS X/Darwin-specific "
+ "feature.");
+#else
+ tt_int_op(tdata->opt->TransProxyType_parsed, OP_EQ, TPT_IPFW);
+ tt_str_op(msg, OP_EQ, "Cannot use TransProxyType without any valid "
+ "TransPort or TransListenAddress.");
+#endif
+ tor_free(msg);
+
+ // Test unknown trans proxy
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TransProxyType non-existant\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Unrecognized value for TransProxyType");
+ tor_free(msg);
+
+ // Test trans proxy success
+ free_options_test_data(tdata);
+ tdata = NULL;
+
+#if defined(linux)
+ tdata = get_options_test_data("TransProxyType tproxy\n"
+ "TransPort 127.0.0.1:123\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+#endif
+#if defined(__FreeBSD_kernel__) || defined( DARWIN )
+ tdata = get_options_test_data("TransProxyType ipfw\n"
+ "TransPort 127.0.0.1:123\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+#endif
+#if defined(__OpenBSD__)
+ tdata = get_options_test_data("TransProxyType pf-divert\n"
+ "TransPort 127.0.0.1:123\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+#endif
+
+ // Assert that a test has run for some TransProxyType
+ tt_assert(tdata);
+
+#else
+ tdata = get_options_test_data("TransPort 127.0.0.1:555\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TransPort and TransListenAddress are disabled in "
+ "this build.");
+ tor_free(msg);
+#endif
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+NS_DECL(country_t, geoip_get_country, (const char *country));
+
+static country_t
+NS(geoip_get_country)(const char *countrycode)
+{
+ (void)countrycode;
+ CALLED(geoip_get_country)++;
+
+ return 1;
+}
+
+static void
+test_options_validate__exclude_nodes(void *ignored)
+{
+ (void)ignored;
+
+ NS_MOCK(geoip_get_country);
+
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ options_test_data_t *tdata = get_options_test_data(
+ "ExcludeExitNodes {us}\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(smartlist_len(tdata->opt->ExcludeExitNodesUnion_->list), OP_EQ, 1);
+ tt_str_op((char *)
+ (smartlist_get(tdata->opt->ExcludeExitNodesUnion_->list, 0)),
+ OP_EQ, "{us}");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ExcludeNodes {cn}\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(smartlist_len(tdata->opt->ExcludeExitNodesUnion_->list), OP_EQ, 1);
+ tt_str_op((char *)
+ (smartlist_get(tdata->opt->ExcludeExitNodesUnion_->list, 0)),
+ OP_EQ, "{cn}");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ExcludeNodes {cn}\n"
+ "ExcludeExitNodes {us} {cn}\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(smartlist_len(tdata->opt->ExcludeExitNodesUnion_->list), OP_EQ, 2);
+ tt_str_op((char *)
+ (smartlist_get(tdata->opt->ExcludeExitNodesUnion_->list, 0)),
+ OP_EQ, "{us} {cn}");
+ tt_str_op((char *)
+ (smartlist_get(tdata->opt->ExcludeExitNodesUnion_->list, 1)),
+ OP_EQ, "{cn}");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ExcludeNodes {cn}\n"
+ "StrictNodes 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg(
+ "You have asked to exclude certain relays from all positions "
+ "in your circuits. Expect hidden services and other Tor "
+ "features to be broken in unpredictable ways.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ExcludeNodes {cn}\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_no_log_msg(
+ "You have asked to exclude certain relays from all positions "
+ "in your circuits. Expect hidden services and other Tor "
+ "features to be broken in unpredictable ways.\n");
+ tor_free(msg);
+
+ done:
+ NS_UNMOCK(geoip_get_country);
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__scheduler(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+ options_test_data_t *tdata = get_options_test_data(
+ "SchedulerLowWaterMark__ 0\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Bad SchedulerLowWaterMark__ option\n");
+ tor_free(msg);
+
+ // TODO: this test cannot run on platforms where UINT32_MAX == UINT64_MAX.
+ // I suspect it's unlikely this branch can actually happen
+ /* free_options_test_data(tdata); */
+ /* tdata = get_options_test_data( */
+ /* "SchedulerLowWaterMark 10000000000000000000\n"); */
+ /* tdata->opt->SchedulerLowWaterMark__ = (uint64_t)UINT32_MAX; */
+ /* tdata->opt->SchedulerLowWaterMark__++; */
+ /* mock_clean_saved_logs(); */
+ /* ret = options_validate(tdata->old_opt, tdata->opt, */
+ /* tdata->def_opt, 0, &msg); */
+ /* tt_int_op(ret, OP_EQ, -1); */
+ /* expect_log_msg("Bad SchedulerLowWaterMark__ option\n"); */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SchedulerLowWaterMark__ 42\n"
+ "SchedulerHighWaterMark__ 42\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Bad SchedulerHighWaterMark option\n");
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__node_families(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "NodeFamily flux, flax\n"
+ "NodeFamily somewhere\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(tdata->opt->NodeFamilySets);
+ tt_int_op(smartlist_len(tdata->opt->NodeFamilySets), OP_EQ, 2);
+ tt_str_op((char *)(smartlist_get(
+ ((routerset_t *)smartlist_get(tdata->opt->NodeFamilySets, 0))->list, 0)),
+ OP_EQ, "flux");
+ tt_str_op((char *)(smartlist_get(
+ ((routerset_t *)smartlist_get(tdata->opt->NodeFamilySets, 0))->list, 1)),
+ OP_EQ, "flax");
+ tt_str_op((char *)(smartlist_get(
+ ((routerset_t *)smartlist_get(tdata->opt->NodeFamilySets, 1))->list, 0)),
+ OP_EQ, "somewhere");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!tdata->opt->NodeFamilySets);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("NodeFamily !flux\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(tdata->opt->NodeFamilySets);
+ tt_int_op(smartlist_len(tdata->opt->NodeFamilySets), OP_EQ, 0);
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__tlsec(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+ options_test_data_t *tdata = get_options_test_data(
+ "TLSECGroup ed25519\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Unrecognized TLSECGroup: Falling back to the default.\n");
+ tt_assert(!tdata->opt->TLSECGroup);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TLSECGroup P224\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_no_log_msg(
+ "Unrecognized TLSECGroup: Falling back to the default.\n");
+ tt_assert(tdata->opt->TLSECGroup);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("TLSECGroup P256\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_no_log_msg(
+ "Unrecognized TLSECGroup: Falling back to the default.\n");
+ tt_assert(tdata->opt->TLSECGroup);
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__token_bucket(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data("");
+
+ tdata->opt->TokenBucketRefillInterval = 0;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
+ tor_free(msg);
+
+ tdata->opt->TokenBucketRefillInterval = 1001;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__recommended_packages(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ options_test_data_t *tdata = get_options_test_data(
+ "RecommendedPackages foo 1.2 http://foo.com sha1=123123123123\n"
+ "RecommendedPackages invalid-package-line\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_no_log_msg("Invalid RecommendedPackage line "
+ "invalid-package-line will be ignored\n");
+
+ done:
+ escaped(NULL); // This will free the leaking memory from the previous escaped
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__fetch_dir(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "FetchDirInfoExtraEarly 1\n"
+ "FetchDirInfoEarly 0\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "FetchDirInfoExtraEarly requires that you"
+ " also set FetchDirInfoEarly");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("FetchDirInfoExtraEarly 1\n"
+ "FetchDirInfoEarly 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_NE, "FetchDirInfoExtraEarly requires that you"
+ " also set FetchDirInfoEarly");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__conn_limit(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "ConnLimit 0\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "ConnLimit must be greater than 0, but was set to 0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "MaxClientCircuitsPending must be between 1 and 1024, "
+ "but was set to 0");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__paths_needed(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ options_test_data_t *tdata = get_options_test_data(
+ "PathsNeededToBuildCircuits 0.1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(tdata->opt->PathsNeededToBuildCircuits > 0.24 &&
+ tdata->opt->PathsNeededToBuildCircuits < 0.26);
+ expect_log_msg("PathsNeededToBuildCircuits is too low. "
+ "Increasing to 0.25\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data("PathsNeededToBuildCircuits 0.99\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(tdata->opt->PathsNeededToBuildCircuits > 0.94 &&
+ tdata->opt->PathsNeededToBuildCircuits < 0.96);
+ expect_log_msg("PathsNeededToBuildCircuits is "
+ "too high. Decreasing to 0.95\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data("PathsNeededToBuildCircuits 0.91\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(tdata->opt->PathsNeededToBuildCircuits > 0.90 &&
+ tdata->opt->PathsNeededToBuildCircuits < 0.92);
+ expect_no_log_entry();
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__max_client_circuits(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "MaxClientCircuitsPending 0\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "MaxClientCircuitsPending must be between 1 and 1024,"
+ " but was set to 0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("MaxClientCircuitsPending 1025\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "MaxClientCircuitsPending must be between 1 and 1024,"
+ " but was set to 1025");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "KeepalivePeriod option must be positive.");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__ports(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "FirewallPorts 65537\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Port '65537' out of range in FirewallPorts");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("FirewallPorts 1\n"
+ "LongLivedPorts 124444\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Port '124444' out of range in LongLivedPorts");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("FirewallPorts 1\n"
+ "LongLivedPorts 2\n"
+ "RejectPlaintextPorts 112233\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Port '112233' out of range in RejectPlaintextPorts");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("FirewallPorts 1\n"
+ "LongLivedPorts 2\n"
+ "RejectPlaintextPorts 3\n"
+ "WarnPlaintextPorts 65536\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Port '65536' out of range in WarnPlaintextPorts");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("FirewallPorts 1\n"
+ "LongLivedPorts 2\n"
+ "RejectPlaintextPorts 3\n"
+ "WarnPlaintextPorts 4\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "KeepalivePeriod option must be positive.");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__reachable_addresses(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_NOTICE);
+ options_test_data_t *tdata = get_options_test_data(
+ "FascistFirewall 1\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Converting FascistFirewall config "
+ "option to new format: \"ReachableDirAddresses *:80\"\n");
+ tt_str_op(tdata->opt->ReachableDirAddresses->value, OP_EQ, "*:80");
+ expect_log_msg("Converting FascistFirewall config "
+ "option to new format: \"ReachableORAddresses *:443\"\n");
+ tt_str_op(tdata->opt->ReachableORAddresses->value, OP_EQ, "*:443");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data("FascistFirewall 1\n"
+ "ReachableDirAddresses *:81\n"
+ "ReachableORAddresses *:444\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+ tdata->opt->FirewallPorts = smartlist_new();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_entry();
+ tt_str_op(tdata->opt->ReachableDirAddresses->value, OP_EQ, "*:81");
+ tt_str_op(tdata->opt->ReachableORAddresses->value, OP_EQ, "*:444");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data("FascistFirewall 1\n"
+ "FirewallPort 123\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Converting FascistFirewall and "
+ "FirewallPorts config options to new format: "
+ "\"ReachableAddresses *:123\"\n");
+ tt_str_op(tdata->opt->ReachableAddresses->value, OP_EQ, "*:123");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data("FascistFirewall 1\n"
+ "ReachableAddresses *:82\n"
+ "ReachableAddresses *:83\n"
+ "ReachableAddresses reject *:*\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_entry();
+ tt_str_op(tdata->opt->ReachableAddresses->value, OP_EQ, "*:82");
+ tor_free(msg);
+
+#define SERVERS_REACHABLE_MSG "Servers must be able to freely connect to" \
+ " the rest of the Internet, so they must not set Reachable*Addresses or" \
+ " FascistFirewall or FirewallPorts or ClientUseIPv4 0."
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ReachableAddresses *:82\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, SERVERS_REACHABLE_MSG);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ReachableORAddresses *:82\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, SERVERS_REACHABLE_MSG);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ReachableDirAddresses *:82\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, SERVERS_REACHABLE_MSG);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("ClientUseIPv4 0\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, SERVERS_REACHABLE_MSG);
+ tor_free(msg);
+
+ /* Test IPv4-only clients setting IPv6 preferences */
+
+#define WARN_PLEASE_USE_IPV6_OR_LOG_MSG \
+ "ClientPreferIPv6ORPort 1 is ignored unless tor is using IPv6. " \
+ "Please set ClientUseIPv6 1, ClientUseIPv4 0, or configure bridges.\n"
+
+#define WARN_PLEASE_USE_IPV6_DIR_LOG_MSG \
+ "ClientPreferIPv6DirPort 1 is ignored unless tor is using IPv6. " \
+ "Please set ClientUseIPv6 1, ClientUseIPv4 0, or configure bridges.\n"
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientUseIPv4 1\n"
+ "ClientUseIPv6 0\n"
+ "UseBridges 0\n"
+ "ClientPreferIPv6ORPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(WARN_PLEASE_USE_IPV6_OR_LOG_MSG);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientUseIPv4 1\n"
+ "ClientUseIPv6 0\n"
+ "UseBridges 0\n"
+ "ClientPreferIPv6DirPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(WARN_PLEASE_USE_IPV6_DIR_LOG_MSG);
+ tor_free(msg);
+
+ /* Now test an IPv4/IPv6 client setting IPv6 preferences */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientUseIPv4 1\n"
+ "ClientUseIPv6 1\n"
+ "ClientPreferIPv6ORPort 1\n"
+ "ClientPreferIPv6DirPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_ptr_op(msg, OP_EQ, NULL);
+
+ /* Now test an IPv6 client setting IPv6 preferences */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientUseIPv6 1\n"
+ "ClientPreferIPv6ORPort 1\n"
+ "ClientPreferIPv6DirPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_ptr_op(msg, OP_EQ, NULL);
+
+ /* And an implicit (IPv4 disabled) IPv6 client setting IPv6 preferences */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientUseIPv4 0\n"
+ "ClientPreferIPv6ORPort 1\n"
+ "ClientPreferIPv6DirPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_ptr_op(msg, OP_EQ, NULL);
+
+ /* And an implicit (bridge) client setting IPv6 preferences */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "UseBridges 1\n"
+ "Bridge 127.0.0.1:12345\n"
+ "ClientPreferIPv6ORPort 1\n"
+ "ClientPreferIPv6DirPort 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_ptr_op(msg, OP_EQ, NULL);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__use_bridges(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "UseBridges 1\n"
+ "ClientUseIPv4 1\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Servers must be able to freely connect to the rest of"
+ " the Internet, so they must not set UseBridges.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("UseBridges 1\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_NE, "Servers must be able to freely connect to the rest of"
+ " the Internet, so they must not set UseBridges.");
+ tor_free(msg);
+
+ NS_MOCK(geoip_get_country);
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("UseBridges 1\n"
+ "EntryNodes {cn}\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "You cannot set both UseBridges and EntryNodes.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "UseBridges 1\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "If you set UseBridges, you must specify at least one bridge.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "UseBridges 1\n"
+ "Bridge 10.0.0.1\n"
+ "Bridge !!!\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Bridge line did not parse. See logs for details.");
+ tor_free(msg);
+
+ done:
+ NS_UNMOCK(geoip_get_country);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__entry_nodes(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ NS_MOCK(geoip_get_country);
+ options_test_data_t *tdata = get_options_test_data(
+ "EntryNodes {cn}\n"
+ "UseEntryGuards 0\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "If EntryNodes is set, UseEntryGuards must be enabled.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("EntryNodes {cn}\n"
+ "UseEntryGuards 1\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "KeepalivePeriod option must be positive.");
+ tor_free(msg);
+
+ done:
+ NS_UNMOCK(geoip_get_country);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__invalid_nodes(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "AllowInvalidNodes something_stupid\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Unrecognized value 'something_stupid' in AllowInvalidNodes");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AllowInvalidNodes entry, middle, exit\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->AllowInvalid_, OP_EQ, ALLOW_INVALID_ENTRY |
+ ALLOW_INVALID_EXIT | ALLOW_INVALID_MIDDLE);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("AllowInvalidNodes introduction, rendezvous\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->AllowInvalid_, OP_EQ, ALLOW_INVALID_INTRODUCTION |
+ ALLOW_INVALID_RENDEZVOUS);
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__safe_logging(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = get_options_test_data(
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->SafeLogging_, OP_EQ, SAFELOG_SCRUB_NONE);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SafeLogging 0\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->SafeLogging_, OP_EQ, SAFELOG_SCRUB_NONE);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SafeLogging Relay\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->SafeLogging_, OP_EQ, SAFELOG_SCRUB_RELAY);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SafeLogging 1\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_int_op(tdata->opt->SafeLogging_, OP_EQ, SAFELOG_SCRUB_ALL);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("SafeLogging stuffy\n"
+ "MaxClientCircuitsPending 1\n"
+ "ConnLimit 1\n"
+ "SchedulerHighWaterMark__ 42\n"
+ "SchedulerLowWaterMark__ 10\n");
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Unrecognized value '\"stuffy\"' in SafeLogging");
+ tor_free(msg);
+
+ done:
+ escaped(NULL); // This will free the leaking memory from the previous escaped
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__publish_server_descriptor(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ options_test_data_t *tdata = get_options_test_data(
+ "PublishServerDescriptor bridge\n" TEST_OPTIONS_DEFAULT_VALUES
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("PublishServerDescriptor humma\n"
+ TEST_OPTIONS_DEFAULT_VALUES);
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Unrecognized value in PublishServerDescriptor");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("PublishServerDescriptor bridge, v3\n"
+ TEST_OPTIONS_DEFAULT_VALUES);
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Bridges are not supposed to publish router "
+ "descriptors to the directory authorities. Please correct your "
+ "PublishServerDescriptor line.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("BridgeRelay 1\n"
+ "PublishServerDescriptor v3\n"
+ TEST_OPTIONS_DEFAULT_VALUES);
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Bridges are not supposed to publish router "
+ "descriptors to the directory authorities. Please correct your "
+ "PublishServerDescriptor line.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("BridgeRelay 1\n" TEST_OPTIONS_DEFAULT_VALUES);
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_NE, "Bridges are not supposed to publish router "
+ "descriptors to the directory authorities. Please correct your "
+ "PublishServerDescriptor line.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data("BridgeRelay 1\n"
+ "DirPort 999\n" TEST_OPTIONS_DEFAULT_VALUES);
+
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ expect_log_msg("Can't set a DirPort on a bridge "
+ "relay; disabling DirPort\n");
+ tt_assert(!tdata->opt->DirPort_lines);
+ tt_assert(!tdata->opt->DirPort_set);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__testing(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+#define ENSURE_DEFAULT(varname, varval) \
+ STMT_BEGIN \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES \
+ #varname " " #varval "\n"); \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ tt_str_op(msg, OP_EQ, \
+ #varname " may only be changed in testing Tor networks!"); \
+ tt_int_op(ret, OP_EQ, -1); \
+ tor_free(msg); \
+ \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES \
+ #varname " " #varval "\n" \
+ VALID_DIR_AUTH \
+ "TestingTorNetwork 1\n"); \
+ \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ if (msg) { \
+ tt_str_op(msg, OP_NE, \
+ #varname " may only be changed in testing Tor networks!"); \
+ tor_free(msg); \
+ } \
+ \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES \
+ #varname " " #varval "\n" \
+ "___UsingTestNetworkDefaults 1\n"); \
+ \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ if (msg) { \
+ tt_str_op(msg, OP_NE, \
+ #varname " may only be changed in testing Tor networks!"); \
+ tor_free(msg); \
+ } \
+ STMT_END
+
+ ENSURE_DEFAULT(TestingV3AuthInitialVotingInterval, 3600);
+ ENSURE_DEFAULT(TestingV3AuthInitialVoteDelay, 3000);
+ ENSURE_DEFAULT(TestingV3AuthInitialDistDelay, 3000);
+ ENSURE_DEFAULT(TestingV3AuthVotingStartOffset, 3000);
+ ENSURE_DEFAULT(TestingAuthDirTimeToLearnReachability, 3000);
+ ENSURE_DEFAULT(TestingEstimatedDescriptorPropagationTime, 3000);
+ ENSURE_DEFAULT(TestingServerDownloadSchedule, 3000);
+ ENSURE_DEFAULT(TestingClientDownloadSchedule, 3000);
+ ENSURE_DEFAULT(TestingServerConsensusDownloadSchedule, 3000);
+ ENSURE_DEFAULT(TestingClientConsensusDownloadSchedule, 3000);
+ ENSURE_DEFAULT(TestingBridgeDownloadSchedule, 3000);
+ ENSURE_DEFAULT(TestingClientMaxIntervalWithoutRequest, 3000);
+ ENSURE_DEFAULT(TestingDirConnectionMaxStall, 3000);
+ ENSURE_DEFAULT(TestingConsensusMaxDownloadTries, 3000);
+ ENSURE_DEFAULT(TestingDescriptorMaxDownloadTries, 3000);
+ ENSURE_DEFAULT(TestingMicrodescMaxDownloadTries, 3000);
+ ENSURE_DEFAULT(TestingCertMaxDownloadTries, 3000);
+ ENSURE_DEFAULT(TestingAuthKeyLifetime, 3000);
+ ENSURE_DEFAULT(TestingLinkCertLifetime, 3000);
+ ENSURE_DEFAULT(TestingSigningKeySlop, 3000);
+ ENSURE_DEFAULT(TestingAuthKeySlop, 3000);
+ ENSURE_DEFAULT(TestingLinkKeySlop, 3000);
+
+ done:
+ escaped(NULL); // This will free the leaking memory from the previous escaped
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__hidserv(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ options_test_data_t *tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES);
+ tdata->opt->MinUptimeHidServDirectoryV2 = -1;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("MinUptimeHidServDirectoryV2 "
+ "option must be at least 0 seconds. Changing to 0.\n");
+ tt_int_op(tdata->opt->MinUptimeHidServDirectoryV2, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RendPostPeriod 1\n" );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("RendPostPeriod option is too short;"
+ " raising to 600 seconds.\n");
+ tt_int_op(tdata->opt->RendPostPeriod, OP_EQ, 600);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RendPostPeriod 302401\n" );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("RendPostPeriod is too large; "
+ "clipping to 302400s.\n");
+ tt_int_op(tdata->opt->RendPostPeriod, OP_EQ, 302400);
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__predicted_ports(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ options_test_data_t *tdata = get_options_test_data(
+ "PredictedPortsRelevanceTime 100000000\n"
+ TEST_OPTIONS_DEFAULT_VALUES);
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("PredictedPortsRelevanceTime is too "
+ "large; clipping to 3600s.\n");
+ tt_int_op(tdata->opt->PredictedPortsRelevanceTime, OP_EQ, 3600);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__path_bias(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+
+ options_test_data_t *tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "PathBiasNoticeRate 1.1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "PathBiasNoticeRate is too high. It must be between 0 and 1.0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PathBiasWarnRate 1.1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "PathBiasWarnRate is too high. It must be between 0 and 1.0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PathBiasExtremeRate 1.1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "PathBiasExtremeRate is too high. It must be between 0 and 1.0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PathBiasNoticeUseRate 1.1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "PathBiasNoticeUseRate is too high. It must be between 0 and 1.0");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PathBiasExtremeUseRate 1.1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "PathBiasExtremeUseRate is too high. It must be between 0 and 1.0");
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__bandwidth(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+#define ENSURE_BANDWIDTH_PARAM(p) \
+ STMT_BEGIN \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES #p " 3Gb\n"); \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ tt_int_op(ret, OP_EQ, -1); \
+ tt_mem_op(msg, OP_EQ, #p " (3221225471) must be at most 2147483647", 40); \
+ tor_free(msg); \
+ STMT_END
+
+ ENSURE_BANDWIDTH_PARAM(BandwidthRate);
+ ENSURE_BANDWIDTH_PARAM(BandwidthBurst);
+ ENSURE_BANDWIDTH_PARAM(MaxAdvertisedBandwidth);
+ ENSURE_BANDWIDTH_PARAM(RelayBandwidthRate);
+ ENSURE_BANDWIDTH_PARAM(RelayBandwidthBurst);
+ ENSURE_BANDWIDTH_PARAM(PerConnBWRate);
+ ENSURE_BANDWIDTH_PARAM(PerConnBWBurst);
+ ENSURE_BANDWIDTH_PARAM(AuthDirFastGuarantee);
+ ENSURE_BANDWIDTH_PARAM(AuthDirGuardBWGuarantee);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RelayBandwidthRate 1000\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_u64_op(tdata->opt->RelayBandwidthBurst, OP_EQ, 1000);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RelayBandwidthBurst 1001\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_u64_op(tdata->opt->RelayBandwidthRate, OP_EQ, 1001);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RelayBandwidthRate 1001\n"
+ "RelayBandwidthBurst 1000\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "RelayBandwidthBurst must be at least equal to "
+ "RelayBandwidthRate.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "BandwidthRate 1001\n"
+ "BandwidthBurst 1000\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "BandwidthBurst must be at least equal to BandwidthRate.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RelayBandwidthRate 1001\n"
+ "BandwidthRate 1000\n"
+ "BandwidthBurst 1000\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_u64_op(tdata->opt->BandwidthRate, OP_EQ, 1001);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "RelayBandwidthRate 1001\n"
+ "BandwidthRate 1000\n"
+ "RelayBandwidthBurst 1001\n"
+ "BandwidthBurst 1000\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_u64_op(tdata->opt->BandwidthBurst, OP_EQ, 1001);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "BandwidthRate is set to 1 bytes/second. For servers,"
+ " it must be at least 76800.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76800\n"
+ "MaxAdvertisedBandwidth 30000\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "MaxAdvertisedBandwidth is set to 30000 bytes/second."
+ " For servers, it must be at least 38400.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76800\n"
+ "RelayBandwidthRate 1\n"
+ "MaxAdvertisedBandwidth 38400\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "RelayBandwidthRate is set to 1 bytes/second. For "
+ "servers, it must be at least 76800.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76800\n"
+ "BandwidthBurst 76800\n"
+ "RelayBandwidthRate 76800\n"
+ "MaxAdvertisedBandwidth 38400\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__circuits(void *ignored)
+{
+ (void)ignored;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "MaxCircuitDirtiness 2592001\n");
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("MaxCircuitDirtiness option is too "
+ "high; setting to 30 days.\n");
+ tt_int_op(tdata->opt->MaxCircuitDirtiness, OP_EQ, 2592000);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CircuitStreamTimeout 1\n");
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("CircuitStreamTimeout option is too"
+ " short; raising to 10 seconds.\n");
+ tt_int_op(tdata->opt->CircuitStreamTimeout, OP_EQ, 10);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CircuitStreamTimeout 111\n");
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_no_log_msg("CircuitStreamTimeout option is too"
+ " short; raising to 10 seconds.\n");
+ tt_int_op(tdata->opt->CircuitStreamTimeout, OP_EQ, 111);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HeartbeatPeriod 1\n");
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("HeartbeatPeriod option is too short;"
+ " raising to 1800 seconds.\n");
+ tt_int_op(tdata->opt->HeartbeatPeriod, OP_EQ, 1800);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HeartbeatPeriod 1982\n");
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_no_log_msg("HeartbeatPeriod option is too short;"
+ " raising to 1800 seconds.\n");
+ tt_int_op(tdata->opt->HeartbeatPeriod, OP_EQ, 1982);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CircuitBuildTimeout 1\n"
+ );
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_log_msg("CircuitBuildTimeout is shorter (1"
+ " seconds) than the recommended minimum (10 seconds), and "
+ "LearnCircuitBuildTimeout is disabled. If tor isn't working, "
+ "raise this value or enable LearnCircuitBuildTimeout.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ mock_clean_saved_logs();
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CircuitBuildTimeout 11\n"
+ );
+ options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ expect_no_log_msg("CircuitBuildTimeout is shorter (1 "
+ "seconds) than the recommended minimum (10 seconds), and "
+ "LearnCircuitBuildTimeout is disabled. If tor isn't working, "
+ "raise this value or enable LearnCircuitBuildTimeout.\n");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__port_forwarding(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PortForwarding 1\nSandbox 1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "PortForwarding is not compatible with Sandbox;"
+ " at most one can be set");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "PortForwarding 1\nSandbox 0\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ done:
+ free_options_test_data(tdata);
+ policies_free_all();
+ tor_free(msg);
+}
+
+static void
+test_options_validate__tor2web(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Tor2webRendezvousPoints 1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Tor2webRendezvousPoints cannot be set without Tor2webMode.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Tor2webRendezvousPoints 1\nTor2webMode 1\n");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__rend(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "UseEntryGuards 0\n"
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("UseEntryGuards is disabled, but you"
+ " have configured one or more hidden services on this Tor "
+ "instance. Your hidden services will be very easy to locate using"
+ " a well-known attack -- see http://freehaven.net/anonbib/#hs-"
+ "attack06 for details.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "UseEntryGuards 1\n"
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("UseEntryGuards is disabled, but you"
+ " have configured one or more hidden services on this Tor "
+ "instance. Your hidden services will be very easy to locate using"
+ " a well-known attack -- see http://freehaven.net/anonbib/#hs-"
+ "attack06 for details.\n");
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Failed to configure rendezvous options. See logs for details.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HidServAuth failed\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Failed to configure client authorization for hidden "
+ "services. See logs for details.");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__accounting(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccountingRule something_bad\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "AccountingRule must be 'sum', 'max', 'in', or 'out'");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccountingRule sum\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->AccountingRule, OP_EQ, ACCT_SUM);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccountingRule max\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->AccountingRule, OP_EQ, ACCT_MAX);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccountingStart fail\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Failed to parse accounting options. See logs for details.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccountingMax 10\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76800\n"
+ "BandwidthBurst 76800\n"
+ "MaxAdvertisedBandwidth 38400\n"
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ "AccountingMax 10\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("Using accounting with a hidden "
+ "service and an ORPort is risky: your hidden service(s) and "
+ "your public address will all turn off at the same time, "
+ "which may alert observers that they are being run by the "
+ "same party.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ "AccountingMax 10\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("Using accounting with a hidden "
+ "service and an ORPort is risky: your hidden service(s) and "
+ "your public address will all turn off at the same time, "
+ "which may alert observers that they are being run by the "
+ "same party.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service/\n"
+ "HiddenServicePort 80 127.0.0.1:8080\n"
+ "HiddenServiceDir /Library/Tor/var/lib/tor/hidden_service2/\n"
+ "HiddenServicePort 81 127.0.0.1:8081\n"
+ "AccountingMax 10\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("Using accounting with multiple "
+ "hidden services is risky: they will all turn off at the same"
+ " time, which may alert observers that they are being run by "
+ "the same party.\n");
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__proxy(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ sandbox_disable_getaddrinfo_cache();
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 127.0.42.1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HTTPProxyPort, OP_EQ, 80);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 127.0.42.1:444\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HTTPProxyPort, OP_EQ, 444);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy not_so_valid!\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "HTTPProxy failed to parse or resolve. Please fix.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxyAuthenticator "
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreeonetwothreeonetwothree"
+
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "HTTPProxyAuthenticator is too long (>= 512 chars).");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxyAuthenticator validauth\n"
+
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpsProxy 127.0.42.1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HTTPSProxyPort, OP_EQ, 443);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpsProxy 127.0.42.1:444\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HTTPSProxyPort, OP_EQ, 444);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpsProxy not_so_valid!\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "HTTPSProxy failed to parse or resolve. Please fix.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpsProxyAuthenticator "
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreonetwothreonetwothreonetwothre"
+ "onetwothreonetwothreonetwothreonetwothreonetw"
+ "othreonetwothreeonetwothreeonetwothree"
+
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "HTTPSProxyAuthenticator is too long (>= 512 chars).");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpsProxyAuthenticator validauth\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks4Proxy 127.0.42.1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->Socks4ProxyPort, OP_EQ, 1080);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks4Proxy 127.0.42.1:444\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->Socks4ProxyPort, OP_EQ, 444);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks4Proxy not_so_valid!\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Socks4Proxy failed to parse or resolve. Please fix.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5Proxy 127.0.42.1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->Socks5ProxyPort, OP_EQ, 1080);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5Proxy 127.0.42.1:444\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->Socks5ProxyPort, OP_EQ, 444);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5Proxy not_so_valid!\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Socks5Proxy failed to parse or resolve. Please fix.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks4Proxy 215.1.1.1\n"
+ "Socks5Proxy 215.1.1.2\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "You have configured more than one proxy type. "
+ "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 215.1.1.1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("HTTPProxy configured, but no SOCKS "
+ "proxy or HTTPS proxy configured. Watch out: this configuration "
+ "will proxy unencrypted directory connections only.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 215.1.1.1\n"
+ "Socks4Proxy 215.1.1.1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("HTTPProxy configured, but no SOCKS "
+ "proxy or HTTPS proxy configured. Watch out: this configuration "
+ "will proxy unencrypted directory connections only.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 215.1.1.1\n"
+ "Socks5Proxy 215.1.1.1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("HTTPProxy configured, but no SOCKS "
+ "proxy or HTTPS proxy configured. Watch out: this configuration "
+ "will proxy unencrypted directory connections only.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HttpProxy 215.1.1.1\n"
+ "HttpsProxy 215.1.1.1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "HTTPProxy configured, but no SOCKS proxy or HTTPS proxy "
+ "configured. Watch out: this configuration will proxy "
+ "unencrypted directory connections only.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ );
+ tdata->opt->Socks5ProxyUsername = tor_strdup("");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Socks5ProxyUsername must be between 1 and 255 characters.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ );
+ tdata->opt->Socks5ProxyUsername =
+ tor_strdup("ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789AB"
+ "CDEABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCD"
+ "EABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEA"
+ "BCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEABC"
+ "DE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Socks5ProxyUsername must be between 1 and 255 characters.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5ProxyUsername hello_world\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Socks5ProxyPassword must be included with "
+ "Socks5ProxyUsername.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5ProxyUsername hello_world\n"
+ );
+ tdata->opt->Socks5ProxyPassword = tor_strdup("");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Socks5ProxyPassword must be between 1 and 255 characters.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5ProxyUsername hello_world\n"
+ );
+ tdata->opt->Socks5ProxyPassword =
+ tor_strdup("ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789AB"
+ "CDEABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCD"
+ "EABCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEA"
+ "BCDE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789ABCDEABC"
+ "DE0123456789ABCDEABCDE0123456789ABCDEABCDE0123456789");
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Socks5ProxyPassword must be between 1 and 255 characters.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5ProxyUsername hello_world\n"
+ "Socks5ProxyPassword world_hello\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "Socks5ProxyPassword hello_world\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Socks5ProxyPassword must be included with "
+ "Socks5ProxyUsername.");
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ policies_free_all();
+ // sandbox_free_getaddrinfo_cache();
+ tor_free(msg);
+}
+
+static void
+test_options_validate__control(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HashedControlPassword something_incorrect\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Bad HashedControlPassword: wrong length or bad encoding");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "HashedControlPassword 16:872860B76453A77D60CA"
+ "2BB8C1A7042072093276A3D701AD684053EC4C\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "__HashedControlSessionPassword something_incorrect\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Bad HashedControlSessionPassword: wrong length or "
+ "bad encoding");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "__HashedControlSessionPassword 16:872860B7645"
+ "3A77D60CA2BB8C1A7042072093276A3D701AD684053EC"
+ "4C\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(
+ TEST_OPTIONS_DEFAULT_VALUES
+ "__OwningControllerProcess something_incorrect\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Bad OwningControllerProcess: invalid PID");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "__OwningControllerProcess 123\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlPort 127.0.0.1:1234\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "ControlPort is open, but no authentication method has been "
+ "configured. This means that any program on your computer can "
+ "reconfigure your Tor. That's bad! You should upgrade your Tor"
+ " controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlPort 127.0.0.1:1234\n"
+ "HashedControlPassword 16:872860B76453A77D60CA"
+ "2BB8C1A7042072093276A3D701AD684053EC4C\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlPort is open, but no authentication method has been "
+ "configured. This means that any program on your computer can "
+ "reconfigure your Tor. That's bad! You should upgrade your Tor "
+ "controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlPort 127.0.0.1:1234\n"
+ "__HashedControlSessionPassword 16:872860B7645"
+ "3A77D60CA2BB8C1A7042072093276A3D701AD684053EC"
+ "4C\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlPort is open, but no authentication method has been "
+ "configured. This means that any program on your computer can "
+ "reconfigure your Tor. That's bad! You should upgrade your Tor "
+ "controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlPort 127.0.0.1:1234\n"
+ "CookieAuthentication 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlPort is open, but no authentication method has been "
+ "configured. This means that any program on your computer can "
+ "reconfigure your Tor. That's bad! You should upgrade your Tor "
+ "controller as soon as possible.\n");
+ tor_free(msg);
+
+#ifdef HAVE_SYS_UN_H
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlSocket unix:/tmp WorldWritable\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "ControlSocket is world writable, but no authentication method has"
+ " been configured. This means that any program on your computer "
+ "can reconfigure your Tor. That's bad! You should upgrade your "
+ "Tor controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlSocket unix:/tmp WorldWritable\n"
+ "HashedControlPassword 16:872860B76453A77D60CA"
+ "2BB8C1A7042072093276A3D701AD684053EC4C\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlSocket is world writable, but no authentication method has"
+ " been configured. This means that any program on your computer "
+ "can reconfigure your Tor. That's bad! You should upgrade your "
+ "Tor controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlSocket unix:/tmp WorldWritable\n"
+ "__HashedControlSessionPassword 16:872860B7645"
+ "3A77D60CA2BB8C1A7042072093276A3D701AD684053EC"
+ "4C\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlSocket is world writable, but no authentication method has"
+ " been configured. This means that any program on your computer "
+ "can reconfigure your Tor. That's bad! You should upgrade your "
+ "Tor controller as soon as possible.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ControlSocket unix:/tmp WorldWritable\n"
+ "CookieAuthentication 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "ControlSocket is world writable, but no authentication method has"
+ " been configured. This means that any program on your computer "
+ "can reconfigure your Tor. That's bad! You should upgrade your "
+ "Tor controller as soon as possible.\n");
+ tor_free(msg);
+#endif
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CookieAuthFileGroupReadable 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "CookieAuthFileGroupReadable is set, but will have no effect: you "
+ "must specify an explicit CookieAuthFile to have it "
+ "group-readable.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "CookieAuthFileGroupReadable 1\n"
+ "CookieAuthFile /tmp/somewhere\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "CookieAuthFileGroupReadable is set, but will have no effect: you "
+ "must specify an explicit CookieAuthFile to have it "
+ "group-readable.\n");
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__families(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "MyFamily home\n"
+ "BridgeRelay 1\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 51300\n"
+ "BandwidthBurst 51300\n"
+ "MaxAdvertisedBandwidth 25700\n"
+ "DirCache 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "Listing a family for a bridge relay is not supported: it can "
+ "reveal bridge fingerprints to censors. You should also make sure "
+ "you aren't listing this bridge's fingerprint in any other "
+ "MyFamily.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "MyFamily home\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "Listing a family for a bridge relay is not supported: it can "
+ "reveal bridge fingerprints to censors. You should also make sure "
+ "you aren't listing this bridge's fingerprint in any other "
+ "MyFamily.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "MyFamily !\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Invalid nickname '!' in MyFamily line");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "NodeFamily foo\n"
+ "NodeFamily !\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__addr_policies(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ExitPolicy !!!\n"
+ "ExitRelay 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Error in ExitPolicy entry.");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__dir_auth(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_DIR_AUTH
+ VALID_ALT_DIR_AUTH
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Directory authority/fallback line did not parse. See logs for "
+ "details.");
+ expect_log_msg(
+ "You cannot set both DirAuthority and Alternate*Authority.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "TestingTorNetwork may only be configured in combination with a "
+ "non-default set of DirAuthority or both of AlternateDirAuthority "
+ "and AlternateBridgeAuthority configured.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingTorNetwork 1\n"
+ VALID_ALT_DIR_AUTH
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "TestingTorNetwork may only be configured in combination with a "
+ "non-default set of DirAuthority or both of AlternateDirAuthority "
+ "and AlternateBridgeAuthority configured.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingTorNetwork 1\n"
+ VALID_ALT_BRIDGE_AUTH
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingTorNetwork may only be configured in "
+ "combination with a non-default set of DirAuthority or both of "
+ "AlternateDirAuthority and AlternateBridgeAuthority configured.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_ALT_DIR_AUTH
+ VALID_ALT_BRIDGE_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__transport(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_NOTICE);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientTransportPlugin !!\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Invalid client transport line. See logs for details.");
+ expect_log_msg(
+ "Too few arguments on ClientTransportPlugin line.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ClientTransportPlugin foo exec bar\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportPlugin !!\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Invalid server transport line. See logs for details.");
+ expect_log_msg(
+ "Too few arguments on ServerTransportPlugin line.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportPlugin foo exec bar\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "Tor is not configured as a relay but you specified a "
+ "ServerTransportPlugin line (\"foo exec bar\"). The "
+ "ServerTransportPlugin line will be ignored.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportPlugin foo exec bar\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76900\n"
+ "BandwidthBurst 76900\n"
+ "MaxAdvertisedBandwidth 38500\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "Tor is not configured as a relay but you specified a "
+ "ServerTransportPlugin line (\"foo exec bar\"). The "
+ "ServerTransportPlugin line will be ignored.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportListenAddr foo 127.0.0.42:55\n"
+ "ServerTransportListenAddr !\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "ServerTransportListenAddr did not parse. See logs for details.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportListenAddr foo 127.0.0.42:55\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg(
+ "You need at least a single managed-proxy to specify a transport "
+ "listen address. The ServerTransportListenAddr line will be "
+ "ignored.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ServerTransportListenAddr foo 127.0.0.42:55\n"
+ "ServerTransportPlugin foo exec bar\n"
+ "ORListenAddress 127.0.0.1:5555\n"
+ "ORPort 955\n"
+ "BandwidthRate 76900\n"
+ "BandwidthBurst 76900\n"
+ "MaxAdvertisedBandwidth 38500\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "You need at least a single managed-proxy to specify a transport "
+ "listen address. The ServerTransportListenAddr line will be "
+ "ignored.\n");
+
+ done:
+ escaped(NULL); // This will free the leaking memory from the previous escaped
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__constrained_sockets(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ConstrainedSockets 1\n"
+ "ConstrainedSockSize 0\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "ConstrainedSockSize is invalid. Must be a value "
+ "between 2048 and 262144 in 1024 byte increments.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ConstrainedSockets 1\n"
+ "ConstrainedSockSize 263168\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "ConstrainedSockSize is invalid. Must be a value "
+ "between 2048 and 262144 in 1024 byte increments.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ConstrainedSockets 1\n"
+ "ConstrainedSockSize 2047\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "ConstrainedSockSize is invalid. Must be a value "
+ "between 2048 and 262144 in 1024 byte increments.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ConstrainedSockets 1\n"
+ "ConstrainedSockSize 2048\n"
+ "DirPort 999\n"
+ "DirCache 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("You have requested constrained "
+ "socket buffers while also serving directory entries via DirPort."
+ " It is strongly suggested that you disable serving directory"
+ " requests when system TCP buffer resources are scarce.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "ConstrainedSockets 1\n"
+ "ConstrainedSockSize 2048\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg(
+ "You have requested constrained socket buffers while also serving"
+ " directory entries via DirPort. It is strongly suggested that "
+ "you disable serving directory requests when system TCP buffer "
+ "resources are scarce.\n");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__v3_auth(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 1000\n"
+ "V3AuthDistDelay 1000\n"
+ "V3AuthVotingInterval 1000\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
+ "V3AuthVotingInterval");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthVoteDelay is way too low.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 1\n"
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthVoteDelay is way too low.");
+ tor_free(msg);
+
+ // TODO: we can't reach the case of v3authvotedelay lower
+ // than MIN_VOTE_SECONDS but not lower than MIN_VOTE_SECONDS_TESTING,
+ // since they are the same
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthDistDelay 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthDistDelay is way too low.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthDistDelay 1\n"
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthDistDelay is way too low.");
+ tor_free(msg);
+
+ // TODO: we can't reach the case of v3authdistdelay lower than
+ // MIN_DIST_SECONDS but not lower than MIN_DIST_SECONDS_TESTING,
+ // since they are the same
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthNIntervalsValid 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthNIntervalsValid must be at least 2.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 49\n"
+ "V3AuthDistDelay 49\n"
+ "V3AuthVotingInterval 200\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthVotingInterval is insanely low.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 49\n"
+ "V3AuthDistDelay 49\n"
+ "V3AuthVotingInterval 200000\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "V3AuthVotingInterval is insanely high.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 49\n"
+ "V3AuthDistDelay 49\n"
+ "V3AuthVotingInterval 1441\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("V3AuthVotingInterval does not divide"
+ " evenly into 24 hours.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 49\n"
+ "V3AuthDistDelay 49\n"
+ "V3AuthVotingInterval 1440\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("V3AuthVotingInterval does not divide"
+ " evenly into 24 hours.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "V3AuthVoteDelay 49\n"
+ "V3AuthDistDelay 49\n"
+ "V3AuthVotingInterval 299\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("V3AuthVotingInterval is very low. "
+ "This may lead to failure to synchronise for a consensus.\n");
+ tor_free(msg);
+
+ // TODO: It is impossible to reach the case of testingtor network, with
+ // v3authvotinginterval too low
+ /* free_options_test_data(tdata); */
+ /* tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES */
+ /* "V3AuthVoteDelay 1\n" */
+ /* "V3AuthDistDelay 1\n" */
+ /* "V3AuthVotingInterval 9\n" */
+ /* VALID_DIR_AUTH */
+ /* "TestingTorNetwork 1\n" */
+ /* ); */
+ /* ret = options_validate(tdata->old_opt, tdata->opt, */
+ /* tdata->def_opt, 0, &msg); */
+ /* tt_int_op(ret, OP_EQ, -1); */
+ /* tt_str_op(msg, OP_EQ, "V3AuthVotingInterval is insanely low."); */
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingV3AuthInitialVoteDelay 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingV3AuthInitialVoteDelay is way too low.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingV3AuthInitialDistDelay 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingV3AuthInitialDistDelay is way too low.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ tdata->opt->TestingV3AuthVotingStartOffset = 100000;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingV3AuthVotingStartOffset is higher than the "
+ "voting interval.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ );
+ tdata->opt->TestingV3AuthVotingStartOffset = -1;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "TestingV3AuthVotingStartOffset must be non-negative.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ "TestingV3AuthInitialVotingInterval 4\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingV3AuthInitialVotingInterval is insanely low.");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__virtual_addr(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "VirtualAddrNetworkIPv4 !!"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Error parsing VirtualAddressNetwork !!");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "VirtualAddrNetworkIPv6 !!"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "Error parsing VirtualAddressNetworkIPv6 !!");
+ tor_free(msg);
+
+ done:
+ escaped(NULL); // This will free the leaking memory from the previous escaped
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__exits(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AllowSingleHopExits 1"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_log_msg("You have set AllowSingleHopExits; "
+ "now your relay will allow others to make one-hop exits. However,"
+ " since by default most clients avoid relays that set this option,"
+ " most clients will ignore you.\n");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AllowSingleHopExits 1\n"
+ VALID_DIR_AUTH
+ );
+ mock_clean_saved_logs();
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_msg("You have set AllowSingleHopExits; "
+ "now your relay will allow others to make one-hop exits. However,"
+ " since by default most clients avoid relays that set this option,"
+ " most clients will ignore you.\n");
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__testing_options(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+#define TEST_TESTING_OPTION(name, low_val, high_val, err_low) \
+ STMT_BEGIN \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES \
+ VALID_DIR_AUTH \
+ "TestingTorNetwork 1\n" \
+ ); \
+ tdata->opt-> name = low_val; \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ tt_int_op(ret, OP_EQ, -1); \
+ tt_str_op(msg, OP_EQ, #name " " err_low); \
+ tor_free(msg); \
+ \
+ free_options_test_data(tdata); \
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES \
+ VALID_DIR_AUTH \
+ "TestingTorNetwork 1\n" \
+ ); \
+ tdata->opt-> name = high_val; \
+ mock_clean_saved_logs(); \
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);\
+ tt_int_op(ret, OP_EQ, 0); \
+ expect_log_msg( #name " is insanely high.\n"); \
+ tor_free(msg); \
+ STMT_END
+
+ TEST_TESTING_OPTION(TestingAuthDirTimeToLearnReachability, -1, 8000,
+ "must be non-negative.");
+ TEST_TESTING_OPTION(TestingEstimatedDescriptorPropagationTime, -1, 3601,
+ "must be non-negative.");
+ TEST_TESTING_OPTION(TestingClientMaxIntervalWithoutRequest, -1, 3601,
+ "is way too low.");
+ TEST_TESTING_OPTION(TestingDirConnectionMaxStall, 1, 3601,
+ "is way too low.");
+ // TODO: I think this points to a bug/regression in options_validate
+ TEST_TESTING_OPTION(TestingConsensusMaxDownloadTries, 1, 801,
+ "must be greater than 2.");
+ TEST_TESTING_OPTION(TestingDescriptorMaxDownloadTries, 1, 801,
+ "must be greater than 1.");
+ TEST_TESTING_OPTION(TestingMicrodescMaxDownloadTries, 1, 801,
+ "must be greater than 1.");
+ TEST_TESTING_OPTION(TestingCertMaxDownloadTries, 1, 801,
+ "must be greater than 1.");
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableConnBwEvent 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingEnableConnBwEvent may only be changed in "
+ "testing Tor networks!");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableConnBwEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ "___UsingTestNetworkDefaults 0\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableConnBwEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 0\n"
+ "___UsingTestNetworkDefaults 1\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableCellStatsEvent 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingEnableCellStatsEvent may only be changed in "
+ "testing Tor networks!");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableCellStatsEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ "___UsingTestNetworkDefaults 0\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableCellStatsEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 0\n"
+ "___UsingTestNetworkDefaults 1\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableTbEmptyEvent 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ, "TestingEnableTbEmptyEvent may only be changed "
+ "in testing Tor networks!");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableTbEmptyEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 1\n"
+ "___UsingTestNetworkDefaults 0\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "TestingEnableTbEmptyEvent 1\n"
+ VALID_DIR_AUTH
+ "TestingTorNetwork 0\n"
+ "___UsingTestNetworkDefaults 1\n"
+ );
+
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(!msg);
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ teardown_capture_of_logs(previous_log);
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+static void
+test_options_validate__accel(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ char *msg;
+ options_test_data_t *tdata = NULL;
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccelName foo\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HardwareAccel, OP_EQ, 1);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccelName foo\n"
+ );
+ tdata->opt->HardwareAccel = 2;
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tdata->opt->HardwareAccel, OP_EQ, 2);
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccelDir 1\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, -1);
+ tt_str_op(msg, OP_EQ,
+ "Can't use hardware crypto accelerator dir without engine name.");
+ tor_free(msg);
+
+ free_options_test_data(tdata);
+ tdata = get_options_test_data(TEST_OPTIONS_DEFAULT_VALUES
+ "AccelDir 1\n"
+ "AccelName something\n"
+ );
+ ret = options_validate(tdata->old_opt, tdata->opt, tdata->def_opt, 0, &msg);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(msg);
+
+ done:
+ policies_free_all();
+ free_options_test_data(tdata);
+ tor_free(msg);
+}
+
+#define LOCAL_VALIDATE_TEST(name) \
+ { "validate__" #name, test_options_validate__ ## name, TT_FORK, NULL, NULL }
+
struct testcase_t options_tests[] = {
{ "validate", test_options_validate, TT_FORK, NULL, NULL },
- END_OF_TESTCASES
+ { "mem_dircache", test_have_enough_mem_for_dircache, TT_FORK, NULL, NULL },
+ LOCAL_VALIDATE_TEST(uname_for_server),
+ LOCAL_VALIDATE_TEST(outbound_addresses),
+ LOCAL_VALIDATE_TEST(data_directory),
+ LOCAL_VALIDATE_TEST(nickname),
+ LOCAL_VALIDATE_TEST(contactinfo),
+ LOCAL_VALIDATE_TEST(logs),
+ LOCAL_VALIDATE_TEST(authdir),
+ LOCAL_VALIDATE_TEST(relay_with_hidden_services),
+ LOCAL_VALIDATE_TEST(transproxy),
+ LOCAL_VALIDATE_TEST(exclude_nodes),
+ LOCAL_VALIDATE_TEST(scheduler),
+ LOCAL_VALIDATE_TEST(node_families),
+ LOCAL_VALIDATE_TEST(tlsec),
+ LOCAL_VALIDATE_TEST(token_bucket),
+ LOCAL_VALIDATE_TEST(recommended_packages),
+ LOCAL_VALIDATE_TEST(fetch_dir),
+ LOCAL_VALIDATE_TEST(conn_limit),
+ LOCAL_VALIDATE_TEST(paths_needed),
+ LOCAL_VALIDATE_TEST(max_client_circuits),
+ LOCAL_VALIDATE_TEST(ports),
+ LOCAL_VALIDATE_TEST(reachable_addresses),
+ LOCAL_VALIDATE_TEST(use_bridges),
+ LOCAL_VALIDATE_TEST(entry_nodes),
+ LOCAL_VALIDATE_TEST(invalid_nodes),
+ LOCAL_VALIDATE_TEST(safe_logging),
+ LOCAL_VALIDATE_TEST(publish_server_descriptor),
+ LOCAL_VALIDATE_TEST(testing),
+ LOCAL_VALIDATE_TEST(hidserv),
+ LOCAL_VALIDATE_TEST(predicted_ports),
+ LOCAL_VALIDATE_TEST(path_bias),
+ LOCAL_VALIDATE_TEST(bandwidth),
+ LOCAL_VALIDATE_TEST(circuits),
+ LOCAL_VALIDATE_TEST(port_forwarding),
+ LOCAL_VALIDATE_TEST(tor2web),
+ LOCAL_VALIDATE_TEST(rend),
+ LOCAL_VALIDATE_TEST(accounting),
+ LOCAL_VALIDATE_TEST(proxy),
+ LOCAL_VALIDATE_TEST(control),
+ LOCAL_VALIDATE_TEST(families),
+ LOCAL_VALIDATE_TEST(addr_policies),
+ LOCAL_VALIDATE_TEST(dir_auth),
+ LOCAL_VALIDATE_TEST(transport),
+ LOCAL_VALIDATE_TEST(constrained_sockets),
+ LOCAL_VALIDATE_TEST(v3_auth),
+ LOCAL_VALIDATE_TEST(virtual_addr),
+ LOCAL_VALIDATE_TEST(exits),
+ LOCAL_VALIDATE_TEST(testing_options),
+ LOCAL_VALIDATE_TEST(accel),
+ END_OF_TESTCASES /* */
};
diff --git a/src/test/test_policy.c b/src/test/test_policy.c
index 4cdcd034bb..a939ebf54f 100644
--- a/src/test/test_policy.c
+++ b/src/test/test_policy.c
@@ -1,9 +1,12 @@
-/* Copyright (c) 2013, The Tor Project, Inc. */
+/* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "or.h"
+#define CONFIG_PRIVATE
+#include "config.h"
#include "router.h"
#include "routerparse.h"
+#define POLICIES_PRIVATE
#include "policies.h"
#include "test.h"
@@ -22,7 +25,7 @@ test_short_policy_parse(const char *input,
short_policy = parse_short_policy(input);
tt_assert(short_policy);
out = write_short_policy(short_policy);
- tt_str_op(out, ==, expected);
+ tt_str_op(out, OP_EQ, expected);
done:
tor_free(out);
@@ -47,17 +50,20 @@ test_policy_summary_helper(const char *policy_str,
line.value = (char *)policy_str;
line.next = NULL;
- r = policies_parse_exit_policy(&line, &policy, 1, 0, 0, 1);
- test_eq(r, 0);
+ r = policies_parse_exit_policy(&line, &policy,
+ EXIT_POLICY_IPV6_ENABLED |
+ EXIT_POLICY_ADD_DEFAULT, NULL);
+ tt_int_op(r,OP_EQ, 0);
+
summary = policy_summarize(policy, AF_INET);
- test_assert(summary != NULL);
- test_streq(summary, expected_summary);
+ tt_assert(summary != NULL);
+ tt_str_op(summary,OP_EQ, expected_summary);
short_policy = parse_short_policy(summary);
tt_assert(short_policy);
summary_after = write_short_policy(short_policy);
- test_streq(summary, summary_after);
+ tt_str_op(summary,OP_EQ, summary_after);
done:
tor_free(summary_after);
@@ -74,130 +80,296 @@ test_policies_general(void *arg)
int i;
smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
*policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
- *policy7 = NULL;
+ *policy7 = NULL, *policy8 = NULL, *policy9 = NULL,
+ *policy10 = NULL, *policy11 = NULL, *policy12 = NULL;
addr_policy_t *p;
- tor_addr_t tar;
+ tor_addr_t tar, tar2;
+ smartlist_t *addr_list = NULL;
config_line_t line;
smartlist_t *sm = NULL;
char *policy_str = NULL;
short_policy_t *short_parsed = NULL;
+ int malformed_list = -1;
(void)arg;
policy = smartlist_new();
- p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
- test_assert(p != NULL);
- test_eq(ADDR_POLICY_REJECT, p->policy_type);
+ p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
+ tt_int_op(ADDR_POLICY_REJECT,OP_EQ, p->policy_type);
tor_addr_from_ipv4h(&tar, 0xc0a80000u);
- test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
- test_eq(16, p->maskbits);
- test_eq(1, p->prt_min);
- test_eq(65535, p->prt_max);
+ tt_int_op(0,OP_EQ, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
+ tt_int_op(16,OP_EQ, p->maskbits);
+ tt_int_op(1,OP_EQ, p->prt_min);
+ tt_int_op(65535,OP_EQ, p->prt_max);
smartlist_add(policy, p);
tor_addr_from_ipv4h(&tar, 0x01020304u);
- test_assert(ADDR_POLICY_ACCEPTED ==
+ tt_assert(ADDR_POLICY_ACCEPTED ==
compare_tor_addr_to_addr_policy(&tar, 2, policy));
tor_addr_make_unspec(&tar);
- test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
+ tt_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
compare_tor_addr_to_addr_policy(&tar, 2, policy));
tor_addr_from_ipv4h(&tar, 0xc0a80102);
- test_assert(ADDR_POLICY_REJECTED ==
+ tt_assert(ADDR_POLICY_REJECTED ==
compare_tor_addr_to_addr_policy(&tar, 2, policy));
- test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, 1, 0, 1));
- test_assert(policy2);
+ tt_int_op(0, OP_EQ, policies_parse_exit_policy(NULL, &policy2,
+ EXIT_POLICY_IPV6_ENABLED |
+ EXIT_POLICY_REJECT_PRIVATE |
+ EXIT_POLICY_ADD_DEFAULT, NULL));
+
+ tt_assert(policy2);
+
+ tor_addr_from_ipv4h(&tar, 0x0306090cu);
+ tor_addr_parse(&tar2, "[2000::1234]");
+ addr_list = smartlist_new();
+ smartlist_add(addr_list, &tar);
+ smartlist_add(addr_list, &tar2);
+ tt_int_op(0, OP_EQ, policies_parse_exit_policy(NULL, &policy12,
+ EXIT_POLICY_IPV6_ENABLED |
+ EXIT_POLICY_REJECT_PRIVATE |
+ EXIT_POLICY_ADD_DEFAULT,
+ addr_list));
+ smartlist_free(addr_list);
+ addr_list = NULL;
+
+ tt_assert(policy12);
policy3 = smartlist_new();
- p = router_parse_addr_policy_item_from_string("reject *:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject *:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy3, p);
- p = router_parse_addr_policy_item_from_string("accept *:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept *:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy3, p);
policy4 = smartlist_new();
- p = router_parse_addr_policy_item_from_string("accept *:443",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept *:443", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy4, p);
- p = router_parse_addr_policy_item_from_string("accept *:443",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept *:443", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy4, p);
policy5 = smartlist_new();
- p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",
+ -1, &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject *:1-65534", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("reject *:65535", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
- p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept *:1-65535", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy5, p);
policy6 = smartlist_new();
- p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy6, p);
policy7 = smartlist_new();
- p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
- test_assert(p != NULL);
+ p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
smartlist_add(policy7, p);
- test_assert(!exit_policy_is_general_exit(policy));
- test_assert(exit_policy_is_general_exit(policy2));
- test_assert(!exit_policy_is_general_exit(NULL));
- test_assert(!exit_policy_is_general_exit(policy3));
- test_assert(!exit_policy_is_general_exit(policy4));
- test_assert(!exit_policy_is_general_exit(policy5));
- test_assert(!exit_policy_is_general_exit(policy6));
- test_assert(!exit_policy_is_general_exit(policy7));
-
- test_assert(cmp_addr_policies(policy, policy2));
- test_assert(cmp_addr_policies(policy, NULL));
- test_assert(!cmp_addr_policies(policy2, policy2));
- test_assert(!cmp_addr_policies(NULL, NULL));
-
- test_assert(!policy_is_reject_star(policy2, AF_INET));
- test_assert(policy_is_reject_star(policy, AF_INET));
- test_assert(policy_is_reject_star(NULL, AF_INET));
+ tt_int_op(0, OP_EQ, policies_parse_exit_policy(NULL, &policy8,
+ EXIT_POLICY_IPV6_ENABLED |
+ EXIT_POLICY_REJECT_PRIVATE |
+ EXIT_POLICY_ADD_DEFAULT,
+ NULL));
+
+ tt_assert(policy8);
+
+ tt_int_op(0, OP_EQ, policies_parse_exit_policy(NULL, &policy9,
+ EXIT_POLICY_REJECT_PRIVATE |
+ EXIT_POLICY_ADD_DEFAULT,
+ NULL));
+
+ tt_assert(policy9);
+
+ /* accept6 * and reject6 * produce IPv6 wildcards only */
+ policy10 = smartlist_new();
+ p = router_parse_addr_policy_item_from_string("accept6 *:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
+ smartlist_add(policy10, p);
+
+ policy11 = smartlist_new();
+ p = router_parse_addr_policy_item_from_string("reject6 *:*", -1,
+ &malformed_list);
+ tt_assert(p != NULL);
+ smartlist_add(policy11, p);
+
+ tt_assert(!exit_policy_is_general_exit(policy));
+ tt_assert(exit_policy_is_general_exit(policy2));
+ tt_assert(!exit_policy_is_general_exit(NULL));
+ tt_assert(!exit_policy_is_general_exit(policy3));
+ tt_assert(!exit_policy_is_general_exit(policy4));
+ tt_assert(!exit_policy_is_general_exit(policy5));
+ tt_assert(!exit_policy_is_general_exit(policy6));
+ tt_assert(!exit_policy_is_general_exit(policy7));
+ tt_assert(exit_policy_is_general_exit(policy8));
+ tt_assert(exit_policy_is_general_exit(policy9));
+ tt_assert(!exit_policy_is_general_exit(policy10));
+ tt_assert(!exit_policy_is_general_exit(policy11));
+
+ tt_assert(cmp_addr_policies(policy, policy2));
+ tt_assert(cmp_addr_policies(policy, NULL));
+ tt_assert(!cmp_addr_policies(policy2, policy2));
+ tt_assert(!cmp_addr_policies(NULL, NULL));
+
+ tt_assert(!policy_is_reject_star(policy2, AF_INET));
+ tt_assert(policy_is_reject_star(policy, AF_INET));
+ tt_assert(policy_is_reject_star(policy10, AF_INET));
+ tt_assert(!policy_is_reject_star(policy10, AF_INET6));
+ tt_assert(policy_is_reject_star(policy11, AF_INET));
+ tt_assert(policy_is_reject_star(policy11, AF_INET6));
+ tt_assert(policy_is_reject_star(NULL, AF_INET));
+ tt_assert(policy_is_reject_star(NULL, AF_INET6));
addr_policy_list_free(policy);
policy = NULL;
+ /* make sure assume_action works */
+ malformed_list = 0;
+ p = router_parse_addr_policy_item_from_string("127.0.0.1",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("127.0.0.1:*",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("[::]",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("[::]:*",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("[face::b]",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("[b::aaaa]",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("*",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("*4",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("*6",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(p);
+ addr_policy_free(p);
+ tt_assert(!malformed_list);
+
+ /* These are all ambiguous IPv6 addresses, it's good that we reject them */
+ p = router_parse_addr_policy_item_from_string("acce::abcd",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(!p);
+ tt_assert(malformed_list);
+ malformed_list = 0;
+
+ p = router_parse_addr_policy_item_from_string("7:1234",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(!p);
+ tt_assert(malformed_list);
+ malformed_list = 0;
+
+ p = router_parse_addr_policy_item_from_string("::",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(!p);
+ tt_assert(malformed_list);
+ malformed_list = 0;
+
/* make sure compacting logic works. */
policy = NULL;
line.key = (char*)"foo";
line.value = (char*)"accept *:80,reject private:*,reject *:*";
line.next = NULL;
- test_assert(0 == policies_parse_exit_policy(&line, &policy, 1, 0, 0, 1));
- test_assert(policy);
+ tt_int_op(0, OP_EQ, policies_parse_exit_policy(&line,&policy,
+ EXIT_POLICY_IPV6_ENABLED |
+ EXIT_POLICY_ADD_DEFAULT, NULL));
+ tt_assert(policy);
+
//test_streq(policy->string, "accept *:80");
//test_streq(policy->next->string, "reject *:*");
- test_eq(smartlist_len(policy), 4);
+ tt_int_op(smartlist_len(policy),OP_EQ, 4);
/* test policy summaries */
/* check if we properly ignore private IP addresses */
@@ -271,7 +443,7 @@ test_policies_general(void *arg)
/* Try parsing various broken short policies */
#define TT_BAD_SHORT_POLICY(s) \
do { \
- tt_ptr_op(NULL, ==, (short_parsed = parse_short_policy((s)))); \
+ tt_ptr_op(NULL, OP_EQ, (short_parsed = parse_short_policy((s)))); \
} while (0)
TT_BAD_SHORT_POLICY("accept 200-199");
TT_BAD_SHORT_POLICY("");
@@ -287,6 +459,68 @@ test_policies_general(void *arg)
TT_BAD_SHORT_POLICY("accept 1-,3");
TT_BAD_SHORT_POLICY("accept 1-,3");
+ /* Make sure that IPv4 addresses are ignored in accept6/reject6 lines. */
+ p = router_parse_addr_policy_item_from_string("accept6 1.2.3.4:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("reject6 2.4.6.0/24:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(!malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("accept6 *4:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(!malformed_list);
+
+ /* Make sure malformed policies are detected as such. */
+ p = router_parse_addr_policy_item_from_string("bad_token *4:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("accept6 **:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("accept */15:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("reject6 */:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("accept 127.0.0.1/33:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("accept6 [::1]/129:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("reject 8.8.8.8/-1:*", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("reject 8.8.4.4:10-5", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
+ p = router_parse_addr_policy_item_from_string("reject 1.2.3.4:-1", -1,
+ &malformed_list);
+ tt_assert(p == NULL);
+ tt_assert(malformed_list);
+
/* Test a too-long policy. */
{
int i;
@@ -301,7 +535,7 @@ test_policies_general(void *arg)
smartlist_free(chunks);
short_parsed = parse_short_policy(policy);/* shouldn't be accepted */
tor_free(policy);
- tt_ptr_op(NULL, ==, short_parsed);
+ tt_ptr_op(NULL, OP_EQ, short_parsed);
}
/* truncation ports */
@@ -337,6 +571,11 @@ test_policies_general(void *arg)
addr_policy_list_free(policy5);
addr_policy_list_free(policy6);
addr_policy_list_free(policy7);
+ addr_policy_list_free(policy8);
+ addr_policy_list_free(policy9);
+ addr_policy_list_free(policy10);
+ addr_policy_list_free(policy11);
+ addr_policy_list_free(policy12);
tor_free(policy_str);
if (sm) {
SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
@@ -345,11 +584,329 @@ test_policies_general(void *arg)
short_policy_free(short_parsed);
}
+/** Helper: Check that policy_list contains address */
+static int
+test_policy_has_address_helper(const smartlist_t *policy_list,
+ const tor_addr_t *addr)
+{
+ int found = 0;
+
+ tt_assert(policy_list);
+ tt_assert(addr);
+
+ SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t*, p) {
+ if (tor_addr_eq(&p->addr, addr)) {
+ found = 1;
+ }
+ } SMARTLIST_FOREACH_END(p);
+
+ return found;
+
+ done:
+ return 0;
+}
+
+#define TEST_IPV4_ADDR (0x01020304)
+#define TEST_IPV6_ADDR ("2002::abcd")
+
+/** Run unit tests for rejecting the configured addresses on this exit relay
+ * using policies_parse_exit_policy_reject_private */
+static void
+test_policies_reject_exit_address(void *arg)
+{
+ smartlist_t *policy = NULL;
+ tor_addr_t ipv4_addr, ipv6_addr;
+ smartlist_t *ipv4_list, *ipv6_list, *both_list, *dupl_list;
+ (void)arg;
+
+ tor_addr_from_ipv4h(&ipv4_addr, TEST_IPV4_ADDR);
+ tor_addr_parse(&ipv6_addr, TEST_IPV6_ADDR);
+
+ ipv4_list = smartlist_new();
+ ipv6_list = smartlist_new();
+ both_list = smartlist_new();
+ dupl_list = smartlist_new();
+
+ smartlist_add(ipv4_list, &ipv4_addr);
+ smartlist_add(both_list, &ipv4_addr);
+ smartlist_add(dupl_list, &ipv4_addr);
+ smartlist_add(dupl_list, &ipv4_addr);
+ smartlist_add(dupl_list, &ipv4_addr);
+
+ smartlist_add(ipv6_list, &ipv6_addr);
+ smartlist_add(both_list, &ipv6_addr);
+ smartlist_add(dupl_list, &ipv6_addr);
+ smartlist_add(dupl_list, &ipv6_addr);
+
+ /* IPv4-Only Exits */
+
+ /* test that IPv4 addresses are rejected on an IPv4-only exit */
+ policies_parse_exit_policy_reject_private(&policy, 0, ipv4_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* test that IPv6 addresses are NOT rejected on an IPv4-only exit
+ * (all IPv6 addresses are rejected by policies_parse_exit_policy_internal
+ * on IPv4-only exits, so policies_parse_exit_policy_reject_private doesn't
+ * need to do anything) */
+ policies_parse_exit_policy_reject_private(&policy, 0, ipv6_list, 0, 0);
+ tt_assert(policy == NULL);
+
+ /* test that only IPv4 addresses are rejected on an IPv4-only exit */
+ policies_parse_exit_policy_reject_private(&policy, 0, both_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* Test that lists with duplicate entries produce the same results */
+ policies_parse_exit_policy_reject_private(&policy, 0, dupl_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* IPv4/IPv6 Exits */
+
+ /* test that IPv4 addresses are rejected on an IPv4/IPv6 exit */
+ policies_parse_exit_policy_reject_private(&policy, 1, ipv4_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* test that IPv6 addresses are rejected on an IPv4/IPv6 exit */
+ policies_parse_exit_policy_reject_private(&policy, 1, ipv6_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv6_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* test that IPv4 and IPv6 addresses are rejected on an IPv4/IPv6 exit */
+ policies_parse_exit_policy_reject_private(&policy, 1, both_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 2);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ tt_assert(test_policy_has_address_helper(policy, &ipv6_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* Test that lists with duplicate entries produce the same results */
+ policies_parse_exit_policy_reject_private(&policy, 1, dupl_list, 0, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 2);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_addr));
+ tt_assert(test_policy_has_address_helper(policy, &ipv6_addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ done:
+ addr_policy_list_free(policy);
+ smartlist_free(ipv4_list);
+ smartlist_free(ipv6_list);
+ smartlist_free(both_list);
+ smartlist_free(dupl_list);
+}
+
+static smartlist_t *test_configured_ports = NULL;
+
+/** Returns test_configured_ports */
+static const smartlist_t *
+mock_get_configured_ports(void)
+{
+ return test_configured_ports;
+}
+
+/** Run unit tests for rejecting publicly routable configured port addresses
+ * on this exit relay using policies_parse_exit_policy_reject_private */
+static void
+test_policies_reject_port_address(void *arg)
+{
+ smartlist_t *policy = NULL;
+ port_cfg_t *ipv4_port = NULL;
+ port_cfg_t *ipv6_port = NULL;
+ (void)arg;
+
+ test_configured_ports = smartlist_new();
+
+ ipv4_port = port_cfg_new(0);
+ tor_addr_from_ipv4h(&ipv4_port->addr, TEST_IPV4_ADDR);
+ smartlist_add(test_configured_ports, ipv4_port);
+
+ ipv6_port = port_cfg_new(0);
+ tor_addr_parse(&ipv6_port->addr, TEST_IPV6_ADDR);
+ smartlist_add(test_configured_ports, ipv6_port);
+
+ MOCK(get_configured_ports, mock_get_configured_ports);
+
+ /* test that an IPv4 port is rejected on an IPv4-only exit, but an IPv6 port
+ * is NOT rejected (all IPv6 addresses are rejected by
+ * policies_parse_exit_policy_internal on IPv4-only exits, so
+ * policies_parse_exit_policy_reject_private doesn't need to do anything
+ * with IPv6 addresses on IPv4-only exits) */
+ policies_parse_exit_policy_reject_private(&policy, 0, NULL, 0, 1);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 1);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_port->addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* test that IPv4 and IPv6 ports are rejected on an IPv4/IPv6 exit */
+ policies_parse_exit_policy_reject_private(&policy, 1, NULL, 0, 1);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == 2);
+ tt_assert(test_policy_has_address_helper(policy, &ipv4_port->addr));
+ tt_assert(test_policy_has_address_helper(policy, &ipv6_port->addr));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ done:
+ addr_policy_list_free(policy);
+ if (test_configured_ports) {
+ SMARTLIST_FOREACH(test_configured_ports,
+ port_cfg_t *, p, port_cfg_free(p));
+ smartlist_free(test_configured_ports);
+ test_configured_ports = NULL;
+ }
+ UNMOCK(get_configured_ports);
+}
+
+smartlist_t *mock_ipv4_addrs = NULL;
+smartlist_t *mock_ipv6_addrs = NULL;
+
+/* mock get_interface_address6_list, returning a deep copy of the template
+ * address list ipv4_interface_address_list or ipv6_interface_address_list */
+static smartlist_t *
+mock_get_interface_address6_list(int severity,
+ sa_family_t family,
+ int include_internal)
+{
+ (void)severity;
+ (void)include_internal;
+ smartlist_t *clone_list = smartlist_new();
+ smartlist_t *template_list = NULL;
+
+ if (family == AF_INET) {
+ template_list = mock_ipv4_addrs;
+ } else if (family == AF_INET6) {
+ template_list = mock_ipv6_addrs;
+ } else {
+ return NULL;
+ }
+
+ tt_assert(template_list);
+
+ SMARTLIST_FOREACH_BEGIN(template_list, tor_addr_t *, src_addr) {
+ tor_addr_t *dest_addr = malloc(sizeof(tor_addr_t));
+ memset(dest_addr, 0, sizeof(*dest_addr));
+ tor_addr_copy_tight(dest_addr, src_addr);
+ smartlist_add(clone_list, dest_addr);
+ } SMARTLIST_FOREACH_END(src_addr);
+
+ return clone_list;
+
+ done:
+ free_interface_address6_list(clone_list);
+ return NULL;
+}
+
+/** Run unit tests for rejecting publicly routable interface addresses on this
+ * exit relay using policies_parse_exit_policy_reject_private */
+static void
+test_policies_reject_interface_address(void *arg)
+{
+ smartlist_t *policy = NULL;
+ smartlist_t *public_ipv4_addrs =
+ get_interface_address6_list(LOG_INFO, AF_INET, 0);
+ smartlist_t *public_ipv6_addrs =
+ get_interface_address6_list(LOG_INFO, AF_INET6, 0);
+ tor_addr_t ipv4_addr, ipv6_addr;
+ (void)arg;
+
+ /* test that no addresses are rejected when none are supplied/requested */
+ policies_parse_exit_policy_reject_private(&policy, 0, NULL, 0, 0);
+ tt_assert(policy == NULL);
+
+ /* test that only IPv4 interface addresses are rejected on an IPv4-only exit
+ * (and allow for duplicates)
+ */
+ policies_parse_exit_policy_reject_private(&policy, 0, NULL, 1, 0);
+ if (policy) {
+ tt_assert(smartlist_len(policy) <= smartlist_len(public_ipv4_addrs));
+ addr_policy_list_free(policy);
+ policy = NULL;
+ }
+
+ /* test that IPv4 and IPv6 interface addresses are rejected on an IPv4/IPv6
+ * exit (and allow for duplicates) */
+ policies_parse_exit_policy_reject_private(&policy, 1, NULL, 1, 0);
+ if (policy) {
+ tt_assert(smartlist_len(policy) <= (smartlist_len(public_ipv4_addrs)
+ + smartlist_len(public_ipv6_addrs)));
+ addr_policy_list_free(policy);
+ policy = NULL;
+ }
+
+ /* Now do it all again, but mocked */
+ tor_addr_from_ipv4h(&ipv4_addr, TEST_IPV4_ADDR);
+ mock_ipv4_addrs = smartlist_new();
+ smartlist_add(mock_ipv4_addrs, (void *)&ipv4_addr);
+
+ tor_addr_parse(&ipv6_addr, TEST_IPV6_ADDR);
+ mock_ipv6_addrs = smartlist_new();
+ smartlist_add(mock_ipv6_addrs, (void *)&ipv6_addr);
+
+ MOCK(get_interface_address6_list, mock_get_interface_address6_list);
+
+ /* test that no addresses are rejected when none are supplied/requested */
+ policies_parse_exit_policy_reject_private(&policy, 0, NULL, 0, 0);
+ tt_assert(policy == NULL);
+
+ /* test that only IPv4 interface addresses are rejected on an IPv4-only exit
+ */
+ policies_parse_exit_policy_reject_private(&policy, 0, NULL, 1, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == smartlist_len(mock_ipv4_addrs));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ /* test that IPv4 and IPv6 interface addresses are rejected on an IPv4/IPv6
+ * exit */
+ policies_parse_exit_policy_reject_private(&policy, 1, NULL, 1, 0);
+ tt_assert(policy);
+ tt_assert(smartlist_len(policy) == (smartlist_len(mock_ipv4_addrs)
+ + smartlist_len(mock_ipv6_addrs)));
+ addr_policy_list_free(policy);
+ policy = NULL;
+
+ done:
+ addr_policy_list_free(policy);
+ free_interface_address6_list(public_ipv4_addrs);
+ free_interface_address6_list(public_ipv6_addrs);
+
+ UNMOCK(get_interface_address6_list);
+ /* we don't use free_interface_address6_list on these lists because their
+ * address pointers are stack-based */
+ smartlist_free(mock_ipv4_addrs);
+ smartlist_free(mock_ipv6_addrs);
+}
+
+#undef TEST_IPV4_ADDR
+#undef TEST_IPV6_ADDR
+
static void
test_dump_exit_policy_to_string(void *arg)
{
char *ep;
addr_policy_t *policy_entry;
+ int malformed_list = -1;
routerinfo_t *ri = tor_malloc_zero(sizeof(routerinfo_t));
@@ -359,63 +916,68 @@ test_dump_exit_policy_to_string(void *arg)
ri->exit_policy = NULL; // expecting "reject *:*"
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("reject *:*",ep);
+ tt_str_op("reject *:*",OP_EQ, ep);
tor_free(ep);
ri->exit_policy = smartlist_new();
ri->policy_is_reject_star = 0;
- policy_entry = router_parse_addr_policy_item_from_string("accept *:*",-1);
+ policy_entry = router_parse_addr_policy_item_from_string("accept *:*", -1,
+ &malformed_list);
smartlist_add(ri->exit_policy,policy_entry);
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("accept *:*",ep);
+ tt_str_op("accept *:*",OP_EQ, ep);
tor_free(ep);
- policy_entry = router_parse_addr_policy_item_from_string("reject *:25",-1);
+ policy_entry = router_parse_addr_policy_item_from_string("reject *:25", -1,
+ &malformed_list);
smartlist_add(ri->exit_policy,policy_entry);
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("accept *:*\nreject *:25",ep);
+ tt_str_op("accept *:*\nreject *:25",OP_EQ, ep);
tor_free(ep);
policy_entry =
- router_parse_addr_policy_item_from_string("reject 8.8.8.8:*",-1);
+ router_parse_addr_policy_item_from_string("reject 8.8.8.8:*", -1,
+ &malformed_list);
smartlist_add(ri->exit_policy,policy_entry);
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("accept *:*\nreject *:25\nreject 8.8.8.8:*",ep);
+ tt_str_op("accept *:*\nreject *:25\nreject 8.8.8.8:*",OP_EQ, ep);
tor_free(ep);
policy_entry =
- router_parse_addr_policy_item_from_string("reject6 [FC00::]/7:*",-1);
+ router_parse_addr_policy_item_from_string("reject6 [FC00::]/7:*", -1,
+ &malformed_list);
smartlist_add(ri->exit_policy,policy_entry);
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("accept *:*\nreject *:25\nreject 8.8.8.8:*\n"
- "reject6 [fc00::]/7:*",ep);
+ tt_str_op("accept *:*\nreject *:25\nreject 8.8.8.8:*\n"
+ "reject6 [fc00::]/7:*",OP_EQ, ep);
tor_free(ep);
policy_entry =
- router_parse_addr_policy_item_from_string("accept6 [c000::]/3:*",-1);
+ router_parse_addr_policy_item_from_string("accept6 [c000::]/3:*", -1,
+ &malformed_list);
smartlist_add(ri->exit_policy,policy_entry);
ep = router_dump_exit_policy_to_string(ri,1,1);
- test_streq("accept *:*\nreject *:25\nreject 8.8.8.8:*\n"
- "reject6 [fc00::]/7:*\naccept6 [c000::]/3:*",ep);
+ tt_str_op("accept *:*\nreject *:25\nreject 8.8.8.8:*\n"
+ "reject6 [fc00::]/7:*\naccept6 [c000::]/3:*",OP_EQ, ep);
done:
@@ -428,10 +990,861 @@ test_dump_exit_policy_to_string(void *arg)
tor_free(ep);
}
+static routerinfo_t *mock_desc_routerinfo = NULL;
+static const routerinfo_t *
+mock_router_get_my_routerinfo(void)
+{
+ return mock_desc_routerinfo;
+}
+
+#define DEFAULT_POLICY_STRING "reject *:*"
+#define TEST_IPV4_ADDR (0x02040608)
+#define TEST_IPV6_ADDR ("2003::ef01")
+
+static or_options_t mock_options;
+
+static const or_options_t *
+mock_get_options(void)
+{
+ return &mock_options;
+}
+
+/** Run unit tests for generating summary lines of exit policies */
+static void
+test_policies_getinfo_helper_policies(void *arg)
+{
+ (void)arg;
+ int rv = 0;
+ size_t ipv4_len = 0, ipv6_len = 0;
+ char *answer = NULL;
+ const char *errmsg = NULL;
+ routerinfo_t mock_my_routerinfo;
+
+ memset(&mock_my_routerinfo, 0, sizeof(mock_my_routerinfo));
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/default", &answer, &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ tt_assert(strlen(answer) > 0);
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/reject-private/default",
+ &answer, &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ tt_assert(strlen(answer) > 0);
+ tor_free(answer);
+
+ memset(&mock_my_routerinfo, 0, sizeof(routerinfo_t));
+ MOCK(router_get_my_routerinfo, mock_router_get_my_routerinfo);
+ mock_my_routerinfo.exit_policy = smartlist_new();
+ mock_desc_routerinfo = &mock_my_routerinfo;
+
+ memset(&mock_options, 0, sizeof(or_options_t));
+ MOCK(get_options, mock_get_options);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/reject-private/relay",
+ &answer, &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ tt_assert(strlen(answer) == 0);
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/ipv4", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ ipv4_len = strlen(answer);
+ tt_assert(ipv4_len == 0 || ipv4_len == strlen(DEFAULT_POLICY_STRING));
+ tt_assert(ipv4_len == 0 || !strcasecmp(answer, DEFAULT_POLICY_STRING));
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/ipv6", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ ipv6_len = strlen(answer);
+ tt_assert(ipv6_len == 0 || ipv6_len == strlen(DEFAULT_POLICY_STRING));
+ tt_assert(ipv6_len == 0 || !strcasecmp(answer, DEFAULT_POLICY_STRING));
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/full", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ /* It's either empty or it's the default */
+ tt_assert(strlen(answer) == 0 || !strcasecmp(answer, DEFAULT_POLICY_STRING));
+ tor_free(answer);
+
+ mock_my_routerinfo.addr = TEST_IPV4_ADDR;
+ tor_addr_parse(&mock_my_routerinfo.ipv6_addr, TEST_IPV6_ADDR);
+ append_exit_policy_string(&mock_my_routerinfo.exit_policy, "accept *4:*");
+ append_exit_policy_string(&mock_my_routerinfo.exit_policy, "reject *6:*");
+
+ mock_options.IPv6Exit = 1;
+ mock_options.ExitPolicyRejectPrivate = 1;
+ tor_addr_from_ipv4h(&mock_options.OutboundBindAddressIPv4_, TEST_IPV4_ADDR);
+ tor_addr_parse(&mock_options.OutboundBindAddressIPv6_, TEST_IPV6_ADDR);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/reject-private/relay",
+ &answer, &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ tt_assert(strlen(answer) > 0);
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/ipv4", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ ipv4_len = strlen(answer);
+ tt_assert(ipv4_len > 0);
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/ipv6", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ ipv6_len = strlen(answer);
+ tt_assert(ipv6_len > 0);
+ tor_free(answer);
+
+ rv = getinfo_helper_policies(NULL, "exit-policy/full", &answer,
+ &errmsg);
+ tt_assert(rv == 0);
+ tt_assert(answer != NULL);
+ tt_assert(strlen(answer) > 0);
+ tt_assert(strlen(answer) == ipv4_len + ipv6_len + 1);
+ tor_free(answer);
+
+ done:
+ tor_free(answer);
+ UNMOCK(get_options);
+ UNMOCK(router_get_my_routerinfo);
+ addr_policy_list_free(mock_my_routerinfo.exit_policy);
+}
+
+#undef DEFAULT_POLICY_STRING
+#undef TEST_IPV4_ADDR
+#undef TEST_IPV6_ADDR
+
+#define TEST_IPV4_ADDR_STR "1.2.3.4"
+#define TEST_IPV6_ADDR_STR "[1002::4567]"
+#define REJECT_IPv4_FINAL_STR "reject 0.0.0.0/0:*"
+#define REJECT_IPv6_FINAL_STR "reject [::]/0:*"
+
+#define OTHER_IPV4_ADDR_STR "6.7.8.9"
+#define OTHER_IPV6_ADDR_STR "[afff::]"
+
+/** Run unit tests for fascist_firewall_allows_address */
+static void
+test_policies_fascist_firewall_allows_address(void *arg)
+{
+ (void)arg;
+ tor_addr_t ipv4_addr, ipv6_addr, r_ipv4_addr, r_ipv6_addr;
+ tor_addr_t n_ipv4_addr, n_ipv6_addr;
+ const uint16_t port = 1234;
+ smartlist_t *policy = NULL;
+ smartlist_t *e_policy = NULL;
+ addr_policy_t *item = NULL;
+ int malformed_list = 0;
+
+ /* Setup the options and the items in the policies */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ MOCK(get_options, mock_get_options);
+
+ policy = smartlist_new();
+ item = router_parse_addr_policy_item_from_string("accept "
+ TEST_IPV4_ADDR_STR ":*",
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(item);
+ tt_assert(!malformed_list);
+ smartlist_add(policy, item);
+ item = router_parse_addr_policy_item_from_string("accept "
+ TEST_IPV6_ADDR_STR,
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(item);
+ tt_assert(!malformed_list);
+ smartlist_add(policy, item);
+ /* Normally, policy_expand_unspec would do this for us */
+ item = router_parse_addr_policy_item_from_string(REJECT_IPv4_FINAL_STR,
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(item);
+ tt_assert(!malformed_list);
+ smartlist_add(policy, item);
+ item = router_parse_addr_policy_item_from_string(REJECT_IPv6_FINAL_STR,
+ ADDR_POLICY_ACCEPT,
+ &malformed_list);
+ tt_assert(item);
+ tt_assert(!malformed_list);
+ smartlist_add(policy, item);
+ item = NULL;
+
+ e_policy = smartlist_new();
+
+ /*
+ char *polstr = policy_dump_to_string(policy, 1, 1);
+ printf("%s\n", polstr);
+ tor_free(polstr);
+ */
+
+ /* Parse the addresses */
+ tor_addr_parse(&ipv4_addr, TEST_IPV4_ADDR_STR);
+ tor_addr_parse(&ipv6_addr, TEST_IPV6_ADDR_STR);
+ tor_addr_parse(&r_ipv4_addr, OTHER_IPV4_ADDR_STR);
+ tor_addr_parse(&r_ipv6_addr, OTHER_IPV6_ADDR_STR);
+ tor_addr_make_null(&n_ipv4_addr, AF_INET);
+ tor_addr_make_null(&n_ipv6_addr, AF_INET6);
+
+ /* Test the function's address matching with IPv4 and IPv6 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 0;
+
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Preferring IPv4 */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 1, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 1, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 1, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 1, 0)
+ == 0);
+
+ /* Preferring IPv6 */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 1, 1)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 1, 1)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 1, 1)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 1, 1)
+ == 0);
+
+ /* Test the function's address matching with UseBridges on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 1;
+
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Preferring IPv4 */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 1, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 1, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 1, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 1, 0)
+ == 0);
+
+ /* Preferring IPv6 */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 1, 1)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 1, 1)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 1, 1)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 1, 1)
+ == 0);
+
+ /* bridge clients always use IPv6, regardless of ClientUseIPv6 */
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 0;
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Test the function's address matching with IPv4 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 0;
+ mock_options.UseBridges = 0;
+
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Test the function's address matching with IPv6 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 0;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 0;
+
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Test the function's address matching with ClientUseIPv4 0.
+ * This means "use IPv6" regardless of the other settings. */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 0;
+ mock_options.ClientUseIPv6 = 0;
+ mock_options.UseBridges = 0;
+
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&r_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&r_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* Test the function's address matching for unusual inputs */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 1;
+
+ /* NULL and tor_addr_is_null addresses are rejected */
+ tt_assert(fascist_firewall_allows_address(NULL, port, policy, 0, 0) == 0);
+ tt_assert(fascist_firewall_allows_address(&n_ipv4_addr, port, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&n_ipv6_addr, port, policy, 0, 0)
+ == 0);
+
+ /* zero ports are rejected */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, 0, policy, 0, 0)
+ == 0);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, 0, policy, 0, 0)
+ == 0);
+
+ /* NULL and empty policies accept everything */
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, NULL, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, NULL, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv4_addr, port, e_policy, 0, 0)
+ == 1);
+ tt_assert(fascist_firewall_allows_address(&ipv6_addr, port, e_policy, 0, 0)
+ == 1);
+
+ done:
+ addr_policy_free(item);
+ addr_policy_list_free(policy);
+ addr_policy_list_free(e_policy);
+ UNMOCK(get_options);
+}
+
+#undef REJECT_IPv4_FINAL_STR
+#undef REJECT_IPv6_FINAL_STR
+#undef OTHER_IPV4_ADDR_STR
+#undef OTHER_IPV6_ADDR_STR
+
+#define TEST_IPV4_OR_PORT 1234
+#define TEST_IPV4_DIR_PORT 2345
+#define TEST_IPV6_OR_PORT 61234
+#define TEST_IPV6_DIR_PORT 62345
+
+/* Check that fascist_firewall_choose_address_rs() returns the expected
+ * results. */
+#define CHECK_CHOSEN_ADDR_RS(fake_rs, fw_connection, pref_only, expect_rv, \
+ expect_ap) \
+ STMT_BEGIN \
+ tor_addr_port_t chosen_rs_ap; \
+ tor_addr_make_null(&chosen_rs_ap.addr, AF_INET); \
+ chosen_rs_ap.port = 0; \
+ tt_int_op(fascist_firewall_choose_address_rs(&(fake_rs), \
+ (fw_connection), \
+ (pref_only), \
+ &chosen_rs_ap), \
+ OP_EQ, (expect_rv)); \
+ tt_assert(tor_addr_eq(&(expect_ap).addr, &chosen_rs_ap.addr)); \
+ tt_int_op((expect_ap).port, OP_EQ, chosen_rs_ap.port); \
+ STMT_END
+
+/* Check that fascist_firewall_choose_address_node() returns the expected
+ * results. */
+#define CHECK_CHOSEN_ADDR_NODE(fake_node, fw_connection, pref_only, \
+ expect_rv, expect_ap) \
+ STMT_BEGIN \
+ tor_addr_port_t chosen_node_ap; \
+ tor_addr_make_null(&chosen_node_ap.addr, AF_INET); \
+ chosen_node_ap.port = 0; \
+ tt_int_op(fascist_firewall_choose_address_node(&(fake_node), \
+ (fw_connection), \
+ (pref_only), \
+ &chosen_node_ap), \
+ OP_EQ, (expect_rv)); \
+ tt_assert(tor_addr_eq(&(expect_ap).addr, &chosen_node_ap.addr)); \
+ tt_int_op((expect_ap).port, OP_EQ, chosen_node_ap.port); \
+ STMT_END
+
+/* Check that fascist_firewall_choose_address_rs and
+ * fascist_firewall_choose_address_node() both return the expected results. */
+#define CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, fw_connection, pref_only, \
+ expect_rv, expect_ap) \
+ STMT_BEGIN \
+ CHECK_CHOSEN_ADDR_RS(fake_rs, fw_connection, pref_only, expect_rv, \
+ expect_ap); \
+ CHECK_CHOSEN_ADDR_NODE(fake_node, fw_connection, pref_only, expect_rv, \
+ expect_ap); \
+ STMT_END
+
+/** Run unit tests for fascist_firewall_choose_address */
+static void
+test_policies_fascist_firewall_choose_address(void *arg)
+{
+ (void)arg;
+ tor_addr_port_t ipv4_or_ap, ipv4_dir_ap, ipv6_or_ap, ipv6_dir_ap;
+ tor_addr_port_t n_ipv4_ap, n_ipv6_ap;
+
+ /* Setup the options */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ MOCK(get_options, mock_get_options);
+
+ /* Parse the addresses */
+ tor_addr_parse(&ipv4_or_ap.addr, TEST_IPV4_ADDR_STR);
+ ipv4_or_ap.port = TEST_IPV4_OR_PORT;
+ tor_addr_parse(&ipv4_dir_ap.addr, TEST_IPV4_ADDR_STR);
+ ipv4_dir_ap.port = TEST_IPV4_DIR_PORT;
+
+ tor_addr_parse(&ipv6_or_ap.addr, TEST_IPV6_ADDR_STR);
+ ipv6_or_ap.port = TEST_IPV6_OR_PORT;
+ tor_addr_parse(&ipv6_dir_ap.addr, TEST_IPV6_ADDR_STR);
+ ipv6_dir_ap.port = TEST_IPV6_DIR_PORT;
+
+ tor_addr_make_null(&n_ipv4_ap.addr, AF_INET);
+ n_ipv4_ap.port = 0;
+ tor_addr_make_null(&n_ipv6_ap.addr, AF_INET6);
+ n_ipv6_ap.port = 0;
+
+ /* Sanity check fascist_firewall_choose_address with IPv4 and IPv6 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 0;
+
+ /* Prefer IPv4 */
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 1,
+ FIREWALL_OR_CONNECTION, 0, 0)
+ == &ipv4_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 1,
+ FIREWALL_OR_CONNECTION, 1, 0)
+ == &ipv4_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_dir_ap, &ipv6_dir_ap, 1,
+ FIREWALL_DIR_CONNECTION, 0, 0)
+ == &ipv4_dir_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_dir_ap, &ipv6_dir_ap, 1,
+ FIREWALL_DIR_CONNECTION, 1, 0)
+ == &ipv4_dir_ap);
+
+ /* Prefer IPv6 */
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 0,
+ FIREWALL_OR_CONNECTION, 0, 1)
+ == &ipv6_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 0,
+ FIREWALL_OR_CONNECTION, 1, 1)
+ == &ipv6_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_dir_ap, &ipv6_dir_ap, 0,
+ FIREWALL_DIR_CONNECTION, 0, 1)
+ == &ipv6_dir_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_dir_ap, &ipv6_dir_ap, 0,
+ FIREWALL_DIR_CONNECTION, 1, 1)
+ == &ipv6_dir_ap);
+
+ /* Unusual inputs */
+
+ /* null preferred OR addresses */
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &n_ipv6_ap, 0,
+ FIREWALL_OR_CONNECTION, 0, 1)
+ == &ipv4_or_ap);
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &ipv6_or_ap, 1,
+ FIREWALL_OR_CONNECTION, 0, 0)
+ == &ipv6_or_ap);
+
+ /* null both OR addresses */
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &n_ipv6_ap, 0,
+ FIREWALL_OR_CONNECTION, 0, 1)
+ == NULL);
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &n_ipv6_ap, 1,
+ FIREWALL_OR_CONNECTION, 0, 0)
+ == NULL);
+
+ /* null preferred Dir addresses */
+ tt_assert(fascist_firewall_choose_address(&ipv4_dir_ap, &n_ipv6_ap, 0,
+ FIREWALL_DIR_CONNECTION, 0, 1)
+ == &ipv4_dir_ap);
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &ipv6_dir_ap, 1,
+ FIREWALL_DIR_CONNECTION, 0, 0)
+ == &ipv6_dir_ap);
+
+ /* null both Dir addresses */
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &n_ipv6_ap, 0,
+ FIREWALL_DIR_CONNECTION, 0, 1)
+ == NULL);
+ tt_assert(fascist_firewall_choose_address(&n_ipv4_ap, &n_ipv6_ap, 1,
+ FIREWALL_DIR_CONNECTION, 0, 0)
+ == NULL);
+
+ /* Prefer IPv4 but want IPv6 (contradictory) */
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 0,
+ FIREWALL_OR_CONNECTION, 0, 0)
+ == &ipv4_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 0,
+ FIREWALL_OR_CONNECTION, 1, 0)
+ == &ipv4_or_ap);
+
+ /* Prefer IPv6 but want IPv4 (contradictory) */
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 1,
+ FIREWALL_OR_CONNECTION, 0, 1)
+ == &ipv6_or_ap);
+ tt_assert(fascist_firewall_choose_address(&ipv4_or_ap, &ipv6_or_ap, 1,
+ FIREWALL_OR_CONNECTION, 1, 1)
+ == &ipv6_or_ap);
+
+ /* Make a fake rs. There will be no corresponding node.
+ * This is what happens when there's no consensus and we're bootstrapping
+ * from authorities / fallbacks. */
+ routerstatus_t fake_rs;
+ memset(&fake_rs, 0, sizeof(routerstatus_t));
+ /* In a routerstatus, the OR and Dir addresses are the same */
+ fake_rs.addr = tor_addr_to_ipv4h(&ipv4_or_ap.addr);
+ fake_rs.or_port = ipv4_or_ap.port;
+ fake_rs.dir_port = ipv4_dir_ap.port;
+
+ tor_addr_copy(&fake_rs.ipv6_addr, &ipv6_or_ap.addr);
+ fake_rs.ipv6_orport = ipv6_or_ap.port;
+ /* In a routerstatus, the IPv4 and IPv6 DirPorts are the same.*/
+ ipv6_dir_ap.port = TEST_IPV4_DIR_PORT;
+
+ /* Make a fake node. Even though it contains the fake_rs, a lookup won't
+ * find the node from the rs, because they're not in the hash table. */
+ node_t fake_node;
+ memset(&fake_node, 0, sizeof(node_t));
+ fake_node.rs = &fake_rs;
+
+ /* Choose an address with IPv4 and IPv6 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.UseBridges = 0;
+
+ /* Preferring IPv4 */
+ mock_options.ClientPreferIPv6ORPort = 0;
+ mock_options.ClientPreferIPv6DirPort = 0;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Auto (Preferring IPv4) */
+ mock_options.ClientPreferIPv6ORPort = -1;
+ mock_options.ClientPreferIPv6DirPort = -1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Preferring IPv6 */
+ mock_options.ClientPreferIPv6ORPort = 1;
+ mock_options.ClientPreferIPv6DirPort = 1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv6_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv6_dir_ap);
+
+ /* Preferring IPv4 OR / IPv6 Dir */
+ mock_options.ClientPreferIPv6ORPort = 0;
+ mock_options.ClientPreferIPv6DirPort = 1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv6_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv6_dir_ap);
+
+ /* Preferring IPv6 OR / IPv4 Dir */
+ mock_options.ClientPreferIPv6ORPort = 1;
+ mock_options.ClientPreferIPv6DirPort = 0;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Choose an address with UseBridges on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.UseBridges = 1;
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 1;
+
+ /* Preferring IPv4 */
+ mock_options.ClientPreferIPv6ORPort = 0;
+ mock_options.ClientPreferIPv6DirPort = 0;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Auto:
+ * - bridge clients prefer the configured bridge OR address from the node,
+ * (the configured address family sets node.ipv6_preferred)
+ * - other clients prefer IPv4 OR by default (see above),
+ * - all clients, including bridge clients, prefer IPv4 Dir by default.
+ */
+ mock_options.ClientPreferIPv6ORPort = -1;
+ mock_options.ClientPreferIPv6DirPort = -1;
+
+ /* Simulate the initialisation of fake_node.ipv6_preferred with a bridge
+ * configured with an IPv4 address */
+ fake_node.ipv6_preferred = 0;
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 0, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 1, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Simulate the initialisation of fake_node.ipv6_preferred with a bridge
+ * configured with an IPv6 address */
+ fake_node.ipv6_preferred = 1;
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 0, 1, ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 1, 1, ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* When a rs has no node, it defaults to IPv4 under auto. */
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_OR_CONNECTION, 0, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_OR_CONNECTION, 1, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_DIR_CONNECTION, 0, 1, ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_DIR_CONNECTION, 1, 1, ipv4_dir_ap);
+
+ /* Preferring IPv6 */
+ mock_options.ClientPreferIPv6ORPort = 1;
+ mock_options.ClientPreferIPv6DirPort = 1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv6_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv6_dir_ap);
+
+ /* In the default configuration (Auto / IPv6 off), bridge clients should
+ * use both IPv4 and IPv6, but only prefer IPv6 for bridges configured with
+ * an IPv6 address, regardless of ClientUseIPv6. (See above.) */
+ mock_options.ClientUseIPv6 = 0;
+ mock_options.ClientPreferIPv6ORPort = -1;
+ mock_options.ClientPreferIPv6DirPort = -1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred with a bridge
+ * configured with an IPv4 address */
+ fake_node.ipv6_preferred = 0;
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 0, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 1, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Simulate the initialisation of fake_node.ipv6_preferred with a bridge
+ * configured with an IPv6 address */
+ fake_node.ipv6_preferred = 1;
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 0, 1, ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_OR_CONNECTION, 1, 1, ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_NODE(fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* When a rs has no node, it defaults to IPv4 under auto. */
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_OR_CONNECTION, 0, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_OR_CONNECTION, 1, 1, ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_DIR_CONNECTION, 0, 1, ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RS(fake_rs, FIREWALL_DIR_CONNECTION, 1, 1, ipv4_dir_ap);
+
+ /* Choose an address with IPv4 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 1;
+ mock_options.ClientUseIPv6 = 0;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ /* Choose an address with IPv6 on */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 0;
+ mock_options.ClientUseIPv6 = 1;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv6_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv6_dir_ap);
+
+ /* Choose an address with ClientUseIPv4 0.
+ * This means "use IPv6" regardless of the other settings. */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ClientUseIPv4 = 0;
+ mock_options.ClientUseIPv6 = 0;
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv6_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv6_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv6_dir_ap);
+
+ /* Choose an address with ORPort_set 1 (server mode).
+ * This means "use IPv4" regardless of the other settings. */
+ memset(&mock_options, 0, sizeof(or_options_t));
+ mock_options.ORPort_set = 1;
+ mock_options.ClientUseIPv4 = 0;
+ mock_options.ClientUseIPv6 = 1;
+ mock_options.ClientPreferIPv6ORPort = 1;
+ mock_options.ClientPreferIPv6DirPort = 1;
+
+ /* Simulate the initialisation of fake_node.ipv6_preferred */
+ fake_node.ipv6_preferred = fascist_firewall_prefer_ipv6_orport(
+ &mock_options);
+
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 0, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_OR_CONNECTION, 1, 1,
+ ipv4_or_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 0, 1,
+ ipv4_dir_ap);
+ CHECK_CHOSEN_ADDR_RN(fake_rs, fake_node, FIREWALL_DIR_CONNECTION, 1, 1,
+ ipv4_dir_ap);
+
+ done:
+ UNMOCK(get_options);
+}
+
+#undef TEST_IPV4_ADDR_STR
+#undef TEST_IPV6_ADDR_STR
+#undef TEST_IPV4_OR_PORT
+#undef TEST_IPV4_DIR_PORT
+#undef TEST_IPV6_OR_PORT
+#undef TEST_IPV6_DIR_PORT
+
+#undef CHECK_CHOSEN_ADDR_RS
+#undef CHECK_CHOSEN_ADDR_NODE
+#undef CHECK_CHOSEN_ADDR_RN
+
struct testcase_t policy_tests[] = {
{ "router_dump_exit_policy_to_string", test_dump_exit_policy_to_string, 0,
NULL, NULL },
{ "general", test_policies_general, 0, NULL, NULL },
+ { "getinfo_helper_policies", test_policies_getinfo_helper_policies, 0, NULL,
+ NULL },
+ { "reject_exit_address", test_policies_reject_exit_address, 0, NULL, NULL },
+ { "reject_interface_address", test_policies_reject_interface_address, 0,
+ NULL, NULL },
+ { "reject_port_address", test_policies_reject_port_address, 0, NULL, NULL },
+ { "fascist_firewall_allows_address",
+ test_policies_fascist_firewall_allows_address, 0, NULL, NULL },
+ { "fascist_firewall_choose_address",
+ test_policies_fascist_firewall_choose_address, 0, NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_procmon.c b/src/test/test_procmon.c
new file mode 100644
index 0000000000..9e63fc006d
--- /dev/null
+++ b/src/test/test_procmon.c
@@ -0,0 +1,58 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define PROCMON_PRIVATE
+#include "orconfig.h"
+#include "or.h"
+#include "test.h"
+
+#include "procmon.h"
+
+#include "log_test_helpers.h"
+
+#define NS_MODULE procmon
+
+struct event_base;
+
+static void
+test_procmon_tor_process_monitor_new(void *ignored)
+{
+ (void)ignored;
+ tor_process_monitor_t *res;
+ const char *msg;
+
+ res = tor_process_monitor_new(NULL, "probably invalid", 0, NULL, NULL, &msg);
+ tt_assert(!res);
+ tt_str_op(msg, OP_EQ, "invalid PID");
+
+ res = tor_process_monitor_new(NULL, "243443535345454", 0, NULL, NULL, &msg);
+ tt_assert(!res);
+ tt_str_op(msg, OP_EQ, "invalid PID");
+
+ res = tor_process_monitor_new(tor_libevent_get_base(), "43", 0,
+ NULL, NULL, &msg);
+ tt_assert(res);
+ tt_assert(!msg);
+ tor_process_monitor_free(res);
+
+ res = tor_process_monitor_new(tor_libevent_get_base(), "44 hello", 0,
+ NULL, NULL, &msg);
+ tt_assert(res);
+ tt_assert(!msg);
+ tor_process_monitor_free(res);
+
+ res = tor_process_monitor_new(tor_libevent_get_base(), "45:hello", 0,
+ NULL, NULL, &msg);
+ tt_assert(res);
+ tt_assert(!msg);
+
+ done:
+ tor_process_monitor_free(res);
+}
+
+struct testcase_t procmon_tests[] = {
+ { "tor_process_monitor_new", test_procmon_tor_process_monitor_new,
+ TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_pt.c b/src/test/test_pt.c
index f71627df1e..ab8447dcd7 100644
--- a/src/test/test_pt.c
+++ b/src/test/test_pt.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -27,75 +27,76 @@ reset_mp(managed_proxy_t *mp)
}
static void
-test_pt_parsing(void)
+test_pt_parsing(void *arg)
{
char line[200];
transport_t *transport = NULL;
tor_addr_t test_addr;
- managed_proxy_t *mp = tor_malloc(sizeof(managed_proxy_t));
+ managed_proxy_t *mp = tor_malloc_zero(sizeof(managed_proxy_t));
+ (void)arg;
mp->conf_state = PT_PROTO_INFANT;
mp->transports = smartlist_new();
/* incomplete cmethod */
strlcpy(line,"CMETHOD trebuchet",sizeof(line));
- test_assert(parse_cmethod_line(line, mp) < 0);
+ tt_assert(parse_cmethod_line(line, mp) < 0);
reset_mp(mp);
/* wrong proxy type */
strlcpy(line,"CMETHOD trebuchet dog 127.0.0.1:1999",sizeof(line));
- test_assert(parse_cmethod_line(line, mp) < 0);
+ tt_assert(parse_cmethod_line(line, mp) < 0);
reset_mp(mp);
/* wrong addrport */
strlcpy(line,"CMETHOD trebuchet socks4 abcd",sizeof(line));
- test_assert(parse_cmethod_line(line, mp) < 0);
+ tt_assert(parse_cmethod_line(line, mp) < 0);
reset_mp(mp);
/* correct line */
strlcpy(line,"CMETHOD trebuchet socks5 127.0.0.1:1999",sizeof(line));
- test_assert(parse_cmethod_line(line, mp) == 0);
- test_assert(smartlist_len(mp->transports) == 1);
+ tt_assert(parse_cmethod_line(line, mp) == 0);
+ tt_assert(smartlist_len(mp->transports) == 1);
transport = smartlist_get(mp->transports, 0);
/* test registered address of transport */
tor_addr_parse(&test_addr, "127.0.0.1");
- test_assert(tor_addr_eq(&test_addr, &transport->addr));
+ tt_assert(tor_addr_eq(&test_addr, &transport->addr));
/* test registered port of transport */
- test_assert(transport->port == 1999);
+ tt_assert(transport->port == 1999);
/* test registered SOCKS version of transport */
- test_assert(transport->socks_version == PROXY_SOCKS5);
+ tt_assert(transport->socks_version == PROXY_SOCKS5);
/* test registered name of transport */
- test_streq(transport->name, "trebuchet");
+ tt_str_op(transport->name,OP_EQ, "trebuchet");
reset_mp(mp);
/* incomplete smethod */
strlcpy(line,"SMETHOD trebuchet",sizeof(line));
- test_assert(parse_smethod_line(line, mp) < 0);
+ tt_assert(parse_smethod_line(line, mp) < 0);
reset_mp(mp);
/* wrong addr type */
strlcpy(line,"SMETHOD trebuchet abcd",sizeof(line));
- test_assert(parse_smethod_line(line, mp) < 0);
+ tt_assert(parse_smethod_line(line, mp) < 0);
reset_mp(mp);
/* cowwect */
strlcpy(line,"SMETHOD trebuchy 127.0.0.2:2999",sizeof(line));
- test_assert(parse_smethod_line(line, mp) == 0);
- test_assert(smartlist_len(mp->transports) == 1);
+ tt_assert(parse_smethod_line(line, mp) == 0);
+ tt_assert(smartlist_len(mp->transports) == 1);
transport = smartlist_get(mp->transports, 0);
/* test registered address of transport */
tor_addr_parse(&test_addr, "127.0.0.2");
- test_assert(tor_addr_eq(&test_addr, &transport->addr));
+ tt_assert(tor_addr_eq(&test_addr, &transport->addr));
/* test registered port of transport */
- test_assert(transport->port == 2999);
+ tt_assert(transport->port == 2999);
/* test registered name of transport */
- test_streq(transport->name, "trebuchy");
+ tt_str_op(transport->name,OP_EQ, "trebuchy");
reset_mp(mp);
@@ -103,30 +104,30 @@ test_pt_parsing(void)
strlcpy(line,"SMETHOD trebuchet 127.0.0.1:9999 "
"ARGS:counterweight=3,sling=snappy",
sizeof(line));
- test_assert(parse_smethod_line(line, mp) == 0);
- tt_int_op(1, ==, smartlist_len(mp->transports));
+ tt_assert(parse_smethod_line(line, mp) == 0);
+ tt_int_op(1, OP_EQ, smartlist_len(mp->transports));
{
const transport_t *transport = smartlist_get(mp->transports, 0);
tt_assert(transport);
- tt_str_op(transport->name, ==, "trebuchet");
- tt_int_op(transport->port, ==, 9999);
- tt_str_op(fmt_addr(&transport->addr), ==, "127.0.0.1");
- tt_str_op(transport->extra_info_args, ==,
+ tt_str_op(transport->name, OP_EQ, "trebuchet");
+ tt_int_op(transport->port, OP_EQ, 9999);
+ tt_str_op(fmt_addr(&transport->addr), OP_EQ, "127.0.0.1");
+ tt_str_op(transport->extra_info_args, OP_EQ,
"counterweight=3,sling=snappy");
}
reset_mp(mp);
/* unsupported version */
strlcpy(line,"VERSION 666",sizeof(line));
- test_assert(parse_version(line, mp) < 0);
+ tt_assert(parse_version(line, mp) < 0);
/* incomplete VERSION */
strlcpy(line,"VERSION ",sizeof(line));
- test_assert(parse_version(line, mp) < 0);
+ tt_assert(parse_version(line, mp) < 0);
/* correct VERSION */
strlcpy(line,"VERSION 1",sizeof(line));
- test_assert(parse_version(line, mp) == 0);
+ tt_assert(parse_version(line, mp) == 0);
done:
reset_mp(mp);
@@ -150,9 +151,9 @@ test_pt_get_transport_options(void *arg)
execve_args[1] = NULL;
mp = managed_proxy_create(transport_list, execve_args, 1);
- tt_ptr_op(mp, !=, NULL);
+ tt_ptr_op(mp, OP_NE, NULL);
opt_str = get_transport_options_for_server_proxy(mp);
- tt_ptr_op(opt_str, ==, NULL);
+ tt_ptr_op(opt_str, OP_EQ, NULL);
smartlist_add(mp->transports_to_launch, tor_strdup("gruyere"));
smartlist_add(mp->transports_to_launch, tor_strdup("roquefort"));
@@ -175,7 +176,7 @@ test_pt_get_transport_options(void *arg)
options->ServerTransportOptions = cl;
opt_str = get_transport_options_for_server_proxy(mp);
- tt_str_op(opt_str, ==,
+ tt_str_op(opt_str, OP_EQ,
"gruyere:melty=10;gruyere:hardness=se\\;ven;"
"stnectaire:melty=4;stnectaire:hardness=three");
@@ -187,46 +188,47 @@ test_pt_get_transport_options(void *arg)
}
static void
-test_pt_protocol(void)
+test_pt_protocol(void *arg)
{
char line[200];
managed_proxy_t *mp = tor_malloc_zero(sizeof(managed_proxy_t));
+ (void)arg;
mp->conf_state = PT_PROTO_LAUNCHED;
mp->transports = smartlist_new();
- mp->argv = tor_malloc_zero(sizeof(char*)*2);
+ mp->argv = tor_calloc(2, sizeof(char *));
mp->argv[0] = tor_strdup("<testcase>");
/* various wrong protocol runs: */
strlcpy(line,"VERSION 1",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
+ tt_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
strlcpy(line,"VERSION 1",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_BROKEN);
+ tt_assert(mp->conf_state == PT_PROTO_BROKEN);
reset_mp(mp);
strlcpy(line,"CMETHOD trebuchet socks5 127.0.0.1:1999",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_BROKEN);
+ tt_assert(mp->conf_state == PT_PROTO_BROKEN);
reset_mp(mp);
/* correct protocol run: */
strlcpy(line,"VERSION 1",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
+ tt_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
strlcpy(line,"CMETHOD trebuchet socks5 127.0.0.1:1999",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
+ tt_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
strlcpy(line,"CMETHODS DONE",sizeof(line));
handle_proxy_line(line, mp);
- test_assert(mp->conf_state == PT_PROTO_CONFIGURED);
+ tt_assert(mp->conf_state == PT_PROTO_CONFIGURED);
done:
reset_mp(mp);
@@ -260,17 +262,17 @@ test_pt_get_extrainfo_string(void *arg)
mp2 = managed_proxy_create(t2, argv2, 1);
r = parse_smethod_line("SMETHOD hagbard 127.0.0.1:5555", mp1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
r = parse_smethod_line("SMETHOD celine 127.0.0.1:1723 ARGS:card=no-enemy",
mp2);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
/* Force these proxies to look "completed" or they won't generate output. */
mp1->conf_state = mp2->conf_state = PT_PROTO_COMPLETED;
s = pt_get_extra_info_descriptor_string();
tt_assert(s);
- tt_str_op(s, ==,
+ tt_str_op(s, OP_EQ,
"transport hagbard 127.0.0.1:5555\n"
"transport celine 127.0.0.1:1723 card=no-enemy\n");
@@ -331,15 +333,13 @@ static uint16_t controlevent_event = 0;
static smartlist_t *controlevent_msgs = NULL;
static void
-send_control_event_string_replacement(uint16_t event, event_format_t which,
- const char *msg)
+queue_control_event_string_replacement(uint16_t event, char *msg)
{
- (void) which;
++controlevent_n;
controlevent_event = event;
if (!controlevent_msgs)
controlevent_msgs = smartlist_new();
- smartlist_add(controlevent_msgs, tor_strdup(msg));
+ smartlist_add(controlevent_msgs, msg);
}
/* Test the configure_proxy() function. */
@@ -358,12 +358,12 @@ test_pt_configure_proxy(void *arg)
tor_process_handle_destroy_replacement);
MOCK(get_or_state,
get_or_state_replacement);
- MOCK(send_control_event_string,
- send_control_event_string_replacement);
+ MOCK(queue_control_event_string,
+ queue_control_event_string_replacement);
control_testing_set_global_event_mask(EVENT_TRANSPORT_LAUNCHED);
- mp = tor_malloc(sizeof(managed_proxy_t));
+ mp = tor_malloc_zero(sizeof(managed_proxy_t));
mp->conf_state = PT_PROTO_ACCEPTING_METHODS;
mp->transports = smartlist_new();
mp->transports_to_launch = smartlist_new();
@@ -378,33 +378,33 @@ test_pt_configure_proxy(void *arg)
for (i = 0 ; i < 5 ; i++) {
retval = configure_proxy(mp);
/* retval should be zero because proxy hasn't finished configuring yet */
- test_assert(retval == 0);
+ tt_int_op(retval, OP_EQ, 0);
/* check the number of registered transports */
- test_assert(smartlist_len(mp->transports) == i+1);
+ tt_assert(smartlist_len(mp->transports) == i+1);
/* check that the mp is still waiting for transports */
- test_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
+ tt_assert(mp->conf_state == PT_PROTO_ACCEPTING_METHODS);
}
/* this last configure_proxy() should finalize the proxy configuration. */
retval = configure_proxy(mp);
/* retval should be 1 since the proxy finished configuring */
- test_assert(retval == 1);
+ tt_int_op(retval, OP_EQ, 1);
/* check the mp state */
- test_assert(mp->conf_state == PT_PROTO_COMPLETED);
+ tt_assert(mp->conf_state == PT_PROTO_COMPLETED);
- tt_int_op(controlevent_n, ==, 5);
- tt_int_op(controlevent_event, ==, EVENT_TRANSPORT_LAUNCHED);
- tt_int_op(smartlist_len(controlevent_msgs), ==, 5);
+ tt_int_op(controlevent_n, OP_EQ, 5);
+ tt_int_op(controlevent_event, OP_EQ, EVENT_TRANSPORT_LAUNCHED);
+ tt_int_op(smartlist_len(controlevent_msgs), OP_EQ, 5);
smartlist_sort_strings(controlevent_msgs);
- tt_str_op(smartlist_get(controlevent_msgs, 0), ==,
+ tt_str_op(smartlist_get(controlevent_msgs, 0), OP_EQ,
"650 TRANSPORT_LAUNCHED server mock1 127.0.0.1 5551\r\n");
- tt_str_op(smartlist_get(controlevent_msgs, 1), ==,
+ tt_str_op(smartlist_get(controlevent_msgs, 1), OP_EQ,
"650 TRANSPORT_LAUNCHED server mock2 127.0.0.1 5552\r\n");
- tt_str_op(smartlist_get(controlevent_msgs, 2), ==,
+ tt_str_op(smartlist_get(controlevent_msgs, 2), OP_EQ,
"650 TRANSPORT_LAUNCHED server mock3 127.0.0.1 5553\r\n");
- tt_str_op(smartlist_get(controlevent_msgs, 3), ==,
+ tt_str_op(smartlist_get(controlevent_msgs, 3), OP_EQ,
"650 TRANSPORT_LAUNCHED server mock4 127.0.0.1 5554\r\n");
- tt_str_op(smartlist_get(controlevent_msgs, 4), ==,
+ tt_str_op(smartlist_get(controlevent_msgs, 4), OP_EQ,
"650 TRANSPORT_LAUNCHED server mock5 127.0.0.1 5555\r\n");
{ /* check that the transport info were saved properly in the tor state */
@@ -416,13 +416,13 @@ test_pt_configure_proxy(void *arg)
/* Get the bindaddr for "mock1" and check it against the bindaddr
that the mocked tor_get_lines_from_handle() generated. */
transport_in_state = get_transport_in_state_by_name("mock1");
- test_assert(transport_in_state);
+ tt_assert(transport_in_state);
smartlist_split_string(transport_info_sl, transport_in_state->value,
NULL, 0, 0);
name_of_transport = smartlist_get(transport_info_sl, 0);
bindaddr = smartlist_get(transport_info_sl, 1);
- tt_str_op(name_of_transport, ==, "mock1");
- tt_str_op(bindaddr, ==, "127.0.0.1:5551");
+ tt_str_op(name_of_transport, OP_EQ, "mock1");
+ tt_str_op(bindaddr, OP_EQ, "127.0.0.1:5551");
SMARTLIST_FOREACH(transport_info_sl, char *, cp, tor_free(cp));
smartlist_free(transport_info_sl);
@@ -433,7 +433,7 @@ test_pt_configure_proxy(void *arg)
UNMOCK(tor_get_lines_from_handle);
UNMOCK(tor_process_handle_destroy);
UNMOCK(get_or_state);
- UNMOCK(send_control_event_string);
+ UNMOCK(queue_control_event_string);
if (controlevent_msgs) {
SMARTLIST_FOREACH(controlevent_msgs, char *, cp, tor_free(cp));
smartlist_free(controlevent_msgs);
@@ -450,8 +450,86 @@ test_pt_configure_proxy(void *arg)
tor_free(mp);
}
+/* Test the get_pt_proxy_uri() function. */
+static void
+test_get_pt_proxy_uri(void *arg)
+{
+ or_options_t *options = get_options_mutable();
+ char *uri = NULL;
+ int ret;
+ (void) arg;
+
+ /* Test with no proxy. */
+ uri = get_pt_proxy_uri();
+ tt_assert(uri == NULL);
+
+ /* Test with a SOCKS4 proxy. */
+ options->Socks4Proxy = tor_strdup("192.0.2.1:1080");
+ ret = tor_addr_port_lookup(options->Socks4Proxy,
+ &options->Socks4ProxyAddr,
+ &options->Socks4ProxyPort);
+ tt_int_op(ret, OP_EQ, 0);
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "socks4a://192.0.2.1:1080");
+ tor_free(uri);
+ tor_free(options->Socks4Proxy);
+
+ /* Test with a SOCKS5 proxy, no username/password. */
+ options->Socks5Proxy = tor_strdup("192.0.2.1:1080");
+ ret = tor_addr_port_lookup(options->Socks5Proxy,
+ &options->Socks5ProxyAddr,
+ &options->Socks5ProxyPort);
+ tt_int_op(ret, OP_EQ, 0);
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "socks5://192.0.2.1:1080");
+ tor_free(uri);
+
+ /* Test with a SOCKS5 proxy, with username/password. */
+ options->Socks5ProxyUsername = tor_strdup("hwest");
+ options->Socks5ProxyPassword = tor_strdup("r34n1m470r");
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "socks5://hwest:r34n1m470r@192.0.2.1:1080");
+ tor_free(uri);
+ tor_free(options->Socks5Proxy);
+ tor_free(options->Socks5ProxyUsername);
+ tor_free(options->Socks5ProxyPassword);
+
+ /* Test with a HTTPS proxy, no authenticator. */
+ options->HTTPSProxy = tor_strdup("192.0.2.1:80");
+ ret = tor_addr_port_lookup(options->HTTPSProxy,
+ &options->HTTPSProxyAddr,
+ &options->HTTPSProxyPort);
+ tt_int_op(ret, OP_EQ, 0);
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "http://192.0.2.1:80");
+ tor_free(uri);
+
+ /* Test with a HTTPS proxy, with authenticator. */
+ options->HTTPSProxyAuthenticator = tor_strdup("hwest:r34n1m470r");
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "http://hwest:r34n1m470r@192.0.2.1:80");
+ tor_free(uri);
+ tor_free(options->HTTPSProxy);
+ tor_free(options->HTTPSProxyAuthenticator);
+
+ /* Token nod to the fact that IPv6 exists. */
+ options->Socks4Proxy = tor_strdup("[2001:db8::1]:1080");
+ ret = tor_addr_port_lookup(options->Socks4Proxy,
+ &options->Socks4ProxyAddr,
+ &options->Socks4ProxyPort);
+ tt_int_op(ret, OP_EQ, 0);
+ uri = get_pt_proxy_uri();
+ tt_str_op(uri, OP_EQ, "socks4a://[2001:db8::1]:1080");
+ tor_free(uri);
+ tor_free(options->Socks4Proxy);
+
+ done:
+ if (uri)
+ tor_free(uri);
+}
+
#define PT_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_pt_ ## name }
+ { #name, test_pt_ ## name , 0, NULL, NULL }
struct testcase_t pt_tests[] = {
PT_LEGACY(parsing),
@@ -462,6 +540,8 @@ struct testcase_t pt_tests[] = {
NULL, NULL },
{ "configure_proxy",test_pt_configure_proxy, TT_FORK,
NULL, NULL },
+ { "get_pt_proxy_uri", test_get_pt_proxy_uri, TT_FORK,
+ NULL, NULL },
END_OF_TESTCASES
};
diff --git a/src/test/test_relay.c b/src/test/test_relay.c
new file mode 100644
index 0000000000..a7fcad5401
--- /dev/null
+++ b/src/test/test_relay.c
@@ -0,0 +1,126 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+#define CIRCUITBUILD_PRIVATE
+#include "circuitbuild.h"
+#define RELAY_PRIVATE
+#include "relay.h"
+/* For init/free stuff */
+#include "scheduler.h"
+
+/* Test suite stuff */
+#include "test.h"
+#include "fakechans.h"
+
+static or_circuit_t * new_fake_orcirc(channel_t *nchan, channel_t *pchan);
+
+static void test_relay_append_cell_to_circuit_queue(void *arg);
+
+static or_circuit_t *
+new_fake_orcirc(channel_t *nchan, channel_t *pchan)
+{
+ or_circuit_t *orcirc = NULL;
+ circuit_t *circ = NULL;
+
+ orcirc = tor_malloc_zero(sizeof(*orcirc));
+ circ = &(orcirc->base_);
+ circ->magic = OR_CIRCUIT_MAGIC;
+
+ circ->n_chan = nchan;
+ circ->n_circ_id = get_unique_circ_id_by_chan(nchan);
+ circ->n_mux = NULL; /* ?? */
+ cell_queue_init(&(circ->n_chan_cells));
+ circ->n_hop = NULL;
+ circ->streams_blocked_on_n_chan = 0;
+ circ->streams_blocked_on_p_chan = 0;
+ circ->n_delete_pending = 0;
+ circ->p_delete_pending = 0;
+ circ->received_destroy = 0;
+ circ->state = CIRCUIT_STATE_OPEN;
+ circ->purpose = CIRCUIT_PURPOSE_OR;
+ circ->package_window = CIRCWINDOW_START_MAX;
+ circ->deliver_window = CIRCWINDOW_START_MAX;
+ circ->n_chan_create_cell = NULL;
+
+ orcirc->p_chan = pchan;
+ orcirc->p_circ_id = get_unique_circ_id_by_chan(pchan);
+ cell_queue_init(&(orcirc->p_chan_cells));
+
+ return orcirc;
+}
+
+static void
+test_relay_append_cell_to_circuit_queue(void *arg)
+{
+ channel_t *nchan = NULL, *pchan = NULL;
+ or_circuit_t *orcirc = NULL;
+ cell_t *cell = NULL;
+ int old_count, new_count;
+
+ (void)arg;
+
+ /* Make fake channels to be nchan and pchan for the circuit */
+ nchan = new_fake_channel();
+ tt_assert(nchan);
+
+ pchan = new_fake_channel();
+ tt_assert(pchan);
+
+ /* We'll need chans with working cmuxes */
+ nchan->cmux = circuitmux_alloc();
+ pchan->cmux = circuitmux_alloc();
+
+ /* Make a fake orcirc */
+ orcirc = new_fake_orcirc(nchan, pchan);
+ tt_assert(orcirc);
+
+ /* Make a cell */
+ cell = tor_malloc_zero(sizeof(cell_t));
+ make_fake_cell(cell);
+
+ MOCK(scheduler_channel_has_waiting_cells,
+ scheduler_channel_has_waiting_cells_mock);
+
+ /* Append it */
+ old_count = get_mock_scheduler_has_waiting_cells_count();
+ append_cell_to_circuit_queue(TO_CIRCUIT(orcirc), nchan, cell,
+ CELL_DIRECTION_OUT, 0);
+ new_count = get_mock_scheduler_has_waiting_cells_count();
+ tt_int_op(new_count, ==, old_count + 1);
+
+ /* Now try the reverse direction */
+ old_count = get_mock_scheduler_has_waiting_cells_count();
+ append_cell_to_circuit_queue(TO_CIRCUIT(orcirc), pchan, cell,
+ CELL_DIRECTION_IN, 0);
+ new_count = get_mock_scheduler_has_waiting_cells_count();
+ tt_int_op(new_count, ==, old_count + 1);
+
+ UNMOCK(scheduler_channel_has_waiting_cells);
+
+ /* Get rid of the fake channels */
+ MOCK(scheduler_release_channel, scheduler_release_channel_mock);
+ channel_mark_for_close(nchan);
+ channel_mark_for_close(pchan);
+ UNMOCK(scheduler_release_channel);
+
+ /* Shut down channels */
+ channel_free_all();
+
+ done:
+ tor_free(cell);
+ cell_queue_clear(&orcirc->base_.n_chan_cells);
+ cell_queue_clear(&orcirc->p_chan_cells);
+ tor_free(orcirc);
+ free_fake_channel(nchan);
+ free_fake_channel(pchan);
+
+ return;
+}
+
+struct testcase_t relay_tests[] = {
+ { "append_cell_to_circuit_queue", test_relay_append_cell_to_circuit_queue,
+ TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_relaycell.c b/src/test/test_relaycell.c
index 9aff6ab49e..1cd9ff064b 100644
--- a/src/test/test_relaycell.c
+++ b/src/test/test_relaycell.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2014, The Tor Project, Inc. */
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/* Unit tests for handling different kinds of relay cell */
@@ -87,24 +87,24 @@ test_relaycell_resolved(void *arg)
srm_ncalls = mum_ncalls = 0; \
} while (0)
#define ASSERT_MARK_CALLED(reason) do { \
- tt_int_op(mum_ncalls, ==, 1); \
- tt_ptr_op(mum_conn, ==, entryconn); \
- tt_int_op(mum_endreason, ==, (reason)); \
+ tt_int_op(mum_ncalls, OP_EQ, 1); \
+ tt_ptr_op(mum_conn, OP_EQ, entryconn); \
+ tt_int_op(mum_endreason, OP_EQ, (reason)); \
} while (0)
#define ASSERT_RESOLVED_CALLED(atype, answer, ttl, expires) do { \
- tt_int_op(srm_ncalls, ==, 1); \
- tt_ptr_op(srm_conn, ==, entryconn); \
- tt_int_op(srm_atype, ==, (atype)); \
+ tt_int_op(srm_ncalls, OP_EQ, 1); \
+ tt_ptr_op(srm_conn, OP_EQ, entryconn); \
+ tt_int_op(srm_atype, OP_EQ, (atype)); \
if (answer) { \
- tt_int_op(srm_alen, ==, sizeof(answer)-1); \
- tt_int_op(srm_alen, <, 512); \
- tt_int_op(srm_answer_is_set, ==, 1); \
- tt_mem_op(srm_answer, ==, answer, sizeof(answer)-1); \
+ tt_int_op(srm_alen, OP_EQ, sizeof(answer)-1); \
+ tt_int_op(srm_alen, OP_LT, 512); \
+ tt_int_op(srm_answer_is_set, OP_EQ, 1); \
+ tt_mem_op(srm_answer, OP_EQ, answer, sizeof(answer)-1); \
} else { \
- tt_int_op(srm_answer_is_set, ==, 0); \
+ tt_int_op(srm_answer_is_set, OP_EQ, 0); \
} \
- tt_int_op(srm_ttl, ==, ttl); \
- tt_i64_op((int64_t)srm_expires, ==, (int64_t)expires); \
+ tt_int_op(srm_ttl, OP_EQ, ttl); \
+ tt_i64_op(srm_expires, OP_EQ, expires); \
} while (0)
(void)arg;
@@ -130,21 +130,21 @@ test_relaycell_resolved(void *arg)
/* Try with connection in non-RESOLVE_WAIT state: cell gets ignored */
MOCK_RESET();
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
- tt_int_op(srm_ncalls, ==, 0);
- tt_int_op(mum_ncalls, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(srm_ncalls, OP_EQ, 0);
+ tt_int_op(mum_ncalls, OP_EQ, 0);
/* Now put it in the right state. */
ENTRY_TO_CONN(entryconn)->state = AP_CONN_STATE_RESOLVE_WAIT;
entryconn->socks_request->command = SOCKS_COMMAND_RESOLVE;
- entryconn->ipv4_traffic_ok = 1;
- entryconn->ipv6_traffic_ok = 1;
- entryconn->prefer_ipv6_traffic = 0;
+ entryconn->entry_cfg.ipv4_traffic = 1;
+ entryconn->entry_cfg.ipv6_traffic = 1;
+ entryconn->entry_cfg.prefer_ipv6 = 0;
/* We prefer ipv4, so we should get the first ipv4 answer */
MOCK_RESET();
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_IPV4, "\x7f\x00\x01\x02", 256, -1);
@@ -153,16 +153,16 @@ test_relaycell_resolved(void *arg)
MOCK_RESET();
options->ClientDNSRejectInternalAddresses = 1;
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_IPV4, "\x12\x00\x00\x01", 512, -1);
/* now prefer ipv6, and get the first ipv6 answer */
- entryconn->prefer_ipv6_traffic = 1;
+ entryconn->entry_cfg.prefer_ipv6 = 1;
MOCK_RESET();
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_IPV6,
@@ -174,7 +174,7 @@ test_relaycell_resolved(void *arg)
MOCK_RESET();
SET_CELL("\x04\x04\x12\x00\x00\x01\x00\x00\x02\x00");
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_IPV4, "\x12\x00\x00\x01", 512, -1);
@@ -182,19 +182,19 @@ test_relaycell_resolved(void *arg)
/* But if we don't allow IPv4, we report nothing if the cell contains only
* ipv4 */
MOCK_RESET();
- entryconn->ipv4_traffic_ok = 0;
+ entryconn->entry_cfg.ipv4_traffic = 0;
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_ERROR, NULL, -1, -1);
/* If we wanted hostnames, we report nothing, since we only had IPs. */
MOCK_RESET();
- entryconn->ipv4_traffic_ok = 1;
+ entryconn->entry_cfg.ipv4_traffic = 1;
entryconn->socks_request->command = SOCKS_COMMAND_RESOLVE_PTR;
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_ERROR, NULL, -1, -1);
@@ -203,7 +203,7 @@ test_relaycell_resolved(void *arg)
MOCK_RESET();
SET_CELL("\x00\x0fwww.example.com\x00\x01\x00\x00");
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_HOSTNAME, "www.example.com", 65536, -1);
@@ -213,9 +213,9 @@ test_relaycell_resolved(void *arg)
entryconn->socks_request->command = SOCKS_COMMAND_RESOLVE;
SET_CELL("\x04\x04\x01\x02\x03\x04"); /* no ttl */
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_TORPROTOCOL);
- tt_int_op(srm_ncalls, ==, 0);
+ tt_int_op(srm_ncalls, OP_EQ, 0);
/* error on all addresses private */
MOCK_RESET();
@@ -224,7 +224,7 @@ test_relaycell_resolved(void *arg)
/* IPv4: 192.168.1.1, ttl 256 */
"\x04\x04\xc0\xa8\x01\x01\x00\x00\x01\x00");
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_TORPROTOCOL);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_ERROR_TRANSIENT, NULL, 0, TIME_MAX);
@@ -232,7 +232,7 @@ test_relaycell_resolved(void *arg)
MOCK_RESET();
SET_CELL("\xf0\x15" "quiet and meaningless" "\x00\x00\x0f\xff");
r = connection_edge_process_resolved_cell(edgeconn, &cell, &rh);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
ASSERT_MARK_CALLED(END_STREAM_REASON_DONE|
END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
ASSERT_RESOLVED_CALLED(RESOLVED_TYPE_ERROR_TRANSIENT, NULL, -1, -1);
diff --git a/src/test/test_rendcache.c b/src/test/test_rendcache.c
new file mode 100644
index 0000000000..d1b52649b2
--- /dev/null
+++ b/src/test/test_rendcache.c
@@ -0,0 +1,1269 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#include "or.h"
+
+#include "test.h"
+#define RENDCACHE_PRIVATE
+#include "rendcache.h"
+#include "router.h"
+#include "routerlist.h"
+#include "config.h"
+#include <openssl/rsa.h>
+#include "rend_test_helpers.h"
+
+#define NS_MODULE rend_cache
+
+static const int RECENT_TIME = -10;
+static const int TIME_IN_THE_PAST = -(REND_CACHE_MAX_AGE + \
+ REND_CACHE_MAX_SKEW + 10);
+static const int TIME_IN_THE_FUTURE = REND_CACHE_MAX_SKEW + 10;
+
+extern strmap_t *rend_cache;
+extern digestmap_t *rend_cache_v2_dir;
+extern strmap_t *rend_cache_failure;
+extern size_t rend_cache_total_allocation;
+
+static rend_data_t *
+mock_rend_data(const char *onion_address)
+{
+ rend_data_t *rend_query = tor_malloc_zero(sizeof(rend_data_t));
+
+ strlcpy(rend_query->onion_address, onion_address,
+ sizeof(rend_query->onion_address));
+ rend_query->auth_type = REND_NO_AUTH;
+ rend_query->hsdirs_fp = smartlist_new();
+ smartlist_add(rend_query->hsdirs_fp, tor_memdup("aaaaaaaaaaaaaaaaaaaaaaaa",
+ DIGEST_LEN));
+
+ return rend_query;
+}
+
+static void
+test_rend_cache_lookup_entry(void *data)
+{
+ int ret;
+ rend_data_t *mock_rend_query = NULL;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
+ rend_cache_entry_t *entry = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
+ char *service_id = NULL;
+ (void)data;
+
+ rend_cache_init();
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+
+ ret = rend_cache_lookup_entry("abababababababab", 0, NULL);
+ tt_int_op(ret, OP_EQ, -ENOENT);
+
+ ret = rend_cache_lookup_entry("invalid query", 2, NULL);
+ tt_int_op(ret, OP_EQ, -EINVAL);
+
+ ret = rend_cache_lookup_entry("abababababababab", 2, NULL);
+ tt_int_op(ret, OP_EQ, -ENOENT);
+
+ ret = rend_cache_lookup_entry("abababababababab", 4224, NULL);
+ tt_int_op(ret, OP_EQ, -ENOENT);
+
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ rend_cache_store_v2_desc_as_client(desc_holder->desc_str, desc_id_base32,
+ mock_rend_query, NULL);
+
+ ret = rend_cache_lookup_entry(service_id, 2, NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ret = rend_cache_lookup_entry(service_id, 2, &entry);
+ tt_assert(entry);
+ tt_int_op(entry->len, OP_EQ, strlen(desc_holder->desc_str));
+ tt_str_op(entry->desc, OP_EQ, desc_holder->desc_str);
+
+ done:
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_cache_free_all();
+ rend_data_free(mock_rend_query);
+}
+
+static void
+test_rend_cache_store_v2_desc_as_client(void *data)
+{
+ int ret;
+ rend_data_t *mock_rend_query;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
+ rend_cache_entry_t *entry = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
+ char *service_id = NULL;
+ char client_cookie[REND_DESC_COOKIE_LEN];
+ (void)data;
+
+ rend_cache_init();
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+
+ // Test success
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ &entry);
+
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(entry);
+ tt_int_op(entry->len, OP_EQ, strlen(desc_holder->desc_str));
+ tt_str_op(entry->desc, OP_EQ, desc_holder->desc_str);
+
+ // Test various failure modes
+
+ // TODO: a too long desc_id_base32 argument crashes the function
+ /* ret = rend_cache_store_v2_desc_as_client( */
+ /* desc_holder->desc_str, */
+ /* "3TOOLONG3TOOLONG3TOOLONG3TOOLONG3TOOLONG3TOOLONG", */
+ /* &mock_rend_query, NULL); */
+ /* tt_int_op(ret, OP_EQ, -1); */
+
+ // Test bad base32 failure
+ // This causes an assertion failure if we're running with assertions.
+ // But when building without asserts, we can test it.
+#ifdef DISABLE_ASSERTS_IN_UNIT_TESTS
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ "!xqunszqnaolrrfmtzgaki7mxelgvkj", mock_rend_query, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+#endif
+
+ // Test invalid descriptor
+ ret = rend_cache_store_v2_desc_as_client("invalid descriptor",
+ "3xqunszqnaolrrfmtzgaki7mxelgvkje", mock_rend_query, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // TODO: it doesn't seem to be possible to test invalid service ID condition.
+ // that means it is likely not possible to have that condition without
+ // earlier conditions failing first (such as signature checking of the desc)
+
+ rend_cache_free_all();
+
+ // Test mismatch between service ID and onion address
+ rend_cache_init();
+ strncpy(mock_rend_query->onion_address, "abc", REND_SERVICE_ID_LEN_BASE32+1);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32,
+ mock_rend_query, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+ rend_cache_free_all();
+ rend_data_free(mock_rend_query);
+
+ // Test incorrect descriptor ID
+ rend_cache_init();
+ mock_rend_query = mock_rend_data(service_id);
+ desc_id_base32[0]++;
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, -1);
+ desc_id_base32[0]--;
+ rend_cache_free_all();
+
+ // Test too old descriptor
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(TIME_IN_THE_PAST, &desc_holder, &service_id, 3);
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32,
+ mock_rend_query, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+ rend_cache_free_all();
+
+ // Test too new descriptor (in the future)
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(TIME_IN_THE_FUTURE, &desc_holder, &service_id, 3);
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, -1);
+ rend_cache_free_all();
+
+ // Test when a descriptor is already in the cache
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+
+ rend_cache_store_v2_desc_as_client(desc_holder->desc_str, desc_id_base32,
+ mock_rend_query, NULL);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ &entry);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(entry);
+ rend_cache_free_all();
+
+ // Test unsuccessful decrypting of introduction points
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+ mock_rend_query = mock_rend_data(service_id);
+ mock_rend_query->auth_type = REND_BASIC_AUTH;
+ client_cookie[0] = 'A';
+ memcpy(mock_rend_query->descriptor_cookie, client_cookie,
+ REND_DESC_COOKIE_LEN);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+ rend_cache_free_all();
+
+ // Test successful run when we have REND_BASIC_AUTH but not cookie
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+ mock_rend_query = mock_rend_data(service_id);
+ mock_rend_query->auth_type = REND_BASIC_AUTH;
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ rend_cache_free_all();
+
+ // Test when we have no introduction points
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 0);
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, -1);
+ rend_cache_free_all();
+
+ // Test when we have too many intro points
+ rend_cache_init();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_data_free(mock_rend_query);
+
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, MAX_INTRO_POINTS+1);
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ done:
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_cache_free_all();
+ rend_data_free(mock_rend_query);
+}
+
+static void
+test_rend_cache_store_v2_desc_as_client_with_different_time(void *data)
+{
+ int ret;
+ rend_data_t *mock_rend_query;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
+ rend_service_descriptor_t *generated = NULL;
+ smartlist_t *descs = smartlist_new();
+ time_t t;
+ char *service_id = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder_newer;
+ rend_encoded_v2_service_descriptor_t *desc_holder_older;
+
+ t = time(NULL);
+ rend_cache_init();
+
+ create_descriptor(&generated, &service_id, 3);
+
+ generated->timestamp = t + RECENT_TIME;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_newer = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ descs = smartlist_new();
+
+ generated->timestamp = (t + RECENT_TIME) - 20;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_older = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+ (void)data;
+
+ // Test when a descriptor is already in the cache and it is newer than the
+ // one we submit
+ mock_rend_query = mock_rend_data(service_id);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32),
+ desc_holder_newer->desc_id, DIGEST_LEN);
+ rend_cache_store_v2_desc_as_client(desc_holder_newer->desc_str,
+ desc_id_base32, mock_rend_query, NULL);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder_older->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ rend_cache_free_all();
+
+ // Test when an old descriptor is in the cache and we submit a newer one
+ rend_cache_init();
+ rend_cache_store_v2_desc_as_client(desc_holder_older->desc_str,
+ desc_id_base32, mock_rend_query, NULL);
+ ret = rend_cache_store_v2_desc_as_client(desc_holder_newer->desc_str,
+ desc_id_base32, mock_rend_query,
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ rend_encoded_v2_service_descriptor_free(desc_holder_newer);
+ rend_encoded_v2_service_descriptor_free(desc_holder_older);
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ rend_service_descriptor_free(generated);
+ tor_free(service_id);
+ rend_cache_free_all();
+ rend_data_free(mock_rend_query);
+}
+
+#define NS_SUBMODULE lookup_v2_desc_as_dir
+NS_DECL(const routerinfo_t *, router_get_my_routerinfo, (void));
+
+static routerinfo_t *mock_routerinfo;
+
+static const routerinfo_t *
+NS(router_get_my_routerinfo)(void)
+{
+ if (!mock_routerinfo) {
+ mock_routerinfo = tor_malloc(sizeof(routerinfo_t));
+ }
+
+ return mock_routerinfo;
+}
+
+static void
+test_rend_cache_lookup_v2_desc_as_dir(void *data)
+{
+ int ret;
+ char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
+ rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
+ char *service_id = NULL;
+ const char *ret_desc = NULL;
+
+ (void)data;
+
+ NS_MOCK(router_get_my_routerinfo);
+
+ rend_cache_init();
+
+ // Test invalid base32
+ ret = rend_cache_lookup_v2_desc_as_dir("!bababababababab", NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test non-existent descriptor but well formed
+ ret = rend_cache_lookup_v2_desc_as_dir("3xqunszqnaolrrfmtzgaki7mxelgvkje",
+ NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test existing descriptor
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+ rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
+ base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_holder->desc_id,
+ DIGEST_LEN);
+ ret = rend_cache_lookup_v2_desc_as_dir(desc_id_base32, &ret_desc);
+ tt_int_op(ret, OP_EQ, 1);
+ tt_assert(ret_desc);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ tor_free(mock_routerinfo);
+ rend_cache_free_all();
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+}
+
+#undef NS_SUBMODULE
+
+#define NS_SUBMODULE store_v2_desc_as_dir
+NS_DECL(const routerinfo_t *, router_get_my_routerinfo, (void));
+
+static const routerinfo_t *
+NS(router_get_my_routerinfo)(void)
+{
+ return mock_routerinfo;
+}
+
+static void
+test_rend_cache_store_v2_desc_as_dir(void *data)
+{
+ (void)data;
+ int ret;
+ rend_encoded_v2_service_descriptor_t *desc_holder = NULL;
+ char *service_id = NULL;
+
+ NS_MOCK(router_get_my_routerinfo);
+
+ rend_cache_init();
+
+ // Test when we can't parse the descriptor
+ mock_routerinfo = tor_malloc(sizeof(routerinfo_t));
+ ret = rend_cache_store_v2_desc_as_dir("unparseable");
+ tt_int_op(ret, OP_EQ, -1);
+
+ // Test when we have an old descriptor
+ generate_desc(TIME_IN_THE_PAST, &desc_holder, &service_id, 3);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+
+ // Test when we have a descriptor in the future
+ generate_desc(TIME_IN_THE_FUTURE, &desc_holder, &service_id, 3);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+
+ // Test when two descriptors
+ generate_desc(TIME_IN_THE_FUTURE, &desc_holder, &service_id, 3);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+
+ // Test when asking for hidden service statistics HiddenServiceStatistics
+ rend_cache_purge();
+ generate_desc(RECENT_TIME, &desc_holder, &service_id, 3);
+ get_options_mutable()->HiddenServiceStatistics = 1;
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ rend_encoded_v2_service_descriptor_free(desc_holder);
+ tor_free(service_id);
+ rend_cache_free_all();
+ tor_free(mock_routerinfo);
+}
+
+static void
+test_rend_cache_store_v2_desc_as_dir_with_different_time(void *data)
+{
+ (void)data;
+
+ int ret;
+ rend_service_descriptor_t *generated = NULL;
+ smartlist_t *descs = smartlist_new();
+ time_t t;
+ char *service_id = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder_newer;
+ rend_encoded_v2_service_descriptor_t *desc_holder_older;
+
+ NS_MOCK(router_get_my_routerinfo);
+
+ rend_cache_init();
+
+ t = time(NULL);
+
+ create_descriptor(&generated, &service_id, 3);
+ generated->timestamp = t + RECENT_TIME;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_newer = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ descs = smartlist_new();
+
+ generated->timestamp = (t + RECENT_TIME) - 20;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_older = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+
+ // Test when we have a newer descriptor stored
+ mock_routerinfo = tor_malloc(sizeof(routerinfo_t));
+ rend_cache_store_v2_desc_as_dir(desc_holder_newer->desc_str);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder_older->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test when we have an old descriptor stored
+ rend_cache_purge();
+ rend_cache_store_v2_desc_as_dir(desc_holder_older->desc_str);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder_newer->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ rend_cache_free_all();
+ rend_service_descriptor_free(generated);
+ tor_free(service_id);
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ rend_encoded_v2_service_descriptor_free(desc_holder_newer);
+ rend_encoded_v2_service_descriptor_free(desc_holder_older);
+ tor_free(mock_routerinfo);
+}
+
+static void
+test_rend_cache_store_v2_desc_as_dir_with_different_content(void *data)
+{
+ (void)data;
+
+ int ret;
+ rend_service_descriptor_t *generated = NULL;
+ smartlist_t *descs = smartlist_new();
+ time_t t;
+ char *service_id = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder_one = NULL;
+ rend_encoded_v2_service_descriptor_t *desc_holder_two = NULL;
+
+ NS_MOCK(router_get_my_routerinfo);
+
+ rend_cache_init();
+
+ t = time(NULL);
+
+ create_descriptor(&generated, &service_id, 3);
+ generated->timestamp = t + RECENT_TIME;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_one = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ descs = smartlist_new();
+
+ generated->timestamp = t + RECENT_TIME;
+ generated->protocols = 41;
+ rend_encode_v2_descriptors(descs, generated, t + RECENT_TIME, 0,
+ REND_NO_AUTH, NULL, NULL);
+ desc_holder_two = ((rend_encoded_v2_service_descriptor_t *)
+ smartlist_get(descs, 0));
+ smartlist_set(descs, 0, NULL);
+
+ // Test when we have another descriptor stored, with a different descriptor
+ mock_routerinfo = tor_malloc(sizeof(routerinfo_t));
+ rend_cache_store_v2_desc_as_dir(desc_holder_one->desc_str);
+ ret = rend_cache_store_v2_desc_as_dir(desc_holder_two->desc_str);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(router_get_my_routerinfo);
+ rend_cache_free_all();
+ rend_service_descriptor_free(generated);
+ tor_free(service_id);
+ SMARTLIST_FOREACH(descs, rend_encoded_v2_service_descriptor_t *, d,
+ rend_encoded_v2_service_descriptor_free(d));
+ smartlist_free(descs);
+ rend_encoded_v2_service_descriptor_free(desc_holder_one);
+ rend_encoded_v2_service_descriptor_free(desc_holder_two);
+}
+
+#undef NS_SUBMODULE
+
+static void
+test_rend_cache_init(void *data)
+{
+ (void)data;
+
+ tt_assert_msg(!rend_cache, "rend_cache should be NULL when starting");
+ tt_assert_msg(!rend_cache_v2_dir, "rend_cache_v2_dir should be NULL "
+ "when starting");
+ tt_assert_msg(!rend_cache_failure, "rend_cache_failure should be NULL when "
+ "starting");
+
+ rend_cache_init();
+
+ tt_assert_msg(rend_cache, "rend_cache should not be NULL after initing");
+ tt_assert_msg(rend_cache_v2_dir, "rend_cache_v2_dir should not be NULL "
+ "after initing");
+ tt_assert_msg(rend_cache_failure, "rend_cache_failure should not be NULL "
+ "after initing");
+
+ tt_int_op(strmap_size(rend_cache), OP_EQ, 0);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 0);
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 0);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_decrement_allocation(void *data)
+{
+ (void)data;
+
+ // Test when the cache has enough allocations
+ rend_cache_total_allocation = 10;
+ rend_cache_decrement_allocation(3);
+ tt_int_op(rend_cache_total_allocation, OP_EQ, 7);
+
+ // Test when there are not enough allocations
+ rend_cache_total_allocation = 1;
+ rend_cache_decrement_allocation(2);
+ tt_int_op(rend_cache_total_allocation, OP_EQ, 0);
+
+ // And again
+ rend_cache_decrement_allocation(2);
+ tt_int_op(rend_cache_total_allocation, OP_EQ, 0);
+
+ done:
+ (void)0;
+}
+
+static void
+test_rend_cache_increment_allocation(void *data)
+{
+ (void)data;
+
+ // Test when the cache is not overflowing
+ rend_cache_total_allocation = 5;
+ rend_cache_increment_allocation(3);
+ tt_int_op(rend_cache_total_allocation, OP_EQ, 8);
+
+ // Test when there are too many allocations
+ rend_cache_total_allocation = SIZE_MAX-1;
+ rend_cache_increment_allocation(2);
+ tt_u64_op(rend_cache_total_allocation, OP_EQ, SIZE_MAX);
+
+ // And again
+ rend_cache_increment_allocation(2);
+ tt_u64_op(rend_cache_total_allocation, OP_EQ, SIZE_MAX);
+
+ done:
+ (void)0;
+}
+
+static void
+test_rend_cache_failure_intro_entry_new(void *data)
+{
+ time_t now;
+ rend_cache_failure_intro_t *entry;
+ rend_intro_point_failure_t failure;
+
+ (void)data;
+
+ failure = INTRO_POINT_FAILURE_TIMEOUT;
+ now = time(NULL);
+ entry = rend_cache_failure_intro_entry_new(failure);
+
+ tt_int_op(entry->failure_type, OP_EQ, INTRO_POINT_FAILURE_TIMEOUT);
+ tt_int_op(entry->created_ts, OP_GE, now-5);
+ tt_int_op(entry->created_ts, OP_LE, now+5);
+
+ done:
+ tor_free(entry);
+}
+
+static void
+test_rend_cache_failure_intro_lookup(void *data)
+{
+ (void)data;
+ int ret;
+ rend_cache_failure_t *failure;
+ rend_cache_failure_intro_t *ip;
+ rend_cache_failure_intro_t *entry;
+ const char key_ip_one[DIGEST_LEN] = "ip1";
+ const char key_ip_two[DIGEST_LEN] = "ip2";
+ const char key_foo[DIGEST_LEN] = "foo1";
+
+ rend_cache_init();
+
+ failure = rend_cache_failure_entry_new();
+ ip = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ digestmap_set(failure->intro_failures, key_ip_one, ip);
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+
+ // Test not found
+ ret = cache_failure_intro_lookup((const uint8_t *) key_foo, "foo2", NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test found with no intro failures in it
+ ret = cache_failure_intro_lookup((const uint8_t *) key_ip_two, "foo1", NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Test found
+ ret = cache_failure_intro_lookup((const uint8_t *) key_ip_one, "foo1", NULL);
+ tt_int_op(ret, OP_EQ, 1);
+
+ // Test found and asking for entry
+ cache_failure_intro_lookup((const uint8_t *) key_ip_one, "foo1", &entry);
+ tt_assert(entry);
+ tt_assert(entry == ip);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_clean(void *data)
+{
+ rend_cache_entry_t *one, *two;
+ rend_service_descriptor_t *desc_one, *desc_two;
+ strmap_iter_t *iter = NULL;
+ const char *key;
+ void *val;
+
+ (void)data;
+
+ rend_cache_init();
+
+ // Test with empty rendcache
+ rend_cache_clean(time(NULL), REND_CACHE_TYPE_CLIENT);
+ tt_int_op(strmap_size(rend_cache), OP_EQ, 0);
+
+ // Test with two old entries
+ one = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ two = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ desc_one = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc_two = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ one->parsed = desc_one;
+ two->parsed = desc_two;
+
+ desc_one->timestamp = time(NULL) + TIME_IN_THE_PAST;
+ desc_two->timestamp = (time(NULL) + TIME_IN_THE_PAST) - 10;
+ desc_one->pk = pk_generate(0);
+ desc_two->pk = pk_generate(1);
+
+ strmap_set_lc(rend_cache, "foo1", one);
+ strmap_set_lc(rend_cache, "foo2", two);
+
+ rend_cache_clean(time(NULL), REND_CACHE_TYPE_CLIENT);
+ tt_int_op(strmap_size(rend_cache), OP_EQ, 0);
+
+ // Test with one old entry and one newer entry
+ one = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ two = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ desc_one = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc_two = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ one->parsed = desc_one;
+ two->parsed = desc_two;
+
+ desc_one->timestamp = (time(NULL) + TIME_IN_THE_PAST) - 10;
+ desc_two->timestamp = time(NULL) - 100;
+ desc_one->pk = pk_generate(0);
+ desc_two->pk = pk_generate(1);
+
+ strmap_set_lc(rend_cache, "foo1", one);
+ strmap_set_lc(rend_cache, "foo2", two);
+
+ rend_cache_clean(time(NULL), REND_CACHE_TYPE_CLIENT);
+ tt_int_op(strmap_size(rend_cache), OP_EQ, 1);
+
+ iter = strmap_iter_init(rend_cache);
+ strmap_iter_get(iter, &key, &val);
+ tt_str_op(key, OP_EQ, "foo2");
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_failure_entry_new(void *data)
+{
+ rend_cache_failure_t *failure;
+
+ (void)data;
+
+ failure = rend_cache_failure_entry_new();
+ tt_assert(failure);
+ tt_int_op(digestmap_size(failure->intro_failures), OP_EQ, 0);
+
+ done:
+ rend_cache_failure_entry_free(failure);
+}
+
+static void
+test_rend_cache_failure_entry_free(void *data)
+{
+ (void)data;
+
+ // Test that it can deal with a NULL argument
+ rend_cache_failure_entry_free(NULL);
+
+ /* done: */
+ /* (void)0; */
+}
+
+static void
+test_rend_cache_failure_clean(void *data)
+{
+ rend_cache_failure_t *failure;
+ rend_cache_failure_intro_t *ip_one, *ip_two;
+
+ const char key_one[DIGEST_LEN] = "ip1";
+ const char key_two[DIGEST_LEN] = "ip2";
+
+ (void)data;
+
+ rend_cache_init();
+
+ // Test with empty failure cache
+ rend_cache_failure_clean(time(NULL));
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 0);
+
+ // Test with one empty failure entry
+ failure = rend_cache_failure_entry_new();
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+ rend_cache_failure_clean(time(NULL));
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 0);
+
+ // Test with one new intro point
+ failure = rend_cache_failure_entry_new();
+ ip_one = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ digestmap_set(failure->intro_failures, key_one, ip_one);
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+ rend_cache_failure_clean(time(NULL));
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 1);
+
+ // Test with one old intro point
+ rend_cache_failure_purge();
+ failure = rend_cache_failure_entry_new();
+ ip_one = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ ip_one->created_ts = time(NULL) - 7*60;
+ digestmap_set(failure->intro_failures, key_one, ip_one);
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+ rend_cache_failure_clean(time(NULL));
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 0);
+
+ // Test with one old intro point and one new one
+ rend_cache_failure_purge();
+ failure = rend_cache_failure_entry_new();
+ ip_one = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ ip_one->created_ts = time(NULL) - 7*60;
+ digestmap_set(failure->intro_failures, key_one, ip_one);
+ ip_two = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ ip_two->created_ts = time(NULL) - 2*60;
+ digestmap_set(failure->intro_failures, key_two, ip_two);
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+ rend_cache_failure_clean(time(NULL));
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 1);
+ tt_int_op(digestmap_size(failure->intro_failures), OP_EQ, 1);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_failure_remove(void *data)
+{
+ rend_service_descriptor_t *desc;
+ (void)data;
+
+ rend_cache_init();
+
+ // Test that it deals well with a NULL desc
+ rend_cache_failure_remove(NULL);
+
+ // Test a descriptor that isn't in the cache
+ desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc->pk = pk_generate(0);
+ rend_cache_failure_remove(desc);
+
+ // There seems to not exist any way of getting rend_cache_failure_remove()
+ // to fail because of a problem with rend_get_service_id from here
+ rend_cache_free_all();
+
+ rend_service_descriptor_free(desc);
+ /* done: */
+ /* (void)0; */
+}
+
+static void
+test_rend_cache_free_all(void *data)
+{
+ rend_cache_failure_t *failure;
+ rend_cache_entry_t *one;
+ rend_service_descriptor_t *desc_one;
+
+ (void)data;
+
+ rend_cache_init();
+
+ failure = rend_cache_failure_entry_new();
+ strmap_set_lc(rend_cache_failure, "foo1", failure);
+
+ one = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ desc_one = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ one->parsed = desc_one;
+ desc_one->timestamp = time(NULL) + TIME_IN_THE_PAST;
+ desc_one->pk = pk_generate(0);
+ strmap_set_lc(rend_cache, "foo1", one);
+
+ rend_cache_free_all();
+
+ tt_assert(!rend_cache);
+ tt_assert(!rend_cache_v2_dir);
+ tt_assert(!rend_cache_failure);
+ tt_assert(!rend_cache_total_allocation);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_entry_free(void *data)
+{
+ (void)data;
+ rend_cache_entry_t *e;
+
+ // Handles NULL correctly
+ rend_cache_entry_free(NULL);
+
+ // Handles NULL descriptor correctly
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ rend_cache_entry_free(e);
+
+ // Handles non-NULL descriptor correctly
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ e->desc = (char *)malloc(10);
+ rend_cache_entry_free(e);
+
+ /* done: */
+ /* (void)0; */
+}
+
+static void
+test_rend_cache_purge(void *data)
+{
+ (void)data;
+
+ // Deals with a NULL rend_cache
+ rend_cache_purge();
+ tt_assert(rend_cache);
+ tt_assert(strmap_size(rend_cache) == 0);
+
+ // Deals with existing rend_cache
+ rend_cache_free_all();
+ rend_cache_init();
+ tt_assert(rend_cache);
+ tt_assert(strmap_size(rend_cache) == 0);
+
+ rend_cache_purge();
+ tt_assert(rend_cache);
+ tt_assert(strmap_size(rend_cache) == 0);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_failure_intro_add(void *data)
+{
+ (void)data;
+ rend_cache_failure_t *fail_entry;
+ rend_cache_failure_intro_t *entry;
+ const char identity[DIGEST_LEN] = "foo1";
+
+ rend_cache_init();
+
+ // Adds non-existing entry
+ cache_failure_intro_add((const uint8_t *) identity, "foo2",
+ INTRO_POINT_FAILURE_TIMEOUT);
+ fail_entry = strmap_get_lc(rend_cache_failure, "foo2");
+ tt_assert(fail_entry);
+ tt_int_op(digestmap_size(fail_entry->intro_failures), OP_EQ, 1);
+ entry = digestmap_get(fail_entry->intro_failures, identity);
+ tt_assert(entry);
+
+ // Adds existing entry
+ cache_failure_intro_add((const uint8_t *) identity, "foo2",
+ INTRO_POINT_FAILURE_TIMEOUT);
+ fail_entry = strmap_get_lc(rend_cache_failure, "foo2");
+ tt_assert(fail_entry);
+ tt_int_op(digestmap_size(fail_entry->intro_failures), OP_EQ, 1);
+ entry = digestmap_get(fail_entry->intro_failures, identity);
+ tt_assert(entry);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_intro_failure_note(void *data)
+{
+ (void)data;
+ rend_cache_failure_t *fail_entry;
+ rend_cache_failure_intro_t *entry;
+ const char key[DIGEST_LEN] = "foo1";
+
+ rend_cache_init();
+
+ // Test not found
+ rend_cache_intro_failure_note(INTRO_POINT_FAILURE_TIMEOUT,
+ (const uint8_t *) key, "foo2");
+ fail_entry = strmap_get_lc(rend_cache_failure, "foo2");
+ tt_assert(fail_entry);
+ tt_int_op(digestmap_size(fail_entry->intro_failures), OP_EQ, 1);
+ entry = digestmap_get(fail_entry->intro_failures, key);
+ tt_assert(entry);
+ tt_int_op(entry->failure_type, OP_EQ, INTRO_POINT_FAILURE_TIMEOUT);
+
+ // Test found
+ rend_cache_intro_failure_note(INTRO_POINT_FAILURE_UNREACHABLE,
+ (const uint8_t *) key, "foo2");
+ tt_int_op(entry->failure_type, OP_EQ, INTRO_POINT_FAILURE_UNREACHABLE);
+
+ done:
+ rend_cache_free_all();
+}
+
+#define NS_SUBMODULE clean_v2_descs_as_dir
+
+static void
+test_rend_cache_clean_v2_descs_as_dir(void *data)
+{
+ rend_cache_entry_t *e;
+ time_t now;
+ rend_service_descriptor_t *desc;
+ now = time(NULL);
+ const char key[DIGEST_LEN] = "abcde";
+
+ (void)data;
+
+ rend_cache_init();
+
+ // Test running with an empty cache
+ rend_cache_clean_v2_descs_as_dir(now, 0);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 0);
+
+ // Test with only one new entry
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ e->last_served = now;
+ desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc->timestamp = now;
+ desc->pk = pk_generate(0);
+ e->parsed = desc;
+ digestmap_set(rend_cache_v2_dir, key, e);
+
+ rend_cache_clean_v2_descs_as_dir(now, 0);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 1);
+
+ // Test with one old entry
+ desc->timestamp = now - (REND_CACHE_MAX_AGE + REND_CACHE_MAX_SKEW + 1000);
+ rend_cache_clean_v2_descs_as_dir(now, 0);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 0);
+
+ // Test with one entry that has an old last served
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ e->last_served = now - (REND_CACHE_MAX_AGE + REND_CACHE_MAX_SKEW + 1000);
+ desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc->timestamp = now;
+ desc->pk = pk_generate(0);
+ e->parsed = desc;
+ digestmap_set(rend_cache_v2_dir, key, e);
+
+ rend_cache_clean_v2_descs_as_dir(now, 0);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 0);
+
+ // Test a run through asking for a large force_remove
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ e->last_served = now;
+ desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
+ desc->timestamp = now;
+ desc->pk = pk_generate(0);
+ e->parsed = desc;
+ digestmap_set(rend_cache_v2_dir, key, e);
+
+ rend_cache_clean_v2_descs_as_dir(now, 20000);
+ tt_int_op(digestmap_size(rend_cache_v2_dir), OP_EQ, 1);
+
+ done:
+ rend_cache_free_all();
+}
+
+#undef NS_SUBMODULE
+
+static void
+test_rend_cache_entry_allocation(void *data)
+{
+ (void)data;
+
+ size_t ret;
+ rend_cache_entry_t *e = NULL;
+
+ // Handles a null argument
+ ret = rend_cache_entry_allocation(NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ // Handles a non-null argument
+ e = tor_malloc_zero(sizeof(rend_cache_entry_t));
+ ret = rend_cache_entry_allocation(e);
+ tt_int_op(ret, OP_GT, sizeof(rend_cache_entry_t));
+
+ done:
+ tor_free(e);
+}
+
+static void
+test_rend_cache_failure_intro_entry_free(void *data)
+{
+ (void)data;
+ rend_cache_failure_intro_t *entry;
+
+ // Handles a null argument
+ rend_cache_failure_intro_entry_free(NULL);
+
+ // Handles a non-null argument
+ entry = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ rend_cache_failure_intro_entry_free(entry);
+}
+
+static void
+test_rend_cache_failure_purge(void *data)
+{
+ (void)data;
+
+ // Handles a null failure cache
+ strmap_free(rend_cache_failure, rend_cache_failure_entry_free_);
+ rend_cache_failure = NULL;
+
+ rend_cache_failure_purge();
+
+ tt_ptr_op(rend_cache_failure, OP_NE, NULL);
+ tt_int_op(strmap_size(rend_cache_failure), OP_EQ, 0);
+
+ done:
+ rend_cache_free_all();
+}
+
+static void
+test_rend_cache_validate_intro_point_failure(void *data)
+{
+ (void)data;
+ rend_service_descriptor_t *desc = NULL;
+ char *service_id = NULL;
+ rend_intro_point_t *intro = NULL;
+ const char *identity = NULL;
+ rend_cache_failure_t *failure;
+ rend_cache_failure_intro_t *ip;
+
+ rend_cache_init();
+
+ create_descriptor(&desc, &service_id, 3);
+ desc->timestamp = time(NULL) + RECENT_TIME;
+
+ intro = (rend_intro_point_t *)smartlist_get(desc->intro_nodes, 0);
+ identity = intro->extend_info->identity_digest;
+
+ failure = rend_cache_failure_entry_new();
+ ip = rend_cache_failure_intro_entry_new(INTRO_POINT_FAILURE_TIMEOUT);
+ digestmap_set(failure->intro_failures, identity, ip);
+ strmap_set_lc(rend_cache_failure, service_id, failure);
+
+ // Test when we have an intro point in our cache
+ validate_intro_point_failure(desc, service_id);
+ tt_int_op(smartlist_len(desc->intro_nodes), OP_EQ, 2);
+
+ done:
+ rend_cache_free_all();
+ rend_service_descriptor_free(desc);
+ tor_free(service_id);
+}
+
+struct testcase_t rend_cache_tests[] = {
+ { "init", test_rend_cache_init, 0, NULL, NULL },
+ { "decrement_allocation", test_rend_cache_decrement_allocation, 0,
+ NULL, NULL },
+ { "increment_allocation", test_rend_cache_increment_allocation, 0,
+ NULL, NULL },
+ { "clean", test_rend_cache_clean, TT_FORK, NULL, NULL },
+ { "clean_v2_descs_as_dir", test_rend_cache_clean_v2_descs_as_dir, 0,
+ NULL, NULL },
+ { "entry_allocation", test_rend_cache_entry_allocation, 0, NULL, NULL },
+ { "entry_free", test_rend_cache_entry_free, 0, NULL, NULL },
+ { "failure_intro_entry_free", test_rend_cache_failure_intro_entry_free, 0,
+ NULL, NULL },
+ { "free_all", test_rend_cache_free_all, 0, NULL, NULL },
+ { "purge", test_rend_cache_purge, 0, NULL, NULL },
+ { "failure_clean", test_rend_cache_failure_clean, 0, NULL, NULL },
+ { "failure_entry_new", test_rend_cache_failure_entry_new, 0, NULL, NULL },
+ { "failure_entry_free", test_rend_cache_failure_entry_free, 0, NULL, NULL },
+ { "failure_intro_add", test_rend_cache_failure_intro_add, 0, NULL, NULL },
+ { "failure_intro_entry_new", test_rend_cache_failure_intro_entry_new, 0,
+ NULL, NULL },
+ { "failure_intro_lookup", test_rend_cache_failure_intro_lookup, 0,
+ NULL, NULL },
+ { "failure_purge", test_rend_cache_failure_purge, 0, NULL, NULL },
+ { "failure_remove", test_rend_cache_failure_remove, 0, NULL, NULL },
+ { "intro_failure_note", test_rend_cache_intro_failure_note, 0, NULL, NULL },
+ { "lookup", test_rend_cache_lookup_entry, 0, NULL, NULL },
+ { "lookup_v2_desc_as_dir", test_rend_cache_lookup_v2_desc_as_dir, 0,
+ NULL, NULL },
+ { "store_v2_desc_as_client", test_rend_cache_store_v2_desc_as_client, 0,
+ NULL, NULL },
+ { "store_v2_desc_as_client_with_different_time",
+ test_rend_cache_store_v2_desc_as_client_with_different_time, 0,
+ NULL, NULL },
+ { "store_v2_desc_as_dir", test_rend_cache_store_v2_desc_as_dir, 0,
+ NULL, NULL },
+ { "store_v2_desc_as_dir_with_different_time",
+ test_rend_cache_store_v2_desc_as_dir_with_different_time, 0, NULL, NULL },
+ { "store_v2_desc_as_dir_with_different_content",
+ test_rend_cache_store_v2_desc_as_dir_with_different_content, 0,
+ NULL, NULL },
+ { "validate_intro_point_failure",
+ test_rend_cache_validate_intro_point_failure, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_replay.c b/src/test/test_replay.c
index b48f582f5e..e882bc6164 100644
--- a/src/test/test_replay.c
+++ b/src/test/test_replay.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2012-2013, The Tor Project, Inc. */
+/* Copyright (c) 2012-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define REPLAYCACHE_PRIVATE
@@ -17,13 +17,28 @@ static const char *test_buffer =
" occaecat cupidatat non proident, sunt in culpa qui officia deserunt"
" mollit anim id est laborum.";
+static const char *test_buffer_2 =
+ "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis"
+ " praesentium voluptatum deleniti atque corrupti quos dolores et quas"
+ " molestias excepturi sint occaecati cupiditate non provident, similique"
+ " sunt in culpa qui officia deserunt mollitia animi, id est laborum et"
+ " dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio."
+ " Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil"
+ " impedit quo minus id quod maxime placeat facere possimus, omnis voluptas"
+ " assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut"
+ " officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates"
+ " repudiandae sint et molestiae non recusandae. Itaque earum rerum hic"
+ " tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias"
+ " consequatur aut perferendis doloribus asperiores repellat.";
+
static void
-test_replaycache_alloc(void)
+test_replaycache_alloc(void *arg)
{
replaycache_t *r = NULL;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
done:
if (r) replaycache_free(r);
@@ -32,21 +47,22 @@ test_replaycache_alloc(void)
}
static void
-test_replaycache_badalloc(void)
+test_replaycache_badalloc(void *arg)
{
replaycache_t *r = NULL;
/* Negative horizon should fail */
+ (void)arg;
r = replaycache_new(-600, 300);
- test_assert(r == NULL);
+ tt_assert(r == NULL);
/* Negative interval should get adjusted to zero */
r = replaycache_new(600, -300);
- test_assert(r != NULL);
- test_eq(r->scrub_interval, 0);
+ tt_assert(r != NULL);
+ tt_int_op(r->scrub_interval,OP_EQ, 0);
replaycache_free(r);
/* Negative horizon and negative interval should still fail */
r = replaycache_new(-600, -300);
- test_assert(r == NULL);
+ tt_assert(r == NULL);
done:
if (r) replaycache_free(r);
@@ -55,35 +71,43 @@ test_replaycache_badalloc(void)
}
static void
-test_replaycache_free_null(void)
+test_replaycache_free_null(void *arg)
{
+ (void)arg;
replaycache_free(NULL);
/* Assert that we're here without horrible death */
- test_assert(1);
+ tt_assert(1);
done:
return;
}
static void
-test_replaycache_miss(void)
+test_replaycache_miss(void *arg)
{
replaycache_t *r = NULL;
int result;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
result =
replaycache_add_and_test_internal(1200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
+
+ /* make sure a different buffer misses as well */
+ result =
+ replaycache_add_and_test_internal(1200, NULL, test_buffer_2,
+ strlen(test_buffer_2), NULL);
+ tt_int_op(result,OP_EQ, 0);
/* poke the bad-parameter error case too */
result =
replaycache_add_and_test_internal(1200, NULL, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
done:
if (r) replaycache_free(r);
@@ -92,23 +116,36 @@ test_replaycache_miss(void)
}
static void
-test_replaycache_hit(void)
+test_replaycache_hit(void *arg)
{
replaycache_t *r = NULL;
int result;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
result =
replaycache_add_and_test_internal(1200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
result =
replaycache_add_and_test_internal(1300, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
+
+ /* make sure a different buffer misses then hits as well */
+
+ result =
+ replaycache_add_and_test_internal(1200, r, test_buffer_2,
+ strlen(test_buffer_2), NULL);
+ tt_int_op(result,OP_EQ, 0);
+
+ result =
+ replaycache_add_and_test_internal(1300, r, test_buffer_2,
+ strlen(test_buffer_2), NULL);
+ tt_int_op(result,OP_EQ, 1);
done:
if (r) replaycache_free(r);
@@ -117,28 +154,29 @@ test_replaycache_hit(void)
}
static void
-test_replaycache_age(void)
+test_replaycache_age(void *arg)
{
replaycache_t *r = NULL;
int result;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
result =
replaycache_add_and_test_internal(1200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
result =
replaycache_add_and_test_internal(1300, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
result =
replaycache_add_and_test_internal(3000, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
done:
if (r) replaycache_free(r);
@@ -147,25 +185,26 @@ test_replaycache_age(void)
}
static void
-test_replaycache_elapsed(void)
+test_replaycache_elapsed(void *arg)
{
replaycache_t *r = NULL;
int result;
time_t elapsed;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
result =
replaycache_add_and_test_internal(1200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
result =
replaycache_add_and_test_internal(1300, r, test_buffer,
strlen(test_buffer), &elapsed);
- test_eq(result, 1);
- test_eq(elapsed, 100);
+ tt_int_op(result,OP_EQ, 1);
+ tt_int_op(elapsed,OP_EQ, 100);
done:
if (r) replaycache_free(r);
@@ -174,28 +213,29 @@ test_replaycache_elapsed(void)
}
static void
-test_replaycache_noexpire(void)
+test_replaycache_noexpire(void *arg)
{
replaycache_t *r = NULL;
int result;
+ (void)arg;
r = replaycache_new(0, 0);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
result =
replaycache_add_and_test_internal(1200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
result =
replaycache_add_and_test_internal(1300, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
result =
replaycache_add_and_test_internal(3000, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
done:
if (r) replaycache_free(r);
@@ -204,24 +244,25 @@ test_replaycache_noexpire(void)
}
static void
-test_replaycache_scrub(void)
+test_replaycache_scrub(void *arg)
{
replaycache_t *r = NULL;
int result;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
/* Set up like in test_replaycache_hit() */
result =
replaycache_add_and_test_internal(100, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
result =
replaycache_add_and_test_internal(200, r, test_buffer,
strlen(test_buffer), NULL);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
/*
* Poke a few replaycache_scrub_if_needed_internal() error cases that
@@ -231,12 +272,12 @@ test_replaycache_scrub(void)
/* Null cache */
replaycache_scrub_if_needed_internal(300, NULL);
/* Assert we're still here */
- test_assert(1);
+ tt_assert(1);
/* Make sure we hit the aging-out case too */
replaycache_scrub_if_needed_internal(1500, r);
/* Assert that we aged it */
- test_eq(digestmap_size(r->digests_seen), 0);
+ tt_int_op(digest256map_size(r->digests_seen),OP_EQ, 0);
done:
if (r) replaycache_free(r);
@@ -245,29 +286,30 @@ test_replaycache_scrub(void)
}
static void
-test_replaycache_future(void)
+test_replaycache_future(void *arg)
{
replaycache_t *r = NULL;
int result;
time_t elapsed = 0;
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
/* Set up like in test_replaycache_hit() */
result =
replaycache_add_and_test_internal(100, r, test_buffer,
strlen(test_buffer), &elapsed);
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
/* elapsed should still be 0, since it wasn't written */
- test_eq(elapsed, 0);
+ tt_int_op(elapsed,OP_EQ, 0);
result =
replaycache_add_and_test_internal(200, r, test_buffer,
strlen(test_buffer), &elapsed);
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
/* elapsed should be the time since the last hit */
- test_eq(elapsed, 100);
+ tt_int_op(elapsed,OP_EQ, 100);
/*
* Now let's turn the clock back to get coverage on the cache entry from the
@@ -277,9 +319,9 @@ test_replaycache_future(void)
replaycache_add_and_test_internal(150, r, test_buffer,
strlen(test_buffer), &elapsed);
/* We should still get a hit */
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
/* ...but it shouldn't let us see a negative elapsed time */
- test_eq(elapsed, 0);
+ tt_int_op(elapsed,OP_EQ, 0);
done:
if (r) replaycache_free(r);
@@ -288,7 +330,7 @@ test_replaycache_future(void)
}
static void
-test_replaycache_realtime(void)
+test_replaycache_realtime(void *arg)
{
replaycache_t *r = NULL;
/*
@@ -299,26 +341,27 @@ test_replaycache_realtime(void)
int result;
/* Test the realtime as well as *_internal() entry points */
+ (void)arg;
r = replaycache_new(600, 300);
- test_assert(r != NULL);
+ tt_assert(r != NULL);
/* This should miss */
result =
replaycache_add_and_test(r, test_buffer, strlen(test_buffer));
- test_eq(result, 0);
+ tt_int_op(result,OP_EQ, 0);
/* This should hit */
result =
replaycache_add_and_test(r, test_buffer, strlen(test_buffer));
- test_eq(result, 1);
+ tt_int_op(result,OP_EQ, 1);
/* This should hit and return a small elapsed time */
result =
replaycache_add_test_and_elapsed(r, test_buffer,
strlen(test_buffer), &elapsed);
- test_eq(result, 1);
- test_assert(elapsed >= 0);
- test_assert(elapsed <= 5);
+ tt_int_op(result,OP_EQ, 1);
+ tt_assert(elapsed >= 0);
+ tt_assert(elapsed <= 5);
/* Scrub it to exercise that entry point too */
replaycache_scrub_if_needed(r);
@@ -329,7 +372,7 @@ test_replaycache_realtime(void)
}
#define REPLAYCACHE_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_replaycache_ ## name }
+ { #name, test_replaycache_ ## name , 0, NULL, NULL }
struct testcase_t replaycache_tests[] = {
REPLAYCACHE_LEGACY(alloc),
diff --git a/src/test/test_routerkeys.c b/src/test/test_routerkeys.c
index 182e0f6f87..24b0da1c46 100644
--- a/src/test/test_routerkeys.c
+++ b/src/test/test_routerkeys.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
@@ -8,11 +8,17 @@
#include "or.h"
#include "config.h"
#include "router.h"
+#include "routerkeys.h"
#include "util.h"
#include "crypto.h"
-
+#include "torcert.h"
#include "test.h"
+#ifdef _WIN32
+/* For mkdir() */
+#include <direct.h>
+#endif
+
static void
test_routerkeys_write_fingerprint(void *arg)
{
@@ -33,38 +39,38 @@ test_routerkeys_write_fingerprint(void *arg)
set_server_identity_key(key);
set_client_identity_key(crypto_pk_dup_key(key));
- tt_int_op(0, ==, check_private_dir(ddir, CPD_CREATE, NULL));
- tt_int_op(crypto_pk_cmp_keys(get_server_identity_key(),key),==,0);
+ tt_int_op(0, OP_EQ, check_private_dir(ddir, CPD_CREATE, NULL));
+ tt_int_op(crypto_pk_cmp_keys(get_server_identity_key(),key),OP_EQ,0);
/* Write fingerprint file */
- tt_int_op(0, ==, router_write_fingerprint(0));
+ tt_int_op(0, OP_EQ, router_write_fingerprint(0));
cp = read_file_to_str(get_fname("write_fingerprint/fingerprint"),
0, NULL);
crypto_pk_get_fingerprint(key, fp, 0);
tor_asprintf(&cp2, "haflinger %s\n", fp);
- tt_str_op(cp, ==, cp2);
+ tt_str_op(cp, OP_EQ, cp2);
tor_free(cp);
tor_free(cp2);
/* Write hashed-fingerprint file */
- tt_int_op(0, ==, router_write_fingerprint(1));
+ tt_int_op(0, OP_EQ, router_write_fingerprint(1));
cp = read_file_to_str(get_fname("write_fingerprint/hashed-fingerprint"),
0, NULL);
crypto_pk_get_hashed_fingerprint(key, fp);
tor_asprintf(&cp2, "haflinger %s\n", fp);
- tt_str_op(cp, ==, cp2);
+ tt_str_op(cp, OP_EQ, cp2);
tor_free(cp);
tor_free(cp2);
/* Replace outdated file */
write_str_to_file(get_fname("write_fingerprint/hashed-fingerprint"),
"junk goes here", 0);
- tt_int_op(0, ==, router_write_fingerprint(1));
+ tt_int_op(0, OP_EQ, router_write_fingerprint(1));
cp = read_file_to_str(get_fname("write_fingerprint/hashed-fingerprint"),
0, NULL);
crypto_pk_get_hashed_fingerprint(key, fp);
tor_asprintf(&cp2, "haflinger %s\n", fp);
- tt_str_op(cp, ==, cp2);
+ tt_str_op(cp, OP_EQ, cp2);
tor_free(cp);
tor_free(cp2);
@@ -75,11 +81,551 @@ test_routerkeys_write_fingerprint(void *arg)
tor_free(cp2);
}
+static void
+test_routerkeys_ed_certs(void *args)
+{
+ (void)args;
+ ed25519_keypair_t kp1, kp2;
+ tor_cert_t *cert[2] = {NULL, NULL}, *nocert = NULL;
+ tor_cert_t *parsed_cert[2] = {NULL, NULL};
+ time_t now = 1412094534;
+ uint8_t *junk = NULL;
+ char *base64 = NULL;
+
+ tt_int_op(0,==,ed25519_keypair_generate(&kp1, 0));
+ tt_int_op(0,==,ed25519_keypair_generate(&kp2, 0));
+
+ for (int i = 0; i <= 1; ++i) {
+ uint32_t flags = i ? CERT_FLAG_INCLUDE_SIGNING_KEY : 0;
+
+ cert[i] = tor_cert_create(&kp1, 5, &kp2.pubkey, now, 10000, flags);
+ tt_assert(cert[i]);
+
+ tt_assert(cert[i]->sig_bad == 0);
+ tt_assert(cert[i]->sig_ok == 1);
+ tt_assert(cert[i]->cert_expired == 0);
+ tt_assert(cert[i]->cert_valid == 1);
+ tt_int_op(cert[i]->cert_type, ==, 5);
+ tt_mem_op(cert[i]->signed_key.pubkey, ==, &kp2.pubkey.pubkey, 32);
+ tt_mem_op(cert[i]->signing_key.pubkey, ==, &kp1.pubkey.pubkey, 32);
+ tt_int_op(cert[i]->signing_key_included, ==, i);
+
+ tt_assert(cert[i]->encoded);
+ tt_int_op(cert[i]->encoded_len, ==, 104 + 36 * i);
+ tt_int_op(cert[i]->encoded[0], ==, 1);
+ tt_int_op(cert[i]->encoded[1], ==, 5);
+
+ parsed_cert[i] = tor_cert_parse(cert[i]->encoded, cert[i]->encoded_len);
+ tt_assert(parsed_cert[i]);
+ tt_int_op(cert[i]->encoded_len, ==, parsed_cert[i]->encoded_len);
+ tt_mem_op(cert[i]->encoded, ==, parsed_cert[i]->encoded,
+ cert[i]->encoded_len);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == 0);
+ tt_assert(parsed_cert[i]->cert_expired == 0);
+ tt_assert(parsed_cert[i]->cert_valid == 0);
+
+ /* Expired */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp1.pubkey, now + 30000),
+ <, 0);
+ tt_assert(parsed_cert[i]->cert_expired == 1);
+ parsed_cert[i]->cert_expired = 0;
+
+ /* Wrong key */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp2.pubkey, now), <, 0);
+ tt_assert(parsed_cert[i]->sig_bad== 1);
+ parsed_cert[i]->sig_bad = 0;
+
+ /* Missing key */
+ int ok = tor_cert_checksig(parsed_cert[i], NULL, now);
+ tt_int_op(ok < 0, ==, i == 0);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == (i != 0));
+ tt_assert(parsed_cert[i]->cert_valid == (i != 0));
+ parsed_cert[i]->sig_bad = 0;
+ parsed_cert[i]->sig_ok = 0;
+ parsed_cert[i]->cert_valid = 0;
+
+ /* Right key */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp1.pubkey, now), ==, 0);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == 1);
+ tt_assert(parsed_cert[i]->cert_expired == 0);
+ tt_assert(parsed_cert[i]->cert_valid == 1);
+ }
+
+ /* Now try some junky certs. */
+ /* - Truncated */
+ nocert = tor_cert_parse(cert[0]->encoded, cert[0]->encoded_len-1);
+ tt_ptr_op(NULL, ==, nocert);
+
+ /* - First byte modified */
+ cert[0]->encoded[0] = 99;
+ nocert = tor_cert_parse(cert[0]->encoded, cert[0]->encoded_len);
+ tt_ptr_op(NULL, ==, nocert);
+ cert[0]->encoded[0] = 1;
+
+ /* - Extra byte at the end*/
+ junk = tor_malloc_zero(cert[0]->encoded_len + 1);
+ memcpy(junk, cert[0]->encoded, cert[0]->encoded_len);
+ nocert = tor_cert_parse(junk, cert[0]->encoded_len+1);
+ tt_ptr_op(NULL, ==, nocert);
+
+ /* - Multiple signing key instances */
+ tor_free(junk);
+ junk = tor_malloc_zero(104 + 36 * 2);
+ junk[0] = 1; /* version */
+ junk[1] = 5; /* cert type */
+ junk[6] = 1; /* key type */
+ junk[39] = 2; /* n_extensions */
+ junk[41] = 32; /* extlen */
+ junk[42] = 4; /* exttype */
+ junk[77] = 32; /* extlen */
+ junk[78] = 4; /* exttype */
+ nocert = tor_cert_parse(junk, 104 + 36 * 2);
+ tt_ptr_op(NULL, ==, nocert);
+
+ done:
+ tor_cert_free(cert[0]);
+ tor_cert_free(cert[1]);
+ tor_cert_free(parsed_cert[0]);
+ tor_cert_free(parsed_cert[1]);
+ tor_cert_free(nocert);
+ tor_free(junk);
+ tor_free(base64);
+}
+
+static void
+test_routerkeys_ed_key_create(void *arg)
+{
+ (void)arg;
+ tor_cert_t *cert = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL;
+ time_t now = time(NULL);
+
+ /* This is a simple alias for 'make a new keypair' */
+ kp1 = ed_key_new(NULL, 0, 0, 0, 0, &cert);
+ tt_assert(kp1);
+
+ /* Create a new certificate signed by kp1. */
+ kp2 = ed_key_new(kp1, INIT_ED_KEY_NEEDCERT, now, 3600, 4, &cert);
+ tt_assert(kp2);
+ tt_assert(cert);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, sizeof(ed25519_public_key_t));
+ tt_assert(! cert->signing_key_included);
+
+ tt_int_op(cert->valid_until, >=, now);
+ tt_int_op(cert->valid_until, <=, now+7200);
+
+ /* Create a new key-including certificate signed by kp1 */
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+ cert = NULL; kp2 = NULL;
+ kp2 = ed_key_new(kp1, (INIT_ED_KEY_NEEDCERT|
+ INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT),
+ now, 3600, 4, &cert);
+ tt_assert(kp2);
+ tt_assert(cert);
+ tt_assert(cert->signing_key_included);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, sizeof(ed25519_public_key_t));
+ tt_mem_op(&cert->signing_key, ==, &kp1->pubkey,sizeof(ed25519_public_key_t));
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+}
+
+static void
+test_routerkeys_ed_key_init_basic(void *arg)
+{
+ (void) arg;
+
+ tor_cert_t *cert = NULL, *cert2 = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL, *kp3 = NULL;
+ time_t now = time(NULL);
+ char *fname1 = tor_strdup(get_fname("test_ed_key_1"));
+ char *fname2 = tor_strdup(get_fname("test_ed_key_2"));
+ struct stat st;
+
+ unlink(fname1);
+ unlink(fname2);
+
+ /* Fail to load a key that isn't there. */
+ kp1 = ed_key_init_from_file(fname1, 0, LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 == NULL);
+ tt_assert(cert == NULL);
+
+ /* Create the key if requested to do so. */
+ kp1 = ed_key_init_from_file(fname1, INIT_ED_KEY_CREATE, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp1 != NULL);
+ tt_assert(cert == NULL);
+ tt_int_op(stat(get_fname("test_ed_key_1_cert"), &st), <, 0);
+ tt_int_op(stat(get_fname("test_ed_key_1_secret_key"), &st), ==, 0);
+
+ /* Fail to load if we say we need a cert */
+ kp2 = ed_key_init_from_file(fname1, INIT_ED_KEY_NEEDCERT, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 == NULL);
+
+ /* Fail to load if we say the wrong key type */
+ kp2 = ed_key_init_from_file(fname1, 0, LOG_INFO,
+ NULL, now, 0, 6, &cert);
+ tt_assert(kp2 == NULL);
+
+ /* Load successfully if we're not picky, whether we say "create" or not. */
+ kp2 = ed_key_init_from_file(fname1, INIT_ED_KEY_CREATE, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp1));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ kp2 = ed_key_init_from_file(fname1, 0, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp1));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Now create a key with a cert. */
+ kp2 = ed_key_init_from_file(fname2, (INIT_ED_KEY_CREATE|
+ INIT_ED_KEY_NEEDCERT),
+ LOG_INFO, kp1, now, 7200, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert != NULL);
+ tt_mem_op(kp1, !=, kp2, sizeof(*kp1));
+ tt_int_op(stat(get_fname("test_ed_key_2_cert"), &st), ==, 0);
+ tt_int_op(stat(get_fname("test_ed_key_2_secret_key"), &st), ==, 0);
+
+ tt_assert(cert->cert_valid == 1);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, 32);
+
+ /* Now verify we can load the cert... */
+ kp3 = ed_key_init_from_file(fname2, (INIT_ED_KEY_CREATE|
+ INIT_ED_KEY_NEEDCERT),
+ LOG_INFO, kp1, now, 7200, 7, &cert2);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ tt_mem_op(cert2->encoded, ==, cert->encoded, cert->encoded_len);
+ ed25519_keypair_free(kp3); kp3 = NULL;
+ tor_cert_free(cert2); cert2 = NULL;
+
+ /* ... even without create... */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp1, now, 7200, 7, &cert2);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ tt_mem_op(cert2->encoded, ==, cert->encoded, cert->encoded_len);
+ ed25519_keypair_free(kp3); kp3 = NULL;
+ tor_cert_free(cert2); cert2 = NULL;
+
+ /* ... but that we don't crash or anything if we say we don't want it. */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp1, now, 7200, 7, NULL);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ ed25519_keypair_free(kp3); kp3 = NULL;
+
+ /* Fail if we're told the wrong signing key */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp2, now, 7200, 7, &cert2);
+ tt_assert(kp3 == NULL);
+ tt_assert(cert2 == NULL);
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ ed25519_keypair_free(kp3);
+ tor_cert_free(cert);
+ tor_cert_free(cert2);
+ tor_free(fname1);
+ tor_free(fname2);
+}
+
+static void
+test_routerkeys_ed_key_init_split(void *arg)
+{
+ (void) arg;
+
+ tor_cert_t *cert = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL;
+ time_t now = time(NULL);
+ char *fname1 = tor_strdup(get_fname("test_ed_key_3"));
+ char *fname2 = tor_strdup(get_fname("test_ed_key_4"));
+ struct stat st;
+ const uint32_t flags = INIT_ED_KEY_SPLIT|INIT_ED_KEY_MISSING_SECRET_OK;
+
+ unlink(fname1);
+ unlink(fname2);
+
+ /* Can't load key that isn't there. */
+ kp1 = ed_key_init_from_file(fname1, flags, LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 == NULL);
+ tt_assert(cert == NULL);
+
+ /* Create a split key */
+ kp1 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 != NULL);
+ tt_assert(cert == NULL);
+ tt_int_op(stat(get_fname("test_ed_key_3_cert"), &st), <, 0);
+ tt_int_op(stat(get_fname("test_ed_key_3_secret_key"), &st), ==, 0);
+ tt_int_op(stat(get_fname("test_ed_key_3_public_key"), &st), ==, 0);
+
+ /* Load it. */
+ kp2 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp2));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Okay, try killing the secret key and loading it. */
+ unlink(get_fname("test_ed_key_3_secret_key"));
+ kp2 = ed_key_init_from_file(fname1, flags,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(&kp1->pubkey, ==, &kp2->pubkey, sizeof(kp2->pubkey));
+ tt_assert(tor_mem_is_zero((char*)kp2->seckey.seckey,
+ sizeof(kp2->seckey.seckey)));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Even when we're told to "create", don't create if there's a public key */
+ kp2 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(&kp1->pubkey, ==, &kp2->pubkey, sizeof(kp2->pubkey));
+ tt_assert(tor_mem_is_zero((char*)kp2->seckey.seckey,
+ sizeof(kp2->seckey.seckey)));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Make sure we fail on a tag mismatch, though */
+ kp2 = ed_key_init_from_file(fname1, flags,
+ LOG_INFO, NULL, now, 0, 99, &cert);
+ tt_assert(kp2 == NULL);
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+ tor_free(fname1);
+ tor_free(fname2);
+}
+
+static void
+test_routerkeys_ed_keys_init_all(void *arg)
+{
+ (void)arg;
+ char *dir = tor_strdup(get_fname("test_ed_keys_init_all"));
+ or_options_t *options = tor_malloc_zero(sizeof(or_options_t));
+ time_t now = time(NULL);
+ ed25519_public_key_t id;
+ ed25519_keypair_t sign, auth;
+ tor_cert_t *link_cert = NULL;
+
+ get_options_mutable()->ORPort_set = 1;
+
+ crypto_pk_t *rsa = pk_generate(0);
+
+ set_server_identity_key(rsa);
+ set_client_identity_key(rsa);
+
+ router_initialize_tls_context();
+
+ options->SigningKeyLifetime = 30*86400;
+ options->TestingAuthKeyLifetime = 2*86400;
+ options->TestingLinkCertLifetime = 2*86400;
+ options->TestingSigningKeySlop = 2*86400;
+ options->TestingAuthKeySlop = 2*3600;
+ options->TestingLinkKeySlop = 2*3600;
+
+#ifdef _WIN32
+ mkdir(dir);
+ mkdir(get_fname("test_ed_keys_init_all/keys"));
+#else
+ mkdir(dir, 0700);
+ mkdir(get_fname("test_ed_keys_init_all/keys"), 0700);
+#endif
+
+ options->DataDirectory = dir;
+
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now));
+ tt_assert(get_master_identity_key());
+ tt_assert(get_master_identity_key());
+ tt_assert(get_master_signing_keypair());
+ tt_assert(get_current_auth_keypair());
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_cert_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&id, get_master_identity_key(), sizeof(id));
+ memcpy(&sign, get_master_signing_keypair(), sizeof(sign));
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+ link_cert = tor_cert_dup(get_current_link_cert_cert());
+
+ /* Call load_ed_keys again, but nothing has changed. */
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&auth, ==, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(tor_cert_eq(link_cert, get_current_link_cert_cert()));
+
+ /* Force a reload: we make new link/auth keys. */
+ routerkeys_free_all();
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_assert(tor_cert_eq(link_cert, get_current_link_cert_cert()));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_cert_cert());
+ tt_assert(get_current_auth_key_cert());
+ tor_cert_free(link_cert);
+ link_cert = tor_cert_dup(get_current_link_cert_cert());
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Force a link/auth-key regeneration by advancing time. */
+ tt_int_op(0, ==, load_ed_keys(options, now+3*86400));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now+3*86400));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_assert(! tor_cert_eq(link_cert, get_current_link_cert_cert()));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_cert_cert());
+ tt_assert(get_current_auth_key_cert());
+ tor_cert_free(link_cert);
+ link_cert = tor_cert_dup(get_current_link_cert_cert());
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Force a signing-key regeneration by advancing time. */
+ tt_int_op(0, ==, load_ed_keys(options, now+100*86400));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now+100*86400));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, !=, get_master_signing_keypair(), sizeof(sign));
+ tt_assert(! tor_cert_eq(link_cert, get_current_link_cert_cert()));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_cert_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&sign, get_master_signing_keypair(), sizeof(sign));
+ tor_cert_free(link_cert);
+ link_cert = tor_cert_dup(get_current_link_cert_cert());
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Demonstrate that we can start up with no secret identity key */
+ routerkeys_free_all();
+ unlink(get_fname("test_ed_keys_init_all/keys/"
+ "ed25519_master_id_secret_key"));
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_int_op(0, ==, generate_ed_link_cert(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_assert(! tor_cert_eq(link_cert, get_current_link_cert_cert()));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_cert_cert());
+ tt_assert(get_current_auth_key_cert());
+
+ /* But we're in trouble if we have no id key and our signing key has
+ expired. */
+ log_global_min_severity_ = LOG_ERR; /* Suppress warnings.
+ * XXX (better way to do this)? */
+ routerkeys_free_all();
+ tt_int_op(-1, ==, load_ed_keys(options, now+200*86400));
+
+ done:
+ tor_free(dir);
+ tor_free(options);
+ tor_cert_free(link_cert);
+ routerkeys_free_all();
+}
+
+static void
+test_routerkeys_cross_certify_ntor(void *args)
+{
+ (void) args;
+
+ tor_cert_t *cert = NULL;
+ curve25519_keypair_t onion_keys;
+ ed25519_public_key_t master_key;
+ ed25519_public_key_t onion_check_key;
+ time_t now = time(NULL);
+ int sign;
+
+ tt_int_op(0, ==, ed25519_public_from_base64(&master_key,
+ "IamwritingthesetestsOnARainyAfternoonin2014"));
+ tt_int_op(0, ==, curve25519_keypair_generate(&onion_keys, 0));
+ cert = make_ntor_onion_key_crosscert(&onion_keys,
+ &master_key,
+ now, 10000,
+ &sign);
+ tt_assert(cert);
+ tt_assert(sign == 0 || sign == 1);
+ tt_int_op(cert->cert_type, ==, CERT_TYPE_ONION_ID);
+ tt_int_op(1, ==, ed25519_pubkey_eq(&cert->signed_key, &master_key));
+ tt_int_op(0, ==, ed25519_public_key_from_curve25519_public_key(
+ &onion_check_key, &onion_keys.pubkey, sign));
+ tt_int_op(0, ==, tor_cert_checksig(cert, &onion_check_key, now));
+
+ done:
+ tor_cert_free(cert);
+}
+
+static void
+test_routerkeys_cross_certify_tap(void *args)
+{
+ (void)args;
+ uint8_t *cc = NULL;
+ int cc_len;
+ ed25519_public_key_t master_key;
+ crypto_pk_t *onion_key = pk_generate(2), *id_key = pk_generate(1);
+ char digest[20];
+ char buf[128];
+ int n;
+
+ tt_int_op(0, ==, ed25519_public_from_base64(&master_key,
+ "IAlreadyWroteTestsForRouterdescsUsingTheseX"));
+
+ cc = make_tap_onion_key_crosscert(onion_key,
+ &master_key,
+ id_key, &cc_len);
+ tt_assert(cc);
+ tt_assert(cc_len);
+
+ n = crypto_pk_public_checksig(onion_key, buf, sizeof(buf),
+ (char*)cc, cc_len);
+ tt_int_op(n,>,0);
+ tt_int_op(n,==,52);
+
+ crypto_pk_get_digest(id_key, digest);
+ tt_mem_op(buf,==,digest,20);
+ tt_mem_op(buf+20,==,master_key.pubkey,32);
+
+ tt_int_op(0, ==, check_tap_onion_key_crosscert(cc, cc_len,
+ onion_key, &master_key, (uint8_t*)digest));
+
+ done:
+ tor_free(cc);
+ crypto_pk_free(id_key);
+ crypto_pk_free(onion_key);
+}
+
#define TEST(name, flags) \
{ #name , test_routerkeys_ ## name, (flags), NULL, NULL }
struct testcase_t routerkeys_tests[] = {
TEST(write_fingerprint, TT_FORK),
+ TEST(ed_certs, TT_FORK),
+ TEST(ed_key_create, TT_FORK),
+ TEST(ed_key_init_basic, TT_FORK),
+ TEST(ed_key_init_split, TT_FORK),
+ TEST(ed_keys_init_all, TT_FORK),
+ TEST(cross_certify_ntor, 0),
+ TEST(cross_certify_tap, 0),
END_OF_TESTCASES
};
diff --git a/src/test/test_routerlist.c b/src/test/test_routerlist.c
new file mode 100644
index 0000000000..2cffa6e801
--- /dev/null
+++ b/src/test/test_routerlist.c
@@ -0,0 +1,511 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#include <math.h>
+#include <time.h>
+
+#define DIRVOTE_PRIVATE
+#define NETWORKSTATUS_PRIVATE
+#define ROUTERLIST_PRIVATE
+#define TOR_UNIT_TESTING
+#include "or.h"
+#include "config.h"
+#include "connection.h"
+#include "container.h"
+#include "directory.h"
+#include "dirvote.h"
+#include "microdesc.h"
+#include "networkstatus.h"
+#include "nodelist.h"
+#include "policies.h"
+#include "routerlist.h"
+#include "routerparse.h"
+#include "test.h"
+#include "test_dir_common.h"
+
+extern const char AUTHORITY_CERT_1[];
+extern const char AUTHORITY_SIGNKEY_1[];
+extern const char AUTHORITY_CERT_2[];
+extern const char AUTHORITY_SIGNKEY_2[];
+extern const char AUTHORITY_CERT_3[];
+extern const char AUTHORITY_SIGNKEY_3[];
+
+void construct_consensus(char **consensus_text_md);
+
+/* 4 digests + 3 sep + pre + post + NULL */
+static char output[4*BASE64_DIGEST256_LEN+3+2+2+1];
+
+static void
+mock_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose,
+ const char *resource, int pds_flags,
+ download_want_authority_t want_authority)
+{
+ (void)dir_purpose;
+ (void)router_purpose;
+ (void)pds_flags;
+ (void)want_authority;
+ tt_assert(resource);
+ strlcpy(output, resource, sizeof(output));
+ done:
+ ;
+}
+
+static void
+test_routerlist_initiate_descriptor_downloads(void *arg)
+{
+ const char *prose = "unhurried and wise, we perceive.";
+ smartlist_t *digests = smartlist_new();
+ (void)arg;
+
+ for (int i = 0; i < 20; i++) {
+ smartlist_add(digests, (char*)prose);
+ }
+
+ MOCK(directory_get_from_dirserver, mock_get_from_dirserver);
+ initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_MICRODESC,
+ digests, 3, 7, 0);
+ UNMOCK(directory_get_from_dirserver);
+
+ tt_str_op(output, OP_EQ, "d/"
+ "dW5odXJyaWVkIGFuZCB3aXNlLCB3ZSBwZXJjZWl2ZS4-"
+ "dW5odXJyaWVkIGFuZCB3aXNlLCB3ZSBwZXJjZWl2ZS4-"
+ "dW5odXJyaWVkIGFuZCB3aXNlLCB3ZSBwZXJjZWl2ZS4-"
+ "dW5odXJyaWVkIGFuZCB3aXNlLCB3ZSBwZXJjZWl2ZS4"
+ ".z");
+
+ done:
+ smartlist_free(digests);
+}
+
+static int count = 0;
+
+static void
+mock_initiate_descriptor_downloads(const routerstatus_t *source,
+ int purpose, smartlist_t *digests,
+ int lo, int hi, int pds_flags)
+{
+ (void)source;
+ (void)purpose;
+ (void)digests;
+ (void)pds_flags;
+ (void)hi;
+ (void)lo;
+ count += 1;
+}
+
+static void
+test_routerlist_launch_descriptor_downloads(void *arg)
+{
+ smartlist_t *downloadable = smartlist_new();
+ time_t now = time(NULL);
+ char *cp;
+ (void)arg;
+
+ for (int i = 0; i < 100; i++) {
+ cp = tor_malloc(DIGEST256_LEN);
+ tt_assert(cp);
+ crypto_rand(cp, DIGEST256_LEN);
+ smartlist_add(downloadable, cp);
+ }
+
+ MOCK(initiate_descriptor_downloads, mock_initiate_descriptor_downloads);
+ launch_descriptor_downloads(DIR_PURPOSE_FETCH_MICRODESC, downloadable,
+ NULL, now);
+ tt_int_op(3, ==, count);
+ UNMOCK(initiate_descriptor_downloads);
+
+ done:
+ SMARTLIST_FOREACH(downloadable, char *, cp1, tor_free(cp1));
+ smartlist_free(downloadable);
+}
+
+void
+construct_consensus(char **consensus_text_md)
+{
+ networkstatus_t *vote = NULL;
+ networkstatus_t *v1 = NULL, *v2 = NULL, *v3 = NULL;
+ networkstatus_voter_info_t *voter = NULL;
+ authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
+ crypto_pk_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
+ crypto_pk_t *sign_skey_leg=NULL;
+ time_t now = time(NULL);
+ smartlist_t *votes = NULL;
+ int n_vrs;
+
+ tt_assert(!dir_common_authority_pk_init(&cert1, &cert2, &cert3,
+ &sign_skey_1, &sign_skey_2,
+ &sign_skey_3));
+ sign_skey_leg = pk_generate(4);
+
+ dir_common_construct_vote_1(&vote, cert1, sign_skey_1,
+ &dir_common_gen_routerstatus_for_v3ns,
+ &v1, &n_vrs, now, 1);
+ networkstatus_vote_free(vote);
+ tt_assert(v1);
+ tt_int_op(n_vrs, ==, 4);
+ tt_int_op(smartlist_len(v1->routerstatus_list), ==, 4);
+
+ dir_common_construct_vote_2(&vote, cert2, sign_skey_2,
+ &dir_common_gen_routerstatus_for_v3ns,
+ &v2, &n_vrs, now, 1);
+ networkstatus_vote_free(vote);
+ tt_assert(v2);
+ tt_int_op(n_vrs, ==, 4);
+ tt_int_op(smartlist_len(v2->routerstatus_list), ==, 4);
+
+ dir_common_construct_vote_3(&vote, cert3, sign_skey_3,
+ &dir_common_gen_routerstatus_for_v3ns,
+ &v3, &n_vrs, now, 1);
+
+ tt_assert(v3);
+ tt_int_op(n_vrs, ==, 4);
+ tt_int_op(smartlist_len(v3->routerstatus_list), ==, 4);
+ networkstatus_vote_free(vote);
+ votes = smartlist_new();
+ smartlist_add(votes, v1);
+ smartlist_add(votes, v2);
+ smartlist_add(votes, v3);
+
+ *consensus_text_md = networkstatus_compute_consensus(votes, 3,
+ cert1->identity_key,
+ sign_skey_1,
+ "AAAAAAAAAAAAAAAAAAAA",
+ sign_skey_leg,
+ FLAV_MICRODESC);
+
+ tt_assert(*consensus_text_md);
+
+ done:
+ tor_free(voter);
+ networkstatus_vote_free(v1);
+ networkstatus_vote_free(v2);
+ networkstatus_vote_free(v3);
+ smartlist_free(votes);
+ authority_cert_free(cert1);
+ authority_cert_free(cert2);
+ authority_cert_free(cert3);
+ crypto_pk_free(sign_skey_1);
+ crypto_pk_free(sign_skey_2);
+ crypto_pk_free(sign_skey_3);
+ crypto_pk_free(sign_skey_leg);
+}
+
+static int mock_usable_consensus_flavor_value = FLAV_NS;
+
+static int
+mock_usable_consensus_flavor(void)
+{
+ return mock_usable_consensus_flavor_value;
+}
+
+static void
+test_router_pick_directory_server_impl(void *arg)
+{
+ (void)arg;
+
+ networkstatus_t *con_md = NULL;
+ char *consensus_text_md = NULL;
+ int flags = PDS_IGNORE_FASCISTFIREWALL|PDS_RETRY_IF_NO_SERVERS;
+ or_options_t *options = get_options_mutable();
+ const routerstatus_t *rs = NULL;
+ options->UseMicrodescriptors = 1;
+ char *router1_id = NULL, *router2_id = NULL, *router3_id = NULL;
+ node_t *node_router1 = NULL, *node_router2 = NULL, *node_router3 = NULL;
+ config_line_t *policy_line = NULL;
+ time_t now = time(NULL);
+ int tmp_dirport1, tmp_dirport3;
+
+ (void)arg;
+
+ MOCK(usable_consensus_flavor, mock_usable_consensus_flavor);
+
+ /* With no consensus, we must be bootstrapping, regardless of time or flavor
+ */
+ mock_usable_consensus_flavor_value = FLAV_NS;
+ tt_assert(networkstatus_consensus_is_bootstrapping(now));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2000));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2*24*60*60));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now - 2*24*60*60));
+
+ mock_usable_consensus_flavor_value = FLAV_MICRODESC;
+ tt_assert(networkstatus_consensus_is_bootstrapping(now));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2000));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2*24*60*60));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now - 2*24*60*60));
+
+ /* No consensus available, fail early */
+ rs = router_pick_directory_server_impl(V3_DIRINFO, (const int) 0, NULL);
+ tt_assert(rs == NULL);
+
+ construct_consensus(&consensus_text_md);
+ tt_assert(consensus_text_md);
+ con_md = networkstatus_parse_vote_from_string(consensus_text_md, NULL,
+ NS_TYPE_CONSENSUS);
+ tt_assert(con_md);
+ tt_int_op(con_md->flavor,==, FLAV_MICRODESC);
+ tt_assert(con_md->routerstatus_list);
+ tt_int_op(smartlist_len(con_md->routerstatus_list), ==, 3);
+ tt_assert(!networkstatus_set_current_consensus_from_ns(con_md,
+ "microdesc"));
+
+ /* If the consensus time or flavor doesn't match, we are still
+ * bootstrapping */
+ mock_usable_consensus_flavor_value = FLAV_NS;
+ tt_assert(networkstatus_consensus_is_bootstrapping(now));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2000));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2*24*60*60));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now - 2*24*60*60));
+
+ /* With a valid consensus for the current time and flavor, we stop
+ * bootstrapping, even if we have no certificates */
+ mock_usable_consensus_flavor_value = FLAV_MICRODESC;
+ tt_assert(!networkstatus_consensus_is_bootstrapping(now + 2000));
+ tt_assert(!networkstatus_consensus_is_bootstrapping(con_md->valid_after));
+ tt_assert(!networkstatus_consensus_is_bootstrapping(con_md->valid_until));
+ tt_assert(!networkstatus_consensus_is_bootstrapping(con_md->valid_until
+ + 24*60*60));
+ /* These times are outside the test validity period */
+ tt_assert(networkstatus_consensus_is_bootstrapping(now));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now + 2*24*60*60));
+ tt_assert(networkstatus_consensus_is_bootstrapping(now - 2*24*60*60));
+
+ nodelist_set_consensus(con_md);
+ nodelist_assert_ok();
+
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ /* We should not fail now we have a consensus and routerstatus_list
+ * and nodelist are populated. */
+ tt_assert(rs != NULL);
+
+ /* Manipulate the nodes so we get the dir server we expect */
+ router1_id = tor_malloc(DIGEST_LEN);
+ memset(router1_id, TEST_DIR_ROUTER_ID_1, DIGEST_LEN);
+ router2_id = tor_malloc(DIGEST_LEN);
+ memset(router2_id, TEST_DIR_ROUTER_ID_2, DIGEST_LEN);
+ router3_id = tor_malloc(DIGEST_LEN);
+ memset(router3_id, TEST_DIR_ROUTER_ID_3, DIGEST_LEN);
+
+ node_router1 = node_get_mutable_by_id(router1_id);
+ node_router2 = node_get_mutable_by_id(router2_id);
+ node_router3 = node_get_mutable_by_id(router3_id);
+
+ node_router1->is_possible_guard = 1;
+
+ node_router1->is_running = 0;
+ node_router3->is_running = 0;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router2_id, DIGEST_LEN));
+ rs = NULL;
+ node_router1->is_running = 1;
+ node_router3->is_running = 1;
+
+ node_router1->rs->is_v2_dir = 0;
+ node_router3->rs->is_v2_dir = 0;
+ tmp_dirport1 = node_router1->rs->dir_port;
+ tmp_dirport3 = node_router3->rs->dir_port;
+ node_router1->rs->dir_port = 0;
+ node_router3->rs->dir_port = 0;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router2_id, DIGEST_LEN));
+ rs = NULL;
+ node_router1->rs->is_v2_dir = 1;
+ node_router3->rs->is_v2_dir = 1;
+ node_router1->rs->dir_port = tmp_dirport1;
+ node_router3->rs->dir_port = tmp_dirport3;
+
+ node_router1->is_valid = 0;
+ node_router3->is_valid = 0;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router2_id, DIGEST_LEN));
+ rs = NULL;
+ node_router1->is_valid = 1;
+ node_router3->is_valid = 1;
+
+ flags |= PDS_FOR_GUARD;
+ node_router1->using_as_guard = 1;
+ node_router2->using_as_guard = 1;
+ node_router3->using_as_guard = 1;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs == NULL);
+ node_router1->using_as_guard = 0;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router1_id, DIGEST_LEN));
+ rs = NULL;
+ node_router2->using_as_guard = 0;
+ node_router3->using_as_guard = 0;
+
+ /* One not valid, one guard. This should leave one remaining */
+ node_router1->is_valid = 0;
+ node_router2->using_as_guard = 1;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router3_id, DIGEST_LEN));
+ rs = NULL;
+ node_router1->is_valid = 1;
+ node_router2->using_as_guard = 0;
+
+ /* Manipulate overloaded */
+
+ node_router2->rs->last_dir_503_at = now;
+ node_router3->rs->last_dir_503_at = now;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router1_id, DIGEST_LEN));
+ node_router2->rs->last_dir_503_at = 0;
+ node_router3->rs->last_dir_503_at = 0;
+
+ /* Set a Fascist firewall */
+ flags &= ~ PDS_IGNORE_FASCISTFIREWALL;
+ policy_line = tor_malloc_zero(sizeof(config_line_t));
+ policy_line->key = tor_strdup("ReachableORAddresses");
+ policy_line->value = tor_strdup("accept *:442, reject *:*");
+ options->ReachableORAddresses = policy_line;
+ policies_parse_from_options(options);
+
+ node_router1->rs->or_port = 444;
+ node_router2->rs->or_port = 443;
+ node_router3->rs->or_port = 442;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router3_id, DIGEST_LEN));
+ node_router1->rs->or_port = 442;
+ node_router2->rs->or_port = 443;
+ node_router3->rs->or_port = 444;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router1_id, DIGEST_LEN));
+
+ /* Fascist firewall and overloaded */
+ node_router1->rs->or_port = 442;
+ node_router2->rs->or_port = 443;
+ node_router3->rs->or_port = 442;
+ node_router3->rs->last_dir_503_at = now;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router1_id, DIGEST_LEN));
+ node_router3->rs->last_dir_503_at = 0;
+
+ /* Fascists against OR and Dir */
+ policy_line = tor_malloc_zero(sizeof(config_line_t));
+ policy_line->key = tor_strdup("ReachableAddresses");
+ policy_line->value = tor_strdup("accept *:80, reject *:*");
+ options->ReachableDirAddresses = policy_line;
+ policies_parse_from_options(options);
+ node_router1->rs->or_port = 442;
+ node_router2->rs->or_port = 441;
+ node_router3->rs->or_port = 443;
+ node_router1->rs->dir_port = 80;
+ node_router2->rs->dir_port = 80;
+ node_router3->rs->dir_port = 81;
+ node_router1->rs->last_dir_503_at = now;
+ rs = router_pick_directory_server_impl(V3_DIRINFO, flags, NULL);
+ tt_assert(rs != NULL);
+ tt_assert(tor_memeq(rs->identity_digest, router1_id, DIGEST_LEN));
+ node_router1->rs->last_dir_503_at = 0;
+
+ done:
+ UNMOCK(usable_consensus_flavor);
+ if (router1_id)
+ tor_free(router1_id);
+ if (router2_id)
+ tor_free(router2_id);
+ if (router3_id)
+ tor_free(router3_id);
+ if (options->ReachableORAddresses ||
+ options->ReachableDirAddresses)
+ policies_free_all();
+ tor_free(consensus_text_md);
+ networkstatus_vote_free(con_md);
+}
+
+connection_t *mocked_connection = NULL;
+
+/* Mock connection_get_by_type_addr_port_purpose by returning
+ * mocked_connection. */
+static connection_t *
+mock_connection_get_by_type_addr_port_purpose(int type,
+ const tor_addr_t *addr,
+ uint16_t port, int purpose)
+{
+ (void)type;
+ (void)addr;
+ (void)port;
+ (void)purpose;
+
+ return mocked_connection;
+}
+
+#define TEST_ADDR_STR "127.0.0.1"
+#define TEST_DIR_PORT 12345
+
+static void
+test_routerlist_router_is_already_dir_fetching(void *arg)
+{
+ (void)arg;
+ tor_addr_port_t test_ap, null_addr_ap, zero_port_ap;
+
+ /* Setup */
+ tor_addr_parse(&test_ap.addr, TEST_ADDR_STR);
+ test_ap.port = TEST_DIR_PORT;
+ tor_addr_make_null(&null_addr_ap.addr, AF_INET6);
+ null_addr_ap.port = TEST_DIR_PORT;
+ tor_addr_parse(&zero_port_ap.addr, TEST_ADDR_STR);
+ zero_port_ap.port = 0;
+ MOCK(connection_get_by_type_addr_port_purpose,
+ mock_connection_get_by_type_addr_port_purpose);
+
+ /* Test that we never get 1 from a NULL connection */
+ mocked_connection = NULL;
+ tt_assert(router_is_already_dir_fetching(&test_ap, 1, 1) == 0);
+ tt_assert(router_is_already_dir_fetching(&test_ap, 1, 0) == 0);
+ tt_assert(router_is_already_dir_fetching(&test_ap, 0, 1) == 0);
+ /* We always expect 0 in these cases */
+ tt_assert(router_is_already_dir_fetching(&test_ap, 0, 0) == 0);
+ tt_assert(router_is_already_dir_fetching(NULL, 1, 1) == 0);
+ tt_assert(router_is_already_dir_fetching(&null_addr_ap, 1, 1) == 0);
+ tt_assert(router_is_already_dir_fetching(&zero_port_ap, 1, 1) == 0);
+
+ /* Test that we get 1 with a connection in the appropriate circumstances */
+ mocked_connection = connection_new(CONN_TYPE_DIR, AF_INET);
+ tt_assert(router_is_already_dir_fetching(&test_ap, 1, 1) == 1);
+ tt_assert(router_is_already_dir_fetching(&test_ap, 1, 0) == 1);
+ tt_assert(router_is_already_dir_fetching(&test_ap, 0, 1) == 1);
+
+ /* Test that we get 0 even with a connection in the appropriate
+ * circumstances */
+ tt_assert(router_is_already_dir_fetching(&test_ap, 0, 0) == 0);
+ tt_assert(router_is_already_dir_fetching(NULL, 1, 1) == 0);
+ tt_assert(router_is_already_dir_fetching(&null_addr_ap, 1, 1) == 0);
+ tt_assert(router_is_already_dir_fetching(&zero_port_ap, 1, 1) == 0);
+
+ done:
+ /* If a connection is never set up, connection_free chokes on it. */
+ if (mocked_connection) {
+ buf_free(mocked_connection->inbuf);
+ buf_free(mocked_connection->outbuf);
+ }
+ tor_free(mocked_connection);
+ UNMOCK(connection_get_by_type_addr_port_purpose);
+}
+
+#undef TEST_ADDR_STR
+#undef TEST_DIR_PORT
+
+#define NODE(name, flags) \
+ { #name, test_routerlist_##name, (flags), NULL, NULL }
+#define ROUTER(name,flags) \
+ { #name, test_router_##name, (flags), NULL, NULL }
+
+struct testcase_t routerlist_tests[] = {
+ NODE(initiate_descriptor_downloads, 0),
+ NODE(launch_descriptor_downloads, 0),
+ NODE(router_is_already_dir_fetching, TT_FORK),
+ ROUTER(pick_directory_server_impl, TT_FORK),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_routerset.c b/src/test/test_routerset.c
new file mode 100644
index 0000000000..74b39c0486
--- /dev/null
+++ b/src/test/test_routerset.c
@@ -0,0 +1,2221 @@
+#define ROUTERSET_PRIVATE
+
+#include "or.h"
+#include "geoip.h"
+#include "routerset.h"
+#include "routerparse.h"
+#include "policies.h"
+#include "nodelist.h"
+#include "test.h"
+
+#define NS_MODULE routerset
+
+#define NS_SUBMODULE routerset_new
+
+/*
+ * Functional (blackbox) test to determine that each member of the routerset
+ * is non-NULL
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *rs;
+ (void)arg;
+
+ rs = routerset_new();
+
+ tt_ptr_op(rs, OP_NE, NULL);
+ tt_ptr_op(rs->list, OP_NE, NULL);
+ tt_ptr_op(rs->names, OP_NE, NULL);
+ tt_ptr_op(rs->digests, OP_NE, NULL);
+ tt_ptr_op(rs->policies, OP_NE, NULL);
+ tt_ptr_op(rs->country_names, OP_NE, NULL);
+
+ done:
+ routerset_free(rs);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_get_countryname
+
+/*
+ * Functional test to strip the braces from a "{xx}" country code string.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ const char *input;
+ char *name;
+ (void)arg;
+
+ /* strlen(c) < 4 */
+ input = "xxx";
+ name = routerset_get_countryname(input);
+ tt_ptr_op(name, OP_EQ, NULL);
+ tor_free(name);
+
+ /* c[0] != '{' */
+ input = "xxx}";
+ name = routerset_get_countryname(input);
+ tt_ptr_op(name, OP_EQ, NULL);
+ tor_free(name);
+
+ /* c[3] != '}' */
+ input = "{xxx";
+ name = routerset_get_countryname(input);
+ tt_ptr_op(name, OP_EQ, NULL);
+ tor_free(name);
+
+ /* tor_strlower */
+ input = "{XX}";
+ name = routerset_get_countryname(input);
+ tt_str_op(name, OP_EQ, "xx");
+ tor_free(name);
+
+ input = "{xx}";
+ name = routerset_get_countryname(input);
+ tt_str_op(name, OP_EQ, "xx");
+ done:
+ tor_free(name);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_refresh_counties, geoip_not_loaded)
+
+/*
+ * Structural (whitebox) test for routerset_refresh_counties, when the GeoIP DB
+ * is not loaded.
+ */
+
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+NS_DECL(int, geoip_get_n_countries, (void));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ (void)arg;
+
+ NS_MOCK(geoip_is_loaded);
+ NS_MOCK(geoip_get_n_countries);
+
+ routerset_refresh_countries(set);
+
+ tt_ptr_op(set->countries, OP_EQ, NULL);
+ tt_int_op(set->n_countries, OP_EQ, 0);
+ tt_int_op(CALLED(geoip_is_loaded), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_n_countries), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(geoip_is_loaded);
+ NS_UNMOCK(geoip_get_n_countries);
+ routerset_free(set);
+}
+
+static int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ (void)family;
+ CALLED(geoip_is_loaded)++;
+
+ return 0;
+}
+
+static int
+NS(geoip_get_n_countries)(void)
+{
+ CALLED(geoip_get_n_countries)++;
+
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_refresh_counties, no_countries)
+
+/*
+ * Structural test for routerset_refresh_counties, when there are no countries.
+ */
+
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+NS_DECL(int, geoip_get_n_countries, (void));
+NS_DECL(country_t, geoip_get_country, (const char *country));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ (void)arg;
+
+ NS_MOCK(geoip_is_loaded);
+ NS_MOCK(geoip_get_n_countries);
+ NS_MOCK(geoip_get_country);
+
+ routerset_refresh_countries(set);
+
+ tt_ptr_op(set->countries, OP_NE, NULL);
+ tt_int_op(set->n_countries, OP_EQ, 1);
+ tt_int_op((unsigned int)(*set->countries), OP_EQ, 0);
+ tt_int_op(CALLED(geoip_is_loaded), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_n_countries), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_country), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(geoip_is_loaded);
+ NS_UNMOCK(geoip_get_n_countries);
+ NS_UNMOCK(geoip_get_country);
+ routerset_free(set);
+}
+
+static int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ (void)family;
+ CALLED(geoip_is_loaded)++;
+
+ return 1;
+}
+
+static int
+NS(geoip_get_n_countries)(void)
+{
+ CALLED(geoip_get_n_countries)++;
+
+ return 1;
+}
+
+static country_t
+NS(geoip_get_country)(const char *countrycode)
+{
+ (void)countrycode;
+ CALLED(geoip_get_country)++;
+
+ return 1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_refresh_counties, one_valid_country)
+
+/*
+ * Structural test for routerset_refresh_counties, with one valid country.
+ */
+
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+NS_DECL(int, geoip_get_n_countries, (void));
+NS_DECL(country_t, geoip_get_country, (const char *country));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ (void)arg;
+
+ NS_MOCK(geoip_is_loaded);
+ NS_MOCK(geoip_get_n_countries);
+ NS_MOCK(geoip_get_country);
+ smartlist_add(set->country_names, tor_strndup("foo", 3));
+
+ routerset_refresh_countries(set);
+
+ tt_ptr_op(set->countries, OP_NE, NULL);
+ tt_int_op(set->n_countries, OP_EQ, 2);
+ tt_int_op(CALLED(geoip_is_loaded), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_n_countries), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_country), OP_EQ, 1);
+ tt_int_op((unsigned int)(*set->countries), OP_NE, 0);
+
+ done:
+ NS_UNMOCK(geoip_is_loaded);
+ NS_UNMOCK(geoip_get_n_countries);
+ NS_UNMOCK(geoip_get_country);
+ routerset_free(set);
+}
+
+static int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ (void)family;
+ CALLED(geoip_is_loaded)++;
+
+ return 1;
+}
+
+static int
+NS(geoip_get_n_countries)(void)
+{
+ CALLED(geoip_get_n_countries)++;
+
+ return 2;
+}
+
+static country_t
+NS(geoip_get_country)(const char *countrycode)
+{
+ (void)countrycode;
+ CALLED(geoip_get_country)++;
+
+ return 1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_refresh_counties, one_invalid_country)
+
+/*
+ * Structural test for routerset_refresh_counties, with one invalid
+ * country code..
+ */
+
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+NS_DECL(int, geoip_get_n_countries, (void));
+NS_DECL(country_t, geoip_get_country, (const char *country));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ (void)arg;
+
+ NS_MOCK(geoip_is_loaded);
+ NS_MOCK(geoip_get_n_countries);
+ NS_MOCK(geoip_get_country);
+ smartlist_add(set->country_names, tor_strndup("foo", 3));
+
+ routerset_refresh_countries(set);
+
+ tt_ptr_op(set->countries, OP_NE, NULL);
+ tt_int_op(set->n_countries, OP_EQ, 2);
+ tt_int_op(CALLED(geoip_is_loaded), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_n_countries), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_country), OP_EQ, 1);
+ tt_int_op((unsigned int)(*set->countries), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(geoip_is_loaded);
+ NS_UNMOCK(geoip_get_n_countries);
+ NS_UNMOCK(geoip_get_country);
+ routerset_free(set);
+}
+
+static int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ (void)family;
+ CALLED(geoip_is_loaded)++;
+
+ return 1;
+}
+
+static int
+NS(geoip_get_n_countries)(void)
+{
+ CALLED(geoip_get_n_countries)++;
+
+ return 2;
+}
+
+static country_t
+NS(geoip_get_country)(const char *countrycode)
+{
+ (void)countrycode;
+ CALLED(geoip_get_country)++;
+
+ return -1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, malformed)
+
+/*
+ * Functional test, with a malformed string to parse.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ const char *s = "_";
+ int r;
+ (void)arg;
+
+ r = routerset_parse(set, s, "");
+
+ tt_int_op(r, OP_EQ, -1);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, valid_hexdigest)
+
+/*
+ * Functional test for routerset_parse, that routerset_parse returns 0
+ * on a valid hexdigest entry.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ set = routerset_new();
+ s = "$0000000000000000000000000000000000000000";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(digestmap_isempty(set->digests), OP_NE, 1);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, valid_nickname)
+
+/*
+ * Functional test for routerset_parse, when given a valid nickname as input.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ set = routerset_new();
+ s = "fred";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(strmap_isempty(set->names), OP_NE, 1);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, get_countryname)
+
+/*
+ * Functional test for routerset_parse, when given a valid countryname.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ set = routerset_new();
+ s = "{cc}";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(set->country_names), OP_NE, 0);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, policy_wildcard)
+
+/*
+ * Structural test for routerset_parse, when given a valid wildcard policy.
+ */
+
+NS_DECL(addr_policy_t *, router_parse_addr_policy_item_from_string,
+ (const char *s, int assume_action, int *malformed_list));
+
+addr_policy_t *NS(mock_addr_policy);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ NS_MOCK(router_parse_addr_policy_item_from_string);
+ NS(mock_addr_policy) = tor_malloc_zero(sizeof(addr_policy_t));
+
+ set = routerset_new();
+ s = "*";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(set->policies), OP_NE, 0);
+ tt_int_op(CALLED(router_parse_addr_policy_item_from_string), OP_EQ, 1);
+
+ done:
+ routerset_free(set);
+}
+
+addr_policy_t *
+NS(router_parse_addr_policy_item_from_string)(const char *s,
+ int assume_action,
+ int *malformed_list)
+{
+ (void)s;
+ (void)assume_action;
+ (void)malformed_list;
+ CALLED(router_parse_addr_policy_item_from_string)++;
+
+ return NS(mock_addr_policy);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, policy_ipv4)
+
+/*
+ * Structural test for routerset_parse, when given a valid IPv4 address
+ * literal policy.
+ */
+
+NS_DECL(addr_policy_t *, router_parse_addr_policy_item_from_string,
+ (const char *s, int assume_action, int *bogus));
+
+addr_policy_t *NS(mock_addr_policy);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ NS_MOCK(router_parse_addr_policy_item_from_string);
+ NS(mock_addr_policy) = tor_malloc_zero(sizeof(addr_policy_t));
+
+ set = routerset_new();
+ s = "127.0.0.1";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(set->policies), OP_NE, 0);
+ tt_int_op(CALLED(router_parse_addr_policy_item_from_string), OP_EQ, 1);
+
+ done:
+ routerset_free(set);
+}
+
+addr_policy_t *
+NS(router_parse_addr_policy_item_from_string)(const char *s, int assume_action,
+ int *bogus)
+{
+ (void)s;
+ (void)assume_action;
+ CALLED(router_parse_addr_policy_item_from_string)++;
+ *bogus = 0;
+
+ return NS(mock_addr_policy);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_parse, policy_ipv6)
+
+/*
+ * Structural test for routerset_parse, when given a valid IPv6 address
+ * literal policy.
+ */
+
+NS_DECL(addr_policy_t *, router_parse_addr_policy_item_from_string,
+ (const char *s, int assume_action, int *bad));
+
+addr_policy_t *NS(mock_addr_policy);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ const char *s;
+ int r;
+ (void)arg;
+
+ NS_MOCK(router_parse_addr_policy_item_from_string);
+ NS(mock_addr_policy) = tor_malloc_zero(sizeof(addr_policy_t));
+
+ set = routerset_new();
+ s = "::1";
+ r = routerset_parse(set, s, "");
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(smartlist_len(set->policies), OP_NE, 0);
+ tt_int_op(CALLED(router_parse_addr_policy_item_from_string), OP_EQ, 1);
+
+ done:
+ routerset_free(set);
+}
+
+addr_policy_t *
+NS(router_parse_addr_policy_item_from_string)(const char *s,
+ int assume_action, int *bad)
+{
+ (void)s;
+ (void)assume_action;
+ CALLED(router_parse_addr_policy_item_from_string)++;
+ *bad = 0;
+
+ return NS(mock_addr_policy);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_union, source_bad)
+
+/*
+ * Structural test for routerset_union, when given a bad source argument.
+ */
+
+NS_DECL(smartlist_t *, smartlist_new, (void));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set, *bad_set;
+ (void)arg;
+
+ set = routerset_new();
+ bad_set = routerset_new();
+ smartlist_free(bad_set->list);
+ bad_set->list = NULL;
+
+ NS_MOCK(smartlist_new);
+
+ routerset_union(set, NULL);
+ tt_int_op(CALLED(smartlist_new), OP_EQ, 0);
+
+ routerset_union(set, bad_set);
+ tt_int_op(CALLED(smartlist_new), OP_EQ, 0);
+
+ done:
+ NS_UNMOCK(smartlist_new);
+ routerset_free(set);
+
+ /* Just recreate list, so we can simply use routerset_free. */
+ bad_set->list = smartlist_new();
+ routerset_free(bad_set);
+}
+
+static smartlist_t *
+NS(smartlist_new)(void)
+{
+ CALLED(smartlist_new)++;
+
+ return NULL;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_union, one)
+
+/*
+ * Functional test for routerset_union.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *src = routerset_new();
+ routerset_t *tgt;
+ (void)arg;
+
+ tgt = routerset_new();
+ smartlist_add(src->list, tor_strdup("{xx}"));
+ routerset_union(tgt, src);
+
+ tt_int_op(smartlist_len(tgt->list), OP_NE, 0);
+
+ done:
+ routerset_free(src);
+ routerset_free(tgt);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_is_list
+
+/*
+ * Functional tests for routerset_is_list.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set;
+ addr_policy_t *policy;
+ int is_list;
+ (void)arg;
+
+ /* len(set->country_names) == 0, len(set->policies) == 0 */
+ set = routerset_new();
+ is_list = routerset_is_list(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_list, OP_NE, 0);
+
+ /* len(set->country_names) != 0, len(set->policies) == 0 */
+ set = routerset_new();
+ smartlist_add(set->country_names, tor_strndup("foo", 3));
+ is_list = routerset_is_list(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_list, OP_EQ, 0);
+
+ /* len(set->country_names) == 0, len(set->policies) != 0 */
+ set = routerset_new();
+ policy = tor_malloc_zero(sizeof(addr_policy_t));
+ smartlist_add(set->policies, (void *)policy);
+ is_list = routerset_is_list(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_list, OP_EQ, 0);
+
+ /* len(set->country_names) != 0, len(set->policies) != 0 */
+ set = routerset_new();
+ smartlist_add(set->country_names, tor_strndup("foo", 3));
+ policy = tor_malloc_zero(sizeof(addr_policy_t));
+ smartlist_add(set->policies, (void *)policy);
+ is_list = routerset_is_list(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_list, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_needs_geoip
+
+/*
+ * Functional tests for routerset_needs_geoip.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ const routerset_t *set;
+ int needs_geoip;
+ (void)arg;
+
+ set = NULL;
+ needs_geoip = routerset_needs_geoip(set);
+ tt_int_op(needs_geoip, OP_EQ, 0);
+
+ set = routerset_new();
+ needs_geoip = routerset_needs_geoip(set);
+ routerset_free((routerset_t *)set);
+ tt_int_op(needs_geoip, OP_EQ, 0);
+ set = NULL;
+
+ set = routerset_new();
+ smartlist_add(set->country_names, tor_strndup("xx", 2));
+ needs_geoip = routerset_needs_geoip(set);
+ routerset_free((routerset_t *)set);
+ set = NULL;
+ tt_int_op(needs_geoip, OP_NE, 0);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_is_empty
+
+/*
+ * Functional tests for routerset_is_empty.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = NULL;
+ int is_empty;
+ (void)arg;
+
+ is_empty = routerset_is_empty(set);
+ tt_int_op(is_empty, OP_NE, 0);
+
+ set = routerset_new();
+ is_empty = routerset_is_empty(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_empty, OP_NE, 0);
+
+ set = routerset_new();
+ smartlist_add(set->list, tor_strdup("{xx}"));
+ is_empty = routerset_is_empty(set);
+ routerset_free(set);
+ set = NULL;
+ tt_int_op(is_empty, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, null_set_or_null_set_list)
+
+/*
+ * Functional test for routerset_contains, when given a NULL set or the
+ * set has a NULL list.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = NULL;
+ int contains;
+ (void)arg;
+
+ contains = routerset_contains(set, NULL, 0, NULL, NULL, 0);
+
+ tt_int_op(contains, OP_EQ, 0);
+
+ set = tor_malloc_zero(sizeof(routerset_t));
+ set->list = NULL;
+ contains = routerset_contains(set, NULL, 0, NULL, NULL, 0);
+ tor_free(set);
+ tt_int_op(contains, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_null_nickname)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset but a
+ * NULL nickname.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ char *nickname = NULL;
+ int contains;
+ (void)arg;
+
+ contains = routerset_contains(set, NULL, 0, nickname, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_nickname)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset
+ * and the nickname is in the routerset.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ const char *nickname;
+ int contains;
+ (void)arg;
+
+ nickname = "Foo"; /* This tests the lowercase comparison as well. */
+ strmap_set_lc(set->names, nickname, (void *)1);
+ contains = routerset_contains(set, NULL, 0, nickname, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 4);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_no_nickname)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset
+ * and the nickname is not in the routerset.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains;
+ (void)arg;
+
+ strmap_set_lc(set->names, "bar", (void *)1);
+ contains = routerset_contains(set, NULL, 0, "foo", NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_digest)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset
+ * and the digest is contained in the routerset.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains;
+ uint8_t foo[20] = { 2, 3, 4 };
+ (void)arg;
+
+ digestmap_set(set->digests, (const char*)foo, (void *)1);
+ contains = routerset_contains(set, NULL, 0, NULL, (const char*)foo, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 4);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_no_digest)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset
+ * and the digest is not contained in the routerset.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains;
+ uint8_t bar[20] = { 9, 10, 11, 55 };
+ uint8_t foo[20] = { 1, 2, 3, 4};
+ (void)arg;
+
+ digestmap_set(set->digests, (const char*)bar, (void *)1);
+ contains = routerset_contains(set, NULL, 0, NULL, (const char*)foo, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_null_digest)
+
+/*
+ * Functional test for routerset_contains, when given a valid routerset
+ * and the digest is NULL.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains;
+ uint8_t bar[20] = { 9, 10, 11, 55 };
+ (void)arg;
+
+ digestmap_set(set->digests, (const char*)bar, (void *)1);
+ contains = routerset_contains(set, NULL, 0, NULL, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_addr)
+
+/*
+ * Structural test for routerset_contains, when given a valid routerset
+ * and the address is rejected by policy.
+ */
+
+NS_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
+ (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
+
+static tor_addr_t MOCK_TOR_ADDR;
+#define MOCK_TOR_ADDR_PTR (&MOCK_TOR_ADDR)
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ tor_addr_t *addr = MOCK_TOR_ADDR_PTR;
+ int contains;
+ (void)arg;
+
+ NS_MOCK(compare_tor_addr_to_addr_policy);
+
+ contains = routerset_contains(set, addr, 0, NULL, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(CALLED(compare_tor_addr_to_addr_policy), OP_EQ, 1);
+ tt_int_op(contains, OP_EQ, 3);
+
+ done:
+ ;
+}
+
+addr_policy_result_t
+NS(compare_tor_addr_to_addr_policy)(const tor_addr_t *addr, uint16_t port,
+ const smartlist_t *policy)
+{
+ (void)port;
+ (void)policy;
+ CALLED(compare_tor_addr_to_addr_policy)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+ return ADDR_POLICY_REJECTED;
+
+ done:
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_no_addr)
+
+/*
+ * Structural test for routerset_contains, when given a valid routerset
+ * and the address is not rejected by policy.
+ */
+
+NS_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
+ (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ tor_addr_t *addr = MOCK_TOR_ADDR_PTR;
+ int contains;
+ (void)arg;
+
+ NS_MOCK(compare_tor_addr_to_addr_policy);
+
+ contains = routerset_contains(set, addr, 0, NULL, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(CALLED(compare_tor_addr_to_addr_policy), OP_EQ, 1);
+ tt_int_op(contains, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+addr_policy_result_t
+NS(compare_tor_addr_to_addr_policy)(const tor_addr_t *addr, uint16_t port,
+ const smartlist_t *policy)
+{
+ (void)port;
+ (void)policy;
+ CALLED(compare_tor_addr_to_addr_policy)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ return ADDR_POLICY_ACCEPTED;
+
+ done:
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, set_and_null_addr)
+
+/*
+ * Structural test for routerset_contains, when given a valid routerset
+ * and the address is NULL.
+ */
+
+NS_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
+ (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains;
+ (void)arg;
+
+ NS_MOCK(compare_tor_addr_to_addr_policy);
+
+ contains = routerset_contains(set, NULL, 0, NULL, NULL, 0);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+
+ done:
+ ;
+}
+
+addr_policy_result_t
+NS(compare_tor_addr_to_addr_policy)(const tor_addr_t *addr, uint16_t port,
+ const smartlist_t *policy)
+{
+ (void)port;
+ (void)policy;
+ CALLED(compare_tor_addr_to_addr_policy)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ return ADDR_POLICY_ACCEPTED;
+
+ done:
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, countries_no_geoip)
+
+/*
+ * Structural test for routerset_contains, when there is no matching country
+ * for the address.
+ */
+
+NS_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
+ (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
+NS_DECL(int, geoip_get_country_by_addr, (const tor_addr_t *addr));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains = 1;
+ (void)arg;
+
+ NS_MOCK(compare_tor_addr_to_addr_policy);
+ NS_MOCK(geoip_get_country_by_addr);
+
+ set->countries = bitarray_init_zero(1);
+ bitarray_set(set->countries, 1);
+ contains = routerset_contains(set, MOCK_TOR_ADDR_PTR, 0, NULL, NULL, -1);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 0);
+ tt_int_op(CALLED(compare_tor_addr_to_addr_policy), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_country_by_addr), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+addr_policy_result_t
+NS(compare_tor_addr_to_addr_policy)(const tor_addr_t *addr, uint16_t port,
+ const smartlist_t *policy)
+{
+ (void)port;
+ (void)policy;
+ CALLED(compare_tor_addr_to_addr_policy)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ done:
+ return ADDR_POLICY_ACCEPTED;
+}
+
+int
+NS(geoip_get_country_by_addr)(const tor_addr_t *addr)
+{
+ CALLED(geoip_get_country_by_addr)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ done:
+ return -1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains, countries_geoip)
+
+/*
+ * Structural test for routerset_contains, when there a matching country
+ * for the address.
+ */
+
+NS_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
+ (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
+NS_DECL(int, geoip_get_country_by_addr, (const tor_addr_t *addr));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int contains = 1;
+ (void)arg;
+
+ NS_MOCK(compare_tor_addr_to_addr_policy);
+ NS_MOCK(geoip_get_country_by_addr);
+
+ set->n_countries = 2;
+ set->countries = bitarray_init_zero(1);
+ bitarray_set(set->countries, 1);
+ contains = routerset_contains(set, MOCK_TOR_ADDR_PTR, 0, NULL, NULL, -1);
+ routerset_free(set);
+
+ tt_int_op(contains, OP_EQ, 2);
+ tt_int_op(CALLED(compare_tor_addr_to_addr_policy), OP_EQ, 1);
+ tt_int_op(CALLED(geoip_get_country_by_addr), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+addr_policy_result_t
+NS(compare_tor_addr_to_addr_policy)(const tor_addr_t *addr, uint16_t port,
+ const smartlist_t *policy)
+{
+ (void)port;
+ (void)policy;
+ CALLED(compare_tor_addr_to_addr_policy)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ done:
+ return ADDR_POLICY_ACCEPTED;
+}
+
+int
+NS(geoip_get_country_by_addr)(const tor_addr_t *addr)
+{
+ CALLED(geoip_get_country_by_addr)++;
+ tt_ptr_op(addr, OP_EQ, MOCK_TOR_ADDR_PTR);
+
+ done:
+ return 1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_add_unknown_ccs, only_flag_and_no_ccs)
+
+/*
+ * Functional test for routerset_add_unknown_ccs, where only_if_some_cc_set
+ * is set and there are no country names.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ routerset_t **setp = &set;
+ int r;
+ (void)arg;
+
+ r = routerset_add_unknown_ccs(setp, 1);
+
+ tt_int_op(r, OP_EQ, 0);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_add_unknown_ccs, creates_set)
+
+/*
+ * Functional test for routerset_add_unknown_ccs, where the set argument
+ * is created if passed in as NULL.
+ */
+
+/* The mock is only used to stop the test from asserting erroneously. */
+NS_DECL(country_t, geoip_get_country, (const char *country));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = NULL;
+ routerset_t **setp = &set;
+ int r;
+ (void)arg;
+
+ NS_MOCK(geoip_get_country);
+
+ r = routerset_add_unknown_ccs(setp, 0);
+
+ tt_ptr_op(*setp, OP_NE, NULL);
+ tt_int_op(r, OP_EQ, 0);
+
+ done:
+ if (set != NULL)
+ routerset_free(set);
+}
+
+country_t
+NS(geoip_get_country)(const char *country)
+{
+ (void)country;
+ CALLED(geoip_get_country)++;
+
+ return -1;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_add_unknown_ccs, add_unknown)
+
+/*
+ * Structural test for routerset_add_unknown_ccs, that the "{??}"
+ * country code is added to the list.
+ */
+
+NS_DECL(country_t, geoip_get_country, (const char *country));
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ routerset_t **setp = &set;
+ int r;
+ (void)arg;
+
+ NS_MOCK(geoip_get_country);
+ NS_MOCK(geoip_is_loaded);
+
+ r = routerset_add_unknown_ccs(setp, 0);
+
+ tt_int_op(r, OP_EQ, 1);
+ tt_int_op(smartlist_contains_string(set->country_names, "??"), OP_EQ, 1);
+ tt_int_op(smartlist_contains_string(set->list, "{??}"), OP_EQ, 1);
+
+ done:
+ if (set != NULL)
+ routerset_free(set);
+}
+
+country_t
+NS(geoip_get_country)(const char *country)
+{
+ int arg_is_qq, arg_is_a1;
+
+ CALLED(geoip_get_country)++;
+
+ arg_is_qq = !strcmp(country, "??");
+ arg_is_a1 = !strcmp(country, "A1");
+
+ tt_int_op(arg_is_qq || arg_is_a1, OP_EQ, 1);
+
+ if (arg_is_qq)
+ return 1;
+
+ done:
+ return -1;
+}
+
+int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ CALLED(geoip_is_loaded)++;
+
+ tt_int_op(family, OP_EQ, AF_INET);
+
+ done:
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_add_unknown_ccs, add_a1)
+
+/*
+ * Structural test for routerset_add_unknown_ccs, that the "{a1}"
+ * country code is added to the list.
+ */
+
+NS_DECL(country_t, geoip_get_country, (const char *country));
+NS_DECL(int, geoip_is_loaded, (sa_family_t family));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ routerset_t **setp = &set;
+ int r;
+ (void)arg;
+
+ NS_MOCK(geoip_get_country);
+ NS_MOCK(geoip_is_loaded);
+
+ r = routerset_add_unknown_ccs(setp, 0);
+
+ tt_int_op(r, OP_EQ, 1);
+ tt_int_op(smartlist_contains_string(set->country_names, "a1"), OP_EQ, 1);
+ tt_int_op(smartlist_contains_string(set->list, "{a1}"), OP_EQ, 1);
+
+ done:
+ if (set != NULL)
+ routerset_free(set);
+}
+
+country_t
+NS(geoip_get_country)(const char *country)
+{
+ int arg_is_qq, arg_is_a1;
+
+ CALLED(geoip_get_country)++;
+
+ arg_is_qq = !strcmp(country, "??");
+ arg_is_a1 = !strcmp(country, "A1");
+
+ tt_int_op(arg_is_qq || arg_is_a1, OP_EQ, 1);
+
+ if (arg_is_a1)
+ return 1;
+
+ done:
+ return -1;
+}
+
+int
+NS(geoip_is_loaded)(sa_family_t family)
+{
+ CALLED(geoip_is_loaded)++;
+
+ tt_int_op(family, OP_EQ, AF_INET);
+
+ done:
+ return 0;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_contains_extendinfo
+
+/*
+ * Functional test for routerset_contains_extendinfo.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ extend_info_t ei;
+ int r;
+ const char *nickname = "foo";
+ (void)arg;
+
+ memset(&ei, 0, sizeof(ei));
+ strmap_set_lc(set->names, nickname, (void *)1);
+ strncpy(ei.nickname, nickname, sizeof(ei.nickname) - 1);
+ ei.nickname[sizeof(ei.nickname) - 1] = '\0';
+
+ r = routerset_contains_extendinfo(set, &ei);
+
+ tt_int_op(r, OP_EQ, 4);
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_contains_router
+
+/*
+ * Functional test for routerset_contains_router.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ routerinfo_t ri;
+ country_t country = 1;
+ int r;
+ const char *nickname = "foo";
+ (void)arg;
+
+ memset(&ri, 0, sizeof(ri));
+ strmap_set_lc(set->names, nickname, (void *)1);
+ ri.nickname = (char *)nickname;
+
+ r = routerset_contains_router(set, &ri, country);
+
+ tt_int_op(r, OP_EQ, 4);
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_contains_routerstatus
+
+/*
+ * Functional test for routerset_contains_routerstatus.
+ */
+
+// XXX: This is a bit brief. It only populates and tests the nickname fields
+// ie., enough to make the containment check succeed. Perhaps it should do
+// a bit more or test a bit more.
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ routerstatus_t rs;
+ country_t country = 1;
+ int r;
+ const char *nickname = "foo";
+ (void)arg;
+
+ memset(&rs, 0, sizeof(rs));
+ strmap_set_lc(set->names, nickname, (void *)1);
+ strncpy(rs.nickname, nickname, sizeof(rs.nickname) - 1);
+ rs.nickname[sizeof(rs.nickname) - 1] = '\0';
+
+ r = routerset_contains_routerstatus(set, &rs, country);
+
+ tt_int_op(r, OP_EQ, 4);
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains_node, none)
+
+/*
+ * Functional test for routerset_contains_node, when the node has no
+ * routerset or routerinfo.
+ */
+
+node_t NS(mock_node);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int r;
+ (void)arg;
+
+ NS(mock_node).ri = NULL;
+ NS(mock_node).rs = NULL;
+
+ r = routerset_contains_node(set, &NS(mock_node));
+ tt_int_op(r, OP_EQ, 0);
+
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains_node, routerstatus)
+
+/*
+ * Functional test for routerset_contains_node, when the node has a
+ * routerset and no routerinfo.
+ */
+
+node_t NS(mock_node);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int r;
+ const char *nickname = "foo";
+ routerstatus_t rs;
+ (void)arg;
+
+ strmap_set_lc(set->names, nickname, (void *)1);
+
+ strncpy(rs.nickname, nickname, sizeof(rs.nickname) - 1);
+ rs.nickname[sizeof(rs.nickname) - 1] = '\0';
+ NS(mock_node).ri = NULL;
+ NS(mock_node).rs = &rs;
+
+ r = routerset_contains_node(set, &NS(mock_node));
+
+ tt_int_op(r, OP_EQ, 4);
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_contains_node, routerinfo)
+
+/*
+ * Functional test for routerset_contains_node, when the node has no
+ * routerset and a routerinfo.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ int r;
+ const char *nickname = "foo";
+ routerinfo_t ri;
+ node_t mock_node;
+ (void)arg;
+
+ strmap_set_lc(set->names, nickname, (void *)1);
+
+ ri.nickname = (char *)nickname;
+ mock_node.ri = &ri;
+ mock_node.rs = NULL;
+
+ r = routerset_contains_node(set, &mock_node);
+
+ tt_int_op(r, OP_EQ, 4);
+ done:
+ routerset_free(set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, no_routerset)
+
+/*
+ * Functional test for routerset_get_all_nodes, when routerset is NULL or
+ * the routerset list is NULL.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ smartlist_t *out = smartlist_new();
+ routerset_t *set = NULL;
+ (void)arg;
+
+ tt_int_op(smartlist_len(out), OP_EQ, 0);
+ routerset_get_all_nodes(out, NULL, NULL, 0);
+
+ tt_int_op(smartlist_len(out), OP_EQ, 0);
+
+ set = routerset_new();
+ smartlist_free(set->list);
+ routerset_get_all_nodes(out, NULL, NULL, 0);
+ tt_int_op(smartlist_len(out), OP_EQ, 0);
+
+ /* Just recreate list, so we can simply use routerset_free. */
+ set->list = smartlist_new();
+
+ done:
+ routerset_free(set);
+ smartlist_free(out);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, list_with_no_nodes)
+
+/*
+ * Structural test for routerset_get_all_nodes, when the routerset list
+ * is empty.
+ */
+
+NS_DECL(const node_t *, node_get_by_nickname,
+ (const char *nickname, int warn_if_unused));
+const char *NS(mock_nickname);
+
+static void
+NS(test_main)(void *arg)
+{
+ smartlist_t *out = smartlist_new();
+ routerset_t *set = routerset_new();
+ int out_len;
+ (void)arg;
+
+ NS_MOCK(node_get_by_nickname);
+
+ NS(mock_nickname) = "foo";
+ smartlist_add(set->list, tor_strdup(NS(mock_nickname)));
+
+ routerset_get_all_nodes(out, set, NULL, 0);
+ out_len = smartlist_len(out);
+
+ smartlist_free(out);
+ routerset_free(set);
+
+ tt_int_op(out_len, OP_EQ, 0);
+ tt_int_op(CALLED(node_get_by_nickname), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+const node_t *
+NS(node_get_by_nickname)(const char *nickname, int warn_if_unused)
+{
+ CALLED(node_get_by_nickname)++;
+ tt_str_op(nickname, OP_EQ, NS(mock_nickname));
+ tt_int_op(warn_if_unused, OP_EQ, 1);
+
+ done:
+ return NULL;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, list_flag_not_running)
+
+/*
+ * Structural test for routerset_get_all_nodes, with the running_only flag
+ * is set but the nodes are not running.
+ */
+
+NS_DECL(const node_t *, node_get_by_nickname,
+ (const char *nickname, int warn_if_unused));
+const char *NS(mock_nickname);
+node_t NS(mock_node);
+
+static void
+NS(test_main)(void *arg)
+{
+ smartlist_t *out = smartlist_new();
+ routerset_t *set = routerset_new();
+ int out_len;
+ (void)arg;
+
+ NS_MOCK(node_get_by_nickname);
+
+ NS(mock_node).is_running = 0;
+ NS(mock_nickname) = "foo";
+ smartlist_add(set->list, tor_strdup(NS(mock_nickname)));
+
+ routerset_get_all_nodes(out, set, NULL, 1);
+ out_len = smartlist_len(out);
+
+ smartlist_free(out);
+ routerset_free(set);
+
+ tt_int_op(out_len, OP_EQ, 0);
+ tt_int_op(CALLED(node_get_by_nickname), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+const node_t *
+NS(node_get_by_nickname)(const char *nickname, int warn_if_unused)
+{
+ CALLED(node_get_by_nickname)++;
+ tt_str_op(nickname, OP_EQ, NS(mock_nickname));
+ tt_int_op(warn_if_unused, OP_EQ, 1);
+
+ done:
+ return &NS(mock_node);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, list)
+
+/*
+ * Structural test for routerset_get_all_nodes.
+ */
+
+NS_DECL(const node_t *, node_get_by_nickname,
+ (const char *nickname, int warn_if_unused));
+char *NS(mock_nickname);
+node_t NS(mock_node);
+
+static void
+NS(test_main)(void *arg)
+{
+ smartlist_t *out = smartlist_new();
+ routerset_t *set = routerset_new();
+ int out_len;
+ node_t *ent;
+ (void)arg;
+
+ NS_MOCK(node_get_by_nickname);
+
+ NS(mock_nickname) = tor_strdup("foo");
+ smartlist_add(set->list, NS(mock_nickname));
+
+ routerset_get_all_nodes(out, set, NULL, 0);
+ out_len = smartlist_len(out);
+ ent = (node_t *)smartlist_get(out, 0);
+
+ smartlist_free(out);
+ routerset_free(set);
+
+ tt_int_op(out_len, OP_EQ, 1);
+ tt_ptr_op(ent, OP_EQ, &NS(mock_node));
+ tt_int_op(CALLED(node_get_by_nickname), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+const node_t *
+NS(node_get_by_nickname)(const char *nickname, int warn_if_unused)
+{
+ CALLED(node_get_by_nickname)++;
+ tt_str_op(nickname, OP_EQ, NS(mock_nickname));
+ tt_int_op(warn_if_unused, OP_EQ, 1);
+
+ done:
+ return &NS(mock_node);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, nodelist_with_no_nodes)
+
+/*
+ * Structural test for routerset_get_all_nodes, when the nodelist has no nodes.
+ */
+
+NS_DECL(smartlist_t *, nodelist_get_list, (void));
+
+smartlist_t *NS(mock_smartlist);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ smartlist_t *out = smartlist_new();
+ int r;
+ (void)arg;
+
+ NS_MOCK(nodelist_get_list);
+
+ smartlist_add(set->country_names, tor_strdup("{xx}"));
+ NS(mock_smartlist) = smartlist_new();
+
+ routerset_get_all_nodes(out, set, NULL, 1);
+ r = smartlist_len(out);
+ routerset_free(set);
+ smartlist_free(out);
+ smartlist_free(NS(mock_smartlist));
+
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(CALLED(nodelist_get_list), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+smartlist_t *
+NS(nodelist_get_list)(void)
+{
+ CALLED(nodelist_get_list)++;
+
+ return NS(mock_smartlist);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_get_all_nodes, nodelist_flag_not_running)
+
+/*
+ * Structural test for routerset_get_all_nodes, with a non-list routerset
+ * the running_only flag is set, but the nodes are not running.
+ */
+
+NS_DECL(smartlist_t *, nodelist_get_list, (void));
+
+smartlist_t *NS(mock_smartlist);
+node_t NS(mock_node);
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ smartlist_t *out = smartlist_new();
+ int r;
+ (void)arg;
+
+ NS_MOCK(nodelist_get_list);
+
+ smartlist_add(set->country_names, tor_strdup("{xx}"));
+ NS(mock_smartlist) = smartlist_new();
+ NS(mock_node).is_running = 0;
+ smartlist_add(NS(mock_smartlist), (void *)&NS(mock_node));
+
+ routerset_get_all_nodes(out, set, NULL, 1);
+ r = smartlist_len(out);
+ routerset_free(set);
+ smartlist_free(out);
+ smartlist_free(NS(mock_smartlist));
+
+ tt_int_op(r, OP_EQ, 0);
+ tt_int_op(CALLED(nodelist_get_list), OP_EQ, 1);
+
+ done:
+ ;
+}
+
+smartlist_t *
+NS(nodelist_get_list)(void)
+{
+ CALLED(nodelist_get_list)++;
+
+ return NS(mock_smartlist);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_subtract_nodes
+
+/*
+ * Functional test for routerset_subtract_nodes.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = routerset_new();
+ smartlist_t *list = smartlist_new();
+ const char *nickname = "foo";
+ routerinfo_t ri;
+ node_t mock_node;
+ (void)arg;
+
+ strmap_set_lc(set->names, nickname, (void *)1);
+
+ ri.nickname = (char *)nickname;
+ mock_node.rs = NULL;
+ mock_node.ri = &ri;
+ smartlist_add(list, (void *)&mock_node);
+
+ tt_int_op(smartlist_len(list), OP_NE, 0);
+ routerset_subtract_nodes(list, set);
+
+ tt_int_op(smartlist_len(list), OP_EQ, 0);
+ done:
+ routerset_free(set);
+ smartlist_free(list);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_subtract_nodes, null_routerset)
+
+/*
+ * Functional test for routerset_subtract_nodes, with a NULL routerset.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = NULL;
+ smartlist_t *list = smartlist_new();
+ const char *nickname = "foo";
+ routerinfo_t ri;
+ node_t mock_node;
+ (void)arg;
+
+ ri.nickname = (char *)nickname;
+ mock_node.ri = &ri;
+ smartlist_add(list, (void *)&mock_node);
+
+ tt_int_op(smartlist_len(list), OP_NE, 0);
+ routerset_subtract_nodes(list, set);
+
+ tt_int_op(smartlist_len(list), OP_NE, 0);
+ done:
+ routerset_free(set);
+ smartlist_free(list);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_to_string
+
+/*
+ * Functional test for routerset_to_string.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *set = NULL;
+ char *s = NULL;
+ (void)arg;
+
+ set = NULL;
+ s = routerset_to_string(set);
+ tt_str_op(s, OP_EQ, "");
+ tor_free(s);
+
+ set = routerset_new();
+ s = routerset_to_string(set);
+ tt_str_op(s, OP_EQ, "");
+ tor_free(s);
+ routerset_free(set); set = NULL;
+
+ set = routerset_new();
+ smartlist_add(set->list, tor_strndup("a", 1));
+ s = routerset_to_string(set);
+ tt_str_op(s, OP_EQ, "a");
+ tor_free(s);
+ routerset_free(set); set = NULL;
+
+ set = routerset_new();
+ smartlist_add(set->list, tor_strndup("a", 1));
+ smartlist_add(set->list, tor_strndup("b", 1));
+ s = routerset_to_string(set);
+ tt_str_op(s, OP_EQ, "a,b");
+ tor_free(s);
+ routerset_free(set); set = NULL;
+
+ done:
+ tor_free(s);
+ routerset_free((routerset_t *)set);
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_equal, empty_empty)
+
+/*
+ * Functional test for routerset_equal, with both routersets empty.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *a = routerset_new(), *b = routerset_new();
+ int r;
+ (void)arg;
+
+ r = routerset_equal(a, b);
+ routerset_free(a);
+ routerset_free(b);
+
+ tt_int_op(r, OP_EQ, 1);
+
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_equal, empty_not_empty)
+
+/*
+ * Functional test for routerset_equal, with one routersets empty.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *a = routerset_new(), *b = routerset_new();
+ int r;
+ (void)arg;
+
+ smartlist_add(b->list, tor_strdup("{xx}"));
+ r = routerset_equal(a, b);
+ routerset_free(a);
+ routerset_free(b);
+
+ tt_int_op(r, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_equal, differing_lengths)
+
+/*
+ * Functional test for routerset_equal, with the routersets having
+ * differing lengths.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *a = routerset_new(), *b = routerset_new();
+ int r;
+ (void)arg;
+
+ smartlist_add(a->list, tor_strdup("{aa}"));
+ smartlist_add(b->list, tor_strdup("{b1}"));
+ smartlist_add(b->list, tor_strdup("{b2}"));
+ r = routerset_equal(a, b);
+ routerset_free(a);
+ routerset_free(b);
+
+ tt_int_op(r, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_equal, unequal)
+
+/*
+ * Functional test for routerset_equal, with the routersets being
+ * different.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *a = routerset_new(), *b = routerset_new();
+ int r;
+ (void)arg;
+
+ smartlist_add(a->list, tor_strdup("foo"));
+ smartlist_add(b->list, tor_strdup("bar"));
+ r = routerset_equal(a, b);
+ routerset_free(a);
+ routerset_free(b);
+
+ tt_int_op(r, OP_EQ, 0);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_equal, equal)
+
+/*
+ * Functional test for routerset_equal, with the routersets being
+ * equal.
+ */
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *a = routerset_new(), *b = routerset_new();
+ int r;
+ (void)arg;
+
+ smartlist_add(a->list, tor_strdup("foo"));
+ smartlist_add(b->list, tor_strdup("foo"));
+ r = routerset_equal(a, b);
+ routerset_free(a);
+ routerset_free(b);
+
+ tt_int_op(r, OP_EQ, 1);
+ done:
+ ;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE ASPECT(routerset_free, null_routerset)
+
+/*
+ * Structural test for routerset_free, where the routerset is NULL.
+ */
+
+NS_DECL(void, smartlist_free, (smartlist_t *sl));
+
+static void
+NS(test_main)(void *arg)
+{
+ (void)arg;
+
+ NS_MOCK(smartlist_free);
+
+ routerset_free(NULL);
+
+ tt_int_op(CALLED(smartlist_free), OP_EQ, 0);
+
+ done:
+ ;
+}
+
+void
+NS(smartlist_free)(smartlist_t *s)
+{
+ (void)s;
+ CALLED(smartlist_free)++;
+}
+
+#undef NS_SUBMODULE
+#define NS_SUBMODULE routerset_free
+
+/*
+ * Structural test for routerset_free.
+ */
+
+NS_DECL(void, smartlist_free, (smartlist_t *sl));
+NS_DECL(void, strmap_free,(strmap_t *map, void (*free_val)(void*)));
+NS_DECL(void, digestmap_free, (digestmap_t *map, void (*free_val)(void*)));
+
+static void
+NS(test_main)(void *arg)
+{
+ routerset_t *routerset = routerset_new();
+ (void)arg;
+
+ NS_MOCK(smartlist_free);
+ NS_MOCK(strmap_free);
+ NS_MOCK(digestmap_free);
+
+ routerset_free(routerset);
+
+ tt_int_op(CALLED(smartlist_free), OP_NE, 0);
+ tt_int_op(CALLED(strmap_free), OP_NE, 0);
+ tt_int_op(CALLED(digestmap_free), OP_NE, 0);
+
+ done:
+ ;
+}
+
+void
+NS(smartlist_free)(smartlist_t *s)
+{
+ CALLED(smartlist_free)++;
+ smartlist_free__real(s);
+}
+
+void
+NS(strmap_free)(strmap_t *map, void (*free_val)(void*))
+{
+ CALLED(strmap_free)++;
+ strmap_free__real(map, free_val);
+}
+
+void
+NS(digestmap_free)(digestmap_t *map, void (*free_val)(void*))
+{
+ CALLED(digestmap_free)++;
+ digestmap_free__real(map, free_val);
+}
+
+#undef NS_SUBMODULE
+
+struct testcase_t routerset_tests[] = {
+ TEST_CASE(routerset_new),
+ TEST_CASE(routerset_get_countryname),
+ TEST_CASE(routerset_is_list),
+ TEST_CASE(routerset_needs_geoip),
+ TEST_CASE(routerset_is_empty),
+ TEST_CASE_ASPECT(routerset_contains, null_set_or_null_set_list),
+ TEST_CASE_ASPECT(routerset_contains, set_and_nickname),
+ TEST_CASE_ASPECT(routerset_contains, set_and_null_nickname),
+ TEST_CASE_ASPECT(routerset_contains, set_and_no_nickname),
+ TEST_CASE_ASPECT(routerset_contains, set_and_digest),
+ TEST_CASE_ASPECT(routerset_contains, set_and_no_digest),
+ TEST_CASE_ASPECT(routerset_contains, set_and_null_digest),
+ TEST_CASE_ASPECT(routerset_contains, set_and_addr),
+ TEST_CASE_ASPECT(routerset_contains, set_and_no_addr),
+ TEST_CASE_ASPECT(routerset_contains, set_and_null_addr),
+ TEST_CASE_ASPECT(routerset_contains, countries_no_geoip),
+ TEST_CASE_ASPECT(routerset_contains, countries_geoip),
+ TEST_CASE_ASPECT(routerset_add_unknown_ccs, only_flag_and_no_ccs),
+ TEST_CASE_ASPECT(routerset_add_unknown_ccs, creates_set),
+ TEST_CASE_ASPECT(routerset_add_unknown_ccs, add_unknown),
+ TEST_CASE_ASPECT(routerset_add_unknown_ccs, add_a1),
+ TEST_CASE(routerset_contains_extendinfo),
+ TEST_CASE(routerset_contains_router),
+ TEST_CASE(routerset_contains_routerstatus),
+ TEST_CASE_ASPECT(routerset_contains_node, none),
+ TEST_CASE_ASPECT(routerset_contains_node, routerinfo),
+ TEST_CASE_ASPECT(routerset_contains_node, routerstatus),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, no_routerset),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, list_with_no_nodes),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, list_flag_not_running),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, list),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, nodelist_with_no_nodes),
+ TEST_CASE_ASPECT(routerset_get_all_nodes, nodelist_flag_not_running),
+ TEST_CASE_ASPECT(routerset_refresh_counties, geoip_not_loaded),
+ TEST_CASE_ASPECT(routerset_refresh_counties, no_countries),
+ TEST_CASE_ASPECT(routerset_refresh_counties, one_valid_country),
+ TEST_CASE_ASPECT(routerset_refresh_counties, one_invalid_country),
+ TEST_CASE_ASPECT(routerset_union, source_bad),
+ TEST_CASE_ASPECT(routerset_union, one),
+ TEST_CASE_ASPECT(routerset_parse, malformed),
+ TEST_CASE_ASPECT(routerset_parse, valid_hexdigest),
+ TEST_CASE_ASPECT(routerset_parse, valid_nickname),
+ TEST_CASE_ASPECT(routerset_parse, get_countryname),
+ TEST_CASE_ASPECT(routerset_parse, policy_wildcard),
+ TEST_CASE_ASPECT(routerset_parse, policy_ipv4),
+ TEST_CASE_ASPECT(routerset_parse, policy_ipv6),
+ TEST_CASE(routerset_subtract_nodes),
+ TEST_CASE_ASPECT(routerset_subtract_nodes, null_routerset),
+ TEST_CASE(routerset_to_string),
+ TEST_CASE_ASPECT(routerset_equal, empty_empty),
+ TEST_CASE_ASPECT(routerset_equal, empty_not_empty),
+ TEST_CASE_ASPECT(routerset_equal, differing_lengths),
+ TEST_CASE_ASPECT(routerset_equal, unequal),
+ TEST_CASE_ASPECT(routerset_equal, equal),
+ TEST_CASE_ASPECT(routerset_free, null_routerset),
+ TEST_CASE(routerset_free),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_scheduler.c b/src/test/test_scheduler.c
new file mode 100644
index 0000000000..6e9889b48b
--- /dev/null
+++ b/src/test/test_scheduler.c
@@ -0,0 +1,774 @@
+/* Copyright (c) 2014-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include <math.h>
+
+#include "orconfig.h"
+
+/* Libevent stuff */
+#ifdef HAVE_EVENT2_EVENT_H
+#include <event2/event.h>
+#else
+#include <event.h>
+#endif
+
+#define TOR_CHANNEL_INTERNAL_
+#define CHANNEL_PRIVATE_
+#include "or.h"
+#include "compat_libevent.h"
+#include "channel.h"
+#define SCHEDULER_PRIVATE_
+#include "scheduler.h"
+
+/* Test suite stuff */
+#include "test.h"
+#include "fakechans.h"
+
+/* Statics in scheduler.c exposed to the test suite */
+extern smartlist_t *channels_pending;
+extern struct event *run_sched_ev;
+extern uint64_t queue_heuristic;
+extern time_t queue_heuristic_timestamp;
+
+/* Event base for scheduelr tests */
+static struct event_base *mock_event_base = NULL;
+
+/* Statics controlling mocks */
+static circuitmux_t *mock_ccm_tgt_1 = NULL;
+static circuitmux_t *mock_ccm_tgt_2 = NULL;
+
+static circuitmux_t *mock_cgp_tgt_1 = NULL;
+static circuitmux_policy_t *mock_cgp_val_1 = NULL;
+static circuitmux_t *mock_cgp_tgt_2 = NULL;
+static circuitmux_policy_t *mock_cgp_val_2 = NULL;
+static int scheduler_compare_channels_mock_ctr = 0;
+static int scheduler_run_mock_ctr = 0;
+
+static void channel_flush_some_cells_mock_free_all(void);
+static void channel_flush_some_cells_mock_set(channel_t *chan,
+ ssize_t num_cells);
+
+/* Setup for mock event stuff */
+static void mock_event_free_all(void);
+static void mock_event_init(void);
+
+/* Mocks used by scheduler tests */
+static ssize_t channel_flush_some_cells_mock(channel_t *chan,
+ ssize_t num_cells);
+static int circuitmux_compare_muxes_mock(circuitmux_t *cmux_1,
+ circuitmux_t *cmux_2);
+static const circuitmux_policy_t * circuitmux_get_policy_mock(
+ circuitmux_t *cmux);
+static int scheduler_compare_channels_mock(const void *c1_v,
+ const void *c2_v);
+static void scheduler_run_noop_mock(void);
+static struct event_base * tor_libevent_get_base_mock(void);
+
+/* Scheduler test cases */
+static void test_scheduler_channel_states(void *arg);
+static void test_scheduler_compare_channels(void *arg);
+static void test_scheduler_initfree(void *arg);
+static void test_scheduler_loop(void *arg);
+static void test_scheduler_queue_heuristic(void *arg);
+
+/* Mock event init/free */
+
+/* Shamelessly stolen from compat_libevent.c */
+#define V(major, minor, patch) \
+ (((major) << 24) | ((minor) << 16) | ((patch) << 8))
+
+static void
+mock_event_free_all(void)
+{
+ tt_assert(mock_event_base != NULL);
+
+ if (mock_event_base) {
+ event_base_free(mock_event_base);
+ mock_event_base = NULL;
+ }
+
+ tt_ptr_op(mock_event_base, ==, NULL);
+
+ done:
+ return;
+}
+
+static void
+mock_event_init(void)
+{
+#ifdef HAVE_EVENT2_EVENT_H
+ struct event_config *cfg = NULL;
+#endif
+
+ tt_ptr_op(mock_event_base, ==, NULL);
+
+ /*
+ * Really cut down from tor_libevent_initialize of
+ * src/common/compat_libevent.c to kill config dependencies
+ */
+
+ if (!mock_event_base) {
+#ifdef HAVE_EVENT2_EVENT_H
+ cfg = event_config_new();
+#if LIBEVENT_VERSION_NUMBER >= V(2,0,9)
+ /* We can enable changelist support with epoll, since we don't give
+ * Libevent any dup'd fds. This lets us avoid some syscalls. */
+ event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
+#endif
+ mock_event_base = event_base_new_with_config(cfg);
+ event_config_free(cfg);
+#else
+ mock_event_base = event_init();
+#endif
+ }
+
+ tt_assert(mock_event_base != NULL);
+
+ done:
+ return;
+}
+
+/* Mocks */
+
+typedef struct {
+ const channel_t *chan;
+ ssize_t cells;
+} flush_mock_channel_t;
+
+static smartlist_t *chans_for_flush_mock = NULL;
+
+static void
+channel_flush_some_cells_mock_free_all(void)
+{
+ if (chans_for_flush_mock) {
+ SMARTLIST_FOREACH_BEGIN(chans_for_flush_mock,
+ flush_mock_channel_t *,
+ flush_mock_ch) {
+ SMARTLIST_DEL_CURRENT(chans_for_flush_mock, flush_mock_ch);
+ tor_free(flush_mock_ch);
+ } SMARTLIST_FOREACH_END(flush_mock_ch);
+
+ smartlist_free(chans_for_flush_mock);
+ chans_for_flush_mock = NULL;
+ }
+}
+
+static void
+channel_flush_some_cells_mock_set(channel_t *chan, ssize_t num_cells)
+{
+ flush_mock_channel_t *flush_mock_ch = NULL;
+
+ if (!chan) return;
+ if (num_cells <= 0) return;
+
+ if (!chans_for_flush_mock) {
+ chans_for_flush_mock = smartlist_new();
+ }
+
+ SMARTLIST_FOREACH_BEGIN(chans_for_flush_mock,
+ flush_mock_channel_t *,
+ flush_mock_ch) {
+ if (flush_mock_ch != NULL && flush_mock_ch->chan != NULL) {
+ if (flush_mock_ch->chan == chan) {
+ /* Found it */
+ flush_mock_ch->cells = num_cells;
+ break;
+ }
+ } else {
+ /* That shouldn't be there... */
+ SMARTLIST_DEL_CURRENT(chans_for_flush_mock, flush_mock_ch);
+ tor_free(flush_mock_ch);
+ }
+ } SMARTLIST_FOREACH_END(flush_mock_ch);
+
+ if (!flush_mock_ch) {
+ /* The loop didn't find it */
+ flush_mock_ch = tor_malloc_zero(sizeof(*flush_mock_ch));
+ flush_mock_ch->chan = chan;
+ flush_mock_ch->cells = num_cells;
+ smartlist_add(chans_for_flush_mock, flush_mock_ch);
+ }
+}
+
+static ssize_t
+channel_flush_some_cells_mock(channel_t *chan, ssize_t num_cells)
+{
+ ssize_t flushed = 0, max;
+ char unlimited = 0;
+ flush_mock_channel_t *found = NULL;
+
+ tt_assert(chan != NULL);
+ if (chan) {
+ if (num_cells < 0) {
+ num_cells = 0;
+ unlimited = 1;
+ }
+
+ /* Check if we have it */
+ if (chans_for_flush_mock != NULL) {
+ SMARTLIST_FOREACH_BEGIN(chans_for_flush_mock,
+ flush_mock_channel_t *,
+ flush_mock_ch) {
+ if (flush_mock_ch != NULL && flush_mock_ch->chan != NULL) {
+ if (flush_mock_ch->chan == chan) {
+ /* Found it */
+ found = flush_mock_ch;
+ break;
+ }
+ } else {
+ /* That shouldn't be there... */
+ SMARTLIST_DEL_CURRENT(chans_for_flush_mock, flush_mock_ch);
+ tor_free(flush_mock_ch);
+ }
+ } SMARTLIST_FOREACH_END(flush_mock_ch);
+
+ if (found) {
+ /* We found one */
+ if (found->cells < 0) found->cells = 0;
+
+ if (unlimited) max = found->cells;
+ else max = MIN(found->cells, num_cells);
+
+ flushed += max;
+ found->cells -= max;
+
+ if (found->cells <= 0) {
+ smartlist_remove(chans_for_flush_mock, found);
+ tor_free(found);
+ }
+ }
+ }
+ }
+
+ done:
+ return flushed;
+}
+
+static int
+circuitmux_compare_muxes_mock(circuitmux_t *cmux_1,
+ circuitmux_t *cmux_2)
+{
+ int result = 0;
+
+ tt_assert(cmux_1 != NULL);
+ tt_assert(cmux_2 != NULL);
+
+ if (cmux_1 != cmux_2) {
+ if (cmux_1 == mock_ccm_tgt_1 && cmux_2 == mock_ccm_tgt_2) result = -1;
+ else if (cmux_1 == mock_ccm_tgt_2 && cmux_2 == mock_ccm_tgt_1) {
+ result = 1;
+ } else {
+ if (cmux_1 == mock_ccm_tgt_1 || cmux_1 == mock_ccm_tgt_2) result = -1;
+ else if (cmux_2 == mock_ccm_tgt_1 || cmux_2 == mock_ccm_tgt_2) {
+ result = 1;
+ } else {
+ result = circuitmux_compare_muxes__real(cmux_1, cmux_2);
+ }
+ }
+ }
+ /* else result = 0 always */
+
+ done:
+ return result;
+}
+
+static const circuitmux_policy_t *
+circuitmux_get_policy_mock(circuitmux_t *cmux)
+{
+ const circuitmux_policy_t *result = NULL;
+
+ tt_assert(cmux != NULL);
+ if (cmux) {
+ if (cmux == mock_cgp_tgt_1) result = mock_cgp_val_1;
+ else if (cmux == mock_cgp_tgt_2) result = mock_cgp_val_2;
+ else result = circuitmux_get_policy__real(cmux);
+ }
+
+ done:
+ return result;
+}
+
+static int
+scheduler_compare_channels_mock(const void *c1_v,
+ const void *c2_v)
+{
+ uintptr_t p1, p2;
+
+ p1 = (uintptr_t)(c1_v);
+ p2 = (uintptr_t)(c2_v);
+
+ ++scheduler_compare_channels_mock_ctr;
+
+ if (p1 == p2) return 0;
+ else if (p1 < p2) return 1;
+ else return -1;
+}
+
+static void
+scheduler_run_noop_mock(void)
+{
+ ++scheduler_run_mock_ctr;
+}
+
+static struct event_base *
+tor_libevent_get_base_mock(void)
+{
+ return mock_event_base;
+}
+
+/* Test cases */
+
+static void
+test_scheduler_channel_states(void *arg)
+{
+ channel_t *ch1 = NULL, *ch2 = NULL;
+ int old_count;
+
+ (void)arg;
+
+ /* Set up libevent and scheduler */
+
+ mock_event_init();
+ MOCK(tor_libevent_get_base, tor_libevent_get_base_mock);
+ scheduler_init();
+ /*
+ * Install the compare channels mock so we can test
+ * scheduler_touch_channel().
+ */
+ MOCK(scheduler_compare_channels, scheduler_compare_channels_mock);
+ /*
+ * Disable scheduler_run so we can just check the state transitions
+ * without having to make everything it might call work too.
+ */
+ MOCK(scheduler_run, scheduler_run_noop_mock);
+
+ tt_int_op(smartlist_len(channels_pending), ==, 0);
+
+ /* Set up a fake channel */
+ ch1 = new_fake_channel();
+ tt_assert(ch1);
+
+ /* Start it off in OPENING */
+ ch1->state = CHANNEL_STATE_OPENING;
+ /* We'll need a cmux */
+ ch1->cmux = circuitmux_alloc();
+ /* Try to register it */
+ channel_register(ch1);
+ tt_assert(ch1->registered);
+
+ /* It should start off in SCHED_CHAN_IDLE */
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_IDLE);
+
+ /* Now get another one */
+ ch2 = new_fake_channel();
+ tt_assert(ch2);
+ ch2->state = CHANNEL_STATE_OPENING;
+ ch2->cmux = circuitmux_alloc();
+ channel_register(ch2);
+ tt_assert(ch2->registered);
+
+ /* Send it to SCHED_CHAN_WAITING_TO_WRITE */
+ scheduler_channel_has_waiting_cells(ch1);
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_WAITING_TO_WRITE);
+
+ /* This should send it to SCHED_CHAN_PENDING */
+ scheduler_channel_wants_writes(ch1);
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 1);
+
+ /* Now send ch2 to SCHED_CHAN_WAITING_FOR_CELLS */
+ scheduler_channel_wants_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+
+ /* Drop ch2 back to idle */
+ scheduler_channel_doesnt_want_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_IDLE);
+
+ /* ...and back to SCHED_CHAN_WAITING_FOR_CELLS */
+ scheduler_channel_wants_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+
+ /* ...and this should kick ch2 into SCHED_CHAN_PENDING */
+ scheduler_channel_has_waiting_cells(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 2);
+
+ /* This should send ch2 to SCHED_CHAN_WAITING_TO_WRITE */
+ scheduler_channel_doesnt_want_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_TO_WRITE);
+ tt_int_op(smartlist_len(channels_pending), ==, 1);
+
+ /* ...and back to SCHED_CHAN_PENDING */
+ scheduler_channel_wants_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 2);
+
+ /* Now we exercise scheduler_touch_channel */
+ old_count = scheduler_compare_channels_mock_ctr;
+ scheduler_touch_channel(ch1);
+ tt_assert(scheduler_compare_channels_mock_ctr > old_count);
+
+ /* Close */
+ channel_mark_for_close(ch1);
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_CLOSING);
+ channel_mark_for_close(ch2);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_CLOSING);
+ channel_closed(ch1);
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_CLOSED);
+ ch1 = NULL;
+ channel_closed(ch2);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_CLOSED);
+ ch2 = NULL;
+
+ /* Shut things down */
+
+ channel_free_all();
+ scheduler_free_all();
+ mock_event_free_all();
+
+ done:
+ tor_free(ch1);
+ tor_free(ch2);
+
+ UNMOCK(scheduler_compare_channels);
+ UNMOCK(scheduler_run);
+ UNMOCK(tor_libevent_get_base);
+
+ return;
+}
+
+static void
+test_scheduler_compare_channels(void *arg)
+{
+ /* We don't actually need whole fake channels... */
+ channel_t c1, c2;
+ /* ...and some dummy circuitmuxes too */
+ circuitmux_t *cm1 = NULL, *cm2 = NULL;
+ int result;
+
+ (void)arg;
+
+ /* We can't actually see sizeof(circuitmux_t) from here */
+ cm1 = tor_malloc_zero(sizeof(void *));
+ cm2 = tor_malloc_zero(sizeof(void *));
+
+ c1.cmux = cm1;
+ c2.cmux = cm2;
+
+ /* Configure circuitmux_get_policy() mock */
+ mock_cgp_tgt_1 = cm1;
+ mock_cgp_tgt_2 = cm2;
+
+ /*
+ * This is to test the different-policies case, which uses the policy
+ * cast to an uintptr_t as an arbitrary but definite thing to compare.
+ */
+ mock_cgp_val_1 = tor_malloc_zero(16);
+ mock_cgp_val_2 = tor_malloc_zero(16);
+ if ( ((uintptr_t) mock_cgp_val_1) > ((uintptr_t) mock_cgp_val_2) ) {
+ void *tmp = mock_cgp_val_1;
+ mock_cgp_val_1 = mock_cgp_val_2;
+ mock_cgp_val_2 = tmp;
+ }
+
+ MOCK(circuitmux_get_policy, circuitmux_get_policy_mock);
+
+ /* Now set up circuitmux_compare_muxes() mock using cm1/cm2 */
+ mock_ccm_tgt_1 = cm1;
+ mock_ccm_tgt_2 = cm2;
+ MOCK(circuitmux_compare_muxes, circuitmux_compare_muxes_mock);
+
+ /* Equal-channel case */
+ result = scheduler_compare_channels(&c1, &c1);
+ tt_int_op(result, ==, 0);
+
+ /* Distinct channels, distinct policies */
+ result = scheduler_compare_channels(&c1, &c2);
+ tt_int_op(result, ==, -1);
+ result = scheduler_compare_channels(&c2, &c1);
+ tt_int_op(result, ==, 1);
+
+ /* Distinct channels, same policy */
+ tor_free(mock_cgp_val_2);
+ mock_cgp_val_2 = mock_cgp_val_1;
+ result = scheduler_compare_channels(&c1, &c2);
+ tt_int_op(result, ==, -1);
+ result = scheduler_compare_channels(&c2, &c1);
+ tt_int_op(result, ==, 1);
+
+ done:
+
+ UNMOCK(circuitmux_compare_muxes);
+ mock_ccm_tgt_1 = NULL;
+ mock_ccm_tgt_2 = NULL;
+
+ UNMOCK(circuitmux_get_policy);
+ mock_cgp_tgt_1 = NULL;
+ mock_cgp_tgt_2 = NULL;
+
+ tor_free(cm1);
+ tor_free(cm2);
+
+ if (mock_cgp_val_1 != mock_cgp_val_2)
+ tor_free(mock_cgp_val_1);
+ tor_free(mock_cgp_val_2);
+ mock_cgp_val_1 = NULL;
+ mock_cgp_val_2 = NULL;
+
+ return;
+}
+
+static void
+test_scheduler_initfree(void *arg)
+{
+ (void)arg;
+
+ tt_ptr_op(channels_pending, ==, NULL);
+ tt_ptr_op(run_sched_ev, ==, NULL);
+
+ mock_event_init();
+ MOCK(tor_libevent_get_base, tor_libevent_get_base_mock);
+
+ scheduler_init();
+
+ tt_assert(channels_pending != NULL);
+ tt_assert(run_sched_ev != NULL);
+
+ scheduler_free_all();
+
+ UNMOCK(tor_libevent_get_base);
+ mock_event_free_all();
+
+ tt_ptr_op(channels_pending, ==, NULL);
+ tt_ptr_op(run_sched_ev, ==, NULL);
+
+ done:
+ return;
+}
+
+static void
+test_scheduler_loop(void *arg)
+{
+ channel_t *ch1 = NULL, *ch2 = NULL;
+
+ (void)arg;
+
+ /* Set up libevent and scheduler */
+
+ mock_event_init();
+ MOCK(tor_libevent_get_base, tor_libevent_get_base_mock);
+ scheduler_init();
+ /*
+ * Install the compare channels mock so we can test
+ * scheduler_touch_channel().
+ */
+ MOCK(scheduler_compare_channels, scheduler_compare_channels_mock);
+ /*
+ * Disable scheduler_run so we can just check the state transitions
+ * without having to make everything it might call work too.
+ */
+ MOCK(scheduler_run, scheduler_run_noop_mock);
+
+ tt_int_op(smartlist_len(channels_pending), ==, 0);
+
+ /* Set up a fake channel */
+ ch1 = new_fake_channel();
+ tt_assert(ch1);
+
+ /* Start it off in OPENING */
+ ch1->state = CHANNEL_STATE_OPENING;
+ /* We'll need a cmux */
+ ch1->cmux = circuitmux_alloc();
+ /* Try to register it */
+ channel_register(ch1);
+ tt_assert(ch1->registered);
+ /* Finish opening it */
+ channel_change_state(ch1, CHANNEL_STATE_OPEN);
+
+ /* It should start off in SCHED_CHAN_IDLE */
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_IDLE);
+
+ /* Now get another one */
+ ch2 = new_fake_channel();
+ tt_assert(ch2);
+ ch2->state = CHANNEL_STATE_OPENING;
+ ch2->cmux = circuitmux_alloc();
+ channel_register(ch2);
+ tt_assert(ch2->registered);
+ /*
+ * Don't open ch2; then channel_num_cells_writeable() will return
+ * zero and we'll get coverage of that exception case in scheduler_run()
+ */
+
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_OPEN);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_OPENING);
+
+ /* Send it to SCHED_CHAN_WAITING_TO_WRITE */
+ scheduler_channel_has_waiting_cells(ch1);
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_WAITING_TO_WRITE);
+
+ /* This should send it to SCHED_CHAN_PENDING */
+ scheduler_channel_wants_writes(ch1);
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 1);
+
+ /* Now send ch2 to SCHED_CHAN_WAITING_FOR_CELLS */
+ scheduler_channel_wants_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+
+ /* Drop ch2 back to idle */
+ scheduler_channel_doesnt_want_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_IDLE);
+
+ /* ...and back to SCHED_CHAN_WAITING_FOR_CELLS */
+ scheduler_channel_wants_writes(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+
+ /* ...and this should kick ch2 into SCHED_CHAN_PENDING */
+ scheduler_channel_has_waiting_cells(ch2);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 2);
+
+ /*
+ * Now we've got two pending channels and need to fire off
+ * scheduler_run(); first, unmock it.
+ */
+
+ UNMOCK(scheduler_run);
+
+ scheduler_run();
+
+ /* Now re-mock it */
+ MOCK(scheduler_run, scheduler_run_noop_mock);
+
+ /*
+ * Assert that they're still in the states we left and aren't still
+ * pending
+ */
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_OPEN);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_OPENING);
+ tt_assert(ch1->scheduler_state != SCHED_CHAN_PENDING);
+ tt_assert(ch2->scheduler_state != SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 0);
+
+ /* Now, finish opening ch2, and get both back to pending */
+ channel_change_state(ch2, CHANNEL_STATE_OPEN);
+ scheduler_channel_wants_writes(ch1);
+ scheduler_channel_wants_writes(ch2);
+ scheduler_channel_has_waiting_cells(ch1);
+ scheduler_channel_has_waiting_cells(ch2);
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_OPEN);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_OPEN);
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_PENDING);
+ tt_int_op(smartlist_len(channels_pending), ==, 2);
+
+ /* Now, set up the channel_flush_some_cells() mock */
+ MOCK(channel_flush_some_cells, channel_flush_some_cells_mock);
+ /*
+ * 16 cells on ch1 means it'll completely drain into the 32 cells
+ * fakechan's num_cells_writeable() returns.
+ */
+ channel_flush_some_cells_mock_set(ch1, 16);
+ /*
+ * This one should get sent back to pending, since num_cells_writeable()
+ * will still return non-zero.
+ */
+ channel_flush_some_cells_mock_set(ch2, 48);
+
+ /*
+ * And re-run the scheduler_run() loop with non-zero returns from
+ * channel_flush_some_cells() this time.
+ */
+ UNMOCK(scheduler_run);
+
+ scheduler_run();
+
+ /* Now re-mock it */
+ MOCK(scheduler_run, scheduler_run_noop_mock);
+
+ /*
+ * ch1 should have gone to SCHED_CHAN_WAITING_FOR_CELLS, with 16 flushed
+ * and 32 writeable.
+ */
+ tt_int_op(ch1->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+ /*
+ * ...ch2 should also have gone to SCHED_CHAN_WAITING_FOR_CELLS, with
+ * channel_more_to_flush() returning false and channel_num_cells_writeable()
+ * > 0/
+ */
+ tt_int_op(ch2->scheduler_state, ==, SCHED_CHAN_WAITING_FOR_CELLS);
+
+ /* Close */
+ channel_mark_for_close(ch1);
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_CLOSING);
+ channel_mark_for_close(ch2);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_CLOSING);
+ channel_closed(ch1);
+ tt_int_op(ch1->state, ==, CHANNEL_STATE_CLOSED);
+ ch1 = NULL;
+ channel_closed(ch2);
+ tt_int_op(ch2->state, ==, CHANNEL_STATE_CLOSED);
+ ch2 = NULL;
+
+ /* Shut things down */
+ channel_flush_some_cells_mock_free_all();
+ channel_free_all();
+ scheduler_free_all();
+ mock_event_free_all();
+
+ done:
+ tor_free(ch1);
+ tor_free(ch2);
+
+ UNMOCK(channel_flush_some_cells);
+ UNMOCK(scheduler_compare_channels);
+ UNMOCK(scheduler_run);
+ UNMOCK(tor_libevent_get_base);
+}
+
+static void
+test_scheduler_queue_heuristic(void *arg)
+{
+ time_t now = approx_time();
+ uint64_t qh;
+
+ (void)arg;
+
+ queue_heuristic = 0;
+ queue_heuristic_timestamp = 0;
+
+ /* Not yet inited case */
+ scheduler_update_queue_heuristic(now - 180);
+ tt_u64_op(queue_heuristic, ==, 0);
+ tt_int_op(queue_heuristic_timestamp, ==, now - 180);
+
+ queue_heuristic = 1000000000L;
+ queue_heuristic_timestamp = now - 120;
+
+ scheduler_update_queue_heuristic(now - 119);
+ tt_u64_op(queue_heuristic, ==, 500000000L);
+ tt_int_op(queue_heuristic_timestamp, ==, now - 119);
+
+ scheduler_update_queue_heuristic(now - 116);
+ tt_u64_op(queue_heuristic, ==, 62500000L);
+ tt_int_op(queue_heuristic_timestamp, ==, now - 116);
+
+ qh = scheduler_get_queue_heuristic();
+ tt_u64_op(qh, ==, 0);
+
+ done:
+ return;
+}
+
+struct testcase_t scheduler_tests[] = {
+ { "channel_states", test_scheduler_channel_states, TT_FORK, NULL, NULL },
+ { "compare_channels", test_scheduler_compare_channels,
+ TT_FORK, NULL, NULL },
+ { "initfree", test_scheduler_initfree, TT_FORK, NULL, NULL },
+ { "loop", test_scheduler_loop, TT_FORK, NULL, NULL },
+ { "queue_heuristic", test_scheduler_queue_heuristic,
+ TT_FORK, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_slow.c b/src/test/test_slow.c
new file mode 100644
index 0000000000..c1d2e81914
--- /dev/null
+++ b/src/test/test_slow.c
@@ -0,0 +1,29 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file test_slow.c
+ * \brief Slower unit tests for many pieces of the lower level Tor modules.
+ **/
+
+#include "orconfig.h"
+
+#include <stdio.h>
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "or.h"
+#include "test.h"
+
+extern struct testcase_t slow_crypto_tests[];
+extern struct testcase_t slow_util_tests[];
+
+struct testgroup_t testgroups[] = {
+ { "slow/crypto/", slow_crypto_tests },
+ { "slow/util/", slow_util_tests },
+ END_OF_GROUPS
+};
+
diff --git a/src/test/test_socks.c b/src/test/test_socks.c
index 4ce61e068b..6da09fd653 100644
--- a/src/test/test_socks.c
+++ b/src/test/test_socks.c
@@ -1,6 +1,6 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "or.h"
@@ -61,10 +61,10 @@ test_socks_4_unsupported_commands(void *ptr)
/* SOCKS 4 Send BIND [02] to IP address 2.2.2.2:4369 */
ADD_DATA(buf, "\x04\x02\x11\x11\x02\x02\x02\x02\x00");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == -1);
- test_eq(4, socks->socks_version);
- test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
+ tt_int_op(4,OP_EQ, socks->socks_version);
+ tt_int_op(0,OP_EQ, socks->replylen); /* XXX: shouldn't tor reply? */
done:
;
@@ -76,49 +76,49 @@ test_socks_4_supported_commands(void *ptr)
{
SOCKS_TEST_INIT();
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
/* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4370 */
ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x03\x00");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(4, socks->socks_version);
- test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
- test_eq(SOCKS_COMMAND_CONNECT, socks->command);
- test_streq("2.2.2.3", socks->address);
- test_eq(4370, socks->port);
- test_assert(socks->got_auth == 0);
- test_assert(! socks->username);
-
- test_eq(0, buf_datalen(buf));
+ tt_int_op(4,OP_EQ, socks->socks_version);
+ tt_int_op(0,OP_EQ, socks->replylen); /* XXX: shouldn't tor reply? */
+ tt_int_op(SOCKS_COMMAND_CONNECT,OP_EQ, socks->command);
+ tt_str_op("2.2.2.3",OP_EQ, socks->address);
+ tt_int_op(4370,OP_EQ, socks->port);
+ tt_assert(socks->got_auth == 0);
+ tt_assert(! socks->username);
+
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
socks_request_clear(socks);
/* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4369 with userid*/
ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x04me\x00");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(4, socks->socks_version);
- test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
- test_eq(SOCKS_COMMAND_CONNECT, socks->command);
- test_streq("2.2.2.4", socks->address);
- test_eq(4370, socks->port);
- test_assert(socks->got_auth == 1);
- test_assert(socks->username);
- test_eq(2, socks->usernamelen);
- test_memeq("me", socks->username, 2);
-
- test_eq(0, buf_datalen(buf));
+ tt_int_op(4,OP_EQ, socks->socks_version);
+ tt_int_op(0,OP_EQ, socks->replylen); /* XXX: shouldn't tor reply? */
+ tt_int_op(SOCKS_COMMAND_CONNECT,OP_EQ, socks->command);
+ tt_str_op("2.2.2.4",OP_EQ, socks->address);
+ tt_int_op(4370,OP_EQ, socks->port);
+ tt_assert(socks->got_auth == 1);
+ tt_assert(socks->username);
+ tt_int_op(2,OP_EQ, socks->usernamelen);
+ tt_mem_op("me",OP_EQ, socks->username, 2);
+
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
socks_request_clear(socks);
/* SOCKS 4a Send RESOLVE [F0] request for torproject.org */
ADD_DATA(buf, "\x04\xF0\x01\x01\x00\x00\x00\x02me\x00torproject.org\x00");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(4, socks->socks_version);
- test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
- test_streq("torproject.org", socks->address);
+ tt_int_op(4,OP_EQ, socks->socks_version);
+ tt_int_op(0,OP_EQ, socks->replylen); /* XXX: shouldn't tor reply? */
+ tt_str_op("torproject.org",OP_EQ, socks->address);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
done:
;
@@ -133,33 +133,43 @@ test_socks_5_unsupported_commands(void *ptr)
/* SOCKS 5 Send unsupported BIND [02] command */
ADD_DATA(buf, "\x05\x02\x00\x01");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), 0);
- test_eq(0, buf_datalen(buf));
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, 0);
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
ADD_DATA(buf, "\x05\x02\x00\x01\x02\x02\x02\x01\x01\x01");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), -1);
- /* XXX: shouldn't tor reply 'command not supported' [07]? */
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_COMMAND_NOT_SUPPORTED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
buf_clear(buf);
socks_request_clear(socks);
/* SOCKS 5 Send unsupported UDP_ASSOCIATE [03] command */
- ADD_DATA(buf, "\x05\x03\x00\x01\x02");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), 0);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(2, socks->reply[1]);
+ ADD_DATA(buf, "\x05\x02\x00\x01");
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, 0);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
ADD_DATA(buf, "\x05\x03\x00\x01\x02\x02\x02\x01\x01\x01");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), -1);
- /* XXX: shouldn't tor reply 'command not supported' [07]? */
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_COMMAND_NOT_SUPPORTED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
done:
;
@@ -173,64 +183,100 @@ test_socks_5_supported_commands(void *ptr)
/* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
ADD_DATA(buf, "\x05\x01\x00");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), 0);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, 0);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
ADD_DATA(buf, "\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), 1);
- test_streq("2.2.2.2", socks->address);
- test_eq(4369, socks->port);
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, 1);
+ tt_str_op("2.2.2.2",OP_EQ, socks->address);
+ tt_int_op(4369,OP_EQ, socks->port);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
socks_request_clear(socks);
/* SOCKS 5 Send CONNECT [01] to FQDN torproject.org:4369 */
ADD_DATA(buf, "\x05\x01\x00");
ADD_DATA(buf, "\x05\x01\x00\x03\x0Etorproject.org\x11\x11");
- test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
- get_options()->SafeSocks), 1);
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, 1);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(0, socks->reply[1]);
- test_streq("torproject.org", socks->address);
- test_eq(4369, socks->port);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
+ tt_str_op("torproject.org",OP_EQ, socks->address);
+ tt_int_op(4369,OP_EQ, socks->port);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
socks_request_clear(socks);
/* SOCKS 5 Send RESOLVE [F0] request for torproject.org:4369 */
ADD_DATA(buf, "\x05\x01\x00");
ADD_DATA(buf, "\x05\xF0\x00\x03\x0Etorproject.org\x01\x02");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(0, socks->reply[1]);
- test_streq("torproject.org", socks->address);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
+ tt_str_op("torproject.org",OP_EQ, socks->address);
+
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
+ socks_request_clear(socks);
+
+ /* SOCKS 5 Should reject RESOLVE [F0] request for IPv4 address
+ * string if SafeSocks is enabled. */
+
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\xF0\x00\x03\x07");
+ ADD_DATA(buf, "8.8.8.8");
+ ADD_DATA(buf, "\x01\x02");
+ tt_assert(fetch_from_buf_socks(buf,socks,get_options()->TestSocks,1)
+ == -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_NOT_ALLOWED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
+
+ socks_request_clear(socks);
+
+ /* SOCKS 5 should reject RESOLVE [F0] reject for IPv6 address
+ * string if SafeSocks is enabled. */
+
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\xF0\x00\x03\x27");
+ ADD_DATA(buf, "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
+ ADD_DATA(buf, "\x01\x02");
+ tt_assert(fetch_from_buf_socks(buf,socks,get_options()->TestSocks,1)
+ == -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_NOT_ALLOWED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
- test_eq(0, buf_datalen(buf));
socks_request_clear(socks);
/* SOCKS 5 Send RESOLVE_PTR [F1] for IP address 2.2.2.5 */
ADD_DATA(buf, "\x05\x01\x00");
ADD_DATA(buf, "\x05\xF1\x00\x01\x02\x02\x02\x05\x01\x03");
- test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ tt_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(0, socks->reply[1]);
- test_streq("2.2.2.5", socks->address);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
+ tt_str_op("2.2.2.5",OP_EQ, socks->address);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
done:
;
@@ -244,30 +290,30 @@ test_socks_5_no_authenticate(void *ptr)
/*SOCKS 5 No Authentication */
ADD_DATA(buf,"\x05\x01\x00");
- test_assert(!fetch_from_buf_socks(buf, socks,
+ tt_assert(!fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks));
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(SOCKS_NO_AUTH, socks->reply[1]);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(SOCKS_NO_AUTH,OP_EQ, socks->reply[1]);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
/*SOCKS 5 Send username/password anyway - pretend to be broken */
ADD_DATA(buf,"\x01\x02\x01\x01\x02\x01\x01");
- test_assert(!fetch_from_buf_socks(buf, socks,
+ tt_assert(!fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks));
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(1, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(1,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
- test_eq(2, socks->usernamelen);
- test_eq(2, socks->passwordlen);
+ tt_int_op(2,OP_EQ, socks->usernamelen);
+ tt_int_op(2,OP_EQ, socks->passwordlen);
- test_memeq("\x01\x01", socks->username, 2);
- test_memeq("\x01\x01", socks->password, 2);
+ tt_mem_op("\x01\x01",OP_EQ, socks->username, 2);
+ tt_mem_op("\x01\x01",OP_EQ, socks->password, 2);
done:
;
@@ -282,31 +328,31 @@ test_socks_5_authenticate(void *ptr)
/* SOCKS 5 Negotiate username/password authentication */
ADD_DATA(buf, "\x05\x01\x02");
- test_assert(!fetch_from_buf_socks(buf, socks,
+ tt_assert(!fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks));
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(SOCKS_USER_PASS, socks->reply[1]);
- test_eq(5, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(SOCKS_USER_PASS,OP_EQ, socks->reply[1]);
+ tt_int_op(5,OP_EQ, socks->socks_version);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
/* SOCKS 5 Send username/password */
ADD_DATA(buf, "\x01\x02me\x08mypasswd");
- test_assert(!fetch_from_buf_socks(buf, socks,
+ tt_assert(!fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks));
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(1, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(1,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
- test_eq(2, socks->usernamelen);
- test_eq(8, socks->passwordlen);
+ tt_int_op(2,OP_EQ, socks->usernamelen);
+ tt_int_op(8,OP_EQ, socks->passwordlen);
- test_memeq("me", socks->username, 2);
- test_memeq("mypasswd", socks->password, 8);
+ tt_mem_op("me",OP_EQ, socks->username, 2);
+ tt_mem_op("mypasswd",OP_EQ, socks->password, 8);
done:
;
@@ -321,34 +367,34 @@ test_socks_5_authenticate_with_data(void *ptr)
/* SOCKS 5 Negotiate username/password authentication */
ADD_DATA(buf, "\x05\x01\x02");
- test_assert(!fetch_from_buf_socks(buf, socks,
+ tt_assert(!fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks));
- test_eq(2, socks->replylen);
- test_eq(5, socks->reply[0]);
- test_eq(SOCKS_USER_PASS, socks->reply[1]);
- test_eq(5, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(5,OP_EQ, socks->reply[0]);
+ tt_int_op(SOCKS_USER_PASS,OP_EQ, socks->reply[1]);
+ tt_int_op(5,OP_EQ, socks->socks_version);
- test_eq(0, buf_datalen(buf));
+ tt_int_op(0,OP_EQ, buf_datalen(buf));
/* SOCKS 5 Send username/password */
/* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
ADD_DATA(buf, "\x01\x02me\x03you\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
- test_assert(fetch_from_buf_socks(buf, socks,
+ tt_assert(fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks) == 1);
- test_eq(5, socks->socks_version);
- test_eq(2, socks->replylen);
- test_eq(1, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(5,OP_EQ, socks->socks_version);
+ tt_int_op(2,OP_EQ, socks->replylen);
+ tt_int_op(1,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
- test_streq("2.2.2.2", socks->address);
- test_eq(4369, socks->port);
+ tt_str_op("2.2.2.2",OP_EQ, socks->address);
+ tt_int_op(4369,OP_EQ, socks->port);
- test_eq(2, socks->usernamelen);
- test_eq(3, socks->passwordlen);
- test_memeq("me", socks->username, 2);
- test_memeq("you", socks->password, 3);
+ tt_int_op(2,OP_EQ, socks->usernamelen);
+ tt_int_op(3,OP_EQ, socks->passwordlen);
+ tt_mem_op("me",OP_EQ, socks->username, 2);
+ tt_mem_op("you",OP_EQ, socks->password, 3);
done:
;
@@ -362,13 +408,85 @@ test_socks_5_auth_before_negotiation(void *ptr)
/* SOCKS 5 Send username/password */
ADD_DATA(buf, "\x01\x02me\x02me");
- test_assert(fetch_from_buf_socks(buf, socks,
+ tt_assert(fetch_from_buf_socks(buf, socks,
get_options()->TestSocks,
get_options()->SafeSocks) == -1);
- test_eq(0, socks->socks_version);
- test_eq(0, socks->replylen);
- test_eq(0, socks->reply[0]);
- test_eq(0, socks->reply[1]);
+ tt_int_op(0,OP_EQ, socks->socks_version);
+ tt_int_op(0,OP_EQ, socks->replylen);
+ tt_int_op(0,OP_EQ, socks->reply[0]);
+ tt_int_op(0,OP_EQ, socks->reply[1]);
+
+ done:
+ ;
+}
+
+/** Perform malformed SOCKS 5 commands */
+static void
+test_socks_5_malformed_commands(void *ptr)
+{
+ SOCKS_TEST_INIT();
+
+ /* XXX: Stringified address length > MAX_SOCKS_ADDR_LEN will never happen */
+
+ /** SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369, with SafeSocks set
+ */
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks, 1),
+ OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_NOT_ALLOWED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
+
+ buf_clear(buf);
+ socks_request_clear(socks);
+
+ /* SOCKS 5 Send RESOLVE_PTR [F1] for FQDN torproject.org */
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\xF1\x00\x03\x0Etorproject.org\x11\x11");
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
+
+ buf_clear(buf);
+ socks_request_clear(socks);
+
+ /* XXX: len + 1 > MAX_SOCKS_ADDR_LEN (FQDN request) will never happen */
+
+ /* SOCKS 5 Send CONNECT [01] to FQDN """"".com */
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\x01\x00\x03\x09\"\"\"\"\".com\x11\x11");
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_GENERAL_ERROR,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
+
+ buf_clear(buf);
+ socks_request_clear(socks);
+
+ /* SOCKS 5 Send CONNECT [01] to address type 0x23 */
+ ADD_DATA(buf, "\x05\x01\x00");
+ ADD_DATA(buf, "\x05\x01\x00\x23\x02\x02\x02\x02\x11\x11");
+ tt_int_op(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
+ get_options()->SafeSocks),OP_EQ, -1);
+
+ tt_int_op(5,OP_EQ,socks->socks_version);
+ tt_int_op(10,OP_EQ,socks->replylen);
+ tt_int_op(5,OP_EQ,socks->reply[0]);
+ tt_int_op(SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED,OP_EQ,socks->reply[1]);
+ tt_int_op(1,OP_EQ,socks->reply[3]);
done:
;
@@ -387,6 +505,7 @@ struct testcase_t socks_tests[] = {
SOCKSENT(5_auth_before_negotiation),
SOCKSENT(5_authenticate),
SOCKSENT(5_authenticate_with_data),
+ SOCKSENT(5_malformed_commands),
END_OF_TESTCASES
};
diff --git a/src/test/test_status.c b/src/test/test_status.c
index 46dd473132..84a0f6c024 100644
--- a/src/test/test_status.c
+++ b/src/test/test_status.c
@@ -30,27 +30,24 @@
* global circuits.
*/
-struct global_circuitlist_s mock_global_circuitlist =
- TOR_LIST_HEAD_INITIALIZER(global_circuitlist);
+static smartlist_t * mock_global_circuitlist = NULL;
-NS_DECL(struct global_circuitlist_s *, circuit_get_global_list, (void));
+NS_DECL(smartlist_t *, circuit_get_global_list, (void));
static void
NS(test_main)(void *arg)
{
/* Choose origin_circuit_t wlog. */
origin_circuit_t *mock_circuit1, *mock_circuit2;
- circuit_t *circ, *tmp;
int expected_circuits = 2, actual_circuits;
(void)arg;
mock_circuit1 = tor_malloc_zero(sizeof(origin_circuit_t));
mock_circuit2 = tor_malloc_zero(sizeof(origin_circuit_t));
- TOR_LIST_INSERT_HEAD(
- &mock_global_circuitlist, TO_CIRCUIT(mock_circuit1), head);
- TOR_LIST_INSERT_HEAD(
- &mock_global_circuitlist, TO_CIRCUIT(mock_circuit2), head);
+ mock_global_circuitlist = smartlist_new();
+ smartlist_add(mock_global_circuitlist, TO_CIRCUIT(mock_circuit1));
+ smartlist_add(mock_global_circuitlist, TO_CIRCUIT(mock_circuit2));
NS_MOCK(circuit_get_global_list);
@@ -58,17 +55,18 @@ NS(test_main)(void *arg)
tt_assert(expected_circuits == actual_circuits);
- done:
- TOR_LIST_FOREACH_SAFE(
- circ, NS(circuit_get_global_list)(), head, tmp);
- tor_free(circ);
- NS_UNMOCK(circuit_get_global_list);
+ done:
+ tor_free(mock_circuit1);
+ tor_free(mock_circuit2);
+ smartlist_free(mock_global_circuitlist);
+ mock_global_circuitlist = NULL;
+ NS_UNMOCK(circuit_get_global_list);
}
-static struct global_circuitlist_s *
+static smartlist_t *
NS(circuit_get_global_list)(void)
{
- return &mock_global_circuitlist;
+ return mock_global_circuitlist;
}
#undef NS_SUBMODULE
@@ -88,62 +86,62 @@ NS(test_main)(void *arg)
expected = "0:00 hours";
actual = secs_to_uptime(0);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "0:00 hours";
actual = secs_to_uptime(1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "0:01 hours";
actual = secs_to_uptime(60);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "0:59 hours";
actual = secs_to_uptime(60 * 59);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1:00 hours";
actual = secs_to_uptime(60 * 60);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "23:59 hours";
actual = secs_to_uptime(60 * 60 * 23 + 60 * 59);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1 day 0:00 hours";
actual = secs_to_uptime(60 * 60 * 23 + 60 * 60);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1 day 0:00 hours";
actual = secs_to_uptime(86400 + 1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1 day 0:01 hours";
actual = secs_to_uptime(86400 + 60);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "10 days 0:00 hours";
actual = secs_to_uptime(86400 * 10);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "10 days 0:00 hours";
actual = secs_to_uptime(864000 + 1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "10 days 0:01 hours";
actual = secs_to_uptime(864000 + 60);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
done:
@@ -169,62 +167,62 @@ NS(test_main)(void *arg)
expected = "0 kB";
actual = bytes_to_usage(0);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "0 kB";
actual = bytes_to_usage(1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1 kB";
actual = bytes_to_usage(1024);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1023 kB";
actual = bytes_to_usage((1 << 20) - 1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.00 MB";
actual = bytes_to_usage((1 << 20));
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.00 MB";
actual = bytes_to_usage((1 << 20) + 5242);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.01 MB";
actual = bytes_to_usage((1 << 20) + 5243);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1024.00 MB";
actual = bytes_to_usage((1 << 30) - 1);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.00 GB";
actual = bytes_to_usage((1 << 30));
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.00 GB";
actual = bytes_to_usage((1 << 30) + 5368709);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "1.01 GB";
actual = bytes_to_usage((1 << 30) + 5368710);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
expected = "10.00 GB";
actual = bytes_to_usage((U64_LITERAL(1) << 30) * 10L);
- tt_str_op(actual, ==, expected);
+ tt_str_op(actual, OP_EQ, expected);
tor_free(actual);
done:
@@ -242,7 +240,6 @@ NS(test_main)(void *arg)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(const routerinfo_t *, router_get_my_routerinfo, (void));
@@ -254,19 +251,17 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(router_get_my_routerinfo);
expected = -1;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
+ tt_int_op(actual, OP_EQ, expected);
done:
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(router_get_my_routerinfo);
}
@@ -283,12 +278,6 @@ NS(we_are_hibernating)(void)
return 0;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- return NULL;
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -313,7 +302,6 @@ NS(router_get_my_routerinfo)(void)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(const routerinfo_t *, router_get_my_routerinfo, (void));
NS_DECL(const node_t *, node_get_by_id, (const char *identity_digest));
@@ -333,7 +321,6 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(router_get_my_routerinfo);
NS_MOCK(node_get_by_id);
@@ -349,13 +336,12 @@ NS(test_main)(void *arg)
expected = 0;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
- tt_int_op(CALLED(logv), ==, 3);
+ tt_int_op(actual, OP_EQ, expected);
+ tt_int_op(CALLED(logv), OP_EQ, 5);
done:
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(router_get_my_routerinfo);
NS_UNMOCK(node_get_by_id);
@@ -376,12 +362,6 @@ NS(we_are_hibernating)(void)
return 0;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- return NULL;
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -413,39 +393,48 @@ NS(logv)(int severity, log_domain_mask_t domain,
switch (CALLED(logv))
{
case 0:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: It seems like we are not in the cached consensus.");
break;
case 1:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: Tor's uptime is %s, with %d circuits open. "
"I've sent %s and received %s.%s");
- tt_str_op(va_arg(ap, char *), ==, "0:00 hours"); /* uptime */
- tt_int_op(va_arg(ap, int), ==, 0); /* count_circuits() */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_rcvd */
- tt_str_op(va_arg(ap, char *), ==, ""); /* hibernating */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:00 hours"); /* uptime */
+ tt_int_op(va_arg(ap, int), OP_EQ, 0); /* count_circuits() */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, ""); /* hibernating */
break;
case 2:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(
- strstr(funcname, "rep_hist_log_circuit_handshake_stats"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_INFO);
+ break;
+ case 3:
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "rep_hist_log_circuit_handshake_stats"),
+ OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Circuit handshake stats since last time: %d/%d TAP, %d/%d NTor.");
- tt_int_op(va_arg(ap, int), ==, 1); /* handshakes assigned (TAP) */
- tt_int_op(va_arg(ap, int), ==, 1); /* handshakes requested (TAP) */
- tt_int_op(va_arg(ap, int), ==, 1); /* handshakes assigned (NTOR) */
- tt_int_op(va_arg(ap, int), ==, 1); /* handshakes requested (NTOR) */
+ tt_int_op(va_arg(ap, int), OP_EQ, 1); /* handshakes assigned (TAP) */
+ tt_int_op(va_arg(ap, int), OP_EQ, 1); /* handshakes requested (TAP) */
+ tt_int_op(va_arg(ap, int), OP_EQ, 1); /* handshakes assigned (NTOR) */
+ tt_int_op(va_arg(ap, int), OP_EQ, 1); /* handshakes requested (NTOR) */
+ break;
+ case 4:
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "rep_hist_log_link_protocol_counts"),
+ OP_NE, NULL);
break;
default:
tt_abort_msg("unexpected call to logv()"); // TODO: prettyprint args
@@ -474,7 +463,6 @@ NS(server_mode)(const or_options_t *options)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(long, get_uptime, (void));
NS_DECL(uint64_t, get_bytes_read, (void));
@@ -483,6 +471,8 @@ NS_DECL(void, logv, (int severity, log_domain_mask_t domain,
const char *funcname, const char *suffix, const char *format, va_list ap));
NS_DECL(int, server_mode, (const or_options_t *options));
+static int NS(n_msgs) = 0;
+
static void
NS(test_main)(void *arg)
{
@@ -491,7 +481,6 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(get_uptime);
NS_MOCK(get_bytes_read);
@@ -504,12 +493,12 @@ NS(test_main)(void *arg)
expected = 0;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
+ tt_int_op(actual, OP_EQ, expected);
+ tt_int_op(NS(n_msgs), OP_EQ, 1);
done:
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(get_uptime);
NS_UNMOCK(get_bytes_read);
@@ -530,12 +519,6 @@ NS(we_are_hibernating)(void)
return 1;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- return NULL;
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -566,18 +549,22 @@ static void
NS(logv)(int severity, log_domain_mask_t domain, const char *funcname,
const char *suffix, const char *format, va_list ap)
{
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ if (severity == LOG_INFO)
+ return;
+ ++NS(n_msgs);
+
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: Tor's uptime is %s, with %d circuits open. "
"I've sent %s and received %s.%s");
- tt_str_op(va_arg(ap, char *), ==, "0:00 hours"); /* uptime */
- tt_int_op(va_arg(ap, int), ==, 0); /* count_circuits() */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_rcvd */
- tt_str_op(va_arg(ap, char *), ==, " We are currently hibernating.");
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:00 hours"); /* uptime */
+ tt_int_op(va_arg(ap, int), OP_EQ, 0); /* count_circuits() */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, " We are currently hibernating.");
done:
;
@@ -601,7 +588,6 @@ NS(server_mode)(const or_options_t *options)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(long, get_uptime, (void));
NS_DECL(uint64_t, get_bytes_read, (void));
@@ -624,7 +610,6 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(get_uptime);
NS_MOCK(get_bytes_read);
@@ -640,13 +625,12 @@ NS(test_main)(void *arg)
expected = 0;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
- tt_int_op(CALLED(logv), ==, 2);
+ tt_int_op(actual, OP_EQ, expected);
+ tt_int_op(CALLED(logv), OP_EQ, 3);
done:
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(get_uptime);
NS_UNMOCK(get_bytes_read);
@@ -671,15 +655,6 @@ NS(we_are_hibernating)(void)
return 0;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- NS(mock_options) = tor_malloc_zero(sizeof(or_options_t));
- NS(mock_options)->AccountingMax = 0;
-
- return NS(mock_options);
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -713,34 +688,41 @@ NS(logv)(int severity, log_domain_mask_t domain,
switch (CALLED(logv))
{
case 0:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: Tor's uptime is %s, with %d circuits open. "
"I've sent %s and received %s.%s");
- tt_str_op(va_arg(ap, char *), ==, "0:00 hours"); /* uptime */
- tt_int_op(va_arg(ap, int), ==, 0); /* count_circuits() */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_rcvd */
- tt_str_op(va_arg(ap, char *), ==, ""); /* hibernating */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:00 hours"); /* uptime */
+ tt_int_op(va_arg(ap, int), OP_EQ, 0); /* count_circuits() */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, ""); /* hibernating */
break;
case 1:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_accounting"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
- "Heartbeat: Accounting enabled. Sent: %s / %s, Received: %s / %s. "
- "The current accounting interval ends on %s, in %s.");
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* acc_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* acc_max */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* acc_rcvd */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* acc_max */
- /* format_local_iso_time uses local tz, just check mins and secs. */
- tt_ptr_op(strstr(va_arg(ap, char *), ":01:00"), !=, NULL); /* end_buf */
- tt_str_op(va_arg(ap, char *), ==, "0:01 hours"); /* remaining */
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_accounting"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
+ "Heartbeat: Accounting enabled. Sent: %s, Received: %s, Used: %s / "
+ "%s, Rule: %s. The current accounting interval ends on %s, in %s.");
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* acc_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* acc_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* acc_used */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* acc_max */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "max"); /* acc_rule */
+ /* format_local_iso_time uses local tz, so we can't just compare
+ * the string against a constant */
+ char datetime[ISO_TIME_LEN+1];
+ format_local_iso_time(datetime, 60);
+ tt_str_op(va_arg(ap, char *), OP_EQ, datetime); /* end_buf */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:01 hours"); /* remaining */
+ break;
+ case 2:
+ tt_int_op(severity, OP_EQ, LOG_INFO);
break;
default:
tt_abort_msg("unexpected call to logv()"); // TODO: prettyprint args
@@ -793,7 +775,6 @@ NS(get_or_state)(void)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(long, get_uptime, (void));
NS_DECL(uint64_t, get_bytes_read, (void));
@@ -811,7 +792,6 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(get_uptime);
NS_MOCK(get_bytes_read);
@@ -822,19 +802,18 @@ NS(test_main)(void *arg)
log_global_min_severity_ = LOG_DEBUG;
stats_n_data_bytes_packaged = RELAY_PAYLOAD_SIZE;
- stats_n_data_cells_packaged = 1;
+ stats_n_data_cells_packaged = 2;
expected = 0;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
- tt_int_op(CALLED(logv), ==, 2);
+ tt_int_op(actual, OP_EQ, expected);
+ tt_int_op(CALLED(logv), OP_EQ, 2);
done:
stats_n_data_bytes_packaged = 0;
stats_n_data_cells_packaged = 0;
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(get_uptime);
NS_UNMOCK(get_bytes_read);
@@ -856,12 +835,6 @@ NS(we_are_hibernating)(void)
return 0;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- return NULL;
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -895,27 +868,29 @@ NS(logv)(int severity, log_domain_mask_t domain, const char *funcname,
switch (CALLED(logv))
{
case 0:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: Tor's uptime is %s, with %d circuits open. "
"I've sent %s and received %s.%s");
- tt_str_op(va_arg(ap, char *), ==, "0:00 hours"); /* uptime */
- tt_int_op(va_arg(ap, int), ==, 0); /* count_circuits() */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_rcvd */
- tt_str_op(va_arg(ap, char *), ==, ""); /* hibernating */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:00 hours"); /* uptime */
+ tt_int_op(va_arg(ap, int), OP_EQ, 0); /* count_circuits() */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, ""); /* hibernating */
break;
case 1:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
- "Average packaged cell fullness: %2.3f%%");
- tt_int_op(fabs(va_arg(ap, double) - 100.0) <= DBL_EPSILON, ==, 1);
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
+ "Average packaged cell fullness: %2.3f%%. "
+ "TLS write overhead: %.f%%");
+ tt_double_op(fabs(va_arg(ap, double) - 50.0), <=, DBL_EPSILON);
+ tt_double_op(fabs(va_arg(ap, double) - 0.0), <=, DBL_EPSILON);
break;
default:
tt_abort_msg("unexpected call to logv()"); // TODO: prettyprint args
@@ -952,7 +927,6 @@ NS(accounting_is_enabled)(const or_options_t *options)
NS_DECL(double, tls_get_write_overhead_ratio, (void));
NS_DECL(int, we_are_hibernating, (void));
-NS_DECL(const or_options_t *, get_options, (void));
NS_DECL(int, public_server_mode, (const or_options_t *options));
NS_DECL(long, get_uptime, (void));
NS_DECL(uint64_t, get_bytes_read, (void));
@@ -970,7 +944,6 @@ NS(test_main)(void *arg)
NS_MOCK(tls_get_write_overhead_ratio);
NS_MOCK(we_are_hibernating);
- NS_MOCK(get_options);
NS_MOCK(public_server_mode);
NS_MOCK(get_uptime);
NS_MOCK(get_bytes_read);
@@ -984,13 +957,12 @@ NS(test_main)(void *arg)
expected = 0;
actual = log_heartbeat(0);
- tt_int_op(actual, ==, expected);
- tt_int_op(CALLED(logv), ==, 2);
+ tt_int_op(actual, OP_EQ, expected);
+ tt_int_op(CALLED(logv), OP_EQ, 2);
done:
NS_UNMOCK(tls_get_write_overhead_ratio);
NS_UNMOCK(we_are_hibernating);
- NS_UNMOCK(get_options);
NS_UNMOCK(public_server_mode);
NS_UNMOCK(get_uptime);
NS_UNMOCK(get_bytes_read);
@@ -1012,12 +984,6 @@ NS(we_are_hibernating)(void)
return 0;
}
-static const or_options_t *
-NS(get_options)(void)
-{
- return NULL;
-}
-
static int
NS(public_server_mode)(const or_options_t *options)
{
@@ -1051,26 +1017,29 @@ NS(logv)(int severity, log_domain_mask_t domain,
switch (CALLED(logv))
{
case 0:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==,
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
"Heartbeat: Tor's uptime is %s, with %d circuits open. "
"I've sent %s and received %s.%s");
- tt_str_op(va_arg(ap, char *), ==, "0:00 hours"); /* uptime */
- tt_int_op(va_arg(ap, int), ==, 0); /* count_circuits() */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_sent */
- tt_str_op(va_arg(ap, char *), ==, "0 kB"); /* bw_rcvd */
- tt_str_op(va_arg(ap, char *), ==, ""); /* hibernating */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0:00 hours"); /* uptime */
+ tt_int_op(va_arg(ap, int), OP_EQ, 0); /* count_circuits() */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_sent */
+ tt_str_op(va_arg(ap, char *), OP_EQ, "0 kB"); /* bw_rcvd */
+ tt_str_op(va_arg(ap, char *), OP_EQ, ""); /* hibernating */
break;
case 1:
- tt_int_op(severity, ==, LOG_NOTICE);
- tt_int_op(domain, ==, LD_HEARTBEAT);
- tt_ptr_op(strstr(funcname, "log_heartbeat"), !=, NULL);
- tt_ptr_op(suffix, ==, NULL);
- tt_str_op(format, ==, "TLS write overhead: %.f%%");
- tt_int_op(fabs(va_arg(ap, double) - 100.0) <= DBL_EPSILON, ==, 1);
+ tt_int_op(severity, OP_EQ, LOG_NOTICE);
+ tt_int_op(domain, OP_EQ, LD_HEARTBEAT);
+ tt_ptr_op(strstr(funcname, "log_heartbeat"), OP_NE, NULL);
+ tt_ptr_op(suffix, OP_EQ, NULL);
+ tt_str_op(format, OP_EQ,
+ "Average packaged cell fullness: %2.3f%%. "
+ "TLS write overhead: %.f%%");
+ tt_int_op(fabs(va_arg(ap, double) - 100.0) <= DBL_EPSILON, OP_EQ, 1);
+ tt_double_op(fabs(va_arg(ap, double) - 100.0), <=, DBL_EPSILON);
break;
default:
tt_abort_msg("unexpected call to logv()"); // TODO: prettyprint args
diff --git a/src/test/test_switch_id.c b/src/test/test_switch_id.c
new file mode 100644
index 0000000000..e12205bb2e
--- /dev/null
+++ b/src/test/test_switch_id.c
@@ -0,0 +1,192 @@
+/* Copyright (c) 2015-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+
+#ifdef HAVE_SYS_CAPABILITY_H
+#include <sys/capability.h>
+#endif
+
+#define TEST_BUILT_WITH_CAPS 0
+#define TEST_HAVE_CAPS 1
+#define TEST_ROOT_CAN_BIND_LOW 2
+#define TEST_SETUID 3
+#define TEST_SETUID_KEEPCAPS 4
+#define TEST_SETUID_STRICT 5
+
+static const struct {
+ const char *name;
+ int test_id;
+} which_test[] = {
+ { "built-with-caps", TEST_BUILT_WITH_CAPS },
+ { "have-caps", TEST_HAVE_CAPS },
+ { "root-bind-low", TEST_ROOT_CAN_BIND_LOW },
+ { "setuid", TEST_SETUID },
+ { "setuid-keepcaps", TEST_SETUID_KEEPCAPS },
+ { "setuid-strict", TEST_SETUID_STRICT },
+ { NULL, 0 }
+};
+
+#if !defined(_WIN32)
+/* 0 on no, 1 on yes, -1 on failure. */
+static int
+check_can_bind_low_ports(void)
+{
+ int port;
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+
+ for (port = 600; port < 1024; ++port) {
+ sin.sin_port = htons(port);
+ tor_socket_t fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (! SOCKET_OK(fd)) {
+ perror("socket");
+ return -1;
+ }
+
+ int one = 1;
+ if (setsockopt(fd, SOL_SOCKET,SO_REUSEADDR, (void*)&one,
+ (socklen_t)sizeof(one))) {
+ perror("setsockopt");
+ tor_close_socket_simple(fd);
+ return -1;
+ }
+
+ int res = bind(fd, (struct sockaddr *)&sin, sizeof(sin));
+ tor_close_socket_simple(fd);
+
+ if (res == 0) {
+ /* bind was successful */
+ return 1;
+ } else if (errno == EACCES || errno == EPERM) {
+ /* Got a permission-denied error. */
+ return 0;
+ } else if (errno == EADDRINUSE) {
+ /* Huh; somebody is using that port. */
+ } else {
+ perror("bind");
+ }
+ }
+
+ return -1;
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+#if defined(_WIN32)
+ (void) argc;
+ (void) argv;
+ (void) which_test;
+
+ fprintf(stderr, "This test is not supported on your OS.\n");
+ return 77;
+#else
+ const char *username;
+ const char *testname;
+ if (argc != 3) {
+ fprintf(stderr, "I want 2 arguments: a username and a command.\n");
+ return 1;
+ }
+ if (getuid() != 0) {
+ fprintf(stderr, "This test only works when it's run as root.\n");
+ return 1;
+ }
+ username = argv[1];
+ testname = argv[2];
+ int test_id = -1;
+ int i;
+ for (i = 0; which_test[i].name; ++i) {
+ if (!strcmp(which_test[i].name, testname)) {
+ test_id = which_test[i].test_id;
+ break;
+ }
+ }
+ if (test_id == -1) {
+ fprintf(stderr, "Unrecognized test '%s'\n", testname);
+ return 1;
+ }
+
+#ifdef HAVE_LINUX_CAPABILITIES
+ const int have_cap_support = 1;
+#else
+ const int have_cap_support = 0;
+#endif
+
+ int okay;
+
+ init_logging(1);
+ log_severity_list_t sev;
+ memset(&sev, 0, sizeof(sev));
+ set_log_severity_config(LOG_WARN, LOG_ERR, &sev);
+ add_stream_log(&sev, "", fileno(stderr));
+
+ switch (test_id)
+ {
+ case TEST_BUILT_WITH_CAPS:
+ /* Succeed if we were built with capability support. */
+ okay = have_cap_support;
+ break;
+ case TEST_HAVE_CAPS:
+ /* Succeed if "capabilities work" == "we were built with capability
+ * support." */
+ okay = have_cap_support == have_capability_support();
+ break;
+ case TEST_ROOT_CAN_BIND_LOW:
+ /* Succeed if root can bind low ports. */
+ okay = check_can_bind_low_ports() == 1;
+ break;
+ case TEST_SETUID:
+ /* Succeed if we can do a setuid with no capability retention, and doing
+ * so makes us lose the ability to bind low ports */
+ case TEST_SETUID_KEEPCAPS:
+ /* Succeed if we can do a setuid with capability retention, and doing so
+ * does not make us lose the ability to bind low ports */
+ {
+ int keepcaps = (test_id == TEST_SETUID_KEEPCAPS);
+ okay = switch_id(username, keepcaps ? SWITCH_ID_KEEP_BINDLOW : 0) == 0;
+ if (okay) {
+ okay = check_can_bind_low_ports() == keepcaps;
+ }
+ break;
+ }
+ case TEST_SETUID_STRICT:
+ /* Succeed if, after a setuid, we cannot setuid back, and we cannot
+ * re-grab any capabilities. */
+ okay = switch_id(username, SWITCH_ID_KEEP_BINDLOW) == 0;
+ if (okay) {
+ /* We'd better not be able to setuid back! */
+ if (setuid(0) == 0 || errno != EPERM) {
+ okay = 0;
+ }
+ }
+#ifdef HAVE_LINUX_CAPABILITIES
+ if (okay) {
+ cap_t caps = cap_get_proc();
+ const cap_value_t caplist[] = {
+ CAP_SETUID,
+ };
+ cap_set_flag(caps, CAP_PERMITTED, 1, caplist, CAP_SET);
+ if (cap_set_proc(caps) == 0 || errno != EPERM) {
+ okay = 0;
+ }
+ cap_free(caps);
+ }
+#endif
+ break;
+ default:
+ fprintf(stderr, "Unsupported test '%s'\n", testname);
+ okay = 0;
+ break;
+ }
+
+ if (!okay) {
+ fprintf(stderr, "Test %s failed!\n", testname);
+ }
+
+ return (okay ? 0 : 1);
+#endif
+}
+
diff --git a/src/test/test_switch_id.sh b/src/test/test_switch_id.sh
new file mode 100755
index 0000000000..1b4e0998b5
--- /dev/null
+++ b/src/test/test_switch_id.sh
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+if test "`id -u`" != '0'; then
+ echo "This test only works when run as root. Skipping." >&2
+ exit 77
+fi
+
+if test "`id -u nobody`" = ""; then
+ echo "This test requires that your system have a 'nobody' user. Sorry." >&2
+ exit 1
+fi
+
+"${builddir:-.}/src/test/test-switch-id" nobody setuid || exit 1
+"${builddir:-.}/src/test/test-switch-id" nobody root-bind-low || exit 1
+"${builddir:-.}/src/test/test-switch-id" nobody setuid-strict || exit 1
+"${builddir:-.}/src/test/test-switch-id" nobody built-with-caps || exit 0
+# ... Go beyond this point only if we were built with capability support.
+
+"${builddir:-.}/src/test/test-switch-id" nobody have-caps || exit 1
+"${builddir:-.}/src/test/test-switch-id" nobody setuid-keepcaps || exit 1
+
+
+echo "All okay"
+
+exit 0
diff --git a/src/test/test_threads.c b/src/test/test_threads.c
new file mode 100644
index 0000000000..1bbe6f5508
--- /dev/null
+++ b/src/test/test_threads.c
@@ -0,0 +1,320 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#include "or.h"
+#include "compat_threads.h"
+#include "test.h"
+
+/** mutex for thread test to stop the threads hitting data at the same time. */
+static tor_mutex_t *thread_test_mutex_ = NULL;
+/** mutexes for the thread test to make sure that the threads have to
+ * interleave somewhat. */
+static tor_mutex_t *thread_test_start1_ = NULL,
+ *thread_test_start2_ = NULL;
+/** Shared strmap for the thread test. */
+static strmap_t *thread_test_strmap_ = NULL;
+/** The name of thread1 for the thread test */
+static char *thread1_name_ = NULL;
+/** The name of thread2 for the thread test */
+static char *thread2_name_ = NULL;
+
+static int thread_fns_failed = 0;
+
+static unsigned long thread_fn_tid1, thread_fn_tid2;
+
+static void thread_test_func_(void* _s) ATTR_NORETURN;
+
+/** How many iterations have the threads in the unit test run? */
+static tor_threadlocal_t count;
+
+/** Helper function for threading unit tests: This function runs in a
+ * subthread. It grabs its own mutex (start1 or start2) to make sure that it
+ * should start, then it repeatedly alters _test_thread_strmap protected by
+ * thread_test_mutex_. */
+static void
+thread_test_func_(void* _s)
+{
+ char *s = _s;
+ int i;
+ tor_mutex_t *m;
+ char buf[64];
+ char **cp;
+ int *mycount = tor_malloc_zero(sizeof(int));
+ tor_threadlocal_set(&count, mycount);
+ if (!strcmp(s, "thread 1")) {
+ m = thread_test_start1_;
+ cp = &thread1_name_;
+ thread_fn_tid1 = tor_get_thread_id();
+ } else {
+ m = thread_test_start2_;
+ cp = &thread2_name_;
+ thread_fn_tid2 = tor_get_thread_id();
+ }
+
+ tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
+ *cp = tor_strdup(buf);
+
+ tor_mutex_acquire(m);
+
+ for (i=0; i<10000; ++i) {
+ tor_mutex_acquire(thread_test_mutex_);
+ strmap_set(thread_test_strmap_, "last to run", *cp);
+ tor_mutex_release(thread_test_mutex_);
+ int *tls_count = tor_threadlocal_get(&count);
+ tor_assert(tls_count == mycount);
+ ++*tls_count;
+ }
+ tor_mutex_acquire(thread_test_mutex_);
+ strmap_set(thread_test_strmap_, s, *cp);
+ if (in_main_thread())
+ ++thread_fns_failed;
+ tor_mutex_release(thread_test_mutex_);
+
+ tor_free(mycount);
+
+ tor_mutex_release(m);
+
+ spawn_exit();
+}
+
+/** Run unit tests for threading logic. */
+static void
+test_threads_basic(void *arg)
+{
+ char *s1 = NULL, *s2 = NULL;
+ int done = 0, timedout = 0;
+ time_t started;
+#ifndef _WIN32
+ struct timeval tv;
+ tv.tv_sec=0;
+ tv.tv_usec=100*1000;
+#endif
+ (void) arg;
+ tt_int_op(tor_threadlocal_init(&count), OP_EQ, 0);
+
+ set_main_thread();
+
+ thread_test_mutex_ = tor_mutex_new();
+ thread_test_start1_ = tor_mutex_new();
+ thread_test_start2_ = tor_mutex_new();
+ thread_test_strmap_ = strmap_new();
+ s1 = tor_strdup("thread 1");
+ s2 = tor_strdup("thread 2");
+ tor_mutex_acquire(thread_test_start1_);
+ tor_mutex_acquire(thread_test_start2_);
+ spawn_func(thread_test_func_, s1);
+ spawn_func(thread_test_func_, s2);
+ tor_mutex_release(thread_test_start2_);
+ tor_mutex_release(thread_test_start1_);
+ started = time(NULL);
+ while (!done) {
+ tor_mutex_acquire(thread_test_mutex_);
+ strmap_assert_ok(thread_test_strmap_);
+ if (strmap_get(thread_test_strmap_, "thread 1") &&
+ strmap_get(thread_test_strmap_, "thread 2")) {
+ done = 1;
+ } else if (time(NULL) > started + 150) {
+ timedout = done = 1;
+ }
+ tor_mutex_release(thread_test_mutex_);
+#ifndef _WIN32
+ /* Prevent the main thread from starving the worker threads. */
+ select(0, NULL, NULL, NULL, &tv);
+#endif
+ }
+ tor_mutex_acquire(thread_test_start1_);
+ tor_mutex_release(thread_test_start1_);
+ tor_mutex_acquire(thread_test_start2_);
+ tor_mutex_release(thread_test_start2_);
+
+ tor_mutex_free(thread_test_mutex_);
+
+ if (timedout) {
+ tt_assert(strmap_get(thread_test_strmap_, "thread 1"));
+ tt_assert(strmap_get(thread_test_strmap_, "thread 2"));
+ tt_assert(!timedout);
+ }
+
+ /* different thread IDs. */
+ tt_assert(strcmp(strmap_get(thread_test_strmap_, "thread 1"),
+ strmap_get(thread_test_strmap_, "thread 2")));
+ tt_assert(!strcmp(strmap_get(thread_test_strmap_, "thread 1"),
+ strmap_get(thread_test_strmap_, "last to run")) ||
+ !strcmp(strmap_get(thread_test_strmap_, "thread 2"),
+ strmap_get(thread_test_strmap_, "last to run")));
+
+ tt_int_op(thread_fns_failed, ==, 0);
+ tt_int_op(thread_fn_tid1, !=, thread_fn_tid2);
+
+ done:
+ tor_free(s1);
+ tor_free(s2);
+ tor_free(thread1_name_);
+ tor_free(thread2_name_);
+ if (thread_test_strmap_)
+ strmap_free(thread_test_strmap_, NULL);
+ if (thread_test_start1_)
+ tor_mutex_free(thread_test_start1_);
+ if (thread_test_start2_)
+ tor_mutex_free(thread_test_start2_);
+}
+
+typedef struct cv_testinfo_s {
+ tor_cond_t *cond;
+ tor_mutex_t *mutex;
+ int value;
+ int addend;
+ int shutdown;
+ int n_shutdown;
+ int n_wakeups;
+ int n_timeouts;
+ int n_threads;
+ const struct timeval *tv;
+} cv_testinfo_t;
+
+static cv_testinfo_t *
+cv_testinfo_new(void)
+{
+ cv_testinfo_t *i = tor_malloc_zero(sizeof(*i));
+ i->cond = tor_cond_new();
+ i->mutex = tor_mutex_new_nonrecursive();
+ return i;
+}
+
+static void
+cv_testinfo_free(cv_testinfo_t *i)
+{
+ if (!i)
+ return;
+ tor_cond_free(i->cond);
+ tor_mutex_free(i->mutex);
+ tor_free(i);
+}
+
+static void cv_test_thr_fn_(void *arg) ATTR_NORETURN;
+
+static void
+cv_test_thr_fn_(void *arg)
+{
+ cv_testinfo_t *i = arg;
+ int tid, r;
+
+ tor_mutex_acquire(i->mutex);
+ tid = i->n_threads++;
+ tor_mutex_release(i->mutex);
+ (void) tid;
+
+ tor_mutex_acquire(i->mutex);
+ while (1) {
+ if (i->addend) {
+ i->value += i->addend;
+ i->addend = 0;
+ }
+
+ if (i->shutdown) {
+ ++i->n_shutdown;
+ i->shutdown = 0;
+ tor_mutex_release(i->mutex);
+ spawn_exit();
+ }
+ r = tor_cond_wait(i->cond, i->mutex, i->tv);
+ ++i->n_wakeups;
+ if (r == 1) {
+ ++i->n_timeouts;
+ tor_mutex_release(i->mutex);
+ spawn_exit();
+ }
+ }
+}
+
+static void
+test_threads_conditionvar(void *arg)
+{
+ cv_testinfo_t *ti=NULL;
+ const struct timeval msec100 = { 0, 100*1000 };
+ const int timeout = !strcmp(arg, "tv");
+
+ ti = cv_testinfo_new();
+ if (timeout) {
+ ti->tv = &msec100;
+ }
+ spawn_func(cv_test_thr_fn_, ti);
+ spawn_func(cv_test_thr_fn_, ti);
+ spawn_func(cv_test_thr_fn_, ti);
+ spawn_func(cv_test_thr_fn_, ti);
+
+ tor_mutex_acquire(ti->mutex);
+ ti->addend = 7;
+ ti->shutdown = 1;
+ tor_cond_signal_one(ti->cond);
+ tor_mutex_release(ti->mutex);
+
+#define SPIN() \
+ while (1) { \
+ tor_mutex_acquire(ti->mutex); \
+ if (ti->addend == 0) { \
+ break; \
+ } \
+ tor_mutex_release(ti->mutex); \
+ }
+
+ SPIN();
+
+ ti->addend = 30;
+ ti->shutdown = 1;
+ tor_cond_signal_all(ti->cond);
+ tor_mutex_release(ti->mutex);
+ SPIN();
+
+ ti->addend = 1000;
+ if (! timeout) ti->shutdown = 1;
+ tor_cond_signal_one(ti->cond);
+ tor_mutex_release(ti->mutex);
+ SPIN();
+ ti->addend = 300;
+ if (! timeout) ti->shutdown = 1;
+ tor_cond_signal_all(ti->cond);
+ tor_mutex_release(ti->mutex);
+
+ SPIN();
+ tor_mutex_release(ti->mutex);
+
+ tt_int_op(ti->value, ==, 1337);
+ if (!timeout) {
+ tt_int_op(ti->n_shutdown, ==, 4);
+ } else {
+#ifdef _WIN32
+ Sleep(500); /* msec */
+#elif defined(HAVE_USLEEP)
+ usleep(500*1000); /* usec */
+#else
+ {
+ struct tv = { 0, 500*1000 };
+ select(0, NULL, NULL, NULL, &tv);
+ }
+#endif
+ tor_mutex_acquire(ti->mutex);
+ tt_int_op(ti->n_shutdown, ==, 2);
+ tt_int_op(ti->n_timeouts, ==, 2);
+ tor_mutex_release(ti->mutex);
+ }
+
+ done:
+ cv_testinfo_free(ti);
+}
+
+#define THREAD_TEST(name) \
+ { #name, test_threads_##name, TT_FORK, NULL, NULL }
+
+struct testcase_t thread_tests[] = {
+ THREAD_TEST(basic),
+ { "conditionvar", test_threads_conditionvar, TT_FORK,
+ &passthrough_setup, (void*)"no-tv" },
+ { "conditionvar_timeout", test_threads_conditionvar, TT_FORK,
+ &passthrough_setup, (void*)"tv" },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_tortls.c b/src/test/test_tortls.c
new file mode 100644
index 0000000000..b9b74a1e96
--- /dev/null
+++ b/src/test/test_tortls.c
@@ -0,0 +1,2836 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define TORTLS_PRIVATE
+#define LOG_PRIVATE
+#include "orconfig.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#ifdef __GNUC__
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#endif
+
+#if __GNUC__ && GCC_VERSION >= 402
+#if GCC_VERSION >= 406
+#pragma GCC diagnostic push
+#endif
+/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
+ * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
+#pragma GCC diagnostic ignored "-Wredundant-decls"
+#endif
+
+#include <openssl/opensslv.h>
+
+#include <openssl/ssl.h>
+#include <openssl/ssl3.h>
+#include <openssl/err.h>
+#include <openssl/asn1t.h>
+#include <openssl/x509.h>
+#include <openssl/rsa.h>
+#include <openssl/evp.h>
+#include <openssl/bn.h>
+
+#if __GNUC__ && GCC_VERSION >= 402
+#if GCC_VERSION >= 406
+#pragma GCC diagnostic pop
+#else
+#pragma GCC diagnostic warning "-Wredundant-decls"
+#endif
+#endif
+
+#include "or.h"
+#include "torlog.h"
+#include "config.h"
+#include "tortls.h"
+
+#include "test.h"
+#include "log_test_helpers.h"
+#define NS_MODULE tortls
+
+extern tor_tls_context_t *server_tls_context;
+extern tor_tls_context_t *client_tls_context;
+
+#if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) \
+ && !defined(LIBRESSL_VERSION_NUMBER)
+#define OPENSSL_OPAQUE
+#define SSL_STATE_STR "before SSL initialization"
+#else
+#define SSL_STATE_STR "before/accept initialization"
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static SSL_METHOD *
+give_me_a_test_method(void)
+{
+ SSL_METHOD *method = tor_malloc_zero(sizeof(SSL_METHOD));
+ memcpy(method, TLSv1_method(), sizeof(SSL_METHOD));
+ return method;
+}
+
+static int
+fake_num_ciphers(void)
+{
+ return 0;
+}
+#endif
+
+static void
+test_tortls_errno_to_tls_error(void *data)
+{
+ (void) data;
+ tt_int_op(tor_errno_to_tls_error(SOCK_ERRNO(ECONNRESET)),OP_EQ,
+ TOR_TLS_ERROR_CONNRESET);
+ tt_int_op(tor_errno_to_tls_error(SOCK_ERRNO(ETIMEDOUT)),OP_EQ,
+ TOR_TLS_ERROR_TIMEOUT);
+ tt_int_op(tor_errno_to_tls_error(SOCK_ERRNO(EHOSTUNREACH)),OP_EQ,
+ TOR_TLS_ERROR_NO_ROUTE);
+ tt_int_op(tor_errno_to_tls_error(SOCK_ERRNO(ENETUNREACH)),OP_EQ,
+ TOR_TLS_ERROR_NO_ROUTE);
+ tt_int_op(tor_errno_to_tls_error(SOCK_ERRNO(ECONNREFUSED)),OP_EQ,
+ TOR_TLS_ERROR_CONNREFUSED);
+ tt_int_op(tor_errno_to_tls_error(0),OP_EQ,TOR_TLS_ERROR_MISC);
+ done:
+ (void)1;
+}
+
+static void
+test_tortls_err_to_string(void *data)
+{
+ (void) data;
+ tt_str_op(tor_tls_err_to_string(1),OP_EQ,"[Not an error.]");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_MISC),OP_EQ,"misc error");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_IO),OP_EQ,"unexpected close");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_CONNREFUSED),OP_EQ,
+ "connection refused");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_CONNRESET),OP_EQ,
+ "connection reset");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_NO_ROUTE),OP_EQ,
+ "host unreachable");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_ERROR_TIMEOUT),OP_EQ,
+ "connection timed out");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_CLOSE),OP_EQ,"closed");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_WANTREAD),OP_EQ,"want to read");
+ tt_str_op(tor_tls_err_to_string(TOR_TLS_WANTWRITE),OP_EQ,"want to write");
+ tt_str_op(tor_tls_err_to_string(-100),OP_EQ,"(unknown error code)");
+ done:
+ (void)1;
+}
+
+static int
+mock_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert)
+{
+ (void) tls;
+ (void) cert; // XXXX look at this.
+ return 1;
+}
+
+static void
+test_tortls_tor_tls_new(void *data)
+{
+ (void) data;
+ MOCK(tor_tls_cert_matches_key, mock_tls_cert_matches_key);
+ crypto_pk_t *key1 = NULL, *key2 = NULL;
+ SSL_METHOD *method = NULL;
+
+ key1 = pk_generate(2);
+ key2 = pk_generate(3);
+
+ tor_tls_t *tls = NULL;
+ tt_int_op(tor_tls_context_init(TOR_TLS_CTX_IS_PUBLIC_SERVER,
+ key1, key2, 86400), OP_EQ, 0);
+ tls = tor_tls_new(-1, 0);
+ tt_want(tls);
+ tor_tls_free(tls); tls = NULL;
+
+ SSL_CTX_free(client_tls_context->ctx);
+ client_tls_context->ctx = NULL;
+ tls = tor_tls_new(-1, 0);
+ tt_assert(!tls);
+
+#ifndef OPENSSL_OPAQUE
+ method = give_me_a_test_method();
+ SSL_CTX *ctx = SSL_CTX_new(method);
+ method->num_ciphers = fake_num_ciphers;
+ client_tls_context->ctx = ctx;
+ tls = tor_tls_new(-1, 0);
+ tt_assert(!tls);
+#endif
+
+ done:
+ UNMOCK(tor_tls_cert_matches_key);
+ crypto_pk_free(key1);
+ crypto_pk_free(key2);
+ tor_tls_free(tls);
+ tor_free(method);
+ tor_tls_free_all();
+}
+
+#define NS_MODULE tortls
+NS_DECL(void, logv, (int severity, log_domain_mask_t domain,
+ const char *funcname, const char *suffix,
+ const char *format, va_list ap));
+
+static void
+NS(logv)(int severity, log_domain_mask_t domain,
+ const char *funcname, const char *suffix, const char *format,
+ va_list ap)
+{
+ (void) severity;
+ (void) domain;
+ (void) funcname;
+ (void) suffix;
+ (void) format;
+ (void) ap; // XXXX look at this.
+ CALLED(logv)++;
+}
+
+static void
+test_tortls_tor_tls_get_error(void *data)
+{
+ (void) data;
+ MOCK(tor_tls_cert_matches_key, mock_tls_cert_matches_key);
+ crypto_pk_t *key1 = NULL, *key2 = NULL;
+ key1 = pk_generate(2);
+ key2 = pk_generate(3);
+
+ tor_tls_t *tls = NULL;
+ tt_int_op(tor_tls_context_init(TOR_TLS_CTX_IS_PUBLIC_SERVER,
+ key1, key2, 86400), OP_EQ, 0);
+ tls = tor_tls_new(-1, 0);
+ NS_MOCK(logv);
+ tt_int_op(CALLED(logv), OP_EQ, 0);
+ tor_tls_get_error(tls, 0, 0,
+ (const char *)"test", 0, 0);
+ tt_int_op(CALLED(logv), OP_EQ, 1);
+
+ done:
+ UNMOCK(tor_tls_cert_matches_key);
+ NS_UNMOCK(logv);
+ crypto_pk_free(key1);
+ crypto_pk_free(key2);
+ tor_tls_free(tls);
+}
+
+static void
+test_tortls_get_state_description(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ char *buf;
+ SSL_CTX *ctx;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(SSLv23_method());
+
+ buf = tor_malloc_zero(1000);
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tor_tls_get_state_description(NULL, buf, 20);
+ tt_str_op(buf, OP_EQ, "(No SSL object)");
+
+ SSL_free(tls->ssl);
+ tls->ssl = NULL;
+ tor_tls_get_state_description(tls, buf, 20);
+ tt_str_op(buf, OP_EQ, "(No SSL object)");
+
+ tls->ssl = SSL_new(ctx);
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in HANDSHAKE");
+
+ tls->state = TOR_TLS_ST_OPEN;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in OPEN");
+
+ tls->state = TOR_TLS_ST_GOTCLOSE;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in GOTCLOSE");
+
+ tls->state = TOR_TLS_ST_SENTCLOSE;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in SENTCLOSE");
+
+ tls->state = TOR_TLS_ST_CLOSED;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in CLOSED");
+
+ tls->state = TOR_TLS_ST_RENEGOTIATE;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in RENEGOTIATE");
+
+ tls->state = TOR_TLS_ST_BUFFEREVENT;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR);
+
+ tls->state = 7;
+ tor_tls_get_state_description(tls, buf, 200);
+ tt_str_op(buf, OP_EQ, SSL_STATE_STR " in unknown TLS state");
+
+ done:
+ SSL_CTX_free(ctx);
+ SSL_free(tls->ssl);
+ tor_free(buf);
+ tor_free(tls);
+}
+
+extern int tor_tls_object_ex_data_index;
+
+static void
+test_tortls_get_by_ssl(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ tor_tls_t *res;
+ SSL_CTX *ctx;
+ SSL *ssl;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+
+ ctx = SSL_CTX_new(SSLv23_method());
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->magic = TOR_TLS_MAGIC;
+
+ ssl = SSL_new(ctx);
+
+ res = tor_tls_get_by_ssl(ssl);
+ tt_assert(!res);
+
+ SSL_set_ex_data(ssl, tor_tls_object_ex_data_index, tls);
+
+ res = tor_tls_get_by_ssl(ssl);
+ tt_assert(res == tls);
+
+ done:
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+ tor_free(tls);
+}
+
+static void
+test_tortls_allocate_tor_tls_object_ex_data_index(void *ignored)
+{
+ (void)ignored;
+ int first;
+
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+
+ first = tor_tls_object_ex_data_index;
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+ tt_int_op(first, OP_EQ, tor_tls_object_ex_data_index);
+
+ done:
+ (void)0;
+}
+
+static void
+test_tortls_log_one_error(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ SSL_CTX *ctx;
+ SSL *ssl = NULL;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(SSLv23_method());
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ int previous_log = setup_capture_of_logs(LOG_INFO);
+
+ tor_tls_log_one_error(NULL, 0, LOG_WARN, 0, "something");
+ expect_log_msg("TLS error while something: "
+ "(null) (in (null):(null):---)\n");
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, 0, LOG_WARN, 0, NULL);
+ expect_log_msg("TLS error: (null) "
+ "(in (null):(null):---)\n");
+
+ mock_clean_saved_logs();
+ tls->address = tor_strdup("127.hello");
+ tor_tls_log_one_error(tls, 0, LOG_WARN, 0, NULL);
+ expect_log_msg("TLS error with 127.hello: "
+ "(null) (in (null):(null):---)\n");
+ tor_free(tls->address);
+
+ mock_clean_saved_logs();
+ tls->address = tor_strdup("127.hello");
+ tor_tls_log_one_error(tls, 0, LOG_WARN, 0, "blarg");
+ expect_log_msg("TLS error while blarg with "
+ "127.hello: (null) (in (null):(null):---)\n");
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, 3), LOG_WARN, 0, NULL);
+ expect_log_msg("TLS error with 127.hello: "
+ "BN lib (in unknown library:(null):---)\n");
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_HTTP_REQUEST),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_HTTPS_PROXY_REQUEST),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_RECORD_LENGTH_MISMATCH),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+
+#ifndef OPENSSL_1_1_API
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_RECORD_TOO_LARGE),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+#endif
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_UNKNOWN_PROTOCOL),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, ERR_PACK(1, 2, SSL_R_UNSUPPORTED_PROTOCOL),
+ LOG_WARN, 0, NULL);
+ expect_log_severity(LOG_INFO);
+
+ tls->ssl = SSL_new(ctx);
+
+ mock_clean_saved_logs();
+ tor_tls_log_one_error(tls, 0, LOG_WARN, 0, NULL);
+ expect_log_msg("TLS error with 127.hello: (null)"
+ " (in (null):(null):" SSL_STATE_STR ")\n");
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+ if (tls && tls->ssl)
+ SSL_free(tls->ssl);
+ if (tls)
+ tor_free(tls->address);
+ tor_free(tls);
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_get_error(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ int ret;
+ SSL_CTX *ctx;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(SSLv23_method());
+ int previous_log = setup_capture_of_logs(LOG_INFO);
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = SSL_new(ctx);
+ SSL_set_bio(tls->ssl, BIO_new(BIO_s_mem()), NULL);
+
+ ret = tor_tls_get_error(tls, 0, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_IO);
+ expect_log_msg("TLS error: unexpected close while"
+ " something (before/accept initialization)\n");
+
+ mock_clean_saved_logs();
+ ret = tor_tls_get_error(tls, 2, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ expect_no_log_entry();
+
+ mock_clean_saved_logs();
+ ret = tor_tls_get_error(tls, 0, 1, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, -11);
+ expect_no_log_entry();
+
+ mock_clean_saved_logs();
+ ERR_clear_error();
+ ERR_put_error(ERR_LIB_BN, 2, -1, "somewhere.c", 99);
+ ret = tor_tls_get_error(tls, 0, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+ expect_log_msg("TLS error while something: (null)"
+ " (in bignum routines:(null):before/accept initialization)\n");
+
+ mock_clean_saved_logs();
+ ERR_clear_error();
+ tls->ssl->rwstate = SSL_READING;
+ SSL_get_rbio(tls->ssl)->flags = BIO_FLAGS_READ;
+ ret = tor_tls_get_error(tls, -1, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, TOR_TLS_WANTREAD);
+ expect_no_log_entry();
+
+ mock_clean_saved_logs();
+ ERR_clear_error();
+ tls->ssl->rwstate = SSL_READING;
+ SSL_get_rbio(tls->ssl)->flags = BIO_FLAGS_WRITE;
+ ret = tor_tls_get_error(tls, -1, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, TOR_TLS_WANTWRITE);
+ expect_no_log_entry();
+
+ mock_clean_saved_logs();
+ ERR_clear_error();
+ tls->ssl->rwstate = 0;
+ tls->ssl->shutdown = SSL_RECEIVED_SHUTDOWN;
+ tls->ssl->s3->warn_alert =SSL_AD_CLOSE_NOTIFY;
+ ret = tor_tls_get_error(tls, 0, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, TOR_TLS_CLOSE);
+ expect_log_entry();
+
+ mock_clean_saved_logs();
+ ret = tor_tls_get_error(tls, 0, 2, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, -10);
+ expect_no_log_entry();
+
+ mock_clean_saved_logs();
+ ERR_put_error(ERR_LIB_SYS, 2, -1, "somewhere.c", 99);
+ ret = tor_tls_get_error(tls, -1, 0, "something", LOG_WARN, 0);
+ tt_int_op(ret, OP_EQ, -9);
+ expect_log_msg("TLS error while something: (null) (in system library:"
+ "connect:before/accept initialization)\n");
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ SSL_free(tls->ssl);
+ tor_free(tls);
+ SSL_CTX_free(ctx);
+}
+#endif
+
+static void
+test_tortls_always_accept_verify_cb(void *ignored)
+{
+ (void)ignored;
+ int ret;
+
+ ret = always_accept_verify_cb(0, NULL);
+ tt_int_op(ret, OP_EQ, 1);
+
+ done:
+ (void)0;
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_x509_cert_free(void *ignored)
+{
+ (void)ignored;
+ tor_x509_cert_t *cert;
+
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ tor_x509_cert_free(cert);
+
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ cert->cert = tor_malloc_zero(sizeof(X509));
+ cert->encoded = tor_malloc_zero(1);
+ tor_x509_cert_free(cert);
+}
+#endif
+
+static void
+test_tortls_x509_cert_get_id_digests(void *ignored)
+{
+ (void)ignored;
+ tor_x509_cert_t *cert;
+ common_digests_t *d;
+ const common_digests_t *res;
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ d = tor_malloc_zero(sizeof(common_digests_t));
+ d->d[0][0] = 42;
+
+ res = tor_x509_cert_get_id_digests(cert);
+ tt_assert(!res);
+
+ cert->pkey_digests_set = 1;
+ cert->pkey_digests = *d;
+ res = tor_x509_cert_get_id_digests(cert);
+ tt_int_op(res->d[0][0], OP_EQ, 42);
+
+ done:
+ tor_free(cert);
+ tor_free(d);
+}
+
+#ifndef OPENSSL_OPAQUE
+static int
+fixed_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
+{
+ (void) a; (void) b;
+ return 1;
+}
+
+static void
+fake_x509_free(X509 *cert)
+{
+ if (cert) {
+ if (cert->cert_info) {
+ if (cert->cert_info->key) {
+ if (cert->cert_info->key->pkey) {
+ tor_free(cert->cert_info->key->pkey);
+ }
+ tor_free(cert->cert_info->key);
+ }
+ tor_free(cert->cert_info);
+ }
+ tor_free(cert);
+ }
+}
+
+static void
+test_tortls_cert_matches_key(void *ignored)
+{
+ (void)ignored;
+ int res;
+ tor_tls_t *tls;
+ tor_x509_cert_t *cert;
+ X509 *one = NULL, *two = NULL;
+ EVP_PKEY_ASN1_METHOD *meth = EVP_PKEY_asn1_new(999, 0, NULL, NULL);
+ EVP_PKEY_asn1_set_public(meth, NULL, NULL, fixed_pub_cmp, NULL, NULL, NULL);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ one = tor_malloc_zero(sizeof(X509));
+ one->references = 1;
+ two = tor_malloc_zero(sizeof(X509));
+ two->references = 1;
+
+ res = tor_tls_cert_matches_key(tls, cert);
+ tt_int_op(res, OP_EQ, 0);
+
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+ tls->ssl->session->peer = one;
+ res = tor_tls_cert_matches_key(tls, cert);
+ tt_int_op(res, OP_EQ, 0);
+
+ cert->cert = two;
+ res = tor_tls_cert_matches_key(tls, cert);
+ tt_int_op(res, OP_EQ, 0);
+
+ one->cert_info = tor_malloc_zero(sizeof(X509_CINF));
+ one->cert_info->key = tor_malloc_zero(sizeof(X509_PUBKEY));
+ one->cert_info->key->pkey = tor_malloc_zero(sizeof(EVP_PKEY));
+ one->cert_info->key->pkey->references = 1;
+ one->cert_info->key->pkey->ameth = meth;
+ one->cert_info->key->pkey->type = 1;
+
+ two->cert_info = tor_malloc_zero(sizeof(X509_CINF));
+ two->cert_info->key = tor_malloc_zero(sizeof(X509_PUBKEY));
+ two->cert_info->key->pkey = tor_malloc_zero(sizeof(EVP_PKEY));
+ two->cert_info->key->pkey->references = 1;
+ two->cert_info->key->pkey->ameth = meth;
+ two->cert_info->key->pkey->type = 2;
+
+ res = tor_tls_cert_matches_key(tls, cert);
+ tt_int_op(res, OP_EQ, 0);
+
+ one->cert_info->key->pkey->type = 1;
+ two->cert_info->key->pkey->type = 1;
+ res = tor_tls_cert_matches_key(tls, cert);
+ tt_int_op(res, OP_EQ, 1);
+
+ done:
+ EVP_PKEY_asn1_free(meth);
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ tor_free(cert);
+ fake_x509_free(one);
+ fake_x509_free(two);
+}
+
+static void
+test_tortls_cert_get_key(void *ignored)
+{
+ (void)ignored;
+ tor_x509_cert_t *cert = NULL;
+ crypto_pk_t *res = NULL;
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ X509 *key = NULL;
+ key = tor_malloc_zero(sizeof(X509));
+ key->references = 1;
+
+ res = tor_tls_cert_get_key(cert);
+ tt_assert(!res);
+
+ cert->cert = key;
+ key->cert_info = tor_malloc_zero(sizeof(X509_CINF));
+ key->cert_info->key = tor_malloc_zero(sizeof(X509_PUBKEY));
+ key->cert_info->key->pkey = tor_malloc_zero(sizeof(EVP_PKEY));
+ key->cert_info->key->pkey->references = 1;
+ key->cert_info->key->pkey->type = 2;
+ res = tor_tls_cert_get_key(cert);
+ tt_assert(!res);
+
+ done:
+ fake_x509_free(key);
+ tor_free(cert);
+ crypto_pk_free(res);
+}
+#endif
+
+static void
+test_tortls_get_my_client_auth_key(void *ignored)
+{
+ (void)ignored;
+ crypto_pk_t *ret;
+ crypto_pk_t *expected;
+ tor_tls_context_t *ctx;
+ RSA *k = RSA_new();
+
+ ctx = tor_malloc_zero(sizeof(tor_tls_context_t));
+ expected = crypto_new_pk_from_rsa_(k);
+ ctx->auth_key = expected;
+
+ client_tls_context = NULL;
+ ret = tor_tls_get_my_client_auth_key();
+ tt_assert(!ret);
+
+ client_tls_context = ctx;
+ ret = tor_tls_get_my_client_auth_key();
+ tt_assert(ret == expected);
+
+ done:
+ RSA_free(k);
+ tor_free(expected);
+ tor_free(ctx);
+}
+
+static void
+test_tortls_get_my_certs(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_context_t *ctx;
+ const tor_x509_cert_t *link_cert_out = NULL;
+ const tor_x509_cert_t *id_cert_out = NULL;
+
+ ctx = tor_malloc_zero(sizeof(tor_tls_context_t));
+
+ client_tls_context = NULL;
+ ret = tor_tls_get_my_certs(0, NULL, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ server_tls_context = NULL;
+ ret = tor_tls_get_my_certs(1, NULL, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ client_tls_context = ctx;
+ ret = tor_tls_get_my_certs(0, NULL, NULL);
+ tt_int_op(ret, OP_EQ, 0);
+
+ client_tls_context = ctx;
+ ret = tor_tls_get_my_certs(0, &link_cert_out, &id_cert_out);
+ tt_int_op(ret, OP_EQ, 0);
+
+ server_tls_context = ctx;
+ ret = tor_tls_get_my_certs(1, &link_cert_out, &id_cert_out);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ (void)1;
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_get_ciphersuite_name(void *ignored)
+{
+ (void)ignored;
+ const char *ret;
+ tor_tls_t *ctx;
+ ctx = tor_malloc_zero(sizeof(tor_tls_t));
+ ctx->ssl = tor_malloc_zero(sizeof(SSL));
+
+ ret = tor_tls_get_ciphersuite_name(ctx);
+ tt_str_op(ret, OP_EQ, "(NONE)");
+
+ done:
+ tor_free(ctx->ssl);
+ tor_free(ctx);
+}
+
+static SSL_CIPHER *
+get_cipher_by_name(const char *name)
+{
+ int i;
+ const SSL_METHOD *method = SSLv23_method();
+ int num = method->num_ciphers();
+ for (i = 0; i < num; ++i) {
+ const SSL_CIPHER *cipher = method->get_cipher(i);
+ const char *ciphername = SSL_CIPHER_get_name(cipher);
+ if (!strcmp(ciphername, name)) {
+ return (SSL_CIPHER *)cipher;
+ }
+ }
+
+ return NULL;
+}
+
+static SSL_CIPHER *
+get_cipher_by_id(uint16_t id)
+{
+ int i;
+ const SSL_METHOD *method = SSLv23_method();
+ int num = method->num_ciphers();
+ for (i = 0; i < num; ++i) {
+ const SSL_CIPHER *cipher = method->get_cipher(i);
+ if (id == (SSL_CIPHER_get_id(cipher) & 0xffff)) {
+ return (SSL_CIPHER *)cipher;
+ }
+ }
+
+ return NULL;
+}
+
+extern uint16_t v2_cipher_list[];
+
+static void
+test_tortls_classify_client_ciphers(void *ignored)
+{
+ (void)ignored;
+ int i;
+ int ret;
+ SSL_CTX *ctx;
+ SSL *ssl;
+ tor_tls_t *tls;
+ STACK_OF(SSL_CIPHER) *ciphers;
+ SSL_CIPHER *tmp_cipher;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->magic = TOR_TLS_MAGIC;
+
+ ctx = SSL_CTX_new(TLSv1_method());
+ ssl = SSL_new(ctx);
+ tls->ssl = ssl;
+
+ ciphers = sk_SSL_CIPHER_new_null();
+
+ ret = tor_tls_classify_client_ciphers(ssl, NULL);
+ tt_int_op(ret, OP_EQ, -1);
+
+ SSL_set_ex_data(ssl, tor_tls_object_ex_data_index, tls);
+ tls->client_cipher_list_type = 42;
+
+ ret = tor_tls_classify_client_ciphers(ssl, NULL);
+ tt_int_op(ret, OP_EQ, 42);
+
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 1);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 1);
+
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, SSL_get_ciphers(ssl));
+ tt_int_op(ret, OP_EQ, 3);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 3);
+
+ SSL_CIPHER *one = get_cipher_by_name(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA),
+ *two = get_cipher_by_name(TLS1_TXT_DHE_RSA_WITH_AES_256_SHA),
+ *three = get_cipher_by_name(SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA),
+ *four = NULL;
+ sk_SSL_CIPHER_push(ciphers, one);
+ sk_SSL_CIPHER_push(ciphers, two);
+ sk_SSL_CIPHER_push(ciphers, three);
+ sk_SSL_CIPHER_push(ciphers, four);
+
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 1);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 1);
+
+ sk_SSL_CIPHER_zero(ciphers);
+
+ one = get_cipher_by_name("ECDH-RSA-AES256-GCM-SHA384");
+ one->id = 0x00ff;
+ two = get_cipher_by_name("ECDH-RSA-AES128-GCM-SHA256");
+ two->id = 0x0000;
+ sk_SSL_CIPHER_push(ciphers, one);
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 3);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 3);
+
+ sk_SSL_CIPHER_push(ciphers, two);
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 3);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 3);
+
+ one->id = 0xC00A;
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 3);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 3);
+
+ sk_SSL_CIPHER_zero(ciphers);
+ for (i=0; v2_cipher_list[i]; i++) {
+ tmp_cipher = get_cipher_by_id(v2_cipher_list[i]);
+ tt_assert(tmp_cipher);
+ sk_SSL_CIPHER_push(ciphers, tmp_cipher);
+ }
+ tls->client_cipher_list_type = 0;
+ ret = tor_tls_classify_client_ciphers(ssl, ciphers);
+ tt_int_op(ret, OP_EQ, 2);
+ tt_int_op(tls->client_cipher_list_type, OP_EQ, 2);
+
+ done:
+ sk_SSL_CIPHER_free(ciphers);
+ SSL_free(tls->ssl);
+ tor_free(tls);
+ SSL_CTX_free(ctx);
+}
+#endif
+
+static void
+test_tortls_client_is_using_v2_ciphers(void *ignored)
+{
+ (void)ignored;
+
+#ifdef HAVE_SSL_GET_CLIENT_CIPHERS
+ tt_skip();
+ done:
+ (void)1;
+#else
+ int ret;
+ SSL_CTX *ctx;
+ SSL *ssl;
+ SSL_SESSION *sess;
+ STACK_OF(SSL_CIPHER) *ciphers;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(TLSv1_method());
+ ssl = SSL_new(ctx);
+ sess = SSL_SESSION_new();
+
+ ret = tor_tls_client_is_using_v2_ciphers(ssl);
+ tt_int_op(ret, OP_EQ, -1);
+
+ ssl->session = sess;
+ ret = tor_tls_client_is_using_v2_ciphers(ssl);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ciphers = sk_SSL_CIPHER_new_null();
+ SSL_CIPHER *one = get_cipher_by_name("ECDH-RSA-AES256-GCM-SHA384");
+ one->id = 0x00ff;
+ sk_SSL_CIPHER_push(ciphers, one);
+ sess->ciphers = ciphers;
+ ret = tor_tls_client_is_using_v2_ciphers(ssl);
+ tt_int_op(ret, OP_EQ, 1);
+ done:
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+#endif
+}
+
+#ifndef OPENSSL_OPAQUE
+static X509 *fixed_try_to_extract_certs_from_tls_cert_out_result = NULL;
+static X509 *fixed_try_to_extract_certs_from_tls_id_cert_out_result = NULL;
+
+static void
+fixed_try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
+ X509 **cert_out, X509 **id_cert_out)
+{
+ (void) severity;
+ (void) tls;
+ *cert_out = fixed_try_to_extract_certs_from_tls_cert_out_result;
+ *id_cert_out = fixed_try_to_extract_certs_from_tls_id_cert_out_result;
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static const char* notCompletelyValidCertString =
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIICVjCCAb8CAg37MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG\n"
+ "A1UECBMFVG9reW8xEDAOBgNVBAcTB0NodW8ta3UxETAPBgNVBAoTCEZyYW5rNERE\n"
+ "MRgwFgYDVQQLEw9XZWJDZXJ0IFN1cHBvcnQxGDAWBgNVBAMTD0ZyYW5rNEREIFdl\n"
+ "YiBDQTEjMCEGCSqGSIb3DQEJARYUc3VwcG9ydEBmcmFuazRkZC5jb20wHhcNMTIw\n"
+ "ODIyMDUyNzIzWhcNMTcwODIxMDUyNzIzWjBKMQswCQYDVQQGEwJKUDEOMAwGA1UE\n"
+ "CAwFVG9reW8xETAPBgNVBAoMCEZyYW5rNEREMRgwFgYDVQQDDA93d3cuZXhhbXBs\n"
+ "ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYBBrx5PlP0WNI/ZdzD\n"
+ "+6Pktmurn+F2kQYbtc7XQh8/LTBvCo+P6iZoLEmUA9e7EXLRxgU1CVqeAi7QcAn9\n"
+ "MwBlc8ksFJHB0rtf9pmf8Oza9E0Bynlq/4/Kb1x+d+AyhL7oK9tQwB24uHOueHi1\n"
+ "C/iVv8CSWKiYe6hzN1txYe8rAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAASPdjigJ\n"
+ "kXCqKWpnZ/Oc75EUcMi6HztaW8abUMlYXPIgkV2F7YanHOB7K4f7OOLjiz8DTPFf\n"
+ "jC9UeuErhaA/zzWi8ewMTFZW/WshOrm3fNvcMrMLKtH534JKvcdMg6qIdjTFINIr\n"
+ "evnAhf0cwULaebn+lMs8Pdl7y37+sfluVok=\n"
+ "-----END CERTIFICATE-----\n";
+#endif
+
+static const char* validCertString = "-----BEGIN CERTIFICATE-----\n"
+ "MIIDpTCCAY0CAg3+MA0GCSqGSIb3DQEBBQUAMF4xCzAJBgNVBAYTAlVTMREwDwYD\n"
+ "VQQIDAhJbGxpbm9pczEQMA4GA1UEBwwHQ2hpY2FnbzEUMBIGA1UECgwLVG9yIFRl\n"
+ "c3RpbmcxFDASBgNVBAMMC1RvciBUZXN0aW5nMB4XDTE1MDkwNjEzMzk1OVoXDTQz\n"
+ "MDEyMjEzMzk1OVowVjELMAkGA1UEBhMCVVMxEDAOBgNVBAcMB0NoaWNhZ28xFDAS\n"
+ "BgNVBAoMC1RvciBUZXN0aW5nMR8wHQYDVQQDDBZ0ZXN0aW5nLnRvcnByb2plY3Qu\n"
+ "b3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoT6uyVVhWyOF3wkHjjYbd\n"
+ "nKaykyRv4JVtKQdZ4OpEErmX1zw4MmyzpQNV6iR4bQnWiyLfzyVJMZDIC/WILBfX\n"
+ "w2Pza/yuLgUvDc3twMuhOACzOQVO8PrEF/aVv2+hbCCy2udXvKhnYn+CCXl3ozc8\n"
+ "XcKYvujTXDyvGWY3xwAjlQIDAQABMA0GCSqGSIb3DQEBBQUAA4ICAQCUvnhzQWuQ\n"
+ "MrN+pERkE+zcTI/9dGS90rUMMLgu8VDNqTa0TUQh8uO0EQ6uDvI8Js6e8tgwS0BR\n"
+ "UBahqb7ZHv+rejGCBr5OudqD+x4STiiuPNJVs86JTLN8SpM9CHjIBH5WCCN2KOy3\n"
+ "mevNoRcRRyYJzSFULCunIK6FGulszigMYGscrO4oiTkZiHPh9KvWT40IMiHfL+Lw\n"
+ "EtEWiLex6064LcA2YQ1AMuSZyCexks63lcfaFmQbkYOKqXa1oLkIRuDsOaSVjTfe\n"
+ "vec+X6jvf12cFTKS5WIeqkKF2Irt+dJoiHEGTe5RscUMN/f+gqHPzfFz5dR23sxo\n"
+ "g+HC6MZHlFkLAOx3wW6epPS8A/m1mw3zMPoTnb2U2YYt8T0dJMMlUn/7Y1sEAa+a\n"
+ "dSTMaeUf6VnJ//11m454EZl1to9Z7oJOgqmFffSrdD4BGIWe8f7hhW6L1Enmqe/J\n"
+ "BKL3wbzZh80O1W0bndAwhnEEhlzneFY84cbBo9pmVxpODHkUcStpr5Z7pBDrcL21\n"
+ "Ss/aB/1YrsVXhdvJdOGxl3Mnl9dUY57CympLGlT8f0pPS6GAKOelECOhFMHmJd8L\n"
+ "dj3XQSmKtYHevZ6IvuMXSlB/fJvSjSlkCuLo5+kJoaqPuRu+i/S1qxeRy3CBwmnE\n"
+ "LdSNdcX4N79GQJ996PA8+mUCQG7YRtK+WA==\n"
+ "-----END CERTIFICATE-----\n";
+
+static const char* caCertString = "-----BEGIN CERTIFICATE-----\n"
+ "MIIFjzCCA3egAwIBAgIJAKd5WgyfPMYRMA0GCSqGSIb3DQEBCwUAMF4xCzAJBgNV\n"
+ "BAYTAlVTMREwDwYDVQQIDAhJbGxpbm9pczEQMA4GA1UEBwwHQ2hpY2FnbzEUMBIG\n"
+ "A1UECgwLVG9yIFRlc3RpbmcxFDASBgNVBAMMC1RvciBUZXN0aW5nMB4XDTE1MDkw\n"
+ "NjEzMzc0MVoXDTQzMDEyMjEzMzc0MVowXjELMAkGA1UEBhMCVVMxETAPBgNVBAgM\n"
+ "CElsbGlub2lzMRAwDgYDVQQHDAdDaGljYWdvMRQwEgYDVQQKDAtUb3IgVGVzdGlu\n"
+ "ZzEUMBIGA1UEAwwLVG9yIFRlc3RpbmcwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw\n"
+ "ggIKAoICAQCpLMUEiLW5leUgBZoEJms2V7lZRhIAjnJBhVMHD0e3UubNknmaQoxf\n"
+ "ARz3rvqOaRd0JlV+qM9qE0DjiYcCVP1cAfqAo9d83uS1vwY3YMVJzADlaIiHfyVW\n"
+ "uEgBy0vvkeUBqaua24dYlcwsemOiXYLu41yM1wkcGHW1AhBNHppY6cznb8TyLgNM\n"
+ "2x3SGUdzc5XMyAFx51faKGBA3wjs+Hg1PLY7d30nmCgEOBavpm5I1disM/0k+Mcy\n"
+ "YmAKEo/iHJX/rQzO4b9znP69juLlR8PDBUJEVIG/CYb6+uw8MjjUyiWXYoqfVmN2\n"
+ "hm/lH8b6rXw1a2Aa3VTeD0DxaWeacMYHY/i01fd5n7hCoDTRNdSw5KJ0L3Z0SKTu\n"
+ "0lzffKzDaIfyZGlpW5qdouACkWYzsaitQOePVE01PIdO30vUfzNTFDfy42ccx3Di\n"
+ "59UCu+IXB+eMtrBfsok0Qc63vtF1linJgjHW1z/8ujk8F7/qkOfODhk4l7wngc2A\n"
+ "EmwWFIFoGaiTEZHB9qteXr4unbXZ0AHpM02uGGwZEGohjFyebEb73M+J57WKKAFb\n"
+ "PqbLcGUksL1SHNBNAJcVLttX55sO4nbidOS/kA3m+F1R04MBTyQF9qA6YDDHqdI3\n"
+ "h/3pw0Z4fxVouTYT4/NfRnX4JTP4u+7Mpcoof28VME0qWqD1LnRhFQIDAQABo1Aw\n"
+ "TjAdBgNVHQ4EFgQUMoAgIXH7pZ3QMRwTjT+DM9Yo/v0wHwYDVR0jBBgwFoAUMoAg\n"
+ "IXH7pZ3QMRwTjT+DM9Yo/v0wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\n"
+ "AgEAUJxacjXR9sT+Xs6ISFiUsyd0T6WVKMnV46xrYJHirGfx+krWHrjxMY+ZtxYD\n"
+ "DBDGlo11Qc4v6QrclNf5QUBfIiGQsP9Cm6hHcQ+Tpg9HHCgSqG1YNPwCPReCR4br\n"
+ "BLvLfrfkcBL2IWM0PdQdCze+59DBfipsULD2mEn9fjYRXQEwb2QWtQ9qRc20Yb/x\n"
+ "Q4b/+CvUodLkaq7B8MHz0BV8HHcBoph6DYaRmO/N+hPauIuSp6XyaGYcEefGKVKj\n"
+ "G2+fcsdyXsoijNdL8vNKwm4j2gVwCBnw16J00yfFoV46YcbfqEdJB2je0XSvwXqt\n"
+ "14AOTngxso2h9k9HLtrfpO1ZG/B5AcCMs1lzbZ2fp5DPHtjvvmvA2RJqgo3yjw4W\n"
+ "4DHAuTglYFlC3mDHNfNtcGP20JvepcQNzNP2UzwcpOc94hfKikOFw+gf9Vf1qd0y\n"
+ "h/Sk6OZHn2+JVUPiWHIQV98Vtoh4RmUZDJD+b55ia3fQGTGzt4z1XFzQYSva5sfs\n"
+ "wocS/papthqWldQU7x+3wofNd5CNU1x6WKXG/yw30IT/4F8ADJD6GeygNT8QJYvt\n"
+ "u/8lAkbOy6B9xGmSvr0Kk1oq9P2NshA6kalxp1Oz/DTNDdL4AeBXV3JmM6WWCjGn\n"
+ "Yy1RT69d0rwYc5u/vnqODz1IjvT90smsrkBumGt791FAFeg=\n"
+ "-----END CERTIFICATE-----\n";
+
+static X509 *
+read_cert_from(const char *str)
+{
+ BIO *bio = BIO_new(BIO_s_mem());
+ BIO_write(bio, str, (int) strlen(str));
+ X509 *res = PEM_read_bio_X509(bio, NULL, NULL, NULL);
+ BIO_free(bio);
+ return res;
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_verify(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ crypto_pk_t *k = NULL;
+ X509 *cert1 = NULL, *cert2 = NULL, *invalidCert = NULL,
+ *validCert = NULL, *caCert = NULL;
+
+ cert1 = tor_malloc_zero(sizeof(X509));
+ cert1->references = 10;
+
+ cert2 = tor_malloc_zero(sizeof(X509));
+ cert2->references = 10;
+
+ validCert = read_cert_from(validCertString);
+ caCert = read_cert_from(caCertString);
+ invalidCert = read_cert_from(notCompletelyValidCertString);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ ret = tor_tls_verify(LOG_WARN, tls, &k);
+ tt_int_op(ret, OP_EQ, -1);
+
+ MOCK(try_to_extract_certs_from_tls, fixed_try_to_extract_certs_from_tls);
+
+ fixed_try_to_extract_certs_from_tls_cert_out_result = cert1;
+ ret = tor_tls_verify(LOG_WARN, tls, &k);
+ tt_int_op(ret, OP_EQ, -1);
+
+ fixed_try_to_extract_certs_from_tls_id_cert_out_result = cert2;
+ ret = tor_tls_verify(LOG_WARN, tls, &k);
+ tt_int_op(ret, OP_EQ, -1);
+
+ fixed_try_to_extract_certs_from_tls_cert_out_result = invalidCert;
+ fixed_try_to_extract_certs_from_tls_id_cert_out_result = invalidCert;
+
+ ret = tor_tls_verify(LOG_WARN, tls, &k);
+ tt_int_op(ret, OP_EQ, -1);
+
+ fixed_try_to_extract_certs_from_tls_cert_out_result = validCert;
+ fixed_try_to_extract_certs_from_tls_id_cert_out_result = caCert;
+
+ ret = tor_tls_verify(LOG_WARN, tls, &k);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_assert(k);
+
+ done:
+ UNMOCK(try_to_extract_certs_from_tls);
+ tor_free(cert1);
+ tor_free(cert2);
+ tor_free(tls);
+ tor_free(k);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_check_lifetime(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ X509 *validCert = read_cert_from(validCertString);
+ time_t now = time(NULL);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ ret = tor_tls_check_lifetime(LOG_WARN, tls, 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+ tls->ssl->session->peer = validCert;
+ ret = tor_tls_check_lifetime(LOG_WARN, tls, 0, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ASN1_STRING_free(validCert->cert_info->validity->notBefore);
+ validCert->cert_info->validity->notBefore = ASN1_TIME_set(NULL, now-10);
+ ASN1_STRING_free(validCert->cert_info->validity->notAfter);
+ validCert->cert_info->validity->notAfter = ASN1_TIME_set(NULL, now+60);
+
+ ret = tor_tls_check_lifetime(LOG_WARN, tls, 0, -1000);
+ tt_int_op(ret, OP_EQ, -1);
+
+ ret = tor_tls_check_lifetime(LOG_WARN, tls, -1000, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ done:
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ X509_free(validCert);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static int fixed_ssl_pending_result = 0;
+
+static int
+fixed_ssl_pending(const SSL *ignored)
+{
+ (void)ignored;
+ return fixed_ssl_pending_result;
+}
+
+static void
+test_tortls_get_pending_bytes(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ SSL_METHOD *method;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ method = tor_malloc_zero(sizeof(SSL_METHOD));
+ method->ssl_pending = fixed_ssl_pending;
+ tls->ssl->method = method;
+
+ fixed_ssl_pending_result = 42;
+ ret = tor_tls_get_pending_bytes(tls);
+ tt_int_op(ret, OP_EQ, 42);
+
+ done:
+ tor_free(method);
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+static void
+test_tortls_get_forced_write_size(void *ignored)
+{
+ (void)ignored;
+ long ret;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tls->wantwrite_n = 43;
+ ret = tor_tls_get_forced_write_size(tls);
+ tt_int_op(ret, OP_EQ, 43);
+
+ done:
+ tor_free(tls);
+}
+
+extern uint64_t total_bytes_written_over_tls;
+extern uint64_t total_bytes_written_by_tls;
+
+static void
+test_tortls_get_write_overhead_ratio(void *ignored)
+{
+ (void)ignored;
+ double ret;
+
+ total_bytes_written_over_tls = 0;
+ ret = tls_get_write_overhead_ratio();
+ tt_int_op(ret, OP_EQ, 1.0);
+
+ total_bytes_written_by_tls = 10;
+ total_bytes_written_over_tls = 1;
+ ret = tls_get_write_overhead_ratio();
+ tt_int_op(ret, OP_EQ, 10.0);
+
+ total_bytes_written_by_tls = 10;
+ total_bytes_written_over_tls = 2;
+ ret = tls_get_write_overhead_ratio();
+ tt_int_op(ret, OP_EQ, 5.0);
+
+ done:
+ (void)0;
+}
+
+static void
+test_tortls_used_v1_handshake(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ // These tests assume both V2 handshake server and client are enabled
+ tls->wasV2Handshake = 0;
+ ret = tor_tls_used_v1_handshake(tls);
+ tt_int_op(ret, OP_EQ, 1);
+
+ tls->wasV2Handshake = 1;
+ ret = tor_tls_used_v1_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ tor_free(tls);
+}
+
+static void
+test_tortls_get_num_server_handshakes(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tls->server_handshake_count = 3;
+ ret = tor_tls_get_num_server_handshakes(tls);
+ tt_int_op(ret, OP_EQ, 3);
+
+ done:
+ tor_free(tls);
+}
+
+static void
+test_tortls_server_got_renegotiate(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tls->got_renegotiate = 1;
+ ret = tor_tls_server_got_renegotiate(tls);
+ tt_int_op(ret, OP_EQ, 1);
+
+ done:
+ tor_free(tls);
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_SSL_SESSION_get_master_key(void *ignored)
+{
+ (void)ignored;
+ size_t ret;
+ tor_tls_t *tls;
+ uint8_t *out;
+ out = tor_malloc_zero(1);
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+ tls->ssl->session->master_key_length = 1;
+
+#ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
+ tls->ssl->session->master_key[0] = 43;
+ ret = SSL_SESSION_get_master_key(tls->ssl->session, out, 0);
+ tt_int_op(ret, OP_EQ, 1);
+ tt_int_op(out[0], OP_EQ, 0);
+
+ ret = SSL_SESSION_get_master_key(tls->ssl->session, out, 1);
+ tt_int_op(ret, OP_EQ, 1);
+ tt_int_op(out[0], OP_EQ, 43);
+
+ done:
+#endif
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ tor_free(out);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_get_tlssecrets(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ uint8_t *secret_out = tor_malloc_zero(DIGEST256_LEN);;
+ tor_tls_t *tls;
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+ tls->ssl->session->master_key_length = 1;
+ tls->ssl->s3 = tor_malloc_zero(sizeof(SSL3_STATE));
+
+ ret = tor_tls_get_tlssecrets(tls, secret_out);
+ tt_int_op(ret, OP_EQ, 0);
+
+ done:
+ tor_free(secret_out);
+ tor_free(tls->ssl->s3);
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_get_buffer_sizes(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ size_t rbuf_c=-1, rbuf_b=-1, wbuf_c=-1, wbuf_b=-1;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->s3 = tor_malloc_zero(sizeof(SSL3_STATE));
+
+ tls->ssl->s3->rbuf.buf = NULL;
+ tls->ssl->s3->rbuf.len = 1;
+ tls->ssl->s3->rbuf.offset = 0;
+ tls->ssl->s3->rbuf.left = 42;
+
+ tls->ssl->s3->wbuf.buf = NULL;
+ tls->ssl->s3->wbuf.len = 2;
+ tls->ssl->s3->wbuf.offset = 0;
+ tls->ssl->s3->wbuf.left = 43;
+
+ ret = tor_tls_get_buffer_sizes(tls, &rbuf_c, &rbuf_b, &wbuf_c, &wbuf_b);
+#if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
+ tt_int_op(ret, OP_EQ, -1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(rbuf_c, OP_EQ, 0);
+ tt_int_op(wbuf_c, OP_EQ, 0);
+ tt_int_op(rbuf_b, OP_EQ, 42);
+ tt_int_op(wbuf_b, OP_EQ, 43);
+
+ tls->ssl->s3->rbuf.buf = tor_malloc_zero(1);
+ tls->ssl->s3->wbuf.buf = tor_malloc_zero(1);
+ ret = tor_tls_get_buffer_sizes(tls, &rbuf_c, &rbuf_b, &wbuf_c, &wbuf_b);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(rbuf_c, OP_EQ, 1);
+ tt_int_op(wbuf_c, OP_EQ, 2);
+
+#endif
+
+ done:
+ tor_free(tls->ssl->s3->rbuf.buf);
+ tor_free(tls->ssl->s3->wbuf.buf);
+ tor_free(tls->ssl->s3);
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+static void
+test_tortls_evaluate_ecgroup_for_tls(void *ignored)
+{
+ (void)ignored;
+ int ret;
+
+ ret = evaluate_ecgroup_for_tls(NULL);
+ tt_int_op(ret, OP_EQ, 1);
+
+ ret = evaluate_ecgroup_for_tls("foobar");
+ tt_int_op(ret, OP_EQ, 0);
+
+ ret = evaluate_ecgroup_for_tls("P256");
+ tt_int_op(ret, OP_EQ, 1);
+
+ ret = evaluate_ecgroup_for_tls("P224");
+ // tt_int_op(ret, OP_EQ, 1); This varies between machines
+
+ done:
+ (void)0;
+}
+
+#ifndef OPENSSL_OPAQUE
+typedef struct cert_pkey_st_local
+{
+ X509 *x509;
+ EVP_PKEY *privatekey;
+ const EVP_MD *digest;
+} CERT_PKEY_local;
+
+typedef struct sess_cert_st_local
+{
+ STACK_OF(X509) *cert_chain;
+ int peer_cert_type;
+ CERT_PKEY_local *peer_key;
+ CERT_PKEY_local peer_pkeys[8];
+ int references;
+} SESS_CERT_local;
+
+static void
+test_tortls_try_to_extract_certs_from_tls(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ X509 *cert = NULL, *id_cert = NULL, *c1 = NULL, *c2 = NULL;
+ SESS_CERT_local *sess = NULL;
+
+ c1 = read_cert_from(validCertString);
+ c2 = read_cert_from(caCertString);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+ sess = tor_malloc_zero(sizeof(SESS_CERT_local));
+ tls->ssl->session->sess_cert = (void *)sess;
+
+ try_to_extract_certs_from_tls(LOG_WARN, tls, &cert, &id_cert);
+ tt_assert(!cert);
+ tt_assert(!id_cert);
+
+ tls->ssl->session->peer = c1;
+ try_to_extract_certs_from_tls(LOG_WARN, tls, &cert, &id_cert);
+ tt_assert(cert == c1);
+ tt_assert(!id_cert);
+ X509_free(cert); /* decrease refcnt */
+
+ sess->cert_chain = sk_X509_new_null();
+ try_to_extract_certs_from_tls(LOG_WARN, tls, &cert, &id_cert);
+ tt_assert(cert == c1);
+ tt_assert(!id_cert);
+ X509_free(cert); /* decrease refcnt */
+
+ sk_X509_push(sess->cert_chain, c1);
+ sk_X509_push(sess->cert_chain, c2);
+
+ try_to_extract_certs_from_tls(LOG_WARN, tls, &cert, &id_cert);
+ tt_assert(cert == c1);
+ tt_assert(id_cert);
+ X509_free(cert); /* decrease refcnt */
+
+ done:
+ sk_X509_free(sess->cert_chain);
+ tor_free(sess);
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ X509_free(c1);
+ X509_free(c2);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_get_peer_cert(void *ignored)
+{
+ (void)ignored;
+ tor_x509_cert_t *ret;
+ tor_tls_t *tls;
+ X509 *cert = NULL;
+
+ cert = read_cert_from(validCertString);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+
+ ret = tor_tls_get_peer_cert(tls);
+ tt_assert(!ret);
+
+ tls->ssl->session->peer = cert;
+ ret = tor_tls_get_peer_cert(tls);
+ tt_assert(ret);
+ tt_assert(ret->cert == cert);
+
+ done:
+ tor_x509_cert_free(ret);
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ X509_free(cert);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_peer_has_cert(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ X509 *cert = NULL;
+
+ cert = read_cert_from(validCertString);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->session = tor_malloc_zero(sizeof(SSL_SESSION));
+
+ ret = tor_tls_peer_has_cert(tls);
+ tt_assert(!ret);
+
+ tls->ssl->session->peer = cert;
+ ret = tor_tls_peer_has_cert(tls);
+ tt_assert(ret);
+
+ done:
+ tor_free(tls->ssl->session);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ X509_free(cert);
+}
+#endif
+
+static void
+test_tortls_is_server(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ int ret;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->isServer = 1;
+ ret = tor_tls_is_server(tls);
+ tt_int_op(ret, OP_EQ, 1);
+
+ done:
+ tor_free(tls);
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_session_secret_cb(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ SSL_CTX *ctx;
+ STACK_OF(SSL_CIPHER) *ciphers = NULL;
+ SSL_CIPHER *one;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tls->magic = TOR_TLS_MAGIC;
+
+ ctx = SSL_CTX_new(TLSv1_method());
+ tls->ssl = SSL_new(ctx);
+ SSL_set_ex_data(tls->ssl, tor_tls_object_ex_data_index, tls);
+
+ SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
+
+ tor_tls_session_secret_cb(tls->ssl, NULL, NULL, NULL, NULL, NULL);
+ tt_assert(!tls->ssl->tls_session_secret_cb);
+
+ one = get_cipher_by_name("ECDH-RSA-AES256-GCM-SHA384");
+ one->id = 0x00ff;
+ ciphers = sk_SSL_CIPHER_new_null();
+ sk_SSL_CIPHER_push(ciphers, one);
+
+ tls->client_cipher_list_type = 0;
+ tor_tls_session_secret_cb(tls->ssl, NULL, NULL, ciphers, NULL, NULL);
+ tt_assert(!tls->ssl->tls_session_secret_cb);
+
+ done:
+ sk_SSL_CIPHER_free(ciphers);
+ SSL_free(tls->ssl);
+ SSL_CTX_free(ctx);
+ tor_free(tls);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+/* TODO: It seems block_renegotiation and unblock_renegotiation and
+ * using different blags. This might not be correct */
+static void
+test_tortls_block_renegotiation(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->s3 = tor_malloc_zero(sizeof(SSL3_STATE));
+#ifndef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
+#define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0
+#endif
+
+ tls->ssl->s3->flags = SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
+
+ tor_tls_block_renegotiation(tls);
+
+#ifndef OPENSSL_1_1_API
+ tt_assert(!(tls->ssl->s3->flags &
+ SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
+#endif
+
+ done:
+ tor_free(tls->ssl->s3);
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+
+static void
+test_tortls_unblock_renegotiation(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tor_tls_unblock_renegotiation(tls);
+
+ tt_uint_op(SSL_get_options(tls->ssl) &
+ SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION, OP_EQ,
+ SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
+
+ done:
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_assert_renegotiation_unblocked(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tor_tls_unblock_renegotiation(tls);
+ tor_tls_assert_renegotiation_unblocked(tls);
+ /* No assertion here - this test will fail if tor_assert is turned on
+ * and things are bad. */
+
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+static void
+test_tortls_set_logged_address(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+
+ tor_tls_set_logged_address(tls, "foo bar");
+
+ tt_str_op(tls->address, OP_EQ, "foo bar");
+
+ tor_tls_set_logged_address(tls, "foo bar 2");
+ tt_str_op(tls->address, OP_EQ, "foo bar 2");
+
+ done:
+ tor_free(tls->address);
+ tor_free(tls);
+}
+
+#ifndef OPENSSL_OPAQUE
+static void
+example_cb(tor_tls_t *t, void *arg)
+{
+ (void)t;
+ (void)arg;
+}
+
+static void
+test_tortls_set_renegotiate_callback(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ const char *arg = "hello";
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+
+ tor_tls_set_renegotiate_callback(tls, example_cb, (void*)arg);
+ tt_assert(tls->negotiated_callback == example_cb);
+ tt_assert(tls->callback_arg == arg);
+ tt_assert(!tls->got_renegotiate);
+
+ /* Assumes V2_HANDSHAKE_SERVER */
+ tt_assert(tls->ssl->info_callback == tor_tls_server_info_callback);
+
+ tor_tls_set_renegotiate_callback(tls, NULL, (void*)arg);
+ tt_assert(tls->ssl->info_callback == tor_tls_debug_state_callback);
+
+ done:
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static SSL_CIPHER *fixed_cipher1 = NULL;
+static SSL_CIPHER *fixed_cipher2 = NULL;
+static const SSL_CIPHER *
+fake_get_cipher(unsigned ncipher)
+{
+
+ switch (ncipher) {
+ case 1:
+ return fixed_cipher1;
+ case 2:
+ return fixed_cipher2;
+ default:
+ return NULL;
+ }
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_find_cipher_by_id(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ SSL *ssl;
+ SSL_CTX *ctx;
+ const SSL_METHOD *m = TLSv1_method();
+ SSL_METHOD *empty_method = tor_malloc_zero(sizeof(SSL_METHOD));
+
+ fixed_cipher1 = tor_malloc_zero(sizeof(SSL_CIPHER));
+ fixed_cipher2 = tor_malloc_zero(sizeof(SSL_CIPHER));
+ fixed_cipher2->id = 0xC00A;
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(m);
+ ssl = SSL_new(ctx);
+
+ ret = find_cipher_by_id(ssl, NULL, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ ret = find_cipher_by_id(ssl, m, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ ret = find_cipher_by_id(ssl, m, 0xFFFF);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ret = find_cipher_by_id(ssl, empty_method, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ ret = find_cipher_by_id(ssl, empty_method, 0xFFFF);
+#ifdef HAVE_SSL_CIPHER_FIND
+ tt_int_op(ret, OP_EQ, 0);
+#else
+ tt_int_op(ret, OP_EQ, 1);
+#endif
+
+ empty_method->get_cipher = fake_get_cipher;
+ ret = find_cipher_by_id(ssl, empty_method, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ empty_method->get_cipher = m->get_cipher;
+ empty_method->num_ciphers = m->num_ciphers;
+ ret = find_cipher_by_id(ssl, empty_method, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ empty_method->get_cipher = fake_get_cipher;
+ empty_method->num_ciphers = m->num_ciphers;
+ ret = find_cipher_by_id(ssl, empty_method, 0xC00A);
+ tt_int_op(ret, OP_EQ, 1);
+
+ empty_method->num_ciphers = fake_num_ciphers;
+ ret = find_cipher_by_id(ssl, empty_method, 0xC00A);
+#ifdef HAVE_SSL_CIPHER_FIND
+ tt_int_op(ret, OP_EQ, 1);
+#else
+ tt_int_op(ret, OP_EQ, 0);
+#endif
+
+ done:
+ tor_free(empty_method);
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+ tor_free(fixed_cipher1);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_debug_state_callback(void *ignored)
+{
+ (void)ignored;
+ SSL *ssl;
+ char *buf = tor_malloc_zero(1000);
+ int n;
+
+ int previous_log = setup_capture_of_logs(LOG_DEBUG);
+
+ ssl = tor_malloc_zero(sizeof(SSL));
+
+ tor_tls_debug_state_callback(ssl, 32, 45);
+
+ n = tor_snprintf(buf, 1000, "SSL %p is now in state unknown"
+ " state [type=32,val=45].\n", ssl);
+ /* tor's snprintf returns -1 on error */
+ tt_int_op(n, OP_NE, -1);
+ expect_log_msg(buf);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ tor_free(buf);
+ tor_free(ssl);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_server_info_callback(void *ignored)
+{
+ (void)ignored;
+ tor_tls_t *tls;
+ SSL_CTX *ctx;
+ SSL *ssl;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(TLSv1_method());
+ ssl = SSL_new(ctx);
+
+ tor_tls_allocate_tor_tls_object_ex_data_index();
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->magic = TOR_TLS_MAGIC;
+ tls->ssl = ssl;
+
+ tor_tls_server_info_callback(NULL, 0, 0);
+
+ SSL_set_state(ssl, SSL3_ST_SW_SRVR_HELLO_A);
+ mock_clean_saved_logs();
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ expect_log_msg("Couldn't look up the tls for an SSL*. How odd!\n");
+
+ SSL_set_state(ssl, SSL3_ST_SW_SRVR_HELLO_B);
+ mock_clean_saved_logs();
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ expect_log_msg("Couldn't look up the tls for an SSL*. How odd!\n");
+
+ SSL_set_state(ssl, 99);
+ mock_clean_saved_logs();
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ expect_no_log_entry();
+
+ SSL_set_ex_data(tls->ssl, tor_tls_object_ex_data_index, tls);
+ SSL_set_state(ssl, SSL3_ST_SW_SRVR_HELLO_B);
+ tls->negotiated_callback = 0;
+ tls->server_handshake_count = 120;
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ tt_int_op(tls->server_handshake_count, OP_EQ, 121);
+
+ tls->server_handshake_count = 127;
+ tls->negotiated_callback = (void *)1;
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ tt_int_op(tls->server_handshake_count, OP_EQ, 127);
+ tt_int_op(tls->got_renegotiate, OP_EQ, 1);
+
+ tls->ssl->session = SSL_SESSION_new();
+ tls->wasV2Handshake = 0;
+ tor_tls_server_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 0);
+ tt_int_op(tls->wasV2Handshake, OP_EQ, 0);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+ tor_free(tls);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static int fixed_ssl_read_result_index;
+static int fixed_ssl_read_result[5];
+static int fixed_ssl_shutdown_result;
+
+static int
+fixed_ssl_read(SSL *s, void *buf, int len)
+{
+ (void)s;
+ (void)buf;
+ (void)len;
+ return fixed_ssl_read_result[fixed_ssl_read_result_index++];
+}
+
+static int
+fixed_ssl_shutdown(SSL *s)
+{
+ (void)s;
+ return fixed_ssl_shutdown_result;
+}
+
+#ifndef LIBRESSL_VERSION_NUMBER
+static int fixed_ssl_state_to_set;
+static tor_tls_t *fixed_tls;
+
+static int
+setting_version_ssl_shutdown(SSL *s)
+{
+ s->version = SSL2_VERSION;
+ return fixed_ssl_shutdown_result;
+}
+
+static int
+setting_version_and_state_ssl_shutdown(SSL *s)
+{
+ fixed_tls->state = fixed_ssl_state_to_set;
+ s->version = SSL2_VERSION;
+ return fixed_ssl_shutdown_result;
+}
+#endif
+
+static int
+dummy_handshake_func(SSL *s)
+{
+ (void)s;
+ return 1;
+}
+
+static void
+test_tortls_shutdown(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ SSL_METHOD *method = give_me_a_test_method();
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->ssl->method = method;
+ method->ssl_read = fixed_ssl_read;
+ method->ssl_shutdown = fixed_ssl_shutdown;
+
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, -9);
+
+ tls->state = TOR_TLS_ST_SENTCLOSE;
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = -1;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, -9);
+
+#ifndef LIBRESSL_VERSION_NUMBER
+ tls->ssl->handshake_func = dummy_handshake_func;
+
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = 42;
+ fixed_ssl_read_result[2] = 0;
+ fixed_ssl_shutdown_result = 1;
+ ERR_clear_error();
+ tls->ssl->version = SSL2_VERSION;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_DONE);
+ tt_int_op(tls->state, OP_EQ, TOR_TLS_ST_CLOSED);
+
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = 42;
+ fixed_ssl_read_result[2] = 0;
+ fixed_ssl_shutdown_result = 0;
+ ERR_clear_error();
+ tls->ssl->version = 0;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_DONE);
+ tt_int_op(tls->state, OP_EQ, TOR_TLS_ST_CLOSED);
+
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = 42;
+ fixed_ssl_read_result[2] = 0;
+ fixed_ssl_shutdown_result = 0;
+ ERR_clear_error();
+ tls->ssl->version = 0;
+ method->ssl_shutdown = setting_version_ssl_shutdown;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = 42;
+ fixed_ssl_read_result[2] = 0;
+ fixed_ssl_shutdown_result = 0;
+ fixed_tls = tls;
+ fixed_ssl_state_to_set = TOR_TLS_ST_GOTCLOSE;
+ ERR_clear_error();
+ tls->ssl->version = 0;
+ method->ssl_shutdown = setting_version_and_state_ssl_shutdown;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 10;
+ fixed_ssl_read_result[1] = 42;
+ fixed_ssl_read_result[2] = 0;
+ fixed_ssl_read_result[3] = -1;
+ fixed_ssl_shutdown_result = 0;
+ fixed_tls = tls;
+ fixed_ssl_state_to_set = 0;
+ ERR_clear_error();
+ tls->ssl->version = 0;
+ method->ssl_shutdown = setting_version_and_state_ssl_shutdown;
+ ret = tor_tls_shutdown(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+#endif
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ tor_free(method);
+ tor_free(tls->ssl);
+ tor_free(tls);
+}
+
+static int negotiated_callback_called;
+
+static void
+negotiated_callback_setter(tor_tls_t *t, void *arg)
+{
+ (void)t;
+ (void)arg;
+ negotiated_callback_called++;
+}
+
+static void
+test_tortls_read(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ char buf[100];
+ SSL_METHOD *method = give_me_a_test_method();
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->state = TOR_TLS_ST_OPEN;
+
+ ret = tor_tls_read(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, -9);
+
+ /* These tests assume that V2_HANDSHAKE_SERVER is set */
+ tls->ssl->handshake_func = dummy_handshake_func;
+ tls->ssl->method = method;
+ method->ssl_read = fixed_ssl_read;
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 42;
+ tls->state = TOR_TLS_ST_OPEN;
+ ERR_clear_error();
+ ret = tor_tls_read(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, 42);
+
+ tls->state = TOR_TLS_ST_OPEN;
+ tls->got_renegotiate = 1;
+ fixed_ssl_read_result_index = 0;
+ ERR_clear_error();
+ ret = tor_tls_read(tls, buf, 10);
+ tt_int_op(tls->got_renegotiate, OP_EQ, 0);
+
+ tls->state = TOR_TLS_ST_OPEN;
+ tls->got_renegotiate = 1;
+ negotiated_callback_called = 0;
+ tls->negotiated_callback = negotiated_callback_setter;
+ fixed_ssl_read_result_index = 0;
+ ERR_clear_error();
+ ret = tor_tls_read(tls, buf, 10);
+ tt_int_op(negotiated_callback_called, OP_EQ, 1);
+
+#ifndef LIBRESSL_VERSION_NUMBER
+ fixed_ssl_read_result_index = 0;
+ fixed_ssl_read_result[0] = 0;
+ tls->ssl->version = SSL2_VERSION;
+ ERR_clear_error();
+ ret = tor_tls_read(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, TOR_TLS_CLOSE);
+ tt_int_op(tls->state, OP_EQ, TOR_TLS_ST_CLOSED);
+#endif
+ // TODO: fill up
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ tor_free(method);
+}
+
+static int fixed_ssl_write_result;
+
+static int
+fixed_ssl_write(SSL *s, const void *buf, int len)
+{
+ (void)s;
+ (void)buf;
+ (void)len;
+ return fixed_ssl_write_result;
+}
+
+static void
+test_tortls_write(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ SSL_METHOD *method = give_me_a_test_method();
+ char buf[100];
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = tor_malloc_zero(sizeof(SSL));
+ tls->state = TOR_TLS_ST_OPEN;
+
+ ret = tor_tls_write(tls, buf, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ ret = tor_tls_write(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, -9);
+
+ tls->ssl->method = method;
+ tls->wantwrite_n = 1;
+ ret = tor_tls_write(tls, buf, 10);
+ tt_int_op(tls->wantwrite_n, OP_EQ, 0);
+
+ method->ssl_write = fixed_ssl_write;
+ tls->ssl->handshake_func = dummy_handshake_func;
+ fixed_ssl_write_result = 1;
+ ERR_clear_error();
+ ret = tor_tls_write(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, 1);
+
+ fixed_ssl_write_result = -1;
+ ERR_clear_error();
+ tls->ssl->rwstate = SSL_READING;
+ SSL_set_bio(tls->ssl, BIO_new(BIO_s_mem()), NULL);
+ SSL_get_rbio(tls->ssl)->flags = BIO_FLAGS_READ;
+ ret = tor_tls_write(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, TOR_TLS_WANTREAD);
+
+ ERR_clear_error();
+ tls->ssl->rwstate = SSL_READING;
+ SSL_set_bio(tls->ssl, BIO_new(BIO_s_mem()), NULL);
+ SSL_get_rbio(tls->ssl)->flags = BIO_FLAGS_WRITE;
+ ret = tor_tls_write(tls, buf, 10);
+ tt_int_op(ret, OP_EQ, TOR_TLS_WANTWRITE);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ BIO_free(tls->ssl->rbio);
+ tor_free(tls->ssl);
+ tor_free(tls);
+ tor_free(method);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static int fixed_ssl_accept_result;
+static int fixed_ssl_connect_result;
+
+static int
+setting_error_ssl_accept(SSL *ssl)
+{
+ (void)ssl;
+ ERR_put_error(ERR_LIB_BN, 2, -1, "somewhere.c", 99);
+ ERR_put_error(ERR_LIB_SYS, 2, -1, "somewhere.c", 99);
+ return fixed_ssl_accept_result;
+}
+
+static int
+setting_error_ssl_connect(SSL *ssl)
+{
+ (void)ssl;
+ ERR_put_error(ERR_LIB_BN, 2, -1, "somewhere.c", 99);
+ ERR_put_error(ERR_LIB_SYS, 2, -1, "somewhere.c", 99);
+ return fixed_ssl_connect_result;
+}
+
+static int
+fixed_ssl_accept(SSL *ssl)
+{
+ (void) ssl;
+ return fixed_ssl_accept_result;
+}
+
+static void
+test_tortls_handshake(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ SSL_CTX *ctx;
+ SSL_METHOD *method = give_me_a_test_method();
+ int previous_log = setup_capture_of_logs(LOG_INFO);
+
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ ctx = SSL_CTX_new(TLSv1_method());
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = SSL_new(ctx);
+ tls->state = TOR_TLS_ST_HANDSHAKE;
+
+ ret = tor_tls_handshake(tls);
+ tt_int_op(ret, OP_EQ, -9);
+
+ tls->isServer = 1;
+ tls->state = TOR_TLS_ST_HANDSHAKE;
+ ret = tor_tls_handshake(tls);
+ tt_int_op(ret, OP_EQ, -9);
+
+ tls->ssl->method = method;
+ method->ssl_accept = fixed_ssl_accept;
+ fixed_ssl_accept_result = 2;
+ ERR_clear_error();
+ tls->state = TOR_TLS_ST_HANDSHAKE;
+ ret = tor_tls_handshake(tls);
+ tt_int_op(tls->state, OP_EQ, TOR_TLS_ST_OPEN);
+
+ method->ssl_accept = setting_error_ssl_accept;
+ fixed_ssl_accept_result = 1;
+ ERR_clear_error();
+ mock_clean_saved_logs();
+ tls->state = TOR_TLS_ST_HANDSHAKE;
+ ret = tor_tls_handshake(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+ expect_log_entry();
+ /* This fails on jessie. Investigate why! */
+#if 0
+ expect_log_msg("TLS error while handshaking: (null) (in bignum routines:"
+ "(null):SSLv3 write client hello B)\n");
+ expect_log_msg("TLS error while handshaking: (null) (in system library:"
+ "connect:SSLv3 write client hello B)\n");
+#endif
+ expect_log_severity(LOG_INFO);
+
+ tls->isServer = 0;
+ method->ssl_connect = setting_error_ssl_connect;
+ fixed_ssl_connect_result = 1;
+ ERR_clear_error();
+ mock_clean_saved_logs();
+ tls->state = TOR_TLS_ST_HANDSHAKE;
+ ret = tor_tls_handshake(tls);
+ tt_int_op(ret, OP_EQ, TOR_TLS_ERROR_MISC);
+ expect_log_entry();
+#if 0
+ /* See above */
+ expect_log_msg("TLS error while handshaking: "
+ "(null) (in bignum routines:(null):SSLv3 write client hello B)\n");
+ expect_log_msg("TLS error while handshaking: "
+ "(null) (in system library:connect:SSLv3 write client hello B)\n");
+#endif
+ expect_log_severity(LOG_WARN);
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ SSL_free(tls->ssl);
+ SSL_CTX_free(ctx);
+ tor_free(tls);
+ tor_free(method);
+}
+#endif
+
+#ifndef OPENSSL_OPAQUE
+static void
+test_tortls_finish_handshake(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_t *tls;
+ SSL_CTX *ctx;
+ SSL_METHOD *method = give_me_a_test_method();
+ SSL_library_init();
+ SSL_load_error_strings();
+
+ X509 *c1 = read_cert_from(validCertString);
+ SESS_CERT_local *sess = NULL;
+
+ ctx = SSL_CTX_new(method);
+
+ tls = tor_malloc_zero(sizeof(tor_tls_t));
+ tls->ssl = SSL_new(ctx);
+ tls->state = TOR_TLS_ST_OPEN;
+
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+
+ tls->isServer = 1;
+ tls->wasV2Handshake = 0;
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tls->wasV2Handshake, OP_EQ, 1);
+
+ tls->wasV2Handshake = 1;
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tls->wasV2Handshake, OP_EQ, 1);
+
+ tls->wasV2Handshake = 1;
+ tls->ssl->session = SSL_SESSION_new();
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tls->wasV2Handshake, OP_EQ, 0);
+
+ tls->isServer = 0;
+
+ sess = tor_malloc_zero(sizeof(SESS_CERT_local));
+ tls->ssl->session->sess_cert = (void *)sess;
+ sess->cert_chain = sk_X509_new_null();
+ sk_X509_push(sess->cert_chain, c1);
+ tls->ssl->session->peer = c1;
+ tls->wasV2Handshake = 0;
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, 0);
+ tt_int_op(tls->wasV2Handshake, OP_EQ, 1);
+
+ method->num_ciphers = fake_num_ciphers;
+ ret = tor_tls_finish_handshake(tls);
+ tt_int_op(ret, OP_EQ, -9);
+
+ done:
+ if (sess)
+ sk_X509_free(sess->cert_chain);
+ if (tls->ssl && tls->ssl->session) {
+ tor_free(tls->ssl->session->sess_cert);
+ }
+ SSL_free(tls->ssl);
+ tor_free(tls);
+ SSL_CTX_free(ctx);
+ tor_free(method);
+}
+#endif
+
+static int fixed_crypto_pk_new_result_index;
+static crypto_pk_t *fixed_crypto_pk_new_result[5];
+
+static crypto_pk_t *
+fixed_crypto_pk_new(void)
+{
+ return fixed_crypto_pk_new_result[fixed_crypto_pk_new_result_index++];
+}
+
+#ifndef OPENSSL_OPAQUE
+static int fixed_crypto_pk_generate_key_with_bits_result_index;
+static int fixed_crypto_pk_generate_key_with_bits_result[5];
+static int fixed_tor_tls_create_certificate_result_index;
+static X509 *fixed_tor_tls_create_certificate_result[5];
+static int fixed_tor_x509_cert_new_result_index;
+static tor_x509_cert_t *fixed_tor_x509_cert_new_result[5];
+
+static int
+fixed_crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
+{
+ (void)env;
+ (void)bits;
+ return fixed_crypto_pk_generate_key_with_bits_result[
+ fixed_crypto_pk_generate_key_with_bits_result_index++];
+}
+
+static X509 *
+fixed_tor_tls_create_certificate(crypto_pk_t *rsa,
+ crypto_pk_t *rsa_sign,
+ const char *cname,
+ const char *cname_sign,
+ unsigned int cert_lifetime)
+{
+ (void)rsa;
+ (void)rsa_sign;
+ (void)cname;
+ (void)cname_sign;
+ (void)cert_lifetime;
+ return fixed_tor_tls_create_certificate_result[
+ fixed_tor_tls_create_certificate_result_index++];
+}
+
+static tor_x509_cert_t *
+fixed_tor_x509_cert_new(X509 *x509_cert)
+{
+ (void) x509_cert;
+ return fixed_tor_x509_cert_new_result[
+ fixed_tor_x509_cert_new_result_index++];
+}
+
+static void
+test_tortls_context_new(void *ignored)
+{
+ (void)ignored;
+ tor_tls_context_t *ret;
+ crypto_pk_t *pk1, *pk2, *pk3, *pk4, *pk5, *pk6, *pk7, *pk8, *pk9, *pk10,
+ *pk11, *pk12, *pk13, *pk14, *pk15, *pk16, *pk17, *pk18;
+
+ pk1 = crypto_pk_new();
+ pk2 = crypto_pk_new();
+ pk3 = crypto_pk_new();
+ pk4 = crypto_pk_new();
+ pk5 = crypto_pk_new();
+ pk6 = crypto_pk_new();
+ pk7 = crypto_pk_new();
+ pk8 = crypto_pk_new();
+ pk9 = crypto_pk_new();
+ pk10 = crypto_pk_new();
+ pk11 = crypto_pk_new();
+ pk12 = crypto_pk_new();
+ pk13 = crypto_pk_new();
+ pk14 = crypto_pk_new();
+ pk15 = crypto_pk_new();
+ pk16 = crypto_pk_new();
+ pk17 = crypto_pk_new();
+ pk18 = crypto_pk_new();
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = NULL;
+ MOCK(crypto_pk_new, fixed_crypto_pk_new);
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ MOCK(crypto_pk_generate_key_with_bits,
+ fixed_crypto_pk_generate_key_with_bits);
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk1;
+ fixed_crypto_pk_new_result[1] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result[0] = -1;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk2;
+ fixed_crypto_pk_new_result[1] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result[0] = 0;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk3;
+ fixed_crypto_pk_new_result[1] = pk4;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result[0] = 0;
+ fixed_crypto_pk_generate_key_with_bits_result[1] = -1;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ MOCK(tor_tls_create_certificate, fixed_tor_tls_create_certificate);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk5;
+ fixed_crypto_pk_new_result[1] = pk6;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_crypto_pk_generate_key_with_bits_result[1] = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = NULL;
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk7;
+ fixed_crypto_pk_new_result[1] = pk8;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = NULL;
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk9;
+ fixed_crypto_pk_new_result[1] = pk10;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = NULL;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ MOCK(tor_x509_cert_new, fixed_tor_x509_cert_new);
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk11;
+ fixed_crypto_pk_new_result[1] = pk12;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_x509_cert_new_result_index = 0;
+ fixed_tor_x509_cert_new_result[0] = NULL;
+ fixed_tor_x509_cert_new_result[1] = NULL;
+ fixed_tor_x509_cert_new_result[2] = NULL;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk13;
+ fixed_crypto_pk_new_result[1] = pk14;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_x509_cert_new_result_index = 0;
+ fixed_tor_x509_cert_new_result[0] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ fixed_tor_x509_cert_new_result[1] = NULL;
+ fixed_tor_x509_cert_new_result[2] = NULL;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk15;
+ fixed_crypto_pk_new_result[1] = pk16;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_x509_cert_new_result_index = 0;
+ fixed_tor_x509_cert_new_result[0] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ fixed_tor_x509_cert_new_result[1] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ fixed_tor_x509_cert_new_result[2] = NULL;
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = pk17;
+ fixed_crypto_pk_new_result[1] = pk18;
+ fixed_crypto_pk_new_result[2] = NULL;
+ fixed_crypto_pk_generate_key_with_bits_result_index = 0;
+ fixed_tor_tls_create_certificate_result_index = 0;
+ fixed_tor_tls_create_certificate_result[0] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[1] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_tls_create_certificate_result[2] = tor_malloc_zero(sizeof(X509));
+ fixed_tor_x509_cert_new_result_index = 0;
+ fixed_tor_x509_cert_new_result[0] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ fixed_tor_x509_cert_new_result[1] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ fixed_tor_x509_cert_new_result[2] = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ ret = tor_tls_context_new(NULL, 0, 0, 0);
+ tt_assert(!ret);
+
+ done:
+ UNMOCK(tor_x509_cert_new);
+ UNMOCK(tor_tls_create_certificate);
+ UNMOCK(crypto_pk_generate_key_with_bits);
+ UNMOCK(crypto_pk_new);
+}
+#endif
+
+static int fixed_crypto_pk_get_evp_pkey_result_index = 0;
+static EVP_PKEY *fixed_crypto_pk_get_evp_pkey_result[5];
+
+static EVP_PKEY *
+fixed_crypto_pk_get_evp_pkey_(crypto_pk_t *env, int private)
+{
+ (void) env;
+ (void) private;
+ return fixed_crypto_pk_get_evp_pkey_result[
+ fixed_crypto_pk_get_evp_pkey_result_index++];
+}
+
+static void
+test_tortls_create_certificate(void *ignored)
+{
+ (void)ignored;
+ X509 *ret;
+ crypto_pk_t *pk1, *pk2;
+
+ pk1 = crypto_pk_new();
+ pk2 = crypto_pk_new();
+
+ MOCK(crypto_pk_get_evp_pkey_, fixed_crypto_pk_get_evp_pkey_);
+ fixed_crypto_pk_get_evp_pkey_result_index = 0;
+ fixed_crypto_pk_get_evp_pkey_result[0] = NULL;
+ ret = tor_tls_create_certificate(pk1, pk2, "hello", "hello2", 1);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_get_evp_pkey_result_index = 0;
+ fixed_crypto_pk_get_evp_pkey_result[0] = EVP_PKEY_new();
+ fixed_crypto_pk_get_evp_pkey_result[1] = NULL;
+ ret = tor_tls_create_certificate(pk1, pk2, "hello", "hello2", 1);
+ tt_assert(!ret);
+
+ fixed_crypto_pk_get_evp_pkey_result_index = 0;
+ fixed_crypto_pk_get_evp_pkey_result[0] = EVP_PKEY_new();
+ fixed_crypto_pk_get_evp_pkey_result[1] = EVP_PKEY_new();
+ ret = tor_tls_create_certificate(pk1, pk2, "hello", "hello2", 1);
+ tt_assert(!ret);
+
+ done:
+ UNMOCK(crypto_pk_get_evp_pkey_);
+ crypto_pk_free(pk1);
+ crypto_pk_free(pk2);
+}
+
+static void
+test_tortls_cert_new(void *ignored)
+{
+ (void)ignored;
+ tor_x509_cert_t *ret;
+ X509 *cert = read_cert_from(validCertString);
+
+ ret = tor_x509_cert_new(NULL);
+ tt_assert(!ret);
+
+ ret = tor_x509_cert_new(cert);
+ tt_assert(ret);
+ tor_x509_cert_free(ret);
+ ret = NULL;
+
+#if 0
+ cert = read_cert_from(validCertString);
+ /* XXX this doesn't do what you think: it alters a copy of the pubkey. */
+ X509_get_pubkey(cert)->type = EVP_PKEY_DSA;
+ ret = tor_x509_cert_new(cert);
+ tt_assert(ret);
+#endif
+
+#ifndef OPENSSL_OPAQUE
+ cert = read_cert_from(validCertString);
+ X509_CINF_free(cert->cert_info);
+ cert->cert_info = NULL;
+ ret = tor_x509_cert_new(cert);
+ tt_assert(ret);
+#endif
+
+ done:
+ tor_x509_cert_free(ret);
+}
+
+static void
+test_tortls_cert_is_valid(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_x509_cert_t *cert = NULL, *scert = NULL;
+
+ scert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 0);
+ tor_free(scert);
+ tor_free(cert);
+
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 1);
+
+#ifndef OPENSSL_OPAQUE
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ ASN1_TIME_free(cert->cert->cert_info->validity->notAfter);
+ cert->cert->cert_info->validity->notAfter =
+ ASN1_TIME_set(NULL, time(NULL)-1000000);
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 0);
+
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ X509_PUBKEY_free(cert->cert->cert_info->key);
+ cert->cert->cert_info->key = NULL;
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 1);
+ tt_int_op(ret, OP_EQ, 0);
+#endif
+
+#if 0
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ /* This doesn't actually change the key in the cert. XXXXXX */
+ BN_one(EVP_PKEY_get1_RSA(X509_get_pubkey(cert->cert))->n);
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 1);
+ tt_int_op(ret, OP_EQ, 0);
+
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ /* This doesn't actually change the key in the cert. XXXXXX */
+ X509_get_pubkey(cert->cert)->type = EVP_PKEY_EC;
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 1);
+ tt_int_op(ret, OP_EQ, 0);
+
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ /* This doesn't actually change the key in the cert. XXXXXX */
+ X509_get_pubkey(cert->cert)->type = EVP_PKEY_EC;
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 1);
+
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+ cert = tor_x509_cert_new(read_cert_from(validCertString));
+ scert = tor_x509_cert_new(read_cert_from(caCertString));
+ /* This doesn't actually change the key in the cert. XXXXXX */
+ X509_get_pubkey(cert->cert)->type = EVP_PKEY_EC;
+ X509_get_pubkey(cert->cert)->ameth = NULL;
+ ret = tor_tls_cert_is_valid(LOG_WARN, cert, scert, 0);
+ tt_int_op(ret, OP_EQ, 0);
+#endif
+
+ done:
+ tor_x509_cert_free(cert);
+ tor_x509_cert_free(scert);
+}
+
+static void
+test_tortls_context_init_one(void *ignored)
+{
+ (void)ignored;
+ int ret;
+ tor_tls_context_t *old = NULL;
+
+ MOCK(crypto_pk_new, fixed_crypto_pk_new);
+
+ fixed_crypto_pk_new_result_index = 0;
+ fixed_crypto_pk_new_result[0] = NULL;
+ ret = tor_tls_context_init_one(&old, NULL, 0, 0, 0);
+ tt_int_op(ret, OP_EQ, -1);
+
+ done:
+ UNMOCK(crypto_pk_new);
+}
+
+#define LOCAL_TEST_CASE(name, flags) \
+ { #name, test_tortls_##name, (flags|TT_FORK), NULL, NULL }
+
+#ifdef OPENSSL_OPAQUE
+#define INTRUSIVE_TEST_CASE(name, flags) \
+ { #name, NULL, TT_SKIP, NULL, NULL }
+#else
+#define INTRUSIVE_TEST_CASE(name, flags) LOCAL_TEST_CASE(name, flags)
+#endif
+
+struct testcase_t tortls_tests[] = {
+ LOCAL_TEST_CASE(errno_to_tls_error, 0),
+ LOCAL_TEST_CASE(err_to_string, 0),
+ LOCAL_TEST_CASE(tor_tls_new, TT_FORK),
+ LOCAL_TEST_CASE(tor_tls_get_error, 0),
+ LOCAL_TEST_CASE(get_state_description, TT_FORK),
+ LOCAL_TEST_CASE(get_by_ssl, TT_FORK),
+ LOCAL_TEST_CASE(allocate_tor_tls_object_ex_data_index, TT_FORK),
+ LOCAL_TEST_CASE(log_one_error, TT_FORK),
+ INTRUSIVE_TEST_CASE(get_error, TT_FORK),
+ LOCAL_TEST_CASE(always_accept_verify_cb, 0),
+ INTRUSIVE_TEST_CASE(x509_cert_free, 0),
+ LOCAL_TEST_CASE(x509_cert_get_id_digests, 0),
+ INTRUSIVE_TEST_CASE(cert_matches_key, 0),
+ INTRUSIVE_TEST_CASE(cert_get_key, 0),
+ LOCAL_TEST_CASE(get_my_client_auth_key, TT_FORK),
+ LOCAL_TEST_CASE(get_my_certs, TT_FORK),
+ INTRUSIVE_TEST_CASE(get_ciphersuite_name, 0),
+ INTRUSIVE_TEST_CASE(classify_client_ciphers, 0),
+ LOCAL_TEST_CASE(client_is_using_v2_ciphers, 0),
+ INTRUSIVE_TEST_CASE(verify, 0),
+ INTRUSIVE_TEST_CASE(check_lifetime, 0),
+ INTRUSIVE_TEST_CASE(get_pending_bytes, 0),
+ LOCAL_TEST_CASE(get_forced_write_size, 0),
+ LOCAL_TEST_CASE(get_write_overhead_ratio, TT_FORK),
+ LOCAL_TEST_CASE(used_v1_handshake, TT_FORK),
+ LOCAL_TEST_CASE(get_num_server_handshakes, 0),
+ LOCAL_TEST_CASE(server_got_renegotiate, 0),
+ INTRUSIVE_TEST_CASE(SSL_SESSION_get_master_key, 0),
+ INTRUSIVE_TEST_CASE(get_tlssecrets, 0),
+ INTRUSIVE_TEST_CASE(get_buffer_sizes, 0),
+ LOCAL_TEST_CASE(evaluate_ecgroup_for_tls, 0),
+ INTRUSIVE_TEST_CASE(try_to_extract_certs_from_tls, 0),
+ INTRUSIVE_TEST_CASE(get_peer_cert, 0),
+ INTRUSIVE_TEST_CASE(peer_has_cert, 0),
+ INTRUSIVE_TEST_CASE(shutdown, 0),
+ INTRUSIVE_TEST_CASE(finish_handshake, 0),
+ INTRUSIVE_TEST_CASE(handshake, 0),
+ INTRUSIVE_TEST_CASE(write, 0),
+ INTRUSIVE_TEST_CASE(read, 0),
+ INTRUSIVE_TEST_CASE(server_info_callback, 0),
+ LOCAL_TEST_CASE(is_server, 0),
+ INTRUSIVE_TEST_CASE(assert_renegotiation_unblocked, 0),
+ INTRUSIVE_TEST_CASE(block_renegotiation, 0),
+ INTRUSIVE_TEST_CASE(unblock_renegotiation, 0),
+ INTRUSIVE_TEST_CASE(set_renegotiate_callback, 0),
+ LOCAL_TEST_CASE(set_logged_address, 0),
+ INTRUSIVE_TEST_CASE(find_cipher_by_id, 0),
+ INTRUSIVE_TEST_CASE(session_secret_cb, 0),
+ INTRUSIVE_TEST_CASE(debug_state_callback, 0),
+ INTRUSIVE_TEST_CASE(context_new, 0),
+ LOCAL_TEST_CASE(create_certificate, 0),
+ LOCAL_TEST_CASE(cert_new, 0),
+ LOCAL_TEST_CASE(cert_is_valid, 0),
+ LOCAL_TEST_CASE(context_init_one, 0),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_util.c b/src/test/test_util.c
index 225fb790f9..d534cc0b52 100644
--- a/src/test/test_util.c
+++ b/src/test/test_util.c
@@ -1,27 +1,34 @@
/* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2013, The Tor Project, Inc. */
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "orconfig.h"
#define COMPAT_PRIVATE
#define CONTROL_PRIVATE
-#define MEMPOOL_PRIVATE
#define UTIL_PRIVATE
#include "or.h"
#include "config.h"
#include "control.h"
#include "test.h"
-#ifdef ENABLE_MEMPOOLS
-#include "mempool.h"
-#endif /* ENABLE_MEMPOOLS */
#include "memarea.h"
#include "util_process.h"
+#ifdef HAVE_PWD_H
+#include <pwd.h>
+#endif
+#ifdef HAVE_SYS_UTIME_H
+#include <sys/utime.h>
+#endif
+#ifdef HAVE_UTIME_H
+#include <utime.h>
+#endif
#ifdef _WIN32
#include <tchar.h>
#endif
#include <math.h>
+#include <ctype.h>
+#include <float.h>
/* XXXX this is a minimal wrapper to make the unit tests compile with the
* changed tor_timegm interface. */
@@ -52,20 +59,20 @@ test_util_read_until_eof_impl(const char *fname, size_t file_len,
crypto_rand(test_str, file_len);
r = write_bytes_to_file(fifo_name, test_str, file_len, 1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
fd = open(fifo_name, O_RDONLY|O_BINARY);
- tt_int_op(fd, >=, 0);
+ tt_int_op(fd, OP_GE, 0);
str = read_file_to_str_until_eof(fd, read_limit, &sz);
tt_assert(str != NULL);
if (read_limit < file_len)
- tt_int_op(sz, ==, read_limit);
+ tt_int_op(sz, OP_EQ, read_limit);
else
- tt_int_op(sz, ==, file_len);
+ tt_int_op(sz, OP_EQ, file_len);
- test_mem_op(test_str, ==, str, sz);
- test_assert(str[sz] == '\0');
+ tt_mem_op(test_str, OP_EQ, str, sz);
+ tt_int_op(str[sz], OP_EQ, '\0');
done:
unlink(fifo_name);
@@ -87,6 +94,20 @@ test_util_read_file_eof_tiny_limit(void *arg)
}
static void
+test_util_read_file_eof_one_loop_a(void *arg)
+{
+ (void)arg;
+ test_util_read_until_eof_impl("tor_test_fifo_1ka", 1024, 1023);
+}
+
+static void
+test_util_read_file_eof_one_loop_b(void *arg)
+{
+ (void)arg;
+ test_util_read_until_eof_impl("tor_test_fifo_1kb", 1024, 1024);
+}
+
+static void
test_util_read_file_eof_two_loops(void *arg)
{
(void)arg;
@@ -98,6 +119,14 @@ test_util_read_file_eof_two_loops(void *arg)
}
static void
+test_util_read_file_eof_two_loops_b(void *arg)
+{
+ (void)arg;
+
+ test_util_read_until_eof_impl("tor_test_fifo_2kb", 2048, 2048);
+}
+
+static void
test_util_read_file_eof_zero_bytes(void *arg)
{
(void)arg;
@@ -145,17 +174,17 @@ test_util_write_chunks_to_file(void *arg)
// write a known string to a file where the tempfile will be
r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
// call write_chunks_to_file
r = write_chunks_to_file(fname, chunks, 1, 0);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
// assert the file has been written (expected size)
str = read_file_to_str(fname, RFTS_BIN, &st);
tt_assert(str != NULL);
- tt_u64_op((uint64_t)st.st_size, ==, data_str_len);
- test_mem_op(data_str, ==, str, data_str_len);
+ tt_u64_op((uint64_t)st.st_size, OP_EQ, data_str_len);
+ tt_mem_op(data_str, OP_EQ, str, data_str_len);
tor_free(str);
// assert that the tempfile is removed (should not leave artifacts)
@@ -164,7 +193,7 @@ test_util_write_chunks_to_file(void *arg)
// Remove old testfile for second test
r = unlink(fname);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
tor_free(fname);
tor_free(tempname);
@@ -176,24 +205,24 @@ test_util_write_chunks_to_file(void *arg)
// write a known string to a file where the tempfile will be
r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
// call write_chunks_to_file with no_tempfile = true
r = write_chunks_to_file(fname, chunks, 1, 1);
- tt_int_op(r, ==, 0);
+ tt_int_op(r, OP_EQ, 0);
// assert the file has been written (expected size)
str = read_file_to_str(fname, RFTS_BIN, &st);
tt_assert(str != NULL);
- tt_u64_op((uint64_t)st.st_size, ==, data_str_len);
- test_mem_op(data_str, ==, str, data_str_len);
+ tt_u64_op((uint64_t)st.st_size, OP_EQ, data_str_len);
+ tt_mem_op(data_str, OP_EQ, str, data_str_len);
tor_free(str);
// assert the tempfile still contains the known string
str = read_file_to_str(tempname, RFTS_BIN, &st);
tt_assert(str != NULL);
- tt_u64_op((uint64_t)st.st_size, ==, temp_str_len);
- test_mem_op(temp_str, ==, str, temp_str_len);
+ tt_u64_op((uint64_t)st.st_size, OP_EQ, temp_str_len);
+ tt_mem_op(temp_str, OP_EQ, str, temp_str_len);
done:
unlink(fname);
@@ -206,11 +235,24 @@ test_util_write_chunks_to_file(void *arg)
tor_free(temp_str);
}
+#define _TFE(a, b, f) tt_int_op((a).f, OP_EQ, (b).f)
+/** test the minimum set of struct tm fields needed for a unique epoch value
+ * this is also the set we use to test tor_timegm */
+#define TM_EQUAL(a, b) \
+ TT_STMT_BEGIN \
+ _TFE(a, b, tm_year); \
+ _TFE(a, b, tm_mon ); \
+ _TFE(a, b, tm_mday); \
+ _TFE(a, b, tm_hour); \
+ _TFE(a, b, tm_min ); \
+ _TFE(a, b, tm_sec ); \
+ TT_STMT_END
+
static void
-test_util_time(void)
+test_util_time(void *arg)
{
struct timeval start, end;
- struct tm a_time;
+ struct tm a_time, b_time;
char timestr[128];
time_t t_res;
int i;
@@ -218,117 +260,423 @@ test_util_time(void)
/* Test tv_udiff */
+ (void)arg;
start.tv_sec = 5;
start.tv_usec = 5000;
end.tv_sec = 5;
end.tv_usec = 5000;
- test_eq(0L, tv_udiff(&start, &end));
+ tt_int_op(0L,OP_EQ, tv_udiff(&start, &end));
end.tv_usec = 7000;
- test_eq(2000L, tv_udiff(&start, &end));
+ tt_int_op(2000L,OP_EQ, tv_udiff(&start, &end));
end.tv_sec = 6;
- test_eq(1002000L, tv_udiff(&start, &end));
+ tt_int_op(1002000L,OP_EQ, tv_udiff(&start, &end));
end.tv_usec = 0;
- test_eq(995000L, tv_udiff(&start, &end));
+ tt_int_op(995000L,OP_EQ, tv_udiff(&start, &end));
end.tv_sec = 4;
- test_eq(-1005000L, tv_udiff(&start, &end));
+ tt_int_op(-1005000L,OP_EQ, tv_udiff(&start, &end));
- /* Test tor_timegm */
+ /* Test tor_timegm & tor_gmtime_r */
/* The test values here are confirmed to be correct on a platform
- * with a working timegm. */
+ * with a working timegm & gmtime_r. */
+
+ /* Start with known-zero a_time and b_time.
+ * This avoids passing uninitialised values to TM_EQUAL in a_time.
+ * Zeroing may not be needed for b_time, as long as tor_gmtime_r
+ * never reads the existing values in the structure.
+ * But we really don't want intermittently failing tests. */
+ memset(&a_time, 0, sizeof(struct tm));
+ memset(&b_time, 0, sizeof(struct tm));
+
a_time.tm_year = 2003-1900;
a_time.tm_mon = 7;
a_time.tm_mday = 30;
a_time.tm_hour = 6;
a_time.tm_min = 14;
a_time.tm_sec = 55;
- test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
+ t_res = 1062224095UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+
a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
- test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
+ t_res = 1093846495UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+
a_time.tm_mon = 1; /* Try a leap year, in feb. */
a_time.tm_mday = 10;
- test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
+ t_res = 1076393695UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+
a_time.tm_mon = 0;
- a_time.tm_mday = 10;
- test_eq((time_t) 1073715295UL, tor_timegm(&a_time));
+ t_res = 1073715295UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+
+ /* This value is in range with 32 bit and 64 bit time_t */
+ a_time.tm_year = 2037-1900;
+ t_res = 2115180895UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+
+ /* This value is out of range with 32 bit time_t, but in range for 64 bit
+ * time_t */
+ a_time.tm_year = 2039-1900;
+#if SIZEOF_TIME_T == 4
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+#elif SIZEOF_TIME_T == 8
+ t_res = 2178252895UL;
+ tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
+ tor_gmtime_r(&t_res, &b_time);
+ TM_EQUAL(a_time, b_time);
+#endif
+
+ /* Test tor_timegm out of range */
+
+ /* year */
+
+ /* Wrong year < 1970 */
+ a_time.tm_year = 1969-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = -1-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+#if SIZEOF_INT == 4 || SIZEOF_INT == 8
+ a_time.tm_year = -1*(1 << 16);
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* one of the smallest tm_year values my 64 bit system supports:
+ * t_res = -9223372036854775LL without clamping */
+ a_time.tm_year = -292275055-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = INT32_MIN;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+#endif
+
+#if SIZEOF_INT == 8
+ a_time.tm_year = -1*(1 << 48);
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* while unlikely, the system's gmtime(_r) could return
+ * a "correct" retrospective gregorian negative year value,
+ * which I'm pretty sure is:
+ * -1*(2^63)/60/60/24*2000/730485 + 1970 = -292277022657
+ * 730485 is the number of days in two millenia, including leap days */
+ a_time.tm_year = -292277022657-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = INT64_MIN;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+#endif
+
+ /* Wrong year >= INT32_MAX - 1900 */
+#if SIZEOF_INT == 4 || SIZEOF_INT == 8
+ a_time.tm_year = INT32_MAX-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = INT32_MAX;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+#endif
+
+#if SIZEOF_INT == 8
+ /* one of the largest tm_year values my 64 bit system supports */
+ a_time.tm_year = 292278994-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* while unlikely, the system's gmtime(_r) could return
+ * a "correct" proleptic gregorian year value,
+ * which I'm pretty sure is:
+ * (2^63-1)/60/60/24*2000/730485 + 1970 = 292277026596
+ * 730485 is the number of days in two millenia, including leap days */
+ a_time.tm_year = 292277026596-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = INT64_MAX-1900;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = INT64_MAX;
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+#endif
+
+ /* month */
+ a_time.tm_year = 2007-1900; /* restore valid year */
+
a_time.tm_mon = 12; /* Wrong month, it's 0-based */
- a_time.tm_mday = 10;
- test_eq((time_t) -1, tor_timegm(&a_time));
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
a_time.tm_mon = -1; /* Wrong month */
- a_time.tm_mday = 10;
- test_eq((time_t) -1, tor_timegm(&a_time));
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* day */
+ a_time.tm_mon = 6; /* Try July */
+ a_time.tm_mday = 32; /* Wrong day */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_mon = 5; /* Try June */
+ a_time.tm_mday = 31; /* Wrong day */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = 2008-1900; /* Try a leap year */
+ a_time.tm_mon = 1; /* in feb. */
+ a_time.tm_mday = 30; /* Wrong day */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_year = 2011-1900; /* Try a non-leap year */
+ a_time.tm_mon = 1; /* in feb. */
+ a_time.tm_mday = 29; /* Wrong day */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_mday = 0; /* Wrong day, it's 1-based (to be different) */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* hour */
+ a_time.tm_mday = 3; /* restore valid month day */
+
+ a_time.tm_hour = 24; /* Wrong hour, it's 0-based */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_hour = -1; /* Wrong hour */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* minute */
+ a_time.tm_hour = 22; /* restore valid hour */
+
+ a_time.tm_min = 60; /* Wrong minute, it's 0-based */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_min = -1; /* Wrong minute */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* second */
+ a_time.tm_min = 37; /* restore valid minute */
+
+ a_time.tm_sec = 61; /* Wrong second: 0-based with leap seconds */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ a_time.tm_sec = -1; /* Wrong second */
+ tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
+
+ /* Test tor_gmtime_r out of range */
+
+ /* time_t < 0 yields a year clamped to 1 or 1970,
+ * depending on whether the implementation of the system gmtime(_r)
+ * sets struct tm (1) or not (1970) */
+ t_res = -1;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (1970-1900) ||
+ b_time.tm_year == (1969-1900));
+
+ if (sizeof(time_t) == 4 || sizeof(time_t) == 8) {
+ t_res = -1*(1 << 30);
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (1970-1900) ||
+ b_time.tm_year == (1935-1900));
+
+ t_res = INT32_MIN;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (1970-1900) ||
+ b_time.tm_year == (1901-1900));
+ }
+
+#if SIZEOF_TIME_T == 8
+ {
+ /* one of the smallest tm_year values my 64 bit system supports:
+ * b_time.tm_year == (-292275055LL-1900LL) without clamping */
+ t_res = -9223372036854775LL;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (1970-1900) ||
+ b_time.tm_year == (1-1900));
+
+ /* while unlikely, the system's gmtime(_r) could return
+ * a "correct" retrospective gregorian negative year value,
+ * which I'm pretty sure is:
+ * -1*(2^63)/60/60/24*2000/730485 + 1970 = -292277022657
+ * 730485 is the number of days in two millenia, including leap days
+ * (int64_t)b_time.tm_year == (-292277022657LL-1900LL) without clamping */
+ t_res = INT64_MIN;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (1970-1900) ||
+ b_time.tm_year == (1-1900));
+ }
+#endif
+
+ /* time_t >= INT_MAX yields a year clamped to 2037 or 9999,
+ * depending on whether the implementation of the system gmtime(_r)
+ * sets struct tm (9999) or not (2037) */
+#if SIZEOF_TIME_T == 4 || SIZEOF_TIME_T == 8
+ {
+ t_res = 3*(1 << 29);
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (2021-1900));
+
+ t_res = INT32_MAX;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (2037-1900) ||
+ b_time.tm_year == (2038-1900));
+ }
+#endif
+
+#if SIZEOF_TIME_T == 8
+ {
+ /* one of the largest tm_year values my 64 bit system supports:
+ * b_time.tm_year == (292278994L-1900L) without clamping */
+ t_res = 9223372036854775LL;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (2037-1900) ||
+ b_time.tm_year == (9999-1900));
+
+ /* while unlikely, the system's gmtime(_r) could return
+ * a "correct" proleptic gregorian year value,
+ * which I'm pretty sure is:
+ * (2^63-1)/60/60/24*2000/730485 + 1970 = 292277026596
+ * 730485 is the number of days in two millenia, including leap days
+ * (int64_t)b_time.tm_year == (292277026596L-1900L) without clamping */
+ t_res = INT64_MAX;
+ tor_gmtime_r(&t_res, &b_time);
+ tt_assert(b_time.tm_year == (2037-1900) ||
+ b_time.tm_year == (9999-1900));
+ }
+#endif
/* Test {format,parse}_rfc1123_time */
format_rfc1123_time(timestr, 0);
- test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
+ tt_str_op("Thu, 01 Jan 1970 00:00:00 GMT",OP_EQ, timestr);
format_rfc1123_time(timestr, (time_t)1091580502UL);
- test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
+ tt_str_op("Wed, 04 Aug 2004 00:48:22 GMT",OP_EQ, timestr);
t_res = 0;
i = parse_rfc1123_time(timestr, &t_res);
- test_eq(0,i);
- test_eq(t_res, (time_t)1091580502UL);
- /* The timezone doesn't matter */
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
+
+ /* This value is in range with 32 bit and 64 bit time_t */
+ format_rfc1123_time(timestr, (time_t)2080000000UL);
+ tt_str_op("Fri, 30 Nov 2035 01:46:40 GMT",OP_EQ, timestr);
+
t_res = 0;
- test_eq(0, parse_rfc1123_time("Wed, 04 Aug 2004 00:48:22 ZUL", &t_res));
- test_eq(t_res, (time_t)1091580502UL);
- test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 32 Mar 2011 00:00:00 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 24:00:00 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:60:00 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:62 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 1969 23:59:59 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Ene 2011 23:59:59 GMT", &t_res));
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:59 GM", &t_res));
+ i = parse_rfc1123_time(timestr, &t_res);
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)2080000000UL);
+ /* This value is out of range with 32 bit time_t, but in range for 64 bit
+ * time_t */
+ format_rfc1123_time(timestr, (time_t)2150000000UL);
+#if SIZEOF_TIME_T == 4
#if 0
- /* This fails, I imagine it's important and should be fixed? */
- test_eq(-1, parse_rfc1123_time("Wed, 29 Feb 2011 16:00:00 GMT", &t_res));
- /* Why is this string valid (ie. the test fails because it doesn't
- return -1)? */
- test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:61 GMT", &t_res));
+ /* Wrapping around will have made it this. */
+ /* On windows, at least, this is clipped to 1 Jan 1970. ??? */
+ tt_str_op("Sat, 11 Jan 1902 23:45:04 GMT",OP_EQ, timestr);
#endif
+ /* Make sure that the right date doesn't parse. */
+ strlcpy(timestr, "Wed, 17 Feb 2038 06:13:20 GMT", sizeof(timestr));
+
+ t_res = 0;
+ i = parse_rfc1123_time(timestr, &t_res);
+ tt_int_op(-1,OP_EQ, i);
+#elif SIZEOF_TIME_T == 8
+ tt_str_op("Wed, 17 Feb 2038 06:13:20 GMT",OP_EQ, timestr);
+
+ t_res = 0;
+ i = parse_rfc1123_time(timestr, &t_res);
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)2150000000UL);
+#endif
+
+ /* The timezone doesn't matter */
+ t_res = 0;
+ tt_int_op(0,OP_EQ,
+ parse_rfc1123_time("Wed, 04 Aug 2004 00:48:22 ZUL", &t_res));
+ tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 32 Mar 2011 00:00:00 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 2011 24:00:00 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 2011 23:60:00 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 2011 23:59:62 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 1969 23:59:59 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Ene 2011 23:59:59 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 2011 23:59:59 GM", &t_res));
+
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 29 Feb 2011 16:00:00 GMT", &t_res));
+ tt_int_op(-1,OP_EQ,
+ parse_rfc1123_time("Wed, 30 Mar 2011 23:59:61 GMT", &t_res));
/* Test parse_iso_time */
t_res = 0;
i = parse_iso_time("", &t_res);
- test_eq(-1, i);
+ tt_int_op(-1,OP_EQ, i);
t_res = 0;
i = parse_iso_time("2004-08-32 00:48:22", &t_res);
- test_eq(-1, i);
+ tt_int_op(-1,OP_EQ, i);
t_res = 0;
i = parse_iso_time("1969-08-03 00:48:22", &t_res);
- test_eq(-1, i);
+ tt_int_op(-1,OP_EQ, i);
t_res = 0;
i = parse_iso_time("2004-08-04 00:48:22", &t_res);
- test_eq(0,i);
- test_eq(t_res, (time_t)1091580502UL);
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
t_res = 0;
i = parse_iso_time("2004-8-4 0:48:22", &t_res);
- test_eq(0, i);
- test_eq(t_res, (time_t)1091580502UL);
- test_eq(-1, parse_iso_time("2004-08-zz 99-99x99 GMT", &t_res));
- test_eq(-1, parse_iso_time("2011-03-32 00:00:00 GMT", &t_res));
- test_eq(-1, parse_iso_time("2011-03-30 24:00:00 GMT", &t_res));
- test_eq(-1, parse_iso_time("2011-03-30 23:60:00 GMT", &t_res));
- test_eq(-1, parse_iso_time("2011-03-30 23:59:62 GMT", &t_res));
- test_eq(-1, parse_iso_time("1969-03-30 23:59:59 GMT", &t_res));
- test_eq(-1, parse_iso_time("2011-00-30 23:59:59 GMT", &t_res));
- test_eq(-1, parse_iso_time("2147483647-08-29 14:00:00", &t_res));
- test_eq(-1, parse_iso_time("2011-03-30 23:59", &t_res));
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
+
+ /* This value is in range with 32 bit and 64 bit time_t */
+ t_res = 0;
+ i = parse_iso_time("2035-11-30 01:46:40", &t_res);
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)2080000000UL);
+
+ /* This value is out of range with 32 bit time_t, but in range for 64 bit
+ * time_t */
+ t_res = 0;
+ i = parse_iso_time("2038-02-17 06:13:20", &t_res);
+#if SIZEOF_TIME_T == 4
+ tt_int_op(-1,OP_EQ, i);
+#elif SIZEOF_TIME_T == 8
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(t_res,OP_EQ, (time_t)2150000000UL);
+#endif
+
+ tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-zz 99-99x99", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-32 00:00:00", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 24:00:00", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:60:00", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:59:62", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("1969-03-30 23:59:59", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-00-30 23:59:59", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2147483647-08-29 14:00:00", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:59", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04 00:48:22.100", &t_res));
+ tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04 00:48:22XYZ", &t_res));
/* Test tor_gettimeofday */
@@ -341,14 +689,14 @@ test_util_time(void)
/* now make sure time works. */
tor_gettimeofday(&end);
/* We might've timewarped a little. */
- tt_int_op(tv_udiff(&start, &end), >=, -5000);
+ tt_int_op(tv_udiff(&start, &end), OP_GE, -5000);
/* Test format_iso_time */
- tv.tv_sec = (time_t)1326296338;
+ tv.tv_sec = (time_t)1326296338UL;
tv.tv_usec = 3060;
format_iso_time(timestr, (time_t)tv.tv_sec);
- test_streq("2012-01-11 15:38:58", timestr);
+ tt_str_op("2012-01-11 15:38:58",OP_EQ, timestr);
/* The output of format_local_iso_time will vary by timezone, and setting
our timezone for testing purposes would be a nontrivial flaky pain.
Skip this test for now.
@@ -356,11 +704,33 @@ test_util_time(void)
test_streq("2012-01-11 10:38:58", timestr);
*/
format_iso_time_nospace(timestr, (time_t)tv.tv_sec);
- test_streq("2012-01-11T15:38:58", timestr);
- test_eq(strlen(timestr), ISO_TIME_LEN);
+ tt_str_op("2012-01-11T15:38:58",OP_EQ, timestr);
+ tt_int_op(strlen(timestr),OP_EQ, ISO_TIME_LEN);
format_iso_time_nospace_usec(timestr, &tv);
- test_streq("2012-01-11T15:38:58.003060", timestr);
- test_eq(strlen(timestr), ISO_TIME_USEC_LEN);
+ tt_str_op("2012-01-11T15:38:58.003060",OP_EQ, timestr);
+ tt_int_op(strlen(timestr),OP_EQ, ISO_TIME_USEC_LEN);
+
+ tv.tv_usec = 0;
+ /* This value is in range with 32 bit and 64 bit time_t */
+ tv.tv_sec = (time_t)2080000000UL;
+ format_iso_time(timestr, (time_t)tv.tv_sec);
+ tt_str_op("2035-11-30 01:46:40",OP_EQ, timestr);
+
+ /* This value is out of range with 32 bit time_t, but in range for 64 bit
+ * time_t */
+ tv.tv_sec = (time_t)2150000000UL;
+ format_iso_time(timestr, (time_t)tv.tv_sec);
+#if SIZEOF_TIME_T == 4
+ /* format_iso_time should indicate failure on overflow, but it doesn't yet.
+ * Hopefully #18480 will improve the failure semantics in this case.
+ tt_str_op("2038-02-17 06:13:20",OP_EQ, timestr);
+ */
+#elif SIZEOF_TIME_T == 8
+#ifndef _WIN32
+ /* This SHOULD work on windows too; see bug #18665 */
+ tt_str_op("2038-02-17 06:13:20",OP_EQ, timestr);
+#endif
+#endif
done:
;
@@ -375,61 +745,93 @@ test_util_parse_http_time(void *arg)
#define T(s) do { \
format_iso_time(b, tor_timegm(&a_time)); \
- tt_str_op(b, ==, (s)); \
+ tt_str_op(b, OP_EQ, (s)); \
b[0]='\0'; \
} while (0)
/* Test parse_http_time */
- test_eq(-1, parse_http_time("", &a_time));
- test_eq(-1, parse_http_time("Sunday, 32 Aug 2004 00:48:22 GMT", &a_time));
- test_eq(-1, parse_http_time("Sunday, 3 Aug 1869 00:48:22 GMT", &a_time));
- test_eq(-1, parse_http_time("Sunday, 32-Aug-94 00:48:22 GMT", &a_time));
- test_eq(-1, parse_http_time("Sunday, 3-Ago-04 00:48:22", &a_time));
- test_eq(-1, parse_http_time("Sunday, August the third", &a_time));
- test_eq(-1, parse_http_time("Wednesday,,04 Aug 1994 00:48:22 GMT", &a_time));
-
- test_eq(0, parse_http_time("Wednesday, 04 Aug 1994 00:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Sunday, 32 Aug 2004 00:48:22 GMT", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Sunday, 3 Aug 1869 00:48:22 GMT", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Sunday, 32-Aug-94 00:48:22 GMT", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Sunday, 3-Ago-04 00:48:22", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Sunday, August the third", &a_time));
+ tt_int_op(-1,OP_EQ,
+ parse_http_time("Wednesday,,04 Aug 1994 00:48:22 GMT", &a_time));
+
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Wednesday, 04 Aug 1994 00:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Wednesday, 4 Aug 1994 0:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Wednesday, 4 Aug 1994 0:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Miercoles, 4 Aug 1994 0:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Miercoles, 4 Aug 1994 0:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Wednesday, 04-Aug-94 00:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Wednesday, 04-Aug-94 00:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Wednesday, 4-Aug-94 0:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Wednesday, 4-Aug-94 0:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Miercoles, 4-Aug-94 0:48:22 GMT", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,
+ parse_http_time("Miercoles, 4-Aug-94 0:48:22 GMT", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Wed Aug 04 00:48:22 1994", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ, parse_http_time("Wed Aug 04 00:48:22 1994", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Wed Aug 4 0:48:22 1994", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ, parse_http_time("Wed Aug 4 0:48:22 1994", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Mie Aug 4 0:48:22 1994", &a_time));
- test_eq((time_t)775961302UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ, parse_http_time("Mie Aug 4 0:48:22 1994", &a_time));
+ tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
T("1994-08-04 00:48:22");
- test_eq(0, parse_http_time("Sun, 1 Jan 2012 00:00:00 GMT", &a_time));
- test_eq((time_t)1325376000UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,parse_http_time("Sun, 1 Jan 2012 00:00:00 GMT", &a_time));
+ tt_int_op((time_t)1325376000UL,OP_EQ, tor_timegm(&a_time));
T("2012-01-01 00:00:00");
- test_eq(0, parse_http_time("Mon, 31 Dec 2012 00:00:00 GMT", &a_time));
- test_eq((time_t)1356912000UL, tor_timegm(&a_time));
+ tt_int_op(0,OP_EQ,parse_http_time("Mon, 31 Dec 2012 00:00:00 GMT", &a_time));
+ tt_int_op((time_t)1356912000UL,OP_EQ, tor_timegm(&a_time));
T("2012-12-31 00:00:00");
- test_eq(-1, parse_http_time("2004-08-zz 99-99x99 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-03-32 00:00:00 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-03-30 24:00:00 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-03-30 23:60:00 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-03-30 23:59:62 GMT", &a_time));
- test_eq(-1, parse_http_time("1969-03-30 23:59:59 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-00-30 23:59:59 GMT", &a_time));
- test_eq(-1, parse_http_time("2011-03-30 23:59", &a_time));
+
+ /* This value is in range with 32 bit and 64 bit time_t */
+ tt_int_op(0,OP_EQ,parse_http_time("Fri, 30 Nov 2035 01:46:40 GMT", &a_time));
+ tt_int_op((time_t)2080000000UL,OP_EQ, tor_timegm(&a_time));
+ T("2035-11-30 01:46:40");
+
+ /* This value is out of range with 32 bit time_t, but in range for 64 bit
+ * time_t */
+#if SIZEOF_TIME_T == 4
+ /* parse_http_time should indicate failure on overflow, but it doesn't yet.
+ * Hopefully #18480 will improve the failure semantics in this case. */
+ tt_int_op(0,OP_EQ,parse_http_time("Wed, 17 Feb 2038 06:13:20 GMT", &a_time));
+ tt_int_op((time_t)-1,OP_EQ, tor_timegm(&a_time));
+#elif SIZEOF_TIME_T == 8
+ tt_int_op(0,OP_EQ,parse_http_time("Wed, 17 Feb 2038 06:13:20 GMT", &a_time));
+ tt_int_op((time_t)2150000000UL,OP_EQ, tor_timegm(&a_time));
+ T("2038-02-17 06:13:20");
+#endif
+
+ tt_int_op(-1,OP_EQ, parse_http_time("2004-08-zz 99-99x99 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-03-32 00:00:00 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 24:00:00 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:60:00 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:59:62 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("1969-03-30 23:59:59 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-00-30 23:59:59 GMT", &a_time));
+ tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:59", &a_time));
#undef T
done:
@@ -437,13 +839,14 @@ test_util_parse_http_time(void *arg)
}
static void
-test_util_config_line(void)
+test_util_config_line(void *arg)
{
char buf[1024];
char *k=NULL, *v=NULL;
const char *str;
/* Test parse_config_line_from_str */
+ (void)arg;
strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
"k2\n"
"k3 \n" "\n" " \n" "#comment\n"
@@ -463,110 +866,110 @@ test_util_config_line(void)
str = buf;
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k");
- test_streq(v, "v");
+ tt_str_op(k,OP_EQ, "k");
+ tt_str_op(v,OP_EQ, "v");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "key value with"));
+ tt_assert(!strcmpstart(str, "key value with"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "key");
- test_streq(v, "value with spaces");
+ tt_str_op(k,OP_EQ, "key");
+ tt_str_op(v,OP_EQ, "value with spaces");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "keykey"));
+ tt_assert(!strcmpstart(str, "keykey"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "keykey");
- test_streq(v, "val");
+ tt_str_op(k,OP_EQ, "keykey");
+ tt_str_op(v,OP_EQ, "val");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "k2\n"));
+ tt_assert(!strcmpstart(str, "k2\n"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k2");
- test_streq(v, "");
+ tt_str_op(k,OP_EQ, "k2");
+ tt_str_op(v,OP_EQ, "");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "k3 \n"));
+ tt_assert(!strcmpstart(str, "k3 \n"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k3");
- test_streq(v, "");
+ tt_str_op(k,OP_EQ, "k3");
+ tt_str_op(v,OP_EQ, "");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "#comment"));
+ tt_assert(!strcmpstart(str, "#comment"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k4");
- test_streq(v, "");
+ tt_str_op(k,OP_EQ, "k4");
+ tt_str_op(v,OP_EQ, "");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "k5#abc"));
+ tt_assert(!strcmpstart(str, "k5#abc"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k5");
- test_streq(v, "");
+ tt_str_op(k,OP_EQ, "k5");
+ tt_str_op(v,OP_EQ, "");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "k6"));
+ tt_assert(!strcmpstart(str, "k6"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k6");
- test_streq(v, "val");
+ tt_str_op(k,OP_EQ, "k6");
+ tt_str_op(v,OP_EQ, "val");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "kseven"));
+ tt_assert(!strcmpstart(str, "kseven"));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "kseven");
- test_streq(v, "a quoted \'string");
+ tt_str_op(k,OP_EQ, "kseven");
+ tt_str_op(v,OP_EQ, "a quoted \'string");
tor_free(k); tor_free(v);
- test_assert(!strcmpstart(str, "k8 "));
+ tt_assert(!strcmpstart(str, "k8 "));
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k8");
- test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
+ tt_str_op(k,OP_EQ, "k8");
+ tt_str_op(v,OP_EQ, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k9");
- test_streq(v, "a line that spans two lines.");
+ tt_str_op(k,OP_EQ, "k9");
+ tt_str_op(v,OP_EQ, "a line that spans two lines.");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k10");
- test_streq(v, "more than one continuation");
+ tt_str_op(k,OP_EQ, "k10");
+ tt_str_op(v,OP_EQ, "more than one continuation");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k11");
- test_streq(v, "continuation at the start");
+ tt_str_op(k,OP_EQ, "k11");
+ tt_str_op(v,OP_EQ, "continuation at the start");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k12");
- test_streq(v, "line with a embedded");
+ tt_str_op(k,OP_EQ, "k12");
+ tt_str_op(v,OP_EQ, "line with a embedded");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k13");
- test_streq(v, "continuation at the very start");
+ tt_str_op(k,OP_EQ, "k13");
+ tt_str_op(v,OP_EQ, "continuation at the very start");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k14");
- test_streq(v, "a line that has a comment and" );
+ tt_str_op(k,OP_EQ, "k14");
+ tt_str_op(v,OP_EQ, "a line that has a comment and" );
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k15");
- test_streq(v, "this should be the next new line");
+ tt_str_op(k,OP_EQ, "k15");
+ tt_str_op(v,OP_EQ, "this should be the next new line");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k16");
- test_streq(v, "a line that has a comment and" );
+ tt_str_op(k,OP_EQ, "k16");
+ tt_str_op(v,OP_EQ, "a line that has a comment and" );
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k17");
- test_streq(v, "this should be the next new line");
+ tt_str_op(k,OP_EQ, "k17");
+ tt_str_op(v,OP_EQ, "this should be the next new line");
tor_free(k); tor_free(v);
- test_streq(str, "");
+ tt_str_op(str,OP_EQ, "");
done:
tor_free(k);
@@ -574,7 +977,7 @@ test_util_config_line(void)
}
static void
-test_util_config_line_quotes(void)
+test_util_config_line_quotes(void *arg)
{
char buf1[1024];
char buf2[128];
@@ -584,6 +987,7 @@ test_util_config_line_quotes(void)
const char *str;
/* Test parse_config_line_from_str */
+ (void)arg;
strlcpy(buf1, "kTrailingSpace \"quoted value\" \n"
"kTrailingGarbage \"quoted value\"trailing garbage\n"
, sizeof(buf1));
@@ -596,30 +1000,30 @@ test_util_config_line_quotes(void)
str = buf1;
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "kTrailingSpace");
- test_streq(v, "quoted value");
+ tt_str_op(k,OP_EQ, "kTrailingSpace");
+ tt_str_op(v,OP_EQ, "quoted value");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
str = buf2;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
str = buf3;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
str = buf4;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
done:
@@ -628,13 +1032,14 @@ test_util_config_line_quotes(void)
}
static void
-test_util_config_line_comment_character(void)
+test_util_config_line_comment_character(void *arg)
{
char buf[1024];
char *k=NULL, *v=NULL;
const char *str;
/* Test parse_config_line_from_str */
+ (void)arg;
strlcpy(buf, "k1 \"# in quotes\"\n"
"k2 some value # some comment\n"
"k3 /home/user/myTorNetwork#2\n" /* Testcase for #1323 */
@@ -642,16 +1047,16 @@ test_util_config_line_comment_character(void)
str = buf;
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k1");
- test_streq(v, "# in quotes");
+ tt_str_op(k,OP_EQ, "k1");
+ tt_str_op(v,OP_EQ, "# in quotes");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "k2");
- test_streq(v, "some value");
+ tt_str_op(k,OP_EQ, "k2");
+ tt_str_op(v,OP_EQ, "some value");
tor_free(k); tor_free(v);
- test_streq(str, "k3 /home/user/myTorNetwork#2\n");
+ tt_str_op(str,OP_EQ, "k3 /home/user/myTorNetwork#2\n");
#if 0
str = parse_config_line_from_str(str, &k, &v);
@@ -668,7 +1073,7 @@ test_util_config_line_comment_character(void)
}
static void
-test_util_config_line_escaped_content(void)
+test_util_config_line_escaped_content(void *arg)
{
char buf1[1024];
char buf2[128];
@@ -680,6 +1085,7 @@ test_util_config_line_escaped_content(void)
const char *str;
/* Test parse_config_line_from_str */
+ (void)arg;
strlcpy(buf1, "HexadecimalLower \"\\x2a\"\n"
"HexadecimalUpper \"\\x2A\"\n"
"HexadecimalUpperX \"\\X2A\"\n"
@@ -711,91 +1117,91 @@ test_util_config_line_escaped_content(void)
str = buf1;
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "HexadecimalLower");
- test_streq(v, "*");
+ tt_str_op(k,OP_EQ, "HexadecimalLower");
+ tt_str_op(v,OP_EQ, "*");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "HexadecimalUpper");
- test_streq(v, "*");
+ tt_str_op(k,OP_EQ, "HexadecimalUpper");
+ tt_str_op(v,OP_EQ, "*");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "HexadecimalUpperX");
- test_streq(v, "*");
+ tt_str_op(k,OP_EQ, "HexadecimalUpperX");
+ tt_str_op(v,OP_EQ, "*");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "Octal");
- test_streq(v, "*");
+ tt_str_op(k,OP_EQ, "Octal");
+ tt_str_op(v,OP_EQ, "*");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "Newline");
- test_streq(v, "\n");
+ tt_str_op(k,OP_EQ, "Newline");
+ tt_str_op(v,OP_EQ, "\n");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "Tab");
- test_streq(v, "\t");
+ tt_str_op(k,OP_EQ, "Tab");
+ tt_str_op(v,OP_EQ, "\t");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "CarriageReturn");
- test_streq(v, "\r");
+ tt_str_op(k,OP_EQ, "CarriageReturn");
+ tt_str_op(v,OP_EQ, "\r");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "DoubleQuote");
- test_streq(v, "\"");
+ tt_str_op(k,OP_EQ, "DoubleQuote");
+ tt_str_op(v,OP_EQ, "\"");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "SimpleQuote");
- test_streq(v, "'");
+ tt_str_op(k,OP_EQ, "SimpleQuote");
+ tt_str_op(v,OP_EQ, "'");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "Backslash");
- test_streq(v, "\\");
+ tt_str_op(k,OP_EQ, "Backslash");
+ tt_str_op(v,OP_EQ, "\\");
tor_free(k); tor_free(v);
str = parse_config_line_from_str(str, &k, &v);
- test_streq(k, "Mix");
- test_streq(v, "This is a \"star\":\t'*'\nAnd second line");
+ tt_str_op(k,OP_EQ, "Mix");
+ tt_str_op(v,OP_EQ, "This is a \"star\":\t'*'\nAnd second line");
tor_free(k); tor_free(v);
- test_streq(str, "");
+ tt_str_op(str,OP_EQ, "");
str = buf2;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
str = buf3;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
str = buf4;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
#if 0
str = buf5;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str, OP_EQ, NULL);
tor_free(k); tor_free(v);
#endif
str = buf6;
str = parse_config_line_from_str(str, &k, &v);
- test_eq_ptr(str, NULL);
+ tt_ptr_op(str,OP_EQ, NULL);
tor_free(k); tor_free(v);
done:
@@ -805,46 +1211,47 @@ test_util_config_line_escaped_content(void)
#ifndef _WIN32
static void
-test_util_expand_filename(void)
+test_util_expand_filename(void *arg)
{
char *str;
+ (void)arg;
setenv("HOME", "/home/itv", 1); /* For "internal test value" */
str = expand_filename("");
- test_streq("", str);
+ tt_str_op("",OP_EQ, str);
tor_free(str);
str = expand_filename("/normal/path");
- test_streq("/normal/path", str);
+ tt_str_op("/normal/path",OP_EQ, str);
tor_free(str);
str = expand_filename("/normal/trailing/path/");
- test_streq("/normal/trailing/path/", str);
+ tt_str_op("/normal/trailing/path/",OP_EQ, str);
tor_free(str);
str = expand_filename("~");
- test_streq("/home/itv/", str);
+ tt_str_op("/home/itv/",OP_EQ, str);
tor_free(str);
str = expand_filename("$HOME/nodice");
- test_streq("$HOME/nodice", str);
+ tt_str_op("$HOME/nodice",OP_EQ, str);
tor_free(str);
str = expand_filename("~/");
- test_streq("/home/itv/", str);
+ tt_str_op("/home/itv/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/foobarqux");
- test_streq("/home/itv/foobarqux", str);
+ tt_str_op("/home/itv/foobarqux",OP_EQ, str);
tor_free(str);
str = expand_filename("~/../../etc/passwd");
- test_streq("/home/itv/../../etc/passwd", str);
+ tt_str_op("/home/itv/../../etc/passwd",OP_EQ, str);
tor_free(str);
str = expand_filename("~/trailing/");
- test_streq("/home/itv/trailing/", str);
+ tt_str_op("/home/itv/trailing/",OP_EQ, str);
tor_free(str);
/* Ideally we'd test ~anotheruser, but that's shady to test (we'd
have to somehow inject/fake the get_user_homedir call) */
@@ -853,15 +1260,15 @@ test_util_expand_filename(void)
setenv("HOME", "/home/itv/", 1);
str = expand_filename("~");
- test_streq("/home/itv/", str);
+ tt_str_op("/home/itv/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/");
- test_streq("/home/itv/", str);
+ tt_str_op("/home/itv/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/foo");
- test_streq("/home/itv/foo", str);
+ tt_str_op("/home/itv/foo",OP_EQ, str);
tor_free(str);
/* Try with empty $HOME */
@@ -869,15 +1276,15 @@ test_util_expand_filename(void)
setenv("HOME", "", 1);
str = expand_filename("~");
- test_streq("/", str);
+ tt_str_op("/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/");
- test_streq("/", str);
+ tt_str_op("/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/foobar");
- test_streq("/foobar", str);
+ tt_str_op("/foobar",OP_EQ, str);
tor_free(str);
/* Try with $HOME unset */
@@ -885,15 +1292,15 @@ test_util_expand_filename(void)
unsetenv("HOME");
str = expand_filename("~");
- test_streq("/", str);
+ tt_str_op("/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/");
- test_streq("/", str);
+ tt_str_op("/",OP_EQ, str);
tor_free(str);
str = expand_filename("~/foobar");
- test_streq("/foobar", str);
+ tt_str_op("/foobar",OP_EQ, str);
tor_free(str);
done:
@@ -903,37 +1310,38 @@ test_util_expand_filename(void)
/** Test tor_escape_str_for_pt_args(). */
static void
-test_util_escape_string_socks(void)
+test_util_escape_string_socks(void *arg)
{
char *escaped_string = NULL;
/** Simple backslash escape. */
+ (void)arg;
escaped_string = tor_escape_str_for_pt_args("This is a backslash: \\",";\\");
- test_assert(escaped_string);
- test_streq(escaped_string, "This is a backslash: \\\\");
+ tt_assert(escaped_string);
+ tt_str_op(escaped_string,OP_EQ, "This is a backslash: \\\\");
tor_free(escaped_string);
/** Simple semicolon escape. */
escaped_string = tor_escape_str_for_pt_args("First rule:Do not use ;",";\\");
- test_assert(escaped_string);
- test_streq(escaped_string, "First rule:Do not use \\;");
+ tt_assert(escaped_string);
+ tt_str_op(escaped_string,OP_EQ, "First rule:Do not use \\;");
tor_free(escaped_string);
/** Empty string. */
escaped_string = tor_escape_str_for_pt_args("", ";\\");
- test_assert(escaped_string);
- test_streq(escaped_string, "");
+ tt_assert(escaped_string);
+ tt_str_op(escaped_string,OP_EQ, "");
tor_free(escaped_string);
/** Escape all characters. */
escaped_string = tor_escape_str_for_pt_args(";\\;\\", ";\\");
- test_assert(escaped_string);
- test_streq(escaped_string, "\\;\\\\\\;\\\\");
+ tt_assert(escaped_string);
+ tt_str_op(escaped_string,OP_EQ, "\\;\\\\\\;\\\\");
tor_free(escaped_string);
escaped_string = tor_escape_str_for_pt_args(";", ";\\");
- test_assert(escaped_string);
- test_streq(escaped_string, "\\;");
+ tt_assert(escaped_string);
+ tt_str_op(escaped_string,OP_EQ, "\\;");
tor_free(escaped_string);
done:
@@ -944,288 +1352,291 @@ static void
test_util_string_is_key_value(void *ptr)
{
(void)ptr;
- test_assert(string_is_key_value(LOG_WARN, "key=value"));
- test_assert(string_is_key_value(LOG_WARN, "k=v"));
- test_assert(string_is_key_value(LOG_WARN, "key="));
- test_assert(string_is_key_value(LOG_WARN, "x="));
- test_assert(string_is_key_value(LOG_WARN, "xx="));
- test_assert(!string_is_key_value(LOG_WARN, "=value"));
- test_assert(!string_is_key_value(LOG_WARN, "=x"));
- test_assert(!string_is_key_value(LOG_WARN, "="));
+ tt_assert(string_is_key_value(LOG_WARN, "key=value"));
+ tt_assert(string_is_key_value(LOG_WARN, "k=v"));
+ tt_assert(string_is_key_value(LOG_WARN, "key="));
+ tt_assert(string_is_key_value(LOG_WARN, "x="));
+ tt_assert(string_is_key_value(LOG_WARN, "xx="));
+ tt_assert(!string_is_key_value(LOG_WARN, "=value"));
+ tt_assert(!string_is_key_value(LOG_WARN, "=x"));
+ tt_assert(!string_is_key_value(LOG_WARN, "="));
/* ??? */
- /* test_assert(!string_is_key_value(LOG_WARN, "===")); */
+ /* tt_assert(!string_is_key_value(LOG_WARN, "===")); */
done:
;
}
/** Test basic string functionality. */
static void
-test_util_strmisc(void)
+test_util_strmisc(void *arg)
{
char buf[1024];
int i;
char *cp, *cp_tmp = NULL;
/* Test strl operations */
- test_eq(5, strlcpy(buf, "Hello", 0));
- test_eq(5, strlcpy(buf, "Hello", 10));
- test_streq(buf, "Hello");
- test_eq(5, strlcpy(buf, "Hello", 6));
- test_streq(buf, "Hello");
- test_eq(5, strlcpy(buf, "Hello", 5));
- test_streq(buf, "Hell");
+ (void)arg;
+ tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 0));
+ tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 10));
+ tt_str_op(buf,OP_EQ, "Hello");
+ tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 6));
+ tt_str_op(buf,OP_EQ, "Hello");
+ tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 5));
+ tt_str_op(buf,OP_EQ, "Hell");
strlcpy(buf, "Hello", sizeof(buf));
- test_eq(10, strlcat(buf, "Hello", 5));
+ tt_int_op(10,OP_EQ, strlcat(buf, "Hello", 5));
/* Test strstrip() */
strlcpy(buf, "Testing 1 2 3", sizeof(buf));
tor_strstrip(buf, ",!");
- test_streq(buf, "Testing 1 2 3");
+ tt_str_op(buf,OP_EQ, "Testing 1 2 3");
strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
tor_strstrip(buf, "!? ");
- test_streq(buf, "Testing123");
+ tt_str_op(buf,OP_EQ, "Testing123");
strlcpy(buf, "!!!Testing 1 2 3??", sizeof(buf));
tor_strstrip(buf, "!? ");
- test_streq(buf, "Testing123");
+ tt_str_op(buf,OP_EQ, "Testing123");
/* Test parse_long */
/* Empty/zero input */
- test_eq(0L, tor_parse_long("",10,0,100,&i,NULL));
- test_eq(0, i);
- test_eq(0L, tor_parse_long("0",10,0,100,&i,NULL));
- test_eq(1, i);
+ tt_int_op(0L,OP_EQ, tor_parse_long("",10,0,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(0L,OP_EQ, tor_parse_long("0",10,0,100,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
/* Normal cases */
- test_eq(10L, tor_parse_long("10",10,0,100,&i,NULL));
- test_eq(1, i);
- test_eq(10L, tor_parse_long("10",10,0,10,&i,NULL));
- test_eq(1, i);
- test_eq(10L, tor_parse_long("10",10,10,100,&i,NULL));
- test_eq(1, i);
- test_eq(-50L, tor_parse_long("-50",10,-100,100,&i,NULL));
- test_eq(1, i);
- test_eq(-50L, tor_parse_long("-50",10,-100,0,&i,NULL));
- test_eq(1, i);
- test_eq(-50L, tor_parse_long("-50",10,-50,0,&i,NULL));
- test_eq(1, i);
+ tt_int_op(10L,OP_EQ, tor_parse_long("10",10,0,100,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(10L,OP_EQ, tor_parse_long("10",10,0,10,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(10L,OP_EQ, tor_parse_long("10",10,10,100,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-100,100,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-100,0,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-50,0,&i,NULL));
+ tt_int_op(1,OP_EQ, i);
/* Extra garbage */
- test_eq(0L, tor_parse_long("10m",10,0,100,&i,NULL));
- test_eq(0, i);
- test_eq(0L, tor_parse_long("-50 plus garbage",10,-100,100,&i,NULL));
- test_eq(0, i);
- test_eq(10L, tor_parse_long("10m",10,0,100,&i,&cp));
- test_eq(1, i);
- test_streq(cp, "m");
- test_eq(-50L, tor_parse_long("-50 plus garbage",10,-100,100,&i,&cp));
- test_eq(1, i);
- test_streq(cp, " plus garbage");
+ tt_int_op(0L,OP_EQ, tor_parse_long("10m",10,0,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(0L,OP_EQ, tor_parse_long("-50 plus garbage",10,-100,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(10L,OP_EQ, tor_parse_long("10m",10,0,100,&i,&cp));
+ tt_int_op(1,OP_EQ, i);
+ tt_str_op(cp,OP_EQ, "m");
+ tt_int_op(-50L,OP_EQ, tor_parse_long("-50 plus garbage",10,-100,100,&i,&cp));
+ tt_int_op(1,OP_EQ, i);
+ tt_str_op(cp,OP_EQ, " plus garbage");
/* Out of bounds */
- test_eq(0L, tor_parse_long("10",10,50,100,&i,NULL));
- test_eq(0, i);
- test_eq(0L, tor_parse_long("-50",10,0,100,&i,NULL));
- test_eq(0, i);
+ tt_int_op(0L,OP_EQ, tor_parse_long("10",10,50,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
+ tt_int_op(0L,OP_EQ, tor_parse_long("-50",10,0,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
/* Base different than 10 */
- test_eq(2L, tor_parse_long("10",2,0,100,NULL,NULL));
- test_eq(0L, tor_parse_long("2",2,0,100,NULL,NULL));
- test_eq(0L, tor_parse_long("10",-2,0,100,NULL,NULL));
- test_eq(68284L, tor_parse_long("10abc",16,0,70000,NULL,NULL));
- test_eq(68284L, tor_parse_long("10ABC",16,0,70000,NULL,NULL));
- test_eq(0, tor_parse_long("10ABC",-1,0,70000,&i,NULL));
- test_eq(i, 0);
+ tt_int_op(2L,OP_EQ, tor_parse_long("10",2,0,100,NULL,NULL));
+ tt_int_op(0L,OP_EQ, tor_parse_long("2",2,0,100,NULL,NULL));
+ tt_int_op(0L,OP_EQ, tor_parse_long("10",-2,0,100,NULL,NULL));
+ tt_int_op(68284L,OP_EQ, tor_parse_long("10abc",16,0,70000,NULL,NULL));
+ tt_int_op(68284L,OP_EQ, tor_parse_long("10ABC",16,0,70000,NULL,NULL));
+ tt_int_op(0,OP_EQ, tor_parse_long("10ABC",-1,0,70000,&i,NULL));
+ tt_int_op(i,OP_EQ, 0);
/* Test parse_ulong */
- test_eq(0UL, tor_parse_ulong("",10,0,100,NULL,NULL));
- test_eq(0UL, tor_parse_ulong("0",10,0,100,NULL,NULL));
- test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
- test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
- test_eq(10UL, tor_parse_ulong("10",10,0,10,NULL,NULL));
- test_eq(10UL, tor_parse_ulong("10",10,10,100,NULL,NULL));
- test_eq(0UL, tor_parse_ulong("8",8,0,100,NULL,NULL));
- test_eq(50UL, tor_parse_ulong("50",10,50,100,NULL,NULL));
- test_eq(0UL, tor_parse_ulong("-50",10,-100,100,NULL,NULL));
- test_eq(0UL, tor_parse_ulong("50",-1,50,100,&i,NULL));
- test_eq(0, i);
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("",10,0,100,NULL,NULL));
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("0",10,0,100,NULL,NULL));
+ tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,0,100,NULL,NULL));
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("10",10,50,100,NULL,NULL));
+ tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,0,10,NULL,NULL));
+ tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,10,100,NULL,NULL));
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("8",8,0,100,NULL,NULL));
+ tt_int_op(50UL,OP_EQ, tor_parse_ulong("50",10,50,100,NULL,NULL));
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("-50",10,-100,100,NULL,NULL));
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong("50",-1,50,100,&i,NULL));
+ tt_int_op(0,OP_EQ, i);
/* Test parse_uint64 */
- test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
- test_eq(1, i);
- test_streq(cp, " x");
- test_assert(U64_LITERAL(12345678901) ==
+ tt_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
+ tt_int_op(1,OP_EQ, i);
+ tt_str_op(cp,OP_EQ, " x");
+ tt_assert(U64_LITERAL(12345678901) ==
tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
- test_eq(1, i);
- test_streq(cp, "");
- test_assert(U64_LITERAL(0) ==
+ tt_int_op(1,OP_EQ, i);
+ tt_str_op(cp,OP_EQ, "");
+ tt_assert(U64_LITERAL(0) ==
tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
- test_eq(0, i);
- test_assert(U64_LITERAL(0) ==
+ tt_int_op(0,OP_EQ, i);
+ tt_assert(U64_LITERAL(0) ==
tor_parse_uint64("123",-1,0,INT32_MAX, &i, &cp));
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
{
/* Test parse_double */
double d = tor_parse_double("10", 0, UINT64_MAX,&i,NULL);
- test_eq(1, i);
- test_assert(DBL_TO_U64(d) == 10);
+ tt_int_op(1,OP_EQ, i);
+ tt_assert(DBL_TO_U64(d) == 10);
d = tor_parse_double("0", 0, UINT64_MAX,&i,NULL);
- test_eq(1, i);
- test_assert(DBL_TO_U64(d) == 0);
+ tt_int_op(1,OP_EQ, i);
+ tt_assert(DBL_TO_U64(d) == 0);
d = tor_parse_double(" ", 0, UINT64_MAX,&i,NULL);
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
d = tor_parse_double(".0a", 0, UINT64_MAX,&i,NULL);
- test_eq(0, i);
+ tt_int_op(0,OP_EQ, i);
d = tor_parse_double(".0a", 0, UINT64_MAX,&i,&cp);
- test_eq(1, i);
+ tt_int_op(1,OP_EQ, i);
d = tor_parse_double("-.0", 0, UINT64_MAX,&i,NULL);
- test_eq(1, i);
- test_assert(DBL_TO_U64(d) == 0);
+ tt_int_op(1,OP_EQ, i);
+ tt_assert(DBL_TO_U64(d) == 0);
d = tor_parse_double("-10", -100.0, 100.0,&i,NULL);
- test_eq(1, i);
- test_eq(-10.0, d);
+ tt_int_op(1,OP_EQ, i);
+ tt_int_op(-10.0,OP_EQ, d);
}
{
/* Test tor_parse_* where we overflow/underflow the underlying type. */
/* This string should overflow 64-bit ints. */
#define TOOBIG "100000000000000000000000000"
- test_eq(0L, tor_parse_long(TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
- test_eq(i, 0);
- test_eq(0L, tor_parse_long("-"TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
- test_eq(i, 0);
- test_eq(0UL, tor_parse_ulong(TOOBIG, 10, 0, ULONG_MAX, &i, NULL));
- test_eq(i, 0);
- tt_u64_op(U64_LITERAL(0), ==, tor_parse_uint64(TOOBIG, 10,
+ tt_int_op(0L, OP_EQ,
+ tor_parse_long(TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
+ tt_int_op(i,OP_EQ, 0);
+ tt_int_op(0L,OP_EQ,
+ tor_parse_long("-"TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
+ tt_int_op(i,OP_EQ, 0);
+ tt_int_op(0UL,OP_EQ, tor_parse_ulong(TOOBIG, 10, 0, ULONG_MAX, &i, NULL));
+ tt_int_op(i,OP_EQ, 0);
+ tt_u64_op(U64_LITERAL(0), OP_EQ, tor_parse_uint64(TOOBIG, 10,
0, UINT64_MAX, &i, NULL));
- test_eq(i, 0);
+ tt_int_op(i,OP_EQ, 0);
}
/* Test snprintf */
/* Returning -1 when there's not enough room in the output buffer */
- test_eq(-1, tor_snprintf(buf, 0, "Foo"));
- test_eq(-1, tor_snprintf(buf, 2, "Foo"));
- test_eq(-1, tor_snprintf(buf, 3, "Foo"));
- test_neq(-1, tor_snprintf(buf, 4, "Foo"));
+ tt_int_op(-1,OP_EQ, tor_snprintf(buf, 0, "Foo"));
+ tt_int_op(-1,OP_EQ, tor_snprintf(buf, 2, "Foo"));
+ tt_int_op(-1,OP_EQ, tor_snprintf(buf, 3, "Foo"));
+ tt_int_op(-1,OP_NE, tor_snprintf(buf, 4, "Foo"));
/* Always NUL-terminate the output */
tor_snprintf(buf, 5, "abcdef");
- test_eq(0, buf[4]);
+ tt_int_op(0,OP_EQ, buf[4]);
tor_snprintf(buf, 10, "abcdef");
- test_eq(0, buf[6]);
+ tt_int_op(0,OP_EQ, buf[6]);
/* uint64 */
tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
U64_PRINTF_ARG(U64_LITERAL(12345678901)));
- test_streq("x!12345678901!x", buf);
+ tt_str_op("x!12345678901!x",OP_EQ, buf);
/* Test str{,case}cmpstart */
- test_assert(strcmpstart("abcdef", "abcdef")==0);
- test_assert(strcmpstart("abcdef", "abc")==0);
- test_assert(strcmpstart("abcdef", "abd")<0);
- test_assert(strcmpstart("abcdef", "abb")>0);
- test_assert(strcmpstart("ab", "abb")<0);
- test_assert(strcmpstart("ab", "")==0);
- test_assert(strcmpstart("ab", "ab ")<0);
- test_assert(strcasecmpstart("abcdef", "abCdEF")==0);
- test_assert(strcasecmpstart("abcDeF", "abc")==0);
- test_assert(strcasecmpstart("abcdef", "Abd")<0);
- test_assert(strcasecmpstart("Abcdef", "abb")>0);
- test_assert(strcasecmpstart("ab", "Abb")<0);
- test_assert(strcasecmpstart("ab", "")==0);
- test_assert(strcasecmpstart("ab", "ab ")<0);
+ tt_assert(strcmpstart("abcdef", "abcdef")==0);
+ tt_assert(strcmpstart("abcdef", "abc")==0);
+ tt_assert(strcmpstart("abcdef", "abd")<0);
+ tt_assert(strcmpstart("abcdef", "abb")>0);
+ tt_assert(strcmpstart("ab", "abb")<0);
+ tt_assert(strcmpstart("ab", "")==0);
+ tt_assert(strcmpstart("ab", "ab ")<0);
+ tt_assert(strcasecmpstart("abcdef", "abCdEF")==0);
+ tt_assert(strcasecmpstart("abcDeF", "abc")==0);
+ tt_assert(strcasecmpstart("abcdef", "Abd")<0);
+ tt_assert(strcasecmpstart("Abcdef", "abb")>0);
+ tt_assert(strcasecmpstart("ab", "Abb")<0);
+ tt_assert(strcasecmpstart("ab", "")==0);
+ tt_assert(strcasecmpstart("ab", "ab ")<0);
/* Test str{,case}cmpend */
- test_assert(strcmpend("abcdef", "abcdef")==0);
- test_assert(strcmpend("abcdef", "def")==0);
- test_assert(strcmpend("abcdef", "deg")<0);
- test_assert(strcmpend("abcdef", "dee")>0);
- test_assert(strcmpend("ab", "aab")>0);
- test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
- test_assert(strcasecmpend("abcdef", "dEF")==0);
- test_assert(strcasecmpend("abcdef", "Deg")<0);
- test_assert(strcasecmpend("abcDef", "dee")>0);
- test_assert(strcasecmpend("AB", "abb")<0);
+ tt_assert(strcmpend("abcdef", "abcdef")==0);
+ tt_assert(strcmpend("abcdef", "def")==0);
+ tt_assert(strcmpend("abcdef", "deg")<0);
+ tt_assert(strcmpend("abcdef", "dee")>0);
+ tt_assert(strcmpend("ab", "aab")>0);
+ tt_assert(strcasecmpend("AbcDEF", "abcdef")==0);
+ tt_assert(strcasecmpend("abcdef", "dEF")==0);
+ tt_assert(strcasecmpend("abcdef", "Deg")<0);
+ tt_assert(strcasecmpend("abcDef", "dee")>0);
+ tt_assert(strcasecmpend("AB", "abb")<0);
/* Test digest_is_zero */
memset(buf,0,20);
buf[20] = 'x';
- test_assert(tor_digest_is_zero(buf));
+ tt_assert(tor_digest_is_zero(buf));
buf[19] = 'x';
- test_assert(!tor_digest_is_zero(buf));
+ tt_assert(!tor_digest_is_zero(buf));
/* Test mem_is_zero */
memset(buf,0,128);
buf[128] = 'x';
- test_assert(tor_mem_is_zero(buf, 10));
- test_assert(tor_mem_is_zero(buf, 20));
- test_assert(tor_mem_is_zero(buf, 128));
- test_assert(!tor_mem_is_zero(buf, 129));
+ tt_assert(tor_mem_is_zero(buf, 10));
+ tt_assert(tor_mem_is_zero(buf, 20));
+ tt_assert(tor_mem_is_zero(buf, 128));
+ tt_assert(!tor_mem_is_zero(buf, 129));
buf[60] = (char)255;
- test_assert(!tor_mem_is_zero(buf, 128));
+ tt_assert(!tor_mem_is_zero(buf, 128));
buf[0] = (char)1;
- test_assert(!tor_mem_is_zero(buf, 10));
+ tt_assert(!tor_mem_is_zero(buf, 10));
/* Test 'escaped' */
- test_assert(NULL == escaped(NULL));
- test_streq("\"\"", escaped(""));
- test_streq("\"abcd\"", escaped("abcd"));
- test_streq("\"\\\\ \\n\\r\\t\\\"\\'\"", escaped("\\ \n\r\t\"'"));
- test_streq("\"unnecessary \\'backslashes\\'\"",
+ tt_assert(NULL == escaped(NULL));
+ tt_str_op("\"\"",OP_EQ, escaped(""));
+ tt_str_op("\"abcd\"",OP_EQ, escaped("abcd"));
+ tt_str_op("\"\\\\ \\n\\r\\t\\\"\\'\"",OP_EQ, escaped("\\ \n\r\t\"'"));
+ tt_str_op("\"unnecessary \\'backslashes\\'\"",OP_EQ,
escaped("unnecessary \'backslashes\'"));
/* Non-printable characters appear as octal */
- test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
- test_streq("\"z\\336\\255 ;foo\"", escaped("z\xde\xad\x20;foo"));
+ tt_str_op("\"z\\001abc\\277d\"",OP_EQ, escaped("z\001abc\277d"));
+ tt_str_op("\"z\\336\\255 ;foo\"",OP_EQ, escaped("z\xde\xad\x20;foo"));
/* Test strndup and memdup */
{
const char *s = "abcdefghijklmnopqrstuvwxyz";
cp_tmp = tor_strndup(s, 30);
- test_streq(cp_tmp, s); /* same string, */
- test_neq_ptr(cp_tmp, s); /* but different pointers. */
+ tt_str_op(cp_tmp,OP_EQ, s); /* same string, */
+ tt_ptr_op(cp_tmp,OP_NE,s); /* but different pointers. */
tor_free(cp_tmp);
cp_tmp = tor_strndup(s, 5);
- test_streq(cp_tmp, "abcde");
+ tt_str_op(cp_tmp,OP_EQ, "abcde");
tor_free(cp_tmp);
s = "a\0b\0c\0d\0e\0";
cp_tmp = tor_memdup(s,10);
- test_memeq(cp_tmp, s, 10); /* same ram, */
- test_neq_ptr(cp_tmp, s); /* but different pointers. */
+ tt_mem_op(cp_tmp,OP_EQ, s, 10); /* same ram, */
+ tt_ptr_op(cp_tmp,OP_NE,s); /* but different pointers. */
tor_free(cp_tmp);
}
/* Test str-foo functions */
cp_tmp = tor_strdup("abcdef");
- test_assert(tor_strisnonupper(cp_tmp));
+ tt_assert(tor_strisnonupper(cp_tmp));
cp_tmp[3] = 'D';
- test_assert(!tor_strisnonupper(cp_tmp));
+ tt_assert(!tor_strisnonupper(cp_tmp));
tor_strupper(cp_tmp);
- test_streq(cp_tmp, "ABCDEF");
+ tt_str_op(cp_tmp,OP_EQ, "ABCDEF");
tor_strlower(cp_tmp);
- test_streq(cp_tmp, "abcdef");
- test_assert(tor_strisnonupper(cp_tmp));
- test_assert(tor_strisprint(cp_tmp));
+ tt_str_op(cp_tmp,OP_EQ, "abcdef");
+ tt_assert(tor_strisnonupper(cp_tmp));
+ tt_assert(tor_strisprint(cp_tmp));
cp_tmp[3] = 3;
- test_assert(!tor_strisprint(cp_tmp));
+ tt_assert(!tor_strisprint(cp_tmp));
tor_free(cp_tmp);
/* Test memmem and memstr */
{
const char *haystack = "abcde";
- test_assert(!tor_memmem(haystack, 5, "ef", 2));
- test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
- test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
- test_assert(!tor_memmem(haystack, 4, "cde", 3));
+ tt_assert(!tor_memmem(haystack, 5, "ef", 2));
+ tt_ptr_op(tor_memmem(haystack, 5, "cd", 2),OP_EQ, haystack + 2);
+ tt_ptr_op(tor_memmem(haystack, 5, "cde", 3),OP_EQ, haystack + 2);
+ tt_assert(!tor_memmem(haystack, 4, "cde", 3));
haystack = "ababcad";
- test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
- test_eq_ptr(tor_memmem(haystack, 7, "ad", 2), haystack + 5);
- test_eq_ptr(tor_memmem(haystack, 7, "cad", 3), haystack + 4);
- test_assert(!tor_memmem(haystack, 7, "dadad", 5));
- test_assert(!tor_memmem(haystack, 7, "abcdefghij", 10));
+ tt_ptr_op(tor_memmem(haystack, 7, "abc", 3),OP_EQ, haystack + 2);
+ tt_ptr_op(tor_memmem(haystack, 7, "ad", 2),OP_EQ, haystack + 5);
+ tt_ptr_op(tor_memmem(haystack, 7, "cad", 3),OP_EQ, haystack + 4);
+ tt_assert(!tor_memmem(haystack, 7, "dadad", 5));
+ tt_assert(!tor_memmem(haystack, 7, "abcdefghij", 10));
/* memstr */
- test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
- test_eq_ptr(tor_memstr(haystack, 7, "cad"), haystack + 4);
- test_assert(!tor_memstr(haystack, 6, "cad"));
- test_assert(!tor_memstr(haystack, 7, "cadd"));
- test_assert(!tor_memstr(haystack, 7, "fe"));
- test_assert(!tor_memstr(haystack, 7, "ababcade"));
+ tt_ptr_op(tor_memstr(haystack, 7, "abc"),OP_EQ, haystack + 2);
+ tt_ptr_op(tor_memstr(haystack, 7, "cad"),OP_EQ, haystack + 4);
+ tt_assert(!tor_memstr(haystack, 6, "cad"));
+ tt_assert(!tor_memstr(haystack, 7, "cadd"));
+ tt_assert(!tor_memstr(haystack, 7, "fe"));
+ tt_assert(!tor_memstr(haystack, 7, "ababcade"));
}
/* Test hex_str */
@@ -1234,271 +1645,134 @@ test_util_strmisc(void)
size_t i;
for (i = 0; i < sizeof(binary_data); ++i)
binary_data[i] = i;
- test_streq(hex_str(binary_data, 0), "");
- test_streq(hex_str(binary_data, 1), "00");
- test_streq(hex_str(binary_data, 17), "000102030405060708090A0B0C0D0E0F10");
- test_streq(hex_str(binary_data, 32),
+ tt_str_op(hex_str(binary_data, 0),OP_EQ, "");
+ tt_str_op(hex_str(binary_data, 1),OP_EQ, "00");
+ tt_str_op(hex_str(binary_data, 17),OP_EQ,
+ "000102030405060708090A0B0C0D0E0F10");
+ tt_str_op(hex_str(binary_data, 32),OP_EQ,
"000102030405060708090A0B0C0D0E0F"
"101112131415161718191A1B1C1D1E1F");
- test_streq(hex_str(binary_data, 34),
+ tt_str_op(hex_str(binary_data, 34),OP_EQ,
"000102030405060708090A0B0C0D0E0F"
"101112131415161718191A1B1C1D1E1F");
/* Repeat these tests for shorter strings after longer strings
have been tried, to make sure we're correctly terminating strings */
- test_streq(hex_str(binary_data, 1), "00");
- test_streq(hex_str(binary_data, 0), "");
+ tt_str_op(hex_str(binary_data, 1),OP_EQ, "00");
+ tt_str_op(hex_str(binary_data, 0),OP_EQ, "");
}
/* Test strcmp_opt */
- tt_int_op(strcmp_opt("", "foo"), <, 0);
- tt_int_op(strcmp_opt("", ""), ==, 0);
- tt_int_op(strcmp_opt("foo", ""), >, 0);
+ tt_int_op(strcmp_opt("", "foo"), OP_LT, 0);
+ tt_int_op(strcmp_opt("", ""), OP_EQ, 0);
+ tt_int_op(strcmp_opt("foo", ""), OP_GT, 0);
- tt_int_op(strcmp_opt(NULL, ""), <, 0);
- tt_int_op(strcmp_opt(NULL, NULL), ==, 0);
- tt_int_op(strcmp_opt("", NULL), >, 0);
+ tt_int_op(strcmp_opt(NULL, ""), OP_LT, 0);
+ tt_int_op(strcmp_opt(NULL, NULL), OP_EQ, 0);
+ tt_int_op(strcmp_opt("", NULL), OP_GT, 0);
- tt_int_op(strcmp_opt(NULL, "foo"), <, 0);
- tt_int_op(strcmp_opt("foo", NULL), >, 0);
+ tt_int_op(strcmp_opt(NULL, "foo"), OP_LT, 0);
+ tt_int_op(strcmp_opt("foo", NULL), OP_GT, 0);
/* Test strcmp_len */
- tt_int_op(strcmp_len("foo", "bar", 3), >, 0);
- tt_int_op(strcmp_len("foo", "bar", 2), <, 0); /* First len, then lexical */
- tt_int_op(strcmp_len("foo2", "foo1", 4), >, 0);
- tt_int_op(strcmp_len("foo2", "foo1", 3), <, 0); /* Really stop at len */
- tt_int_op(strcmp_len("foo2", "foo", 3), ==, 0); /* Really stop at len */
- tt_int_op(strcmp_len("blah", "", 4), >, 0);
- tt_int_op(strcmp_len("blah", "", 0), ==, 0);
+ tt_int_op(strcmp_len("foo", "bar", 3), OP_GT, 0);
+ tt_int_op(strcmp_len("foo", "bar", 2), OP_LT, 0);
+ tt_int_op(strcmp_len("foo2", "foo1", 4), OP_GT, 0);
+ tt_int_op(strcmp_len("foo2", "foo1", 3), OP_LT, 0); /* Really stop at len */
+ tt_int_op(strcmp_len("foo2", "foo", 3), OP_EQ, 0); /* Really stop at len */
+ tt_int_op(strcmp_len("blah", "", 4), OP_GT, 0);
+ tt_int_op(strcmp_len("blah", "", 0), OP_EQ, 0);
done:
tor_free(cp_tmp);
}
static void
-test_util_pow2(void)
+test_util_pow2(void *arg)
{
/* Test tor_log2(). */
- test_eq(tor_log2(64), 6);
- test_eq(tor_log2(65), 6);
- test_eq(tor_log2(63), 5);
- test_eq(tor_log2(0), 0); /* incorrect mathematically, but as specified */
- test_eq(tor_log2(1), 0);
- test_eq(tor_log2(2), 1);
- test_eq(tor_log2(3), 1);
- test_eq(tor_log2(4), 2);
- test_eq(tor_log2(5), 2);
- test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
- test_eq(tor_log2(UINT64_MAX), 63);
+ (void)arg;
+ tt_int_op(tor_log2(64),OP_EQ, 6);
+ tt_int_op(tor_log2(65),OP_EQ, 6);
+ tt_int_op(tor_log2(63),OP_EQ, 5);
+ /* incorrect mathematically, but as specified: */
+ tt_int_op(tor_log2(0),OP_EQ, 0);
+ tt_int_op(tor_log2(1),OP_EQ, 0);
+ tt_int_op(tor_log2(2),OP_EQ, 1);
+ tt_int_op(tor_log2(3),OP_EQ, 1);
+ tt_int_op(tor_log2(4),OP_EQ, 2);
+ tt_int_op(tor_log2(5),OP_EQ, 2);
+ tt_int_op(tor_log2(U64_LITERAL(40000000000000000)),OP_EQ, 55);
+ tt_int_op(tor_log2(UINT64_MAX),OP_EQ, 63);
/* Test round_to_power_of_2 */
- tt_u64_op(round_to_power_of_2(120), ==, 128);
- tt_u64_op(round_to_power_of_2(128), ==, 128);
- tt_u64_op(round_to_power_of_2(130), ==, 128);
- tt_u64_op(round_to_power_of_2(U64_LITERAL(40000000000000000)), ==,
+ tt_u64_op(round_to_power_of_2(120), OP_EQ, 128);
+ tt_u64_op(round_to_power_of_2(128), OP_EQ, 128);
+ tt_u64_op(round_to_power_of_2(130), OP_EQ, 128);
+ tt_u64_op(round_to_power_of_2(U64_LITERAL(40000000000000000)), OP_EQ,
U64_LITERAL(1)<<55);
- tt_u64_op(round_to_power_of_2(U64_LITERAL(0xffffffffffffffff)), ==,
+ tt_u64_op(round_to_power_of_2(U64_LITERAL(0xffffffffffffffff)), OP_EQ,
U64_LITERAL(1)<<63);
- tt_u64_op(round_to_power_of_2(0), ==, 1);
- tt_u64_op(round_to_power_of_2(1), ==, 1);
- tt_u64_op(round_to_power_of_2(2), ==, 2);
- tt_u64_op(round_to_power_of_2(3), ==, 2);
- tt_u64_op(round_to_power_of_2(4), ==, 4);
- tt_u64_op(round_to_power_of_2(5), ==, 4);
- tt_u64_op(round_to_power_of_2(6), ==, 4);
- tt_u64_op(round_to_power_of_2(7), ==, 8);
+ tt_u64_op(round_to_power_of_2(0), OP_EQ, 1);
+ tt_u64_op(round_to_power_of_2(1), OP_EQ, 1);
+ tt_u64_op(round_to_power_of_2(2), OP_EQ, 2);
+ tt_u64_op(round_to_power_of_2(3), OP_EQ, 2);
+ tt_u64_op(round_to_power_of_2(4), OP_EQ, 4);
+ tt_u64_op(round_to_power_of_2(5), OP_EQ, 4);
+ tt_u64_op(round_to_power_of_2(6), OP_EQ, 4);
+ tt_u64_op(round_to_power_of_2(7), OP_EQ, 8);
done:
;
}
-/** mutex for thread test to stop the threads hitting data at the same time. */
-static tor_mutex_t *thread_test_mutex_ = NULL;
-/** mutexes for the thread test to make sure that the threads have to
- * interleave somewhat. */
-static tor_mutex_t *thread_test_start1_ = NULL,
- *thread_test_start2_ = NULL;
-/** Shared strmap for the thread test. */
-static strmap_t *thread_test_strmap_ = NULL;
-/** The name of thread1 for the thread test */
-static char *thread1_name_ = NULL;
-/** The name of thread2 for the thread test */
-static char *thread2_name_ = NULL;
-
-static void thread_test_func_(void* _s) ATTR_NORETURN;
-
-/** How many iterations have the threads in the unit test run? */
-static int t1_count = 0, t2_count = 0;
-
-/** Helper function for threading unit tests: This function runs in a
- * subthread. It grabs its own mutex (start1 or start2) to make sure that it
- * should start, then it repeatedly alters _test_thread_strmap protected by
- * thread_test_mutex_. */
-static void
-thread_test_func_(void* _s)
-{
- char *s = _s;
- int i, *count;
- tor_mutex_t *m;
- char buf[64];
- char **cp;
- if (!strcmp(s, "thread 1")) {
- m = thread_test_start1_;
- cp = &thread1_name_;
- count = &t1_count;
- } else {
- m = thread_test_start2_;
- cp = &thread2_name_;
- count = &t2_count;
- }
-
- tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
- *cp = tor_strdup(buf);
-
- tor_mutex_acquire(m);
-
- for (i=0; i<10000; ++i) {
- tor_mutex_acquire(thread_test_mutex_);
- strmap_set(thread_test_strmap_, "last to run", *cp);
- ++*count;
- tor_mutex_release(thread_test_mutex_);
- }
- tor_mutex_acquire(thread_test_mutex_);
- strmap_set(thread_test_strmap_, s, *cp);
- tor_mutex_release(thread_test_mutex_);
-
- tor_mutex_release(m);
-
- spawn_exit();
-}
-
-/** Run unit tests for threading logic. */
-static void
-test_util_threads(void)
-{
- char *s1 = NULL, *s2 = NULL;
- int done = 0, timedout = 0;
- time_t started;
-#ifndef _WIN32
- struct timeval tv;
- tv.tv_sec=0;
- tv.tv_usec=100*1000;
-#endif
-#ifndef TOR_IS_MULTITHREADED
- /* Skip this test if we aren't threading. We should be threading most
- * everywhere by now. */
- if (1)
- return;
-#endif
- thread_test_mutex_ = tor_mutex_new();
- thread_test_start1_ = tor_mutex_new();
- thread_test_start2_ = tor_mutex_new();
- thread_test_strmap_ = strmap_new();
- s1 = tor_strdup("thread 1");
- s2 = tor_strdup("thread 2");
- tor_mutex_acquire(thread_test_start1_);
- tor_mutex_acquire(thread_test_start2_);
- spawn_func(thread_test_func_, s1);
- spawn_func(thread_test_func_, s2);
- tor_mutex_release(thread_test_start2_);
- tor_mutex_release(thread_test_start1_);
- started = time(NULL);
- while (!done) {
- tor_mutex_acquire(thread_test_mutex_);
- strmap_assert_ok(thread_test_strmap_);
- if (strmap_get(thread_test_strmap_, "thread 1") &&
- strmap_get(thread_test_strmap_, "thread 2")) {
- done = 1;
- } else if (time(NULL) > started + 150) {
- timedout = done = 1;
- }
- tor_mutex_release(thread_test_mutex_);
-#ifndef _WIN32
- /* Prevent the main thread from starving the worker threads. */
- select(0, NULL, NULL, NULL, &tv);
-#endif
- }
- tor_mutex_acquire(thread_test_start1_);
- tor_mutex_release(thread_test_start1_);
- tor_mutex_acquire(thread_test_start2_);
- tor_mutex_release(thread_test_start2_);
-
- tor_mutex_free(thread_test_mutex_);
-
- if (timedout) {
- printf("\nTimed out: %d %d", t1_count, t2_count);
- test_assert(strmap_get(thread_test_strmap_, "thread 1"));
- test_assert(strmap_get(thread_test_strmap_, "thread 2"));
- test_assert(!timedout);
- }
-
- /* different thread IDs. */
- test_assert(strcmp(strmap_get(thread_test_strmap_, "thread 1"),
- strmap_get(thread_test_strmap_, "thread 2")));
- test_assert(!strcmp(strmap_get(thread_test_strmap_, "thread 1"),
- strmap_get(thread_test_strmap_, "last to run")) ||
- !strcmp(strmap_get(thread_test_strmap_, "thread 2"),
- strmap_get(thread_test_strmap_, "last to run")));
-
- done:
- tor_free(s1);
- tor_free(s2);
- tor_free(thread1_name_);
- tor_free(thread2_name_);
- if (thread_test_strmap_)
- strmap_free(thread_test_strmap_, NULL);
- if (thread_test_start1_)
- tor_mutex_free(thread_test_start1_);
- if (thread_test_start2_)
- tor_mutex_free(thread_test_start2_);
-}
-
/** Run unit tests for compression functions */
static void
-test_util_gzip(void)
+test_util_gzip(void *arg)
{
char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
const char *ccp2;
size_t len1, len2;
tor_zlib_state_t *state = NULL;
+ (void)arg;
buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
- test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
+ tt_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
if (is_gzip_supported()) {
- test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
+ tt_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
GZIP_METHOD));
- test_assert(buf2);
- test_assert(len1 < strlen(buf1));
- test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
+ tt_assert(buf2);
+ tt_assert(len1 < strlen(buf1));
+ tt_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
- test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
+ tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
GZIP_METHOD, 1, LOG_INFO));
- test_assert(buf3);
- test_eq(strlen(buf1) + 1, len2);
- test_streq(buf1, buf3);
+ tt_assert(buf3);
+ tt_int_op(strlen(buf1) + 1,OP_EQ, len2);
+ tt_str_op(buf1,OP_EQ, buf3);
tor_free(buf2);
tor_free(buf3);
}
- test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
+ tt_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
ZLIB_METHOD));
- test_assert(buf2);
- test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
+ tt_assert(buf2);
+ tt_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
- test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
+ tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
ZLIB_METHOD, 1, LOG_INFO));
- test_assert(buf3);
- test_eq(strlen(buf1) + 1, len2);
- test_streq(buf1, buf3);
+ tt_assert(buf3);
+ tt_int_op(strlen(buf1) + 1,OP_EQ, len2);
+ tt_str_op(buf1,OP_EQ, buf3);
/* Check whether we can uncompress concatenated, compressed strings. */
tor_free(buf3);
- buf2 = tor_realloc(buf2, len1*2);
+ buf2 = tor_reallocarray(buf2, len1, 2);
memcpy(buf2+len1, buf2, len1);
- test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
+ tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
ZLIB_METHOD, 1, LOG_INFO));
- test_eq((strlen(buf1)+1)*2, len2);
- test_memeq(buf3,
+ tt_int_op((strlen(buf1)+1)*2,OP_EQ, len2);
+ tt_mem_op(buf3,OP_EQ,
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
(strlen(buf1)+1)*2);
@@ -1510,7 +1784,7 @@ test_util_gzip(void)
/* Check whether we can uncompress partial strings. */
buf1 =
tor_strdup("String with low redundancy that won't be compressed much.");
- test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
+ tt_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
ZLIB_METHOD));
tt_assert(len1>16);
/* when we allow an incomplete string, we should succeed.*/
@@ -1530,28 +1804,29 @@ test_util_gzip(void)
tor_free(buf1);
tor_free(buf2);
tor_free(buf3);
- state = tor_zlib_new(1, ZLIB_METHOD);
+ state = tor_zlib_new(1, ZLIB_METHOD, HIGH_COMPRESSION);
tt_assert(state);
cp1 = buf1 = tor_malloc(1024);
len1 = 1024;
ccp2 = "ABCDEFGHIJABCDEFGHIJ";
len2 = 21;
- test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
+ tt_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
== TOR_ZLIB_OK);
- test_eq(0, len2); /* Make sure we compressed it all. */
- test_assert(cp1 > buf1);
+ tt_int_op(0,OP_EQ, len2); /* Make sure we compressed it all. */
+ tt_assert(cp1 > buf1);
len2 = 0;
cp2 = cp1;
- test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
+ tt_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
== TOR_ZLIB_DONE);
- test_eq(0, len2);
- test_assert(cp1 > cp2); /* Make sure we really added something. */
+ tt_int_op(0,OP_EQ, len2);
+ tt_assert(cp1 > cp2); /* Make sure we really added something. */
tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
ZLIB_METHOD, 1, LOG_WARN));
- test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
- test_eq(21, len2);
+ /* Make sure it compressed right. */
+ tt_str_op(buf3, OP_EQ, "ABCDEFGHIJABCDEFGHIJ");
+ tt_int_op(21,OP_EQ, len2);
done:
if (state)
@@ -1563,7 +1838,7 @@ test_util_gzip(void)
/** Run unit tests for mmap() wrapper functionality. */
static void
-test_util_mmap(void)
+test_util_mmap(void *arg)
{
char *fname1 = tor_strdup(get_fname("mapped_1"));
char *fname2 = tor_strdup(get_fname("mapped_2"));
@@ -1572,56 +1847,57 @@ test_util_mmap(void)
char *buf = tor_malloc(17000);
tor_mmap_t *mapping = NULL;
+ (void)arg;
crypto_rand(buf, buflen);
mapping = tor_mmap_file(fname1);
- test_assert(! mapping);
+ tt_assert(! mapping);
write_str_to_file(fname1, "Short file.", 1);
mapping = tor_mmap_file(fname1);
- test_assert(mapping);
- test_eq(mapping->size, strlen("Short file."));
- test_streq(mapping->data, "Short file.");
+ tt_assert(mapping);
+ tt_int_op(mapping->size,OP_EQ, strlen("Short file."));
+ tt_str_op(mapping->data,OP_EQ, "Short file.");
#ifdef _WIN32
- tt_int_op(0, ==, tor_munmap_file(mapping));
+ tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
mapping = NULL;
- test_assert(unlink(fname1) == 0);
+ tt_assert(unlink(fname1) == 0);
#else
/* make sure we can unlink. */
- test_assert(unlink(fname1) == 0);
- test_streq(mapping->data, "Short file.");
- tt_int_op(0, ==, tor_munmap_file(mapping));
+ tt_assert(unlink(fname1) == 0);
+ tt_str_op(mapping->data,OP_EQ, "Short file.");
+ tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
mapping = NULL;
#endif
/* Now a zero-length file. */
write_str_to_file(fname1, "", 1);
mapping = tor_mmap_file(fname1);
- test_eq_ptr(mapping, NULL);
- test_eq(ERANGE, errno);
+ tt_ptr_op(mapping,OP_EQ, NULL);
+ tt_int_op(ERANGE,OP_EQ, errno);
unlink(fname1);
/* Make sure that we fail to map a no-longer-existent file. */
mapping = tor_mmap_file(fname1);
- test_assert(! mapping);
+ tt_assert(! mapping);
/* Now try a big file that stretches across a few pages and isn't aligned */
write_bytes_to_file(fname2, buf, buflen, 1);
mapping = tor_mmap_file(fname2);
- test_assert(mapping);
- test_eq(mapping->size, buflen);
- test_memeq(mapping->data, buf, buflen);
- tt_int_op(0, ==, tor_munmap_file(mapping));
+ tt_assert(mapping);
+ tt_int_op(mapping->size,OP_EQ, buflen);
+ tt_mem_op(mapping->data,OP_EQ, buf, buflen);
+ tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
mapping = NULL;
/* Now try a big aligned file. */
write_bytes_to_file(fname3, buf, 16384, 1);
mapping = tor_mmap_file(fname3);
- test_assert(mapping);
- test_eq(mapping->size, 16384);
- test_memeq(mapping->data, buf, 16384);
- tt_int_op(0, ==, tor_munmap_file(mapping));
+ tt_assert(mapping);
+ tt_int_op(mapping->size,OP_EQ, 16384);
+ tt_mem_op(mapping->data,OP_EQ, buf, 16384);
+ tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
mapping = NULL;
done:
@@ -1639,17 +1915,18 @@ test_util_mmap(void)
/** Run unit tests for escaping/unescaping data for use by controllers. */
static void
-test_util_control_formats(void)
+test_util_control_formats(void *arg)
{
char *out = NULL;
const char *inp =
"..This is a test\r\n.of the emergency \n..system.\r\n\rZ.\r\n";
size_t sz;
+ (void)arg;
sz = read_escaped_data(inp, strlen(inp), &out);
- test_streq(out,
+ tt_str_op(out,OP_EQ,
".This is a test\nof the emergency \n.system.\n\rZ.\n");
- test_eq(sz, strlen(out));
+ tt_int_op(sz,OP_EQ, strlen(out));
done:
tor_free(out);
@@ -1669,9 +1946,10 @@ test_util_control_formats(void)
} while (0)
static void
-test_util_sscanf(void)
+test_util_sscanf(void *arg)
{
unsigned u1, u2, u3;
+ unsigned long ulng;
char s1[20], s2[10], s3[10], ch;
int r;
long lng1,lng2;
@@ -1679,186 +1957,336 @@ test_util_sscanf(void)
double d1,d2,d3,d4;
/* Simple tests (malformed patterns, literal matching, ...) */
- test_eq(-1, tor_sscanf("123", "%i", &r)); /* %i is not supported */
- test_eq(-1, tor_sscanf("wrong", "%5c", s1)); /* %c cannot have a number. */
- test_eq(-1, tor_sscanf("hello", "%s", s1)); /* %s needs a number. */
- test_eq(-1, tor_sscanf("prettylongstring", "%999999s", s1));
+ (void)arg;
+ tt_int_op(-1,OP_EQ, tor_sscanf("123", "%i", &r)); /* %i is not supported */
+ tt_int_op(-1,OP_EQ,
+ tor_sscanf("wrong", "%5c", s1)); /* %c cannot have a number. */
+ tt_int_op(-1,OP_EQ, tor_sscanf("hello", "%s", s1)); /* %s needs a number. */
+ tt_int_op(-1,OP_EQ, tor_sscanf("prettylongstring", "%999999s", s1));
#if 0
/* GCC thinks these two are illegal. */
test_eq(-1, tor_sscanf("prettylongstring", "%0s", s1));
test_eq(0, tor_sscanf("prettylongstring", "%10s", NULL));
#endif
/* No '%'-strings: always "success" */
- test_eq(0, tor_sscanf("hello world", "hello world"));
- test_eq(0, tor_sscanf("hello world", "good bye"));
+ tt_int_op(0,OP_EQ, tor_sscanf("hello world", "hello world"));
+ tt_int_op(0,OP_EQ, tor_sscanf("hello world", "good bye"));
/* Excess data */
- test_eq(0, tor_sscanf("hello 3", "%u", &u1)); /* have to match the start */
- test_eq(0, tor_sscanf(" 3 hello", "%u", &u1));
- test_eq(0, tor_sscanf(" 3 hello", "%2u", &u1)); /* not even in this case */
- test_eq(1, tor_sscanf("3 hello", "%u", &u1)); /* but trailing is alright */
+ tt_int_op(0,OP_EQ,
+ tor_sscanf("hello 3", "%u", &u1)); /* have to match the start */
+ tt_int_op(0,OP_EQ, tor_sscanf(" 3 hello", "%u", &u1));
+ tt_int_op(0,OP_EQ,
+ tor_sscanf(" 3 hello", "%2u", &u1)); /* not even in this case */
+ tt_int_op(1,OP_EQ,
+ tor_sscanf("3 hello", "%u", &u1)); /* but trailing is alright */
/* Numbers (ie. %u) */
- test_eq(0, tor_sscanf("hello world 3", "hello worlb %u", &u1)); /* d vs b */
- test_eq(1, tor_sscanf("12345", "%u", &u1));
- test_eq(12345u, u1);
- test_eq(1, tor_sscanf("12346 ", "%u", &u1));
- test_eq(12346u, u1);
- test_eq(0, tor_sscanf(" 12347", "%u", &u1));
- test_eq(1, tor_sscanf(" 12348", " %u", &u1));
- test_eq(12348u, u1);
- test_eq(1, tor_sscanf("0", "%u", &u1));
- test_eq(0u, u1);
- test_eq(1, tor_sscanf("0000", "%u", &u2));
- test_eq(0u, u2);
- test_eq(0, tor_sscanf("", "%u", &u1)); /* absent number */
- test_eq(0, tor_sscanf("A", "%u", &u1)); /* bogus number */
- test_eq(0, tor_sscanf("-1", "%u", &u1)); /* negative number */
- test_eq(1, tor_sscanf("4294967295", "%u", &u1)); /* UINT32_MAX should work */
- test_eq(4294967295u, u1);
- test_eq(0, tor_sscanf("4294967296", "%u", &u1)); /* But not at 32 bits */
- test_eq(1, tor_sscanf("4294967296", "%9u", &u1)); /* but parsing only 9... */
- test_eq(429496729u, u1);
+ tt_int_op(0,OP_EQ,
+ tor_sscanf("hello world 3", "hello worlb %u", &u1)); /* d vs b */
+ tt_int_op(1,OP_EQ, tor_sscanf("12345", "%u", &u1));
+ tt_int_op(12345u,OP_EQ, u1);
+ tt_int_op(1,OP_EQ, tor_sscanf("12346 ", "%u", &u1));
+ tt_int_op(12346u,OP_EQ, u1);
+ tt_int_op(0,OP_EQ, tor_sscanf(" 12347", "%u", &u1));
+ tt_int_op(1,OP_EQ, tor_sscanf(" 12348", " %u", &u1));
+ tt_int_op(12348u,OP_EQ, u1);
+ tt_int_op(1,OP_EQ, tor_sscanf("0", "%u", &u1));
+ tt_int_op(0u,OP_EQ, u1);
+ tt_int_op(1,OP_EQ, tor_sscanf("0000", "%u", &u2));
+ tt_int_op(0u,OP_EQ, u2);
+ tt_int_op(0,OP_EQ, tor_sscanf("", "%u", &u1)); /* absent number */
+ tt_int_op(0,OP_EQ, tor_sscanf("A", "%u", &u1)); /* bogus number */
+ tt_int_op(0,OP_EQ, tor_sscanf("-1", "%u", &u1)); /* negative number */
/* Numbers with size (eg. %2u) */
- test_eq(0, tor_sscanf("-1", "%2u", &u1));
- test_eq(2, tor_sscanf("123456", "%2u%u", &u1, &u2));
- test_eq(12u, u1);
- test_eq(3456u, u2);
- test_eq(1, tor_sscanf("123456", "%8u", &u1));
- test_eq(123456u, u1);
- test_eq(1, tor_sscanf("123457 ", "%8u", &u1));
- test_eq(123457u, u1);
- test_eq(0, tor_sscanf(" 123456", "%8u", &u1));
- test_eq(3, tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3));
- test_eq(12u, u1);
- test_eq(3u, u2);
- test_eq(456u, u3);
- test_eq(3, tor_sscanf("67:8:099", "%2u:%2u:%3u", &u1, &u2, &u3)); /* 0s */
- test_eq(67u, u1);
- test_eq(8u, u2);
- test_eq(99u, u3);
+ tt_int_op(0,OP_EQ, tor_sscanf("-1", "%2u", &u1));
+ tt_int_op(2,OP_EQ, tor_sscanf("123456", "%2u%u", &u1, &u2));
+ tt_int_op(12u,OP_EQ, u1);
+ tt_int_op(3456u,OP_EQ, u2);
+ tt_int_op(1,OP_EQ, tor_sscanf("123456", "%8u", &u1));
+ tt_int_op(123456u,OP_EQ, u1);
+ tt_int_op(1,OP_EQ, tor_sscanf("123457 ", "%8u", &u1));
+ tt_int_op(123457u,OP_EQ, u1);
+ tt_int_op(0,OP_EQ, tor_sscanf(" 123456", "%8u", &u1));
+ tt_int_op(3,OP_EQ, tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3));
+ tt_int_op(12u,OP_EQ, u1);
+ tt_int_op(3u,OP_EQ, u2);
+ tt_int_op(456u,OP_EQ, u3);
+ tt_int_op(3,OP_EQ,
+ tor_sscanf("67:8:099", "%2u:%2u:%3u", &u1, &u2, &u3)); /* 0s */
+ tt_int_op(67u,OP_EQ, u1);
+ tt_int_op(8u,OP_EQ, u2);
+ tt_int_op(99u,OP_EQ, u3);
/* %u does not match space.*/
- test_eq(2, tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3));
- test_eq(12u, u1);
- test_eq(3u, u2);
+ tt_int_op(2,OP_EQ, tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3));
+ tt_int_op(12u,OP_EQ, u1);
+ tt_int_op(3u,OP_EQ, u2);
/* %u does not match negative numbers. */
- test_eq(2, tor_sscanf("67:8:-9", "%2u:%2u:%3u", &u1, &u2, &u3));
- test_eq(67u, u1);
- test_eq(8u, u2);
+ tt_int_op(2,OP_EQ, tor_sscanf("67:8:-9", "%2u:%2u:%3u", &u1, &u2, &u3));
+ tt_int_op(67u,OP_EQ, u1);
+ tt_int_op(8u,OP_EQ, u2);
/* Arbitrary amounts of 0-padding are okay */
- test_eq(3, tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u",
+ tt_int_op(3,OP_EQ, tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u",
&u1, &u2, &u3));
- test_eq(12u, u1);
- test_eq(3u, u2);
- test_eq(99u, u3);
+ tt_int_op(12u,OP_EQ, u1);
+ tt_int_op(3u,OP_EQ, u2);
+ tt_int_op(99u,OP_EQ, u3);
/* Hex (ie. %x) */
- test_eq(3, tor_sscanf("1234 02aBcdEf ff", "%x %x %x", &u1, &u2, &u3));
- test_eq(0x1234, u1);
- test_eq(0x2ABCDEF, u2);
- test_eq(0xFF, u3);
+ tt_int_op(3,OP_EQ,
+ tor_sscanf("1234 02aBcdEf ff", "%x %x %x", &u1, &u2, &u3));
+ tt_int_op(0x1234,OP_EQ, u1);
+ tt_int_op(0x2ABCDEF,OP_EQ, u2);
+ tt_int_op(0xFF,OP_EQ, u3);
/* Width works on %x */
- test_eq(3, tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3));
- test_eq(0xf00d, u1);
- test_eq(0xcafe, u2);
- test_eq(444, u3);
+ tt_int_op(3,OP_EQ, tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3));
+ tt_int_op(0xf00d,OP_EQ, u1);
+ tt_int_op(0xcafe,OP_EQ, u2);
+ tt_int_op(444,OP_EQ, u3);
/* Literal '%' (ie. '%%') */
- test_eq(1, tor_sscanf("99% fresh", "%3u%% fresh", &u1));
- test_eq(99, u1);
- test_eq(0, tor_sscanf("99 fresh", "%% %3u %s", &u1, s1));
- test_eq(1, tor_sscanf("99 fresh", "%3u%% %s", &u1, s1));
- test_eq(2, tor_sscanf("99 fresh", "%3u %5s %%", &u1, s1));
- test_eq(99, u1);
- test_streq(s1, "fresh");
- test_eq(1, tor_sscanf("% boo", "%% %3s", s1));
- test_streq("boo", s1);
+ tt_int_op(1,OP_EQ, tor_sscanf("99% fresh", "%3u%% fresh", &u1));
+ tt_int_op(99,OP_EQ, u1);
+ tt_int_op(0,OP_EQ, tor_sscanf("99 fresh", "%% %3u %s", &u1, s1));
+ tt_int_op(1,OP_EQ, tor_sscanf("99 fresh", "%3u%% %s", &u1, s1));
+ tt_int_op(2,OP_EQ, tor_sscanf("99 fresh", "%3u %5s %%", &u1, s1));
+ tt_int_op(99,OP_EQ, u1);
+ tt_str_op(s1,OP_EQ, "fresh");
+ tt_int_op(1,OP_EQ, tor_sscanf("% boo", "%% %3s", s1));
+ tt_str_op("boo",OP_EQ, s1);
/* Strings (ie. %s) */
- test_eq(2, tor_sscanf("hello", "%3s%7s", s1, s2));
- test_streq(s1, "hel");
- test_streq(s2, "lo");
- test_eq(2, tor_sscanf("WD40", "%2s%u", s3, &u1)); /* %s%u */
- test_streq(s3, "WD");
- test_eq(40, u1);
- test_eq(2, tor_sscanf("WD40", "%3s%u", s3, &u1)); /* %s%u */
- test_streq(s3, "WD4");
- test_eq(0, u1);
- test_eq(2, tor_sscanf("76trombones", "%6u%9s", &u1, s1)); /* %u%s */
- test_eq(76, u1);
- test_streq(s1, "trombones");
- test_eq(1, tor_sscanf("prettylongstring", "%999s", s1));
- test_streq(s1, "prettylongstring");
+ tt_int_op(2,OP_EQ, tor_sscanf("hello", "%3s%7s", s1, s2));
+ tt_str_op(s1,OP_EQ, "hel");
+ tt_str_op(s2,OP_EQ, "lo");
+ tt_int_op(2,OP_EQ, tor_sscanf("WD40", "%2s%u", s3, &u1)); /* %s%u */
+ tt_str_op(s3,OP_EQ, "WD");
+ tt_int_op(40,OP_EQ, u1);
+ tt_int_op(2,OP_EQ, tor_sscanf("WD40", "%3s%u", s3, &u1)); /* %s%u */
+ tt_str_op(s3,OP_EQ, "WD4");
+ tt_int_op(0,OP_EQ, u1);
+ tt_int_op(2,OP_EQ, tor_sscanf("76trombones", "%6u%9s", &u1, s1)); /* %u%s */
+ tt_int_op(76,OP_EQ, u1);
+ tt_str_op(s1,OP_EQ, "trombones");
+ tt_int_op(1,OP_EQ, tor_sscanf("prettylongstring", "%999s", s1));
+ tt_str_op(s1,OP_EQ, "prettylongstring");
/* %s doesn't eat spaces */
- test_eq(2, tor_sscanf("hello world", "%9s %9s", s1, s2));
- test_streq(s1, "hello");
- test_streq(s2, "world");
- test_eq(2, tor_sscanf("bye world?", "%9s %9s", s1, s2));
- test_streq(s1, "bye");
- test_streq(s2, "");
- test_eq(3, tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3)); /* %s can be empty. */
- test_streq(s1, "hi");
- test_streq(s2, "");
- test_streq(s3, "");
-
- test_eq(3, tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
- test_eq(4, tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
- test_eq(' ', ch);
+ tt_int_op(2,OP_EQ, tor_sscanf("hello world", "%9s %9s", s1, s2));
+ tt_str_op(s1,OP_EQ, "hello");
+ tt_str_op(s2,OP_EQ, "world");
+ tt_int_op(2,OP_EQ, tor_sscanf("bye world?", "%9s %9s", s1, s2));
+ tt_str_op(s1,OP_EQ, "bye");
+ tt_str_op(s2,OP_EQ, "");
+ tt_int_op(3,OP_EQ,
+ tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3)); /* %s can be empty. */
+ tt_str_op(s1,OP_EQ, "hi");
+ tt_str_op(s2,OP_EQ, "");
+ tt_str_op(s3,OP_EQ, "");
+
+ tt_int_op(3,OP_EQ, tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
+ tt_int_op(4,OP_EQ,
+ tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
+ tt_int_op(' ',OP_EQ, ch);
r = tor_sscanf("12345 -67890 -1", "%d %ld %d", &int1, &lng1, &int2);
- test_eq(r,3);
- test_eq(int1, 12345);
- test_eq(lng1, -67890);
- test_eq(int2, -1);
+ tt_int_op(r,OP_EQ, 3);
+ tt_int_op(int1,OP_EQ, 12345);
+ tt_int_op(lng1,OP_EQ, -67890);
+ tt_int_op(int2,OP_EQ, -1);
#if SIZEOF_INT == 4
+ /* %u */
+ /* UINT32_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("4294967295", "%u", &u1));
+ tt_int_op(4294967295U,OP_EQ, u1);
+
+ /* But UINT32_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("4294967296", "%u", &u1));
+ /* but parsing only 9... */
+ tt_int_op(1,OP_EQ, tor_sscanf("4294967296", "%9u", &u1));
+ tt_int_op(429496729U,OP_EQ, u1);
+
+ /* %x */
+ /* UINT32_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFF", "%x", &u1));
+ tt_int_op(0xFFFFFFFF,OP_EQ, u1);
+
+ /* But UINT32_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("100000000", "%x", &u1));
+
+ /* %d */
+ /* INT32_MIN and INT32_MAX should work */
r = tor_sscanf("-2147483648. 2147483647.", "%d. %d.", &int1, &int2);
- test_eq(r,2);
- test_eq(int1, -2147483647-1);
- test_eq(int2, 2147483647);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(int1,OP_EQ, -2147483647 - 1);
+ tt_int_op(int2,OP_EQ, 2147483647);
+
+ /* But INT32_MIN - 1 and INT32_MAX + 1 shouldn't work */
+ r = tor_sscanf("-2147483649.", "%d.", &int1);
+ tt_int_op(r,OP_EQ, 0);
- r = tor_sscanf("-2147483679.", "%d.", &int1);
- test_eq(r,0);
+ r = tor_sscanf("2147483648.", "%d.", &int1);
+ tt_int_op(r,OP_EQ, 0);
+
+ /* and the first failure stops further processing */
+ r = tor_sscanf("-2147483648. 2147483648.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 1);
+
+ r = tor_sscanf("-2147483649. 2147483647.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 0);
- r = tor_sscanf("2147483678.", "%d.", &int1);
- test_eq(r,0);
+ r = tor_sscanf("2147483648. -2147483649.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 0);
#elif SIZEOF_INT == 8
+ /* %u */
+ /* UINT64_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551615", "%u", &u1));
+ tt_int_op(18446744073709551615U,OP_EQ, u1);
+
+ /* But UINT64_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("18446744073709551616", "%u", &u1));
+ /* but parsing only 19... */
+ tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551616", "%19u", &u1));
+ tt_int_op(1844674407370955161U,OP_EQ, u1);
+
+ /* %x */
+ /* UINT64_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFFFFFFFFFF", "%x", &u1));
+ tt_int_op(0xFFFFFFFFFFFFFFFF,OP_EQ, u1);
+
+ /* But UINT64_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("10000000000000000", "%x", &u1));
+
+ /* %d */
+ /* INT64_MIN and INT64_MAX should work */
r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
"%d. %d.", &int1, &int2);
- test_eq(r,2);
- test_eq(int1, -9223372036854775807-1);
- test_eq(int2, 9223372036854775807);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(int1,OP_EQ, -9223372036854775807 - 1);
+ tt_int_op(int2,OP_EQ, 9223372036854775807);
+ /* But INT64_MIN - 1 and INT64_MAX + 1 shouldn't work */
r = tor_sscanf("-9223372036854775809.", "%d.", &int1);
- test_eq(r,0);
+ tt_int_op(r,OP_EQ, 0);
r = tor_sscanf("9223372036854775808.", "%d.", &int1);
- test_eq(r,0);
+ tt_int_op(r,OP_EQ, 0);
+
+ /* and the first failure stops further processing */
+ r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 1);
+
+ r = tor_sscanf("-9223372036854775809. 9223372036854775807.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 0);
+
+ r = tor_sscanf("9223372036854775808. -9223372036854775809.",
+ "%d. %d.", &int1, &int2);
+ tt_int_op(r,OP_EQ, 0);
#endif
#if SIZEOF_LONG == 4
+ /* %lu */
+ /* UINT32_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("4294967295", "%lu", &ulng));
+ tt_int_op(4294967295UL,OP_EQ, ulng);
+
+ /* But UINT32_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("4294967296", "%lu", &ulng));
+ /* but parsing only 9... */
+ tt_int_op(1,OP_EQ, tor_sscanf("4294967296", "%9lu", &ulng));
+ tt_int_op(429496729UL,OP_EQ, ulng);
+
+ /* %lx */
+ /* UINT32_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFF", "%lx", &ulng));
+ tt_int_op(0xFFFFFFFFUL,OP_EQ, ulng);
+
+ /* But UINT32_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("100000000", "%lx", &ulng));
+
+ /* %ld */
+ /* INT32_MIN and INT32_MAX should work */
r = tor_sscanf("-2147483648. 2147483647.", "%ld. %ld.", &lng1, &lng2);
- test_eq(r,2);
- test_eq(lng1, -2147483647 - 1);
- test_eq(lng2, 2147483647);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(lng1,OP_EQ, -2147483647L - 1L);
+ tt_int_op(lng2,OP_EQ, 2147483647L);
+
+ /* But INT32_MIN - 1 and INT32_MAX + 1 shouldn't work */
+ r = tor_sscanf("-2147483649.", "%ld.", &lng1);
+ tt_int_op(r,OP_EQ, 0);
+
+ r = tor_sscanf("2147483648.", "%ld.", &lng1);
+ tt_int_op(r,OP_EQ, 0);
+
+ /* and the first failure stops further processing */
+ r = tor_sscanf("-2147483648. 2147483648.",
+ "%ld. %ld.", &lng1, &lng2);
+ tt_int_op(r,OP_EQ, 1);
+
+ r = tor_sscanf("-2147483649. 2147483647.",
+ "%ld. %ld.", &lng1, &lng2);
+ tt_int_op(r,OP_EQ, 0);
+
+ r = tor_sscanf("2147483648. -2147483649.",
+ "%ld. %ld.", &lng1, &lng2);
+ tt_int_op(r,OP_EQ, 0);
#elif SIZEOF_LONG == 8
+ /* %lu */
+ /* UINT64_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551615", "%lu", &ulng));
+ tt_int_op(18446744073709551615UL,OP_EQ, ulng);
+
+ /* But UINT64_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("18446744073709551616", "%lu", &ulng));
+ /* but parsing only 19... */
+ tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551616", "%19lu", &ulng));
+ tt_int_op(1844674407370955161UL,OP_EQ, ulng);
+
+ /* %lx */
+ /* UINT64_MAX should work */
+ tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFFFFFFFFFF", "%lx", &ulng));
+ tt_int_op(0xFFFFFFFFFFFFFFFFUL,OP_EQ, ulng);
+
+ /* But UINT64_MAX + 1 shouldn't work */
+ tt_int_op(0,OP_EQ, tor_sscanf("10000000000000000", "%lx", &ulng));
+
+ /* %ld */
+ /* INT64_MIN and INT64_MAX should work */
r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
"%ld. %ld.", &lng1, &lng2);
- test_eq(r,2);
- test_eq(lng1, -9223372036854775807L - 1);
- test_eq(lng2, 9223372036854775807L);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(lng1,OP_EQ, -9223372036854775807L - 1L);
+ tt_int_op(lng2,OP_EQ, 9223372036854775807L);
+ /* But INT64_MIN - 1 and INT64_MAX + 1 shouldn't work */
+ r = tor_sscanf("-9223372036854775809.", "%ld.", &lng1);
+ tt_int_op(r,OP_EQ, 0);
+
+ r = tor_sscanf("9223372036854775808.", "%ld.", &lng1);
+ tt_int_op(r,OP_EQ, 0);
+
+ /* and the first failure stops further processing */
r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
"%ld. %ld.", &lng1, &lng2);
- test_eq(r,1);
- r = tor_sscanf("-9223372036854775809. 9223372036854775808.",
+ tt_int_op(r,OP_EQ, 1);
+
+ r = tor_sscanf("-9223372036854775809. 9223372036854775807.",
+ "%ld. %ld.", &lng1, &lng2);
+ tt_int_op(r,OP_EQ, 0);
+
+ r = tor_sscanf("9223372036854775808. -9223372036854775809.",
"%ld. %ld.", &lng1, &lng2);
- test_eq(r,0);
+ tt_int_op(r,OP_EQ, 0);
#endif
r = tor_sscanf("123.456 .000007 -900123123.2000787 00003.2",
"%lf %lf %lf %lf", &d1,&d2,&d3,&d4);
- test_eq(r,4);
+ tt_int_op(r,OP_EQ, 4);
test_feq(d1, 123.456);
test_feq(d2, .000007);
test_feq(d3, -900123123.2000787);
@@ -1868,137 +2296,509 @@ test_util_sscanf(void)
;
}
+#define tt_char_op(a,op,b) tt_assert_op_type(a,op,b,char,"%c")
+#define tt_ci_char_op(a,op,b) \
+ tt_char_op(TOR_TOLOWER((int)a),op,TOR_TOLOWER((int)b))
+
+#ifndef HAVE_STRNLEN
+static size_t
+strnlen(const char *s, size_t len)
+{
+ const char *p = memchr(s, 0, len);
+ if (!p)
+ return len;
+ return p - s;
+}
+#endif
+
static void
-test_util_path_is_relative(void)
+test_util_format_time_interval(void *arg)
{
- /* OS-independent tests */
- test_eq(1, path_is_relative(""));
- test_eq(1, path_is_relative("dir"));
- test_eq(1, path_is_relative("dir/"));
- test_eq(1, path_is_relative("./dir"));
- test_eq(1, path_is_relative("../dir"));
+ /* use the same sized buffer and integers as tor uses */
+#define DBUF_SIZE 64
+ char dbuf[DBUF_SIZE];
+#define T_ "%ld"
+ long sec, min, hour, day;
+
+ /* we don't care about the exact spelling of the
+ * second(s), minute(s), hour(s), day(s) labels */
+#define LABEL_SIZE 21
+#define L_ "%20s"
+ char label_s[LABEL_SIZE];
+ char label_m[LABEL_SIZE];
+ char label_h[LABEL_SIZE];
+ char label_d[LABEL_SIZE];
+
+#define TL_ T_ " " L_
- test_eq(0, path_is_relative("/"));
- test_eq(0, path_is_relative("/dir"));
- test_eq(0, path_is_relative("/dir/"));
+ int r;
+
+ (void)arg;
+
+ /* In these tests, we're not picky about
+ * spelling or abbreviations */
+
+ /* seconds: 0, 1, 9, 10, 59 */
+
+ /* ignore exact spelling of "second(s)"*/
+ format_time_interval(dbuf, sizeof(dbuf), 0);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 0);
+
+ format_time_interval(dbuf, sizeof(dbuf), 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 1);
+
+ format_time_interval(dbuf, sizeof(dbuf), 10);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 10);
+
+ format_time_interval(dbuf, sizeof(dbuf), 59);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 59);
+
+ /* negative seconds are reported as their absolute value */
+
+ format_time_interval(dbuf, sizeof(dbuf), -4);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 4);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+
+ format_time_interval(dbuf, sizeof(dbuf), -32);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &sec, label_s);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(sec,OP_EQ, 32);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+
+ /* minutes: 1:00, 1:01, 1:59, 2:00, 2:01, 59:59 */
+
+ /* ignore trailing "0 second(s)", if present */
+ format_time_interval(dbuf, sizeof(dbuf), 60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &min, label_m);
+ tt_int_op(r,OP_EQ, 2);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(min,OP_EQ, 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+
+ /* ignore exact spelling of "minute(s)," and "second(s)" */
+ format_time_interval(dbuf, sizeof(dbuf), 60 + 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 1);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 1);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+
+ format_time_interval(dbuf, sizeof(dbuf), 60*2 - 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 1);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 59);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+
+ /* ignore trailing "0 second(s)", if present */
+ format_time_interval(dbuf, sizeof(dbuf), 60*2);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &min, label_m);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(min,OP_EQ, 2);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* ignore exact spelling of "minute(s)," and "second(s)" */
+ format_time_interval(dbuf, sizeof(dbuf), 60*2 + 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 2);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 1);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+
+ format_time_interval(dbuf, sizeof(dbuf), 60*60 - 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 59);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 59);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+
+ /* negative minutes are reported as their absolute value */
+
+ /* ignore trailing "0 second(s)", if present */
+ format_time_interval(dbuf, sizeof(dbuf), -3*60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &min, label_m);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(min,OP_EQ, 3);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* ignore exact spelling of "minute(s)," and "second(s)" */
+ format_time_interval(dbuf, sizeof(dbuf), -96);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 1);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 36);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+
+ format_time_interval(dbuf, sizeof(dbuf), -2815);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &min, label_m, &sec, label_s);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(min,OP_EQ, 46);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ tt_int_op(sec,OP_EQ, 55);
+ tt_ci_char_op(label_s[0],OP_EQ, 's');
+
+ /* hours: 1:00, 1:00:01, 1:01, 23:59, 23:59:59 */
+ /* always ignore trailing seconds, if present */
+
+ /* ignore trailing "0 minute(s)" etc., if present */
+ format_time_interval(dbuf, sizeof(dbuf), 60*60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &hour, label_h);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(hour,OP_EQ, 1);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+
+ format_time_interval(dbuf, sizeof(dbuf), 60*60 + 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &hour, label_h);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(hour,OP_EQ, 1);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+
+ /* ignore exact spelling of "hour(s)," etc. */
+ format_time_interval(dbuf, sizeof(dbuf), 60*60 + 60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(hour,OP_EQ, 1);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 1);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60 - 60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(hour,OP_EQ, 23);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 59);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60 - 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(hour,OP_EQ, 23);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 59);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* negative hours are reported as their absolute value */
+
+ /* ignore exact spelling of "hour(s)," etc., if present */
+ format_time_interval(dbuf, sizeof(dbuf), -2*60*60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &hour, label_h);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(hour,OP_EQ, 2);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+
+ format_time_interval(dbuf, sizeof(dbuf), -75804);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(hour,OP_EQ, 21);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 3);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* days: 1:00, 1:00:00:01, 1:00:01, 1:01 */
+ /* always ignore trailing seconds, if present */
+
+ /* ignore trailing "0 hours(s)" etc., if present */
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &day, label_d);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(day,OP_EQ, 1);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 1);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_, &day, label_d);
+ tt_int_op(r,OP_EQ, 2);
+ tt_int_op(day,OP_EQ, 1);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+
+ /* ignore exact spelling of "days(s)," etc. */
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ if (r == -1) {
+ /* ignore 0 hours(s), if present */
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &day, label_d, &min, label_m);
+ }
+ tt_assert(r == 4 || r == 6);
+ tt_int_op(day,OP_EQ, 1);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ if (r == 6) {
+ tt_int_op(hour,OP_EQ, 0);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ }
+ tt_int_op(min,OP_EQ, 1);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* ignore trailing "0 minutes(s)" etc., if present */
+ format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 60*60);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_,
+ &day, label_d, &hour, label_h);
+ tt_int_op(r,OP_EQ, 4);
+ tt_int_op(day,OP_EQ, 1);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 1);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+
+ /* negative days are reported as their absolute value */
+
+ format_time_interval(dbuf, sizeof(dbuf), -21936184);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 253);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 21);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 23);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* periods > 1 year are reported in days (warn?) */
+
+ /* ignore exact spelling of "days(s)," etc., if present */
+ format_time_interval(dbuf, sizeof(dbuf), 758635154);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 8780);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 11);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 59);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+ /* negative periods > 1 year are reported in days (warn?) */
+
+ format_time_interval(dbuf, sizeof(dbuf), -1427014922);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 16516);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 9);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 2);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+
+#if SIZEOF_LONG == 4 || SIZEOF_LONG == 8
+
+ /* We can try INT32_MIN/MAX */
+ /* Always ignore second(s) */
+
+ /* INT32_MAX */
+ format_time_interval(dbuf, sizeof(dbuf), 2147483647);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 24855);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 3);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 14);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ /* and 7 seconds - ignored */
+
+ /* INT32_MIN: check that we get the absolute value of interval,
+ * which doesn't actually fit in int32_t.
+ * We expect INT32_MAX or INT32_MAX + 1 with 64 bit longs */
+ format_time_interval(dbuf, sizeof(dbuf), -2147483647L - 1L);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 24855);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 3);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 14);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ /* and 7 or 8 seconds - ignored */
+
+#endif
+
+#if SIZEOF_LONG == 8
+
+ /* We can try INT64_MIN/MAX */
+ /* Always ignore second(s) */
+
+ /* INT64_MAX */
+ format_time_interval(dbuf, sizeof(dbuf), 9223372036854775807L);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 106751991167300L);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 15);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 30);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ /* and 7 seconds - ignored */
+
+ /* INT64_MIN: check that we get the absolute value of interval,
+ * which doesn't actually fit in int64_t.
+ * We expect INT64_MAX */
+ format_time_interval(dbuf, sizeof(dbuf),
+ -9223372036854775807L - 1L);
+ tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
+ r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
+ &day, label_d, &hour, label_h, &min, label_m);
+ tt_int_op(r,OP_EQ, 6);
+ tt_int_op(day,OP_EQ, 106751991167300L);
+ tt_ci_char_op(label_d[0],OP_EQ, 'd');
+ tt_int_op(hour,OP_EQ, 15);
+ tt_ci_char_op(label_h[0],OP_EQ, 'h');
+ tt_int_op(min,OP_EQ, 30);
+ tt_ci_char_op(label_m[0],OP_EQ, 'm');
+ /* and 7 or 8 seconds - ignored */
- /* Windows */
-#ifdef _WIN32
- /* I don't have Windows so I can't test this, hence the "#ifdef
- 0". These are tests that look useful, so please try to get them
- running and uncomment if it all works as it should */
- test_eq(1, path_is_relative("dir"));
- test_eq(1, path_is_relative("dir\\"));
- test_eq(1, path_is_relative("dir\\a:"));
- test_eq(1, path_is_relative("dir\\a:\\"));
- test_eq(1, path_is_relative("http:\\dir"));
-
- test_eq(0, path_is_relative("\\dir"));
- test_eq(0, path_is_relative("a:\\dir"));
- test_eq(0, path_is_relative("z:\\dir"));
#endif
done:
;
}
-#ifdef ENABLE_MEMPOOLS
+#undef tt_char_op
+#undef tt_ci_char_op
+#undef DBUF_SIZE
+#undef T_
+#undef LABEL_SIZE
+#undef L_
+#undef TL_
-/** Run unittests for memory pool allocator */
static void
-test_util_mempool(void)
+test_util_path_is_relative(void *arg)
{
- mp_pool_t *pool = NULL;
- smartlist_t *allocated = NULL;
- int i;
+ /* OS-independent tests */
+ (void)arg;
+ tt_int_op(1,OP_EQ, path_is_relative(""));
+ tt_int_op(1,OP_EQ, path_is_relative("dir"));
+ tt_int_op(1,OP_EQ, path_is_relative("dir/"));
+ tt_int_op(1,OP_EQ, path_is_relative("./dir"));
+ tt_int_op(1,OP_EQ, path_is_relative("../dir"));
- pool = mp_pool_new(1, 100);
- test_assert(pool);
- test_assert(pool->new_chunk_capacity >= 100);
- test_assert(pool->item_alloc_size >= sizeof(void*)+1);
- mp_pool_destroy(pool);
- pool = NULL;
-
- pool = mp_pool_new(241, 2500);
- test_assert(pool);
- test_assert(pool->new_chunk_capacity >= 10);
- test_assert(pool->item_alloc_size >= sizeof(void*)+241);
- test_eq(pool->item_alloc_size & 0x03, 0);
- test_assert(pool->new_chunk_capacity < 60);
-
- allocated = smartlist_new();
- for (i = 0; i < 20000; ++i) {
- if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
- void *m = mp_pool_get(pool);
- memset(m, 0x09, 241);
- smartlist_add(allocated, m);
- //printf("%d: %p\n", i, m);
- //mp_pool_assert_ok(pool);
- } else {
- int idx = crypto_rand_int(smartlist_len(allocated));
- void *m = smartlist_get(allocated, idx);
- //printf("%d: free %p\n", i, m);
- smartlist_del(allocated, idx);
- mp_pool_release(m);
- //mp_pool_assert_ok(pool);
- }
- if (crypto_rand_int(777)==0)
- mp_pool_clean(pool, 1, 1);
+ tt_int_op(0,OP_EQ, path_is_relative("/"));
+ tt_int_op(0,OP_EQ, path_is_relative("/dir"));
+ tt_int_op(0,OP_EQ, path_is_relative("/dir/"));
- if (i % 777)
- mp_pool_assert_ok(pool);
- }
+ /* Windows */
+#ifdef _WIN32
+ /* I don't have Windows so I can't test this, hence the "#ifdef
+ 0". These are tests that look useful, so please try to get them
+ running and uncomment if it all works as it should */
+ tt_int_op(1,OP_EQ, path_is_relative("dir"));
+ tt_int_op(1,OP_EQ, path_is_relative("dir\\"));
+ tt_int_op(1,OP_EQ, path_is_relative("dir\\a:"));
+ tt_int_op(1,OP_EQ, path_is_relative("dir\\a:\\"));
+ tt_int_op(1,OP_EQ, path_is_relative("http:\\dir"));
+
+ tt_int_op(0,OP_EQ, path_is_relative("\\dir"));
+ tt_int_op(0,OP_EQ, path_is_relative("a:\\dir"));
+ tt_int_op(0,OP_EQ, path_is_relative("z:\\dir"));
+#endif
done:
- if (allocated) {
- SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
- mp_pool_assert_ok(pool);
- mp_pool_clean(pool, 0, 0);
- mp_pool_assert_ok(pool);
- smartlist_free(allocated);
- }
-
- if (pool)
- mp_pool_destroy(pool);
+ ;
}
-#endif /* ENABLE_MEMPOOLS */
-
/** Run unittests for memory area allocator */
static void
-test_util_memarea(void)
+test_util_memarea(void *arg)
{
memarea_t *area = memarea_new();
char *p1, *p2, *p3, *p1_orig;
void *malloced_ptr = NULL;
int i;
- test_assert(area);
+ (void)arg;
+ tt_assert(area);
p1_orig = p1 = memarea_alloc(area,64);
p2 = memarea_alloc_zero(area,52);
p3 = memarea_alloc(area,11);
- test_assert(memarea_owns_ptr(area, p1));
- test_assert(memarea_owns_ptr(area, p2));
- test_assert(memarea_owns_ptr(area, p3));
+ tt_assert(memarea_owns_ptr(area, p1));
+ tt_assert(memarea_owns_ptr(area, p2));
+ tt_assert(memarea_owns_ptr(area, p3));
/* Make sure we left enough space. */
- test_assert(p1+64 <= p2);
- test_assert(p2+52 <= p3);
+ tt_assert(p1+64 <= p2);
+ tt_assert(p2+52 <= p3);
/* Make sure we aligned. */
- test_eq(((uintptr_t)p1) % sizeof(void*), 0);
- test_eq(((uintptr_t)p2) % sizeof(void*), 0);
- test_eq(((uintptr_t)p3) % sizeof(void*), 0);
- test_assert(!memarea_owns_ptr(area, p3+8192));
- test_assert(!memarea_owns_ptr(area, p3+30));
- test_assert(tor_mem_is_zero(p2, 52));
+ tt_int_op(((uintptr_t)p1) % sizeof(void*),OP_EQ, 0);
+ tt_int_op(((uintptr_t)p2) % sizeof(void*),OP_EQ, 0);
+ tt_int_op(((uintptr_t)p3) % sizeof(void*),OP_EQ, 0);
+ tt_assert(!memarea_owns_ptr(area, p3+8192));
+ tt_assert(!memarea_owns_ptr(area, p3+30));
+ tt_assert(tor_mem_is_zero(p2, 52));
/* Make sure we don't overalign. */
p1 = memarea_alloc(area, 1);
p2 = memarea_alloc(area, 1);
- test_eq_ptr(p1+sizeof(void*), p2);
+ tt_ptr_op(p1+sizeof(void*),OP_EQ, p2);
{
malloced_ptr = tor_malloc(64);
- test_assert(!memarea_owns_ptr(area, malloced_ptr));
+ tt_assert(!memarea_owns_ptr(area, malloced_ptr));
tor_free(malloced_ptr);
}
@@ -2007,18 +2807,18 @@ test_util_memarea(void)
malloced_ptr = tor_malloc(64);
crypto_rand((char*)malloced_ptr, 64);
p1 = memarea_memdup(area, malloced_ptr, 64);
- test_assert(p1 != malloced_ptr);
- test_memeq(p1, malloced_ptr, 64);
+ tt_assert(p1 != malloced_ptr);
+ tt_mem_op(p1,OP_EQ, malloced_ptr, 64);
tor_free(malloced_ptr);
}
/* memarea_strdup. */
p1 = memarea_strdup(area,"");
p2 = memarea_strdup(area, "abcd");
- test_assert(p1);
- test_assert(p2);
- test_streq(p1, "");
- test_streq(p2, "abcd");
+ tt_assert(p1);
+ tt_assert(p2);
+ tt_str_op(p1,OP_EQ, "");
+ tt_str_op(p2,OP_EQ, "abcd");
/* memarea_strndup. */
{
@@ -2027,33 +2827,33 @@ test_util_memarea(void)
size_t len = strlen(s);
p1 = memarea_strndup(area, s, 1000);
p2 = memarea_strndup(area, s, 10);
- test_streq(p1, s);
- test_assert(p2 >= p1 + len + 1);
- test_memeq(s, p2, 10);
- test_eq(p2[10], '\0');
+ tt_str_op(p1,OP_EQ, s);
+ tt_assert(p2 >= p1 + len + 1);
+ tt_mem_op(s,OP_EQ, p2, 10);
+ tt_int_op(p2[10],OP_EQ, '\0');
p3 = memarea_strndup(area, s, len);
- test_streq(p3, s);
+ tt_str_op(p3,OP_EQ, s);
p3 = memarea_strndup(area, s, len-1);
- test_memeq(s, p3, len-1);
- test_eq(p3[len-1], '\0');
+ tt_mem_op(s,OP_EQ, p3, len-1);
+ tt_int_op(p3[len-1],OP_EQ, '\0');
}
memarea_clear(area);
p1 = memarea_alloc(area, 1);
- test_eq_ptr(p1, p1_orig);
+ tt_ptr_op(p1,OP_EQ, p1_orig);
memarea_clear(area);
/* Check for running over an area's size. */
for (i = 0; i < 512; ++i) {
p1 = memarea_alloc(area, crypto_rand_int(5)+1);
- test_assert(memarea_owns_ptr(area, p1));
+ tt_assert(memarea_owns_ptr(area, p1));
}
memarea_assert_ok(area);
/* Make sure we can allocate a too-big object. */
p1 = memarea_alloc_zero(area, 9000);
p2 = memarea_alloc_zero(area, 16);
- test_assert(memarea_owns_ptr(area, p1));
- test_assert(memarea_owns_ptr(area, p2));
+ tt_assert(memarea_owns_ptr(area, p1));
+ tt_assert(memarea_owns_ptr(area, p2));
done:
memarea_drop_all(area);
@@ -2063,31 +2863,32 @@ test_util_memarea(void)
/** Run unit tests for utility functions to get file names relative to
* the data directory. */
static void
-test_util_datadir(void)
+test_util_datadir(void *arg)
{
char buf[1024];
char *f = NULL;
char *temp_dir = NULL;
+ (void)arg;
temp_dir = get_datadir_fname(NULL);
f = get_datadir_fname("state");
tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
- test_streq(f, buf);
+ tt_str_op(f,OP_EQ, buf);
tor_free(f);
f = get_datadir_fname2("cache", "thingy");
tor_snprintf(buf, sizeof(buf),
"%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
- test_streq(f, buf);
+ tt_str_op(f,OP_EQ, buf);
tor_free(f);
f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
tor_snprintf(buf, sizeof(buf),
"%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
- test_streq(f, buf);
+ tt_str_op(f,OP_EQ, buf);
tor_free(f);
f = get_datadir_fname_suffix("cache", ".foo");
tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
temp_dir);
- test_streq(f, buf);
+ tt_str_op(f,OP_EQ, buf);
done:
tor_free(f);
@@ -2095,13 +2896,14 @@ test_util_datadir(void)
}
static void
-test_util_strtok(void)
+test_util_strtok(void *arg)
{
char buf[128];
char buf2[128];
int i;
char *cp1, *cp2;
+ (void)arg;
for (i = 0; i < 3; i++) {
const char *pad1="", *pad2="";
switch (i) {
@@ -2118,8 +2920,8 @@ test_util_strtok(void)
}
tor_snprintf(buf, sizeof(buf), "%s", pad1);
tor_snprintf(buf2, sizeof(buf2), "%s", pad2);
- test_assert(NULL == tor_strtok_r_impl(buf, " ", &cp1));
- test_assert(NULL == tor_strtok_r_impl(buf2, ".!..;!", &cp2));
+ tt_assert(NULL == tor_strtok_r_impl(buf, " ", &cp1));
+ tt_assert(NULL == tor_strtok_r_impl(buf2, ".!..;!", &cp2));
tor_snprintf(buf, sizeof(buf),
"%sGraved on the dark in gestures of descent%s", pad1, pad1);
@@ -2127,43 +2929,43 @@ test_util_strtok(void)
"%sthey.seemed;;their!.own;most.perfect;monument%s",pad2,pad2);
/* -- "Year's End", Richard Wilbur */
- test_streq("Graved", tor_strtok_r_impl(buf, " ", &cp1));
- test_streq("they", tor_strtok_r_impl(buf2, ".!..;!", &cp2));
+ tt_str_op("Graved",OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
+ tt_str_op("they",OP_EQ, tor_strtok_r_impl(buf2, ".!..;!", &cp2));
#define S1() tor_strtok_r_impl(NULL, " ", &cp1)
#define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
- test_streq("on", S1());
- test_streq("the", S1());
- test_streq("dark", S1());
- test_streq("seemed", S2());
- test_streq("their", S2());
- test_streq("own", S2());
- test_streq("in", S1());
- test_streq("gestures", S1());
- test_streq("of", S1());
- test_streq("most", S2());
- test_streq("perfect", S2());
- test_streq("descent", S1());
- test_streq("monument", S2());
- test_eq_ptr(NULL, S1());
- test_eq_ptr(NULL, S2());
+ tt_str_op("on",OP_EQ, S1());
+ tt_str_op("the",OP_EQ, S1());
+ tt_str_op("dark",OP_EQ, S1());
+ tt_str_op("seemed",OP_EQ, S2());
+ tt_str_op("their",OP_EQ, S2());
+ tt_str_op("own",OP_EQ, S2());
+ tt_str_op("in",OP_EQ, S1());
+ tt_str_op("gestures",OP_EQ, S1());
+ tt_str_op("of",OP_EQ, S1());
+ tt_str_op("most",OP_EQ, S2());
+ tt_str_op("perfect",OP_EQ, S2());
+ tt_str_op("descent",OP_EQ, S1());
+ tt_str_op("monument",OP_EQ, S2());
+ tt_ptr_op(NULL,OP_EQ, S1());
+ tt_ptr_op(NULL,OP_EQ, S2());
}
buf[0] = 0;
- test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
- test_eq_ptr(NULL, tor_strtok_r_impl(buf, "!", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, "!", &cp1));
strlcpy(buf, "Howdy!", sizeof(buf));
- test_streq("Howdy", tor_strtok_r_impl(buf, "!", &cp1));
- test_eq_ptr(NULL, tor_strtok_r_impl(NULL, "!", &cp1));
+ tt_str_op("Howdy",OP_EQ, tor_strtok_r_impl(buf, "!", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(NULL, "!", &cp1));
strlcpy(buf, " ", sizeof(buf));
- test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
strlcpy(buf, " ", sizeof(buf));
- test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
strlcpy(buf, "something ", sizeof(buf));
- test_streq("something", tor_strtok_r_impl(buf, " ", &cp1));
- test_eq_ptr(NULL, tor_strtok_r_impl(NULL, ";", &cp1));
+ tt_str_op("something",OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
+ tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(NULL, ";", &cp1));
done:
;
}
@@ -2183,23 +2985,26 @@ test_util_find_str_at_start_of_line(void *ptr)
(void)ptr;
- test_eq_ptr(long_string, find_str_at_start_of_line(long_string, ""));
- test_eq_ptr(NULL, find_str_at_start_of_line(short_string, "nonsense"));
- test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "nonsense"));
- test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "\n"));
- test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "how "));
- test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "kitty"));
- test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "h"));
- test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "how"));
- test_eq_ptr(line2, find_str_at_start_of_line(long_string, "he"));
- test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hell"));
- test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello k"));
- test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\n"));
- test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\nt"));
- test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third"));
- test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third line"));
- test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "third line\n"));
- test_eq_ptr(short_line2, find_str_at_start_of_line(short_string,
+ tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, ""));
+ tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(short_string, "nonsense"));
+ tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "nonsense"));
+ tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "\n"));
+ tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "how "));
+ tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "kitty"));
+ tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, "h"));
+ tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, "how"));
+ tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "he"));
+ tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "hell"));
+ tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "hello k"));
+ tt_ptr_op(line2,OP_EQ,
+ find_str_at_start_of_line(long_string, "hello kitty\n"));
+ tt_ptr_op(line2,OP_EQ,
+ find_str_at_start_of_line(long_string, "hello kitty\nt"));
+ tt_ptr_op(line3,OP_EQ, find_str_at_start_of_line(long_string, "third"));
+ tt_ptr_op(line3,OP_EQ, find_str_at_start_of_line(long_string, "third line"));
+ tt_ptr_op(NULL, OP_EQ,
+ find_str_at_start_of_line(long_string, "third line\n"));
+ tt_ptr_op(short_line2,OP_EQ, find_str_at_start_of_line(short_string,
"second line\n"));
done:
;
@@ -2210,25 +3015,25 @@ test_util_string_is_C_identifier(void *ptr)
{
(void)ptr;
- test_eq(1, string_is_C_identifier("string_is_C_identifier"));
- test_eq(1, string_is_C_identifier("_string_is_C_identifier"));
- test_eq(1, string_is_C_identifier("_"));
- test_eq(1, string_is_C_identifier("i"));
- test_eq(1, string_is_C_identifier("_____"));
- test_eq(1, string_is_C_identifier("__00__"));
- test_eq(1, string_is_C_identifier("__init__"));
- test_eq(1, string_is_C_identifier("_0"));
- test_eq(1, string_is_C_identifier("_0string_is_C_identifier"));
- test_eq(1, string_is_C_identifier("_0"));
-
- test_eq(0, string_is_C_identifier("0_string_is_C_identifier"));
- test_eq(0, string_is_C_identifier("0"));
- test_eq(0, string_is_C_identifier(""));
- test_eq(0, string_is_C_identifier(";"));
- test_eq(0, string_is_C_identifier("i;"));
- test_eq(0, string_is_C_identifier("_;"));
- test_eq(0, string_is_C_identifier("í"));
- test_eq(0, string_is_C_identifier("ñ"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("string_is_C_identifier"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_string_is_C_identifier"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("i"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_____"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("__00__"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("__init__"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_0"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_0string_is_C_identifier"));
+ tt_int_op(1,OP_EQ, string_is_C_identifier("_0"));
+
+ tt_int_op(0,OP_EQ, string_is_C_identifier("0_string_is_C_identifier"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier("0"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier(""));
+ tt_int_op(0,OP_EQ, string_is_C_identifier(";"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier("i;"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier("_;"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier("í"));
+ tt_int_op(0,OP_EQ, string_is_C_identifier("ñ"));
done:
;
@@ -2245,48 +3050,48 @@ test_util_asprintf(void *ptr)
/* simple string */
r = tor_asprintf(&cp, "simple string 100%% safe");
- test_assert(cp);
- test_streq("simple string 100% safe", cp);
- test_eq(strlen(cp), r);
+ tt_assert(cp);
+ tt_str_op("simple string 100% safe",OP_EQ, cp);
+ tt_int_op(strlen(cp),OP_EQ, r);
tor_free(cp);
/* empty string */
r = tor_asprintf(&cp, "%s", "");
- test_assert(cp);
- test_streq("", cp);
- test_eq(strlen(cp), r);
+ tt_assert(cp);
+ tt_str_op("",OP_EQ, cp);
+ tt_int_op(strlen(cp),OP_EQ, r);
tor_free(cp);
/* numbers (%i) */
r = tor_asprintf(&cp, "I like numbers-%2i, %i, etc.", -1, 2);
- test_assert(cp);
- test_streq("I like numbers--1, 2, etc.", cp);
- test_eq(strlen(cp), r);
+ tt_assert(cp);
+ tt_str_op("I like numbers--1, 2, etc.",OP_EQ, cp);
+ tt_int_op(strlen(cp),OP_EQ, r);
/* don't free cp; next test uses it. */
/* numbers (%d) */
r = tor_asprintf(&cp2, "First=%d, Second=%d", 101, 202);
- test_assert(cp2);
- test_eq(strlen(cp2), r);
- test_streq("First=101, Second=202", cp2);
- test_assert(cp != cp2);
+ tt_assert(cp2);
+ tt_int_op(strlen(cp2),OP_EQ, r);
+ tt_str_op("First=101, Second=202",OP_EQ, cp2);
+ tt_assert(cp != cp2);
tor_free(cp);
tor_free(cp2);
/* Glass-box test: a string exactly 128 characters long. */
r = tor_asprintf(&cp, "Lorem1: %sLorem2: %s", LOREMIPSUM, LOREMIPSUM);
- test_assert(cp);
- test_eq(128, r);
- test_assert(cp[128] == '\0');
- test_streq("Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM, cp);
+ tt_assert(cp);
+ tt_int_op(128,OP_EQ, r);
+ tt_int_op(cp[128], OP_EQ, '\0');
+ tt_str_op("Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM,OP_EQ, cp);
tor_free(cp);
/* String longer than 128 characters */
r = tor_asprintf(&cp, "1: %s 2: %s 3: %s",
LOREMIPSUM, LOREMIPSUM, LOREMIPSUM);
- test_assert(cp);
- test_eq(strlen(cp), r);
- test_streq("1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM, cp);
+ tt_assert(cp);
+ tt_int_op(strlen(cp),OP_EQ, r);
+ tt_str_op("1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM,OP_EQ, cp);
done:
tor_free(cp);
@@ -2307,9 +3112,9 @@ test_util_listdir(void *ptr)
dir1 = tor_strdup(get_fname("some-directory"));
dirname = tor_strdup(get_fname(NULL));
- test_eq(0, write_str_to_file(fname1, "X\n", 0));
- test_eq(0, write_str_to_file(fname2, "Y\n", 0));
- test_eq(0, write_str_to_file(fname3, "Z\n", 0));
+ tt_int_op(0,OP_EQ, write_str_to_file(fname1, "X\n", 0));
+ tt_int_op(0,OP_EQ, write_str_to_file(fname2, "Y\n", 0));
+ tt_int_op(0,OP_EQ, write_str_to_file(fname3, "Z\n", 0));
#ifdef _WIN32
r = mkdir(dir1);
#else
@@ -2322,15 +3127,15 @@ test_util_listdir(void *ptr)
}
dir_contents = tor_listdir(dirname);
- test_assert(dir_contents);
+ tt_assert(dir_contents);
/* make sure that each filename is listed. */
- test_assert(smartlist_contains_string_case(dir_contents, "hopscotch"));
- test_assert(smartlist_contains_string_case(dir_contents, "mumblety-peg"));
- test_assert(smartlist_contains_string_case(dir_contents, ".hidden-file"));
- test_assert(smartlist_contains_string_case(dir_contents, "some-directory"));
+ tt_assert(smartlist_contains_string_case(dir_contents, "hopscotch"));
+ tt_assert(smartlist_contains_string_case(dir_contents, "mumblety-peg"));
+ tt_assert(smartlist_contains_string_case(dir_contents, ".hidden-file"));
+ tt_assert(smartlist_contains_string_case(dir_contents, "some-directory"));
- test_assert(!smartlist_contains_string(dir_contents, "."));
- test_assert(!smartlist_contains_string(dir_contents, ".."));
+ tt_assert(!smartlist_contains_string(dir_contents, "."));
+ tt_assert(!smartlist_contains_string(dir_contents, ".."));
done:
tor_free(fname1);
@@ -2355,9 +3160,9 @@ test_util_parent_dir(void *ptr)
int ok; \
cp = tor_strdup(input); \
ok = get_parent_directory(cp); \
- tt_int_op(expect_ok, ==, ok); \
+ tt_int_op(expect_ok, OP_EQ, ok); \
if (ok==0) \
- tt_str_op(output, ==, cp); \
+ tt_str_op(output, OP_EQ, cp); \
tor_free(cp); \
} while (0);
@@ -2391,6 +3196,54 @@ test_util_parent_dir(void *ptr)
tor_free(cp);
}
+static void
+test_util_ftruncate(void *ptr)
+{
+ char *buf = NULL;
+ const char *fname;
+ int fd = -1;
+ const char *message = "Hello world";
+ const char *message2 = "Hola mundo";
+ struct stat st;
+
+ (void) ptr;
+
+ fname = get_fname("ftruncate");
+
+ fd = tor_open_cloexec(fname, O_WRONLY|O_CREAT, 0600);
+ tt_int_op(fd, OP_GE, 0);
+
+ /* Make the file be there. */
+ tt_int_op(strlen(message), OP_EQ, write_all(fd, message, strlen(message),0));
+ tt_int_op((int)tor_fd_getpos(fd), OP_EQ, strlen(message));
+ tt_int_op(0, OP_EQ, fstat(fd, &st));
+ tt_int_op((int)st.st_size, OP_EQ, strlen(message));
+
+ /* Truncate and see if it got truncated */
+ tt_int_op(0, OP_EQ, tor_ftruncate(fd));
+ tt_int_op((int)tor_fd_getpos(fd), OP_EQ, 0);
+ tt_int_op(0, OP_EQ, fstat(fd, &st));
+ tt_int_op((int)st.st_size, OP_EQ, 0);
+
+ /* Replace, and see if it got replaced */
+ tt_int_op(strlen(message2), OP_EQ,
+ write_all(fd, message2, strlen(message2), 0));
+ tt_int_op((int)tor_fd_getpos(fd), OP_EQ, strlen(message2));
+ tt_int_op(0, OP_EQ, fstat(fd, &st));
+ tt_int_op((int)st.st_size, OP_EQ, strlen(message2));
+
+ close(fd);
+ fd = -1;
+
+ buf = read_file_to_str(fname, 0, NULL);
+ tt_str_op(message2, OP_EQ, buf);
+
+ done:
+ if (fd >= 0)
+ close(fd);
+ tor_free(buf);
+}
+
#ifdef _WIN32
static void
test_util_load_win_lib(void *ptr)
@@ -2422,30 +3275,53 @@ test_util_exit_status(void *ptr)
(void)ptr;
clear_hex_errno(hex_errno);
+ tt_str_op("",OP_EQ, hex_errno);
+
+ clear_hex_errno(hex_errno);
n = format_helper_exit_status(0, 0, hex_errno);
- test_streq("0/0\n", hex_errno);
- test_eq(n, strlen(hex_errno));
+ tt_str_op("0/0\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
+
+#if SIZEOF_INT == 4
clear_hex_errno(hex_errno);
n = format_helper_exit_status(0, 0x7FFFFFFF, hex_errno);
- test_streq("0/7FFFFFFF\n", hex_errno);
- test_eq(n, strlen(hex_errno));
+ tt_str_op("0/7FFFFFFF\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
clear_hex_errno(hex_errno);
n = format_helper_exit_status(0xFF, -0x80000000, hex_errno);
- test_streq("FF/-80000000\n", hex_errno);
- test_eq(n, strlen(hex_errno));
- test_eq(n, HEX_ERRNO_SIZE);
+ tt_str_op("FF/-80000000\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
+ tt_int_op(n,OP_EQ, HEX_ERRNO_SIZE);
+
+#elif SIZEOF_INT == 8
+
+ clear_hex_errno(hex_errno);
+ n = format_helper_exit_status(0, 0x7FFFFFFFFFFFFFFF, hex_errno);
+ tt_str_op("0/7FFFFFFFFFFFFFFF\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
+
+ clear_hex_errno(hex_errno);
+ n = format_helper_exit_status(0xFF, -0x8000000000000000, hex_errno);
+ tt_str_op("FF/-8000000000000000\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
+ tt_int_op(n,OP_EQ, HEX_ERRNO_SIZE);
+
+#endif
clear_hex_errno(hex_errno);
n = format_helper_exit_status(0x7F, 0, hex_errno);
- test_streq("7F/0\n", hex_errno);
- test_eq(n, strlen(hex_errno));
+ tt_str_op("7F/0\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
clear_hex_errno(hex_errno);
n = format_helper_exit_status(0x08, -0x242, hex_errno);
- test_streq("8/-242\n", hex_errno);
- test_eq(n, strlen(hex_errno));
+ tt_str_op("8/-242\n",OP_EQ, hex_errno);
+ tt_int_op(n,OP_EQ, strlen(hex_errno));
+
+ clear_hex_errno(hex_errno);
+ tt_str_op("",OP_EQ, hex_errno);
done:
;
@@ -2453,8 +3329,9 @@ test_util_exit_status(void *ptr)
#endif
#ifndef _WIN32
-/** Check that fgets waits until a full line, and not return a partial line, on
- * a EAGAIN with a non-blocking pipe */
+/* Check that fgets with a non-blocking pipe returns partial lines and sets
+ * EAGAIN, returns full lines and sets no error, and returns NULL on EOF and
+ * sets no error */
static void
test_util_fgets_eagain(void *ptr)
{
@@ -2463,71 +3340,91 @@ test_util_fgets_eagain(void *ptr)
ssize_t retlen;
char *retptr;
FILE *test_stream = NULL;
- char buf[10];
+ char buf[4] = { 0 };
(void)ptr;
+ errno = 0;
+
/* Set up a pipe to test on */
retval = pipe(test_pipe);
- tt_int_op(retval, >=, 0);
+ tt_int_op(retval, OP_EQ, 0);
/* Set up the read-end to be non-blocking */
retval = fcntl(test_pipe[0], F_SETFL, O_NONBLOCK);
- tt_int_op(retval, >=, 0);
+ tt_int_op(retval, OP_EQ, 0);
/* Open it as a stdio stream */
test_stream = fdopen(test_pipe[0], "r");
- tt_ptr_op(test_stream, !=, NULL);
+ tt_ptr_op(test_stream, OP_NE, NULL);
/* Send in a partial line */
retlen = write(test_pipe[1], "A", 1);
- tt_int_op(retlen, ==, 1);
+ tt_int_op(retlen, OP_EQ, 1);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_want(retptr == NULL);
- tt_int_op(errno, ==, EAGAIN);
+ tt_int_op(errno, OP_EQ, EAGAIN);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "A");
+ errno = 0;
/* Send in the rest */
retlen = write(test_pipe[1], "B\n", 2);
- tt_int_op(retlen, ==, 2);
+ tt_int_op(retlen, OP_EQ, 2);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, buf);
- tt_str_op(buf, ==, "AB\n");
+ tt_int_op(errno, OP_EQ, 0);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "B\n");
+ errno = 0;
/* Send in a full line */
retlen = write(test_pipe[1], "CD\n", 3);
- tt_int_op(retlen, ==, 3);
+ tt_int_op(retlen, OP_EQ, 3);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, buf);
- tt_str_op(buf, ==, "CD\n");
+ tt_int_op(errno, OP_EQ, 0);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "CD\n");
+ errno = 0;
/* Send in a partial line */
retlen = write(test_pipe[1], "E", 1);
- tt_int_op(retlen, ==, 1);
+ tt_int_op(retlen, OP_EQ, 1);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, NULL);
- tt_int_op(errno, ==, EAGAIN);
+ tt_int_op(errno, OP_EQ, EAGAIN);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "E");
+ errno = 0;
/* Send in the rest */
retlen = write(test_pipe[1], "F\n", 2);
- tt_int_op(retlen, ==, 2);
+ tt_int_op(retlen, OP_EQ, 2);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, buf);
- tt_str_op(buf, ==, "EF\n");
+ tt_int_op(errno, OP_EQ, 0);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "F\n");
+ errno = 0;
/* Send in a full line and close */
retlen = write(test_pipe[1], "GH", 2);
- tt_int_op(retlen, ==, 2);
+ tt_int_op(retlen, OP_EQ, 2);
retval = close(test_pipe[1]);
+ tt_int_op(retval, OP_EQ, 0);
test_pipe[1] = -1;
- tt_int_op(retval, ==, 0);
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, buf);
- tt_str_op(buf, ==, "GH");
+ tt_int_op(errno, OP_EQ, 0);
+ tt_ptr_op(retptr, OP_EQ, buf);
+ tt_str_op(buf, OP_EQ, "GH");
+ errno = 0;
/* Check for EOF */
retptr = fgets(buf, sizeof(buf), test_stream);
- tt_ptr_op(retptr, ==, NULL);
- tt_int_op(feof(test_stream), >, 0);
+ tt_int_op(errno, OP_EQ, 0);
+ tt_ptr_op(retptr, OP_EQ, NULL);
+ retval = feof(test_stream);
+ tt_int_op(retval, OP_NE, 0);
+ errno = 0;
+
+ /* Check that buf is unchanged according to C99 and C11 */
+ tt_str_op(buf, OP_EQ, "GH");
done:
if (test_stream != NULL)
@@ -2539,315 +3436,6 @@ test_util_fgets_eagain(void *ptr)
}
#endif
-#ifndef BUILDDIR
-#define BUILDDIR "."
-#endif
-
-#ifdef _WIN32
-#define notify_pending_waitpid_callbacks() STMT_NIL
-#define TEST_CHILD "test-child.exe"
-#define EOL "\r\n"
-#else
-#define TEST_CHILD (BUILDDIR "/src/test/test-child")
-#define EOL "\n"
-#endif
-
-/** Helper function for testing tor_spawn_background */
-static void
-run_util_spawn_background(const char *argv[], const char *expected_out,
- const char *expected_err, int expected_exit,
- int expected_status)
-{
- int retval, exit_code;
- ssize_t pos;
- process_handle_t *process_handle=NULL;
- char stdout_buf[100], stderr_buf[100];
- int status;
-
- /* Start the program */
-#ifdef _WIN32
- status = tor_spawn_background(NULL, argv, NULL, &process_handle);
-#else
- status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
-#endif
-
- notify_pending_waitpid_callbacks();
-
- test_eq(expected_status, status);
- if (status == PROCESS_STATUS_ERROR) {
- tt_ptr_op(process_handle, ==, NULL);
- return;
- }
-
- test_assert(process_handle != NULL);
- test_eq(expected_status, process_handle->status);
-
-#ifndef _WIN32
- notify_pending_waitpid_callbacks();
- tt_ptr_op(process_handle->waitpid_cb, !=, NULL);
-#endif
-
-#ifdef _WIN32
- test_assert(process_handle->stdout_pipe != INVALID_HANDLE_VALUE);
- test_assert(process_handle->stderr_pipe != INVALID_HANDLE_VALUE);
-#else
- test_assert(process_handle->stdout_pipe >= 0);
- test_assert(process_handle->stderr_pipe >= 0);
-#endif
-
- /* Check stdout */
- pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
- sizeof(stdout_buf) - 1);
- tt_assert(pos >= 0);
- stdout_buf[pos] = '\0';
- test_eq(strlen(expected_out), pos);
- test_streq(expected_out, stdout_buf);
-
- notify_pending_waitpid_callbacks();
-
- /* Check it terminated correctly */
- retval = tor_get_exit_code(process_handle, 1, &exit_code);
- test_eq(PROCESS_EXIT_EXITED, retval);
- test_eq(expected_exit, exit_code);
- // TODO: Make test-child exit with something other than 0
-
-#ifndef _WIN32
- notify_pending_waitpid_callbacks();
- tt_ptr_op(process_handle->waitpid_cb, ==, NULL);
-#endif
-
- /* Check stderr */
- pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
- sizeof(stderr_buf) - 1);
- test_assert(pos >= 0);
- stderr_buf[pos] = '\0';
- test_streq(expected_err, stderr_buf);
- test_eq(strlen(expected_err), pos);
-
- notify_pending_waitpid_callbacks();
-
- done:
- if (process_handle)
- tor_process_handle_destroy(process_handle, 1);
-}
-
-/** Check that we can launch a process and read the output */
-static void
-test_util_spawn_background_ok(void *ptr)
-{
- const char *argv[] = {TEST_CHILD, "--test", NULL};
- const char *expected_out = "OUT"EOL "--test"EOL "SLEEPING"EOL "DONE" EOL;
- const char *expected_err = "ERR"EOL;
-
- (void)ptr;
-
- run_util_spawn_background(argv, expected_out, expected_err, 0,
- PROCESS_STATUS_RUNNING);
-}
-
-/** Check that failing to find the executable works as expected */
-static void
-test_util_spawn_background_fail(void *ptr)
-{
- const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
- const char *expected_err = "";
- char expected_out[1024];
- char code[32];
-#ifdef _WIN32
- const int expected_status = PROCESS_STATUS_ERROR;
-#else
- /* TODO: Once we can signal failure to exec, set this to be
- * PROCESS_STATUS_ERROR */
- const int expected_status = PROCESS_STATUS_RUNNING;
-#endif
-
- (void)ptr;
-
- tor_snprintf(code, sizeof(code), "%x/%x",
- 9 /* CHILD_STATE_FAILEXEC */ , ENOENT);
- tor_snprintf(expected_out, sizeof(expected_out),
- "ERR: Failed to spawn background process - code %s\n", code);
-
- run_util_spawn_background(argv, expected_out, expected_err, 255,
- expected_status);
-}
-
-/** Test that reading from a handle returns a partial read rather than
- * blocking */
-static void
-test_util_spawn_background_partial_read_impl(int exit_early)
-{
- const int expected_exit = 0;
- const int expected_status = PROCESS_STATUS_RUNNING;
-
- int retval, exit_code;
- ssize_t pos = -1;
- process_handle_t *process_handle=NULL;
- int status;
- char stdout_buf[100], stderr_buf[100];
-
- const char *argv[] = {TEST_CHILD, "--test", NULL};
- const char *expected_out[] = { "OUT" EOL "--test" EOL "SLEEPING" EOL,
- "DONE" EOL,
- NULL };
- const char *expected_err = "ERR" EOL;
-
-#ifndef _WIN32
- int eof = 0;
-#endif
- int expected_out_ctr;
-
- if (exit_early) {
- argv[1] = "--hang";
- expected_out[0] = "OUT"EOL "--hang"EOL "SLEEPING" EOL;
- }
-
- /* Start the program */
-#ifdef _WIN32
- status = tor_spawn_background(NULL, argv, NULL, &process_handle);
-#else
- status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
-#endif
- test_eq(expected_status, status);
- test_assert(process_handle);
- test_eq(expected_status, process_handle->status);
-
- /* Check stdout */
- for (expected_out_ctr = 0; expected_out[expected_out_ctr] != NULL;) {
-#ifdef _WIN32
- pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
- sizeof(stdout_buf) - 1, NULL);
-#else
- /* Check that we didn't read the end of file last time */
- test_assert(!eof);
- pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
- sizeof(stdout_buf) - 1, NULL, &eof);
-#endif
- log_info(LD_GENERAL, "tor_read_all_handle() returned %d", (int)pos);
-
- /* We would have blocked, keep on trying */
- if (0 == pos)
- continue;
-
- test_assert(pos > 0);
- stdout_buf[pos] = '\0';
- test_streq(expected_out[expected_out_ctr], stdout_buf);
- test_eq(strlen(expected_out[expected_out_ctr]), pos);
- expected_out_ctr++;
- }
-
- if (exit_early) {
- tor_process_handle_destroy(process_handle, 1);
- process_handle = NULL;
- goto done;
- }
-
- /* The process should have exited without writing more */
-#ifdef _WIN32
- pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
- sizeof(stdout_buf) - 1,
- process_handle);
- test_eq(0, pos);
-#else
- if (!eof) {
- /* We should have got all the data, but maybe not the EOF flag */
- pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
- sizeof(stdout_buf) - 1,
- process_handle, &eof);
- test_eq(0, pos);
- test_assert(eof);
- }
- /* Otherwise, we got the EOF on the last read */
-#endif
-
- /* Check it terminated correctly */
- retval = tor_get_exit_code(process_handle, 1, &exit_code);
- test_eq(PROCESS_EXIT_EXITED, retval);
- test_eq(expected_exit, exit_code);
-
- // TODO: Make test-child exit with something other than 0
-
- /* Check stderr */
- pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
- sizeof(stderr_buf) - 1);
- test_assert(pos >= 0);
- stderr_buf[pos] = '\0';
- test_streq(expected_err, stderr_buf);
- test_eq(strlen(expected_err), pos);
-
- done:
- tor_process_handle_destroy(process_handle, 1);
-}
-
-static void
-test_util_spawn_background_partial_read(void *arg)
-{
- (void)arg;
- test_util_spawn_background_partial_read_impl(0);
-}
-
-static void
-test_util_spawn_background_exit_early(void *arg)
-{
- (void)arg;
- test_util_spawn_background_partial_read_impl(1);
-}
-
-static void
-test_util_spawn_background_waitpid_notify(void *arg)
-{
- int retval, exit_code;
- process_handle_t *process_handle=NULL;
- int status;
- int ms_timer;
-
- const char *argv[] = {TEST_CHILD, "--fast", NULL};
-
- (void) arg;
-
-#ifdef _WIN32
- status = tor_spawn_background(NULL, argv, NULL, &process_handle);
-#else
- status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
-#endif
-
- tt_int_op(status, ==, PROCESS_STATUS_RUNNING);
- tt_ptr_op(process_handle, !=, NULL);
-
- /* We're not going to look at the stdout/stderr output this time. Instead,
- * we're testing whether notify_pending_waitpid_calbacks() can report the
- * process exit (on unix) and/or whether tor_get_exit_code() can notice it
- * (on windows) */
-
-#ifndef _WIN32
- ms_timer = 30*1000;
- tt_ptr_op(process_handle->waitpid_cb, !=, NULL);
- while (process_handle->waitpid_cb && ms_timer > 0) {
- tor_sleep_msec(100);
- ms_timer -= 100;
- notify_pending_waitpid_callbacks();
- }
- tt_int_op(ms_timer, >, 0);
- tt_ptr_op(process_handle->waitpid_cb, ==, NULL);
-#endif
-
- ms_timer = 30*1000;
- while (((retval = tor_get_exit_code(process_handle, 0, &exit_code))
- == PROCESS_EXIT_RUNNING) && ms_timer > 0) {
- tor_sleep_msec(100);
- ms_timer -= 100;
- }
- tt_int_op(ms_timer, >, 0);
-
- tt_int_op(retval, ==, PROCESS_EXIT_EXITED);
-
- done:
- tor_process_handle_destroy(process_handle, 1);
-}
-
-#undef TEST_CHILD
-#undef EOL
-
/**
* Test for format_hex_number_sigsafe()
*/
@@ -2878,15 +3466,15 @@ test_util_format_hex_number(void *ptr)
for (i = 0; test_data[i].str != NULL; ++i) {
len = format_hex_number_sigsafe(test_data[i].x, buf, sizeof(buf));
- test_neq(len, 0);
- test_eq(len, strlen(buf));
- test_streq(buf, test_data[i].str);
+ tt_int_op(len,OP_NE, 0);
+ tt_int_op(len,OP_EQ, strlen(buf));
+ tt_str_op(buf,OP_EQ, test_data[i].str);
}
- test_eq(4, format_hex_number_sigsafe(0xffff, buf, 5));
- test_streq(buf, "FFFF");
- test_eq(0, format_hex_number_sigsafe(0xffff, buf, 4));
- test_eq(0, format_hex_number_sigsafe(0, buf, 1));
+ tt_int_op(4,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 5));
+ tt_str_op(buf,OP_EQ, "FFFF");
+ tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 4));
+ tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0, buf, 1));
done:
return;
@@ -2922,21 +3510,21 @@ test_util_format_dec_number(void *ptr)
for (i = 0; test_data[i].str != NULL; ++i) {
len = format_dec_number_sigsafe(test_data[i].x, buf, sizeof(buf));
- test_neq(len, 0);
- test_eq(len, strlen(buf));
- test_streq(buf, test_data[i].str);
+ tt_int_op(len,OP_NE, 0);
+ tt_int_op(len,OP_EQ, strlen(buf));
+ tt_str_op(buf,OP_EQ, test_data[i].str);
len = format_dec_number_sigsafe(test_data[i].x, buf,
(int)(strlen(test_data[i].str) + 1));
- test_eq(len, strlen(buf));
- test_streq(buf, test_data[i].str);
+ tt_int_op(len,OP_EQ, strlen(buf));
+ tt_str_op(buf,OP_EQ, test_data[i].str);
}
- test_eq(4, format_dec_number_sigsafe(7331, buf, 5));
- test_streq(buf, "7331");
- test_eq(0, format_dec_number_sigsafe(7331, buf, 4));
- test_eq(1, format_dec_number_sigsafe(0, buf, 2));
- test_eq(0, format_dec_number_sigsafe(0, buf, 1));
+ tt_int_op(4,OP_EQ, format_dec_number_sigsafe(7331, buf, 5));
+ tt_str_op(buf,OP_EQ, "7331");
+ tt_int_op(0,OP_EQ, format_dec_number_sigsafe(7331, buf, 4));
+ tt_int_op(1,OP_EQ, format_dec_number_sigsafe(0, buf, 2));
+ tt_int_op(0,OP_EQ, format_dec_number_sigsafe(0, buf, 1));
done:
return;
@@ -2985,7 +3573,7 @@ test_util_join_win_cmdline(void *ptr)
for (i=0; cmdlines[i]!=NULL; i++) {
log_info(LD_GENERAL, "Joining argvs[%d], expecting <%s>", i, cmdlines[i]);
joined_argv = tor_join_win_cmdline(argvs[i]);
- test_streq(cmdlines[i], joined_argv);
+ tt_str_op(cmdlines[i],OP_EQ, joined_argv);
tor_free(joined_argv);
}
@@ -3040,17 +3628,17 @@ test_util_split_lines(void *ptr)
i, tests[i].orig_length);
SMARTLIST_FOREACH_BEGIN(sl, const char *, line) {
/* Check we have not got too many lines */
- test_assert(j < MAX_SPLIT_LINE_COUNT);
+ tt_int_op(MAX_SPLIT_LINE_COUNT, OP_GT, j);
/* Check that there actually should be a line here */
- test_assert(tests[i].split_line[j] != NULL);
+ tt_assert(tests[i].split_line[j] != NULL);
log_info(LD_GENERAL, "Line %d of test %d, should be <%s>",
j, i, tests[i].split_line[j]);
/* Check that the line is as expected */
- test_streq(line, tests[i].split_line[j]);
+ tt_str_op(line,OP_EQ, tests[i].split_line[j]);
j++;
} SMARTLIST_FOREACH_END(line);
/* Check that we didn't miss some lines */
- test_eq_ptr(NULL, tests[i].split_line[j]);
+ tt_ptr_op(NULL,OP_EQ, tests[i].split_line[j]);
tor_free(orig_line);
smartlist_free(sl);
sl = NULL;
@@ -3062,7 +3650,7 @@ test_util_split_lines(void *ptr)
}
static void
-test_util_di_ops(void)
+test_util_di_ops(void *arg)
{
#define LT -1
#define GT 1
@@ -3082,10 +3670,11 @@ test_util_di_ops(void)
int i;
+ (void)arg;
for (i = 0; examples[i].a; ++i) {
size_t len = strlen(examples[i].a);
int eq1, eq2, neq1, neq2, cmp1, cmp2;
- test_eq(len, strlen(examples[i].b));
+ tt_int_op(len,OP_EQ, strlen(examples[i].b));
/* We do all of the operations, with operands in both orders. */
eq1 = tor_memeq(examples[i].a, examples[i].b, len);
eq2 = tor_memeq(examples[i].b, examples[i].a, len);
@@ -3096,34 +3685,98 @@ test_util_di_ops(void)
/* Check for correctness of cmp1 */
if (cmp1 < 0 && examples[i].want_sign != LT)
- test_fail();
+ TT_DIE(("Assertion failed."));
else if (cmp1 > 0 && examples[i].want_sign != GT)
- test_fail();
+ TT_DIE(("Assertion failed."));
else if (cmp1 == 0 && examples[i].want_sign != EQ)
- test_fail();
+ TT_DIE(("Assertion failed."));
/* Check for consistency of everything else with cmp1 */
- test_eq(eq1, eq2);
- test_eq(neq1, neq2);
- test_eq(cmp1, -cmp2);
- test_eq(eq1, cmp1 == 0);
- test_eq(neq1, !eq1);
+ tt_int_op(eq1,OP_EQ, eq2);
+ tt_int_op(neq1,OP_EQ, neq2);
+ tt_int_op(cmp1,OP_EQ, -cmp2);
+ tt_int_op(eq1,OP_EQ, cmp1 == 0);
+ tt_int_op(neq1,OP_EQ, !eq1);
}
- tt_int_op(1, ==, safe_mem_is_zero("", 0));
- tt_int_op(1, ==, safe_mem_is_zero("", 1));
- tt_int_op(0, ==, safe_mem_is_zero("a", 1));
- tt_int_op(0, ==, safe_mem_is_zero("a", 2));
- tt_int_op(0, ==, safe_mem_is_zero("\0a", 2));
- tt_int_op(1, ==, safe_mem_is_zero("\0\0a", 2));
- tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
- tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
- tt_int_op(0, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
+ {
+ uint8_t zz = 0;
+ uint8_t ii = 0;
+ int z;
+
+ /* exhaustively test tor_memeq and tor_memcmp
+ * against each possible single-byte numeric difference
+ * some arithmetic bugs only appear with certain bit patterns */
+ for (z = 0; z < 256; z++) {
+ for (i = 0; i < 256; i++) {
+ ii = (uint8_t)i;
+ zz = (uint8_t)z;
+ tt_int_op(tor_memeq(&zz, &ii, 1),OP_EQ, zz == ii);
+ tt_int_op(tor_memcmp(&zz, &ii, 1) > 0 ? GT : EQ,OP_EQ,
+ zz > ii ? GT : EQ);
+ tt_int_op(tor_memcmp(&ii, &zz, 1) < 0 ? LT : EQ,OP_EQ,
+ ii < zz ? LT : EQ);
+ }
+ }
+ }
+
+ tt_int_op(1, OP_EQ, safe_mem_is_zero("", 0));
+ tt_int_op(1, OP_EQ, safe_mem_is_zero("", 1));
+ tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 1));
+ tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 2));
+ tt_int_op(0, OP_EQ, safe_mem_is_zero("\0a", 2));
+ tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0a", 2));
+ tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
+ tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
+ tt_int_op(0, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
done:
;
}
+static void
+test_util_di_map(void *arg)
+{
+ (void)arg;
+ di_digest256_map_t *dimap = NULL;
+ uint8_t key1[] = "Robert Anton Wilson ";
+ uint8_t key2[] = "Martin Gardner, _Fads&fallacies";
+ uint8_t key3[] = "Tom Lehrer, _Be Prepared_. ";
+ uint8_t key4[] = "Ursula Le Guin,_A Wizard of... ";
+
+ char dflt_entry[] = "'You have made a good beginning', but no more";
+
+ tt_int_op(32, ==, sizeof(key1));
+ tt_int_op(32, ==, sizeof(key2));
+ tt_int_op(32, ==, sizeof(key3));
+
+ tt_ptr_op(dflt_entry, ==, dimap_search(dimap, key1, dflt_entry));
+
+ char *str1 = tor_strdup("You are precisely as big as what you love"
+ " and precisely as small as what you allow"
+ " to annoy you.");
+ char *str2 = tor_strdup("Let us hope that Lysenko's success in Russia will"
+ " serve for many generations to come as another"
+ " reminder to the world of how quickly and easily"
+ " a science can be corrupted when ignorant"
+ " political leaders deem themselves competent"
+ " to arbitrate scientific disputes");
+ char *str3 = tor_strdup("Don't write naughty words on walls "
+ "if you can't spell.");
+
+ dimap_add_entry(&dimap, key1, str1);
+ dimap_add_entry(&dimap, key2, str2);
+ dimap_add_entry(&dimap, key3, str3);
+
+ tt_ptr_op(str1, ==, dimap_search(dimap, key1, dflt_entry));
+ tt_ptr_op(str3, ==, dimap_search(dimap, key3, dflt_entry));
+ tt_ptr_op(str2, ==, dimap_search(dimap, key2, dflt_entry));
+ tt_ptr_op(dflt_entry, ==, dimap_search(dimap, key4, dflt_entry));
+
+ done:
+ dimap_free(dimap, tor_free_);
+}
+
/**
* Test counting high bits
*/
@@ -3131,12 +3784,12 @@ static void
test_util_n_bits_set(void *ptr)
{
(void)ptr;
- test_eq(0, n_bits_set_u8(0));
- test_eq(1, n_bits_set_u8(1));
- test_eq(3, n_bits_set_u8(7));
- test_eq(1, n_bits_set_u8(8));
- test_eq(2, n_bits_set_u8(129));
- test_eq(8, n_bits_set_u8(255));
+ tt_int_op(0,OP_EQ, n_bits_set_u8(0));
+ tt_int_op(1,OP_EQ, n_bits_set_u8(1));
+ tt_int_op(3,OP_EQ, n_bits_set_u8(7));
+ tt_int_op(1,OP_EQ, n_bits_set_u8(8));
+ tt_int_op(2,OP_EQ, n_bits_set_u8(129));
+ tt_int_op(8,OP_EQ, n_bits_set_u8(255));
done:
;
}
@@ -3157,78 +3810,82 @@ test_util_eat_whitespace(void *ptr)
strlcpy(str, "fuubaar", sizeof(str));
for (i = 0; i < sizeof(ws); ++i) {
str[0] = ws[i];
- test_eq_ptr(str + 1, eat_whitespace(str));
- test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
- test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
}
str[0] = '\n';
- test_eq_ptr(str + 1, eat_whitespace(str));
- test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str, eat_whitespace_no_nl(str));
- test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Empty string */
strlcpy(str, "", sizeof(str));
- test_eq_ptr(str, eat_whitespace(str));
- test_eq_ptr(str, eat_whitespace_eos(str, str));
- test_eq_ptr(str, eat_whitespace_no_nl(str));
- test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_eos(str, str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str));
/* Only ws */
strlcpy(str, " \t\r\n", sizeof(str));
- test_eq_ptr(str + strlen(str), eat_whitespace(str));
- test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + strlen(str) - 1,
+ tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + strlen(str),OP_EQ,
+ eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str + strlen(str) - 1,OP_EQ,
eat_whitespace_no_nl(str));
- test_eq_ptr(str + strlen(str) - 1,
+ tt_ptr_op(str + strlen(str) - 1,OP_EQ,
eat_whitespace_eos_no_nl(str, str + strlen(str)));
strlcpy(str, " \t\r ", sizeof(str));
- test_eq_ptr(str + strlen(str), eat_whitespace(str));
- test_eq_ptr(str + strlen(str),
+ tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + strlen(str),OP_EQ,
eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + strlen(str), eat_whitespace_no_nl(str));
- test_eq_ptr(str + strlen(str),
+ tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str + strlen(str),OP_EQ,
eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Multiple ws */
strlcpy(str, "fuubaar", sizeof(str));
for (i = 0; i < sizeof(ws); ++i)
str[i] = ws[i];
- test_eq_ptr(str + sizeof(ws), eat_whitespace(str));
- test_eq_ptr(str + sizeof(ws), eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + sizeof(ws), eat_whitespace_no_nl(str));
- test_eq_ptr(str + sizeof(ws),
+ tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + sizeof(ws),OP_EQ,
+ eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str + sizeof(ws),OP_EQ,
eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Eat comment */
strlcpy(str, "# Comment \n No Comment", sizeof(str));
- test_streq("No Comment", eat_whitespace(str));
- test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str, eat_whitespace_no_nl(str));
- test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
+ tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Eat comment & ws mix */
strlcpy(str, " # \t Comment \n\t\nNo Comment", sizeof(str));
- test_streq("No Comment", eat_whitespace(str));
- test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
- test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
+ tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Eat entire comment */
strlcpy(str, "#Comment", sizeof(str));
- test_eq_ptr(str + strlen(str), eat_whitespace(str));
- test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str, eat_whitespace_no_nl(str));
- test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + strlen(str),OP_EQ,
+ eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
/* Blank line, then comment */
strlcpy(str, " \t\n # Comment", sizeof(str));
- test_eq_ptr(str + strlen(str), eat_whitespace(str));
- test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
- test_eq_ptr(str + 2, eat_whitespace_no_nl(str));
- test_eq_ptr(str + 2, eat_whitespace_eos_no_nl(str, str + strlen(str)));
+ tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
+ tt_ptr_op(str + strlen(str),OP_EQ,
+ eat_whitespace_eos(str, str + strlen(str)));
+ tt_ptr_op(str + 2,OP_EQ, eat_whitespace_no_nl(str));
+ tt_ptr_op(str + 2,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
done:
;
@@ -3267,11 +3924,11 @@ test_util_sl_new_from_text_lines(void *ptr)
smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz\n");
int sl_len = smartlist_len(sl);
- tt_want_int_op(sl_len, ==, 3);
+ tt_want_int_op(sl_len, OP_EQ, 3);
- if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
- if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
- if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
+ if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
+ if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
+ if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
smartlist_free(sl);
@@ -3281,11 +3938,11 @@ test_util_sl_new_from_text_lines(void *ptr)
smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz");
int sl_len = smartlist_len(sl);
- tt_want_int_op(sl_len, ==, 3);
+ tt_want_int_op(sl_len, OP_EQ, 3);
- if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
- if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
- if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
+ if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
+ if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
+ if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
smartlist_free(sl);
@@ -3295,9 +3952,9 @@ test_util_sl_new_from_text_lines(void *ptr)
smartlist_t *sl = smartlist_new_from_text_lines("foo");
int sl_len = smartlist_len(sl);
- tt_want_int_op(sl_len, ==, 1);
+ tt_want_int_op(sl_len, OP_EQ, 1);
- if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
+ if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
smartlist_free(sl);
@@ -3307,7 +3964,7 @@ test_util_sl_new_from_text_lines(void *ptr)
smartlist_t *sl = smartlist_new_from_text_lines("");
int sl_len = smartlist_len(sl);
- tt_want_int_op(sl_len, ==, 0);
+ tt_want_int_op(sl_len, OP_EQ, 0);
SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
smartlist_free(sl);
@@ -3390,7 +4047,7 @@ test_util_make_environment(void *ptr)
smartlist_sort_strings(env_vars_sorted);
smartlist_sort_strings(env_vars_in_unixoid_env_block_sorted);
- tt_want_int_op(smartlist_len(env_vars_sorted), ==,
+ tt_want_int_op(smartlist_len(env_vars_sorted), OP_EQ,
smartlist_len(env_vars_in_unixoid_env_block_sorted));
{
int len = smartlist_len(env_vars_sorted);
@@ -3401,7 +4058,7 @@ test_util_make_environment(void *ptr)
}
for (i = 0; i < len; ++i) {
- tt_want_str_op(smartlist_get(env_vars_sorted, i), ==,
+ tt_want_str_op(smartlist_get(env_vars_sorted, i), OP_EQ,
smartlist_get(env_vars_in_unixoid_env_block_sorted, i));
}
}
@@ -3483,7 +4140,7 @@ test_util_set_env_var_in_sl(void *ptr)
smartlist_sort_strings(merged_env_vars);
smartlist_sort_strings(expected_resulting_env_vars);
- tt_want_int_op(smartlist_len(merged_env_vars), ==,
+ tt_want_int_op(smartlist_len(merged_env_vars), OP_EQ,
smartlist_len(expected_resulting_env_vars));
{
int len = smartlist_len(merged_env_vars);
@@ -3494,7 +4151,7 @@ test_util_set_env_var_in_sl(void *ptr)
}
for (i = 0; i < len; ++i) {
- tt_want_str_op(smartlist_get(merged_env_vars, i), ==,
+ tt_want_str_op(smartlist_get(merged_env_vars, i), OP_EQ,
smartlist_get(expected_resulting_env_vars, i));
}
}
@@ -3521,8 +4178,8 @@ test_util_weak_random(void *arg)
for (i = 1; i <= 256; ++i) {
for (j=0;j<100;++j) {
int r = tor_weak_random_range(&rng, i);
- tt_int_op(0, <=, r);
- tt_int_op(r, <, i);
+ tt_int_op(0, OP_LE, r);
+ tt_int_op(r, OP_LT, i);
}
}
@@ -3532,7 +4189,7 @@ test_util_weak_random(void *arg)
}
for (i=0;i<16;++i)
- tt_int_op(n[i], >, 0);
+ tt_int_op(n[i], OP_GT, 0);
done:
;
}
@@ -3544,9 +4201,9 @@ test_util_mathlog(void *arg)
(void) arg;
d = tor_mathlog(2.718281828);
- tt_double_op(fabs(d - 1.0), <, .000001);
+ tt_double_op(fabs(d - 1.0), OP_LT, .000001);
d = tor_mathlog(10);
- tt_double_op(fabs(d - 2.30258509), <, .000001);
+ tt_double_op(fabs(d - 2.30258509), OP_LT, .000001);
done:
;
}
@@ -3556,42 +4213,230 @@ test_util_round_to_next_multiple_of(void *arg)
{
(void)arg;
- test_assert(round_uint64_to_next_multiple_of(0,1) == 0);
- test_assert(round_uint64_to_next_multiple_of(0,7) == 0);
+ tt_u64_op(round_uint64_to_next_multiple_of(0,1), ==, 0);
+ tt_u64_op(round_uint64_to_next_multiple_of(0,7), ==, 0);
+
+ tt_u64_op(round_uint64_to_next_multiple_of(99,1), ==, 99);
+ tt_u64_op(round_uint64_to_next_multiple_of(99,7), ==, 105);
+ tt_u64_op(round_uint64_to_next_multiple_of(99,9), ==, 99);
+
+ tt_u64_op(round_uint64_to_next_multiple_of(UINT64_MAX,2), ==,
+ UINT64_MAX);
+
+ tt_i64_op(round_int64_to_next_multiple_of(0,1), ==, 0);
+ tt_i64_op(round_int64_to_next_multiple_of(0,7), ==, 0);
+
+ tt_i64_op(round_int64_to_next_multiple_of(99,1), ==, 99);
+ tt_i64_op(round_int64_to_next_multiple_of(99,7), ==, 105);
+ tt_i64_op(round_int64_to_next_multiple_of(99,9), ==, 99);
+
+ tt_i64_op(round_int64_to_next_multiple_of(-99,1), ==, -99);
+ tt_i64_op(round_int64_to_next_multiple_of(-99,7), ==, -98);
+ tt_i64_op(round_int64_to_next_multiple_of(-99,9), ==, -99);
- test_assert(round_uint64_to_next_multiple_of(99,1) == 99);
- test_assert(round_uint64_to_next_multiple_of(99,7) == 105);
- test_assert(round_uint64_to_next_multiple_of(99,9) == 99);
+ tt_i64_op(round_int64_to_next_multiple_of(INT64_MIN,2), ==, INT64_MIN);
+ tt_i64_op(round_int64_to_next_multiple_of(INT64_MAX,2), ==,
+ INT64_MAX);
+ tt_int_op(round_uint32_to_next_multiple_of(0,1), ==, 0);
+ tt_int_op(round_uint32_to_next_multiple_of(0,7), ==, 0);
+
+ tt_int_op(round_uint32_to_next_multiple_of(99,1), ==, 99);
+ tt_int_op(round_uint32_to_next_multiple_of(99,7), ==, 105);
+ tt_int_op(round_uint32_to_next_multiple_of(99,9), ==, 99);
+
+ tt_int_op(round_uint32_to_next_multiple_of(UINT32_MAX,2), ==,
+ UINT32_MAX);
+
+ tt_uint_op(round_to_next_multiple_of(0,1), ==, 0);
+ tt_uint_op(round_to_next_multiple_of(0,7), ==, 0);
+
+ tt_uint_op(round_to_next_multiple_of(99,1), ==, 99);
+ tt_uint_op(round_to_next_multiple_of(99,7), ==, 105);
+ tt_uint_op(round_to_next_multiple_of(99,9), ==, 99);
+
+ tt_uint_op(round_to_next_multiple_of(UINT_MAX,2), ==,
+ UINT_MAX);
done:
;
}
static void
-test_util_strclear(void *arg)
+test_util_laplace(void *arg)
{
- static const char *vals[] = { "", "a", "abcdef", "abcdefgh", NULL };
- int i;
- char *v = NULL;
+ /* Sample values produced using Python's SciPy:
+ *
+ * >>> from scipy.stats import laplace
+ * >>> laplace.ppf([-0.01, 0.0, 0.01, 0.5, 0.51, 0.99, 1.0, 1.01],
+ ... loc = 24, scale = 24)
+ * array([ nan, -inf, -69.88855213, 24. ,
+ * 24.48486498, 117.88855213, inf, nan])
+ */
+ const double mu = 24.0, b = 24.0;
+ const double delta_f = 15.0, epsilon = 0.3; /* b = 15.0 / 0.3 = 50.0 */
(void)arg;
- for (i = 0; vals[i]; ++i) {
- size_t n;
- v = tor_strdup(vals[i]);
- n = strlen(v);
- tor_strclear(v);
- tt_assert(tor_mem_is_zero(v, n+1));
- tor_free(v);
- }
+ tt_i64_op(INT64_MIN, ==, sample_laplace_distribution(mu, b, 0.0));
+ tt_i64_op(-69, ==, sample_laplace_distribution(mu, b, 0.01));
+ tt_i64_op(24, ==, sample_laplace_distribution(mu, b, 0.5));
+ tt_i64_op(24, ==, sample_laplace_distribution(mu, b, 0.51));
+ tt_i64_op(117, ==, sample_laplace_distribution(mu, b, 0.99));
+
+ /* >>> laplace.ppf([0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99],
+ * ... loc = 0, scale = 50)
+ * array([ -inf, -80.47189562, -34.65735903, 0. ,
+ * 34.65735903, 80.47189562, 195.60115027])
+ */
+ tt_i64_op(INT64_MIN + 20, ==,
+ add_laplace_noise(20, 0.0, delta_f, epsilon));
+
+ tt_i64_op(-60, ==, add_laplace_noise(20, 0.1, delta_f, epsilon));
+ tt_i64_op(-14, ==, add_laplace_noise(20, 0.25, delta_f, epsilon));
+ tt_i64_op(20, ==, add_laplace_noise(20, 0.5, delta_f, epsilon));
+ tt_i64_op(54, ==, add_laplace_noise(20, 0.75, delta_f, epsilon));
+ tt_i64_op(100, ==, add_laplace_noise(20, 0.9, delta_f, epsilon));
+ tt_i64_op(215, ==, add_laplace_noise(20, 0.99, delta_f, epsilon));
+
+ /* Test extreme values of signal with maximally negative values of noise
+ * 1.0000000000000002 is the smallest number > 1
+ * 0.0000000000000002 is the double epsilon (error when calculating near 1)
+ * this is approximately 1/(2^52)
+ * per https://en.wikipedia.org/wiki/Double_precision
+ * (let's not descend into the world of subnormals)
+ * >>> laplace.ppf([0, 0.0000000000000002], loc = 0, scale = 1)
+ * array([ -inf, -35.45506713])
+ */
+ const double noscale_df = 1.0, noscale_eps = 1.0;
+
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(0, 0.0, noscale_df, noscale_eps));
+
+ /* is it clipped to INT64_MIN? */
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(-1, 0.0, noscale_df, noscale_eps));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(INT64_MIN, 0.0,
+ noscale_df, noscale_eps));
+ /* ... even when scaled? */
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(0, 0.0, delta_f, epsilon));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(0, 0.0,
+ DBL_MAX, 1));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(INT64_MIN, 0.0,
+ DBL_MAX, 1));
+
+ /* does it play nice with INT64_MAX? */
+ tt_i64_op((INT64_MIN + INT64_MAX), ==,
+ add_laplace_noise(INT64_MAX, 0.0,
+ noscale_df, noscale_eps));
+
+ /* do near-zero fractional values work? */
+ const double min_dbl_error = 0.0000000000000002;
+
+ tt_i64_op(-35, ==,
+ add_laplace_noise(0, min_dbl_error,
+ noscale_df, noscale_eps));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(INT64_MIN, min_dbl_error,
+ noscale_df, noscale_eps));
+ tt_i64_op((-35 + INT64_MAX), ==,
+ add_laplace_noise(INT64_MAX, min_dbl_error,
+ noscale_df, noscale_eps));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(0, min_dbl_error,
+ DBL_MAX, 1));
+ tt_i64_op((INT64_MAX + INT64_MIN), ==,
+ add_laplace_noise(INT64_MAX, min_dbl_error,
+ DBL_MAX, 1));
+ tt_i64_op(INT64_MIN, ==,
+ add_laplace_noise(INT64_MIN, min_dbl_error,
+ DBL_MAX, 1));
+
+ /* does it play nice with INT64_MAX? */
+ tt_i64_op((INT64_MAX - 35), ==,
+ add_laplace_noise(INT64_MAX, min_dbl_error,
+ noscale_df, noscale_eps));
+
+ /* Test extreme values of signal with maximally positive values of noise
+ * 1.0000000000000002 is the smallest number > 1
+ * 0.9999999999999998 is the greatest number < 1 by calculation
+ * per https://en.wikipedia.org/wiki/Double_precision
+ * >>> laplace.ppf([1.0, 0.9999999999999998], loc = 0, scale = 1)
+ * array([inf, 35.35050621])
+ * but the function rejects p == 1.0, so we just use max_dbl_lt_one
+ */
+ const double max_dbl_lt_one = 0.9999999999999998;
+
+ /* do near-one fractional values work? */
+ tt_i64_op(35, ==,
+ add_laplace_noise(0, max_dbl_lt_one, noscale_df, noscale_eps));
+
+ /* is it clipped to INT64_MAX? */
+ tt_i64_op(INT64_MAX, ==,
+ add_laplace_noise(INT64_MAX - 35, max_dbl_lt_one,
+ noscale_df, noscale_eps));
+ tt_i64_op(INT64_MAX, ==,
+ add_laplace_noise(INT64_MAX - 34, max_dbl_lt_one,
+ noscale_df, noscale_eps));
+ tt_i64_op(INT64_MAX, ==,
+ add_laplace_noise(INT64_MAX, max_dbl_lt_one,
+ noscale_df, noscale_eps));
+ /* ... even when scaled? */
+ tt_i64_op(INT64_MAX, ==,
+ add_laplace_noise(INT64_MAX, max_dbl_lt_one,
+ delta_f, epsilon));
+ tt_i64_op((INT64_MIN + INT64_MAX), ==,
+ add_laplace_noise(INT64_MIN, max_dbl_lt_one,
+ DBL_MAX, 1));
+ tt_i64_op(INT64_MAX, ==,
+ add_laplace_noise(INT64_MAX, max_dbl_lt_one,
+ DBL_MAX, 1));
+ /* does it play nice with INT64_MIN? */
+ tt_i64_op((INT64_MIN + 35), ==,
+ add_laplace_noise(INT64_MIN, max_dbl_lt_one,
+ noscale_df, noscale_eps));
+
done:
- tor_free(v);
+ ;
}
-#define UTIL_LEGACY(name) \
- { #name, legacy_test_helper, 0, &legacy_setup, test_util_ ## name }
+static void
+test_util_clamp_double_to_int64(void *arg)
+{
+ (void)arg;
-#define UTIL_TEST(name, flags) \
- { #name, test_util_ ## name, flags, NULL, NULL }
+ tt_i64_op(INT64_MIN, ==, clamp_double_to_int64(-INFINITY));
+ tt_i64_op(INT64_MIN, ==,
+ clamp_double_to_int64(-1.0 * pow(2.0, 64.0) - 1.0));
+ tt_i64_op(INT64_MIN, ==,
+ clamp_double_to_int64(-1.0 * pow(2.0, 63.0) - 1.0));
+ tt_i64_op(((uint64_t) -1) << 53, ==,
+ clamp_double_to_int64(-1.0 * pow(2.0, 53.0)));
+ tt_i64_op((((uint64_t) -1) << 53) + 1, ==,
+ clamp_double_to_int64(-1.0 * pow(2.0, 53.0) + 1.0));
+ tt_i64_op(-1, ==, clamp_double_to_int64(-1.0));
+ tt_i64_op(0, ==, clamp_double_to_int64(-0.9));
+ tt_i64_op(0, ==, clamp_double_to_int64(-0.1));
+ tt_i64_op(0, ==, clamp_double_to_int64(0.0));
+ tt_i64_op(0, ==, clamp_double_to_int64(NAN));
+ tt_i64_op(0, ==, clamp_double_to_int64(0.1));
+ tt_i64_op(0, ==, clamp_double_to_int64(0.9));
+ tt_i64_op(1, ==, clamp_double_to_int64(1.0));
+ tt_i64_op((((int64_t) 1) << 53) - 1, ==,
+ clamp_double_to_int64(pow(2.0, 53.0) - 1.0));
+ tt_i64_op(((int64_t) 1) << 53, ==,
+ clamp_double_to_int64(pow(2.0, 53.0)));
+ tt_i64_op(INT64_MAX, ==,
+ clamp_double_to_int64(pow(2.0, 63.0)));
+ tt_i64_op(INT64_MAX, ==,
+ clamp_double_to_int64(pow(2.0, 64.0)));
+ tt_i64_op(INT64_MAX, ==, clamp_double_to_int64(INFINITY));
+
+ done:
+ ;
+}
#ifdef FD_CLOEXEC
#define CAN_CHECK_CLOEXEC
@@ -3613,9 +4458,14 @@ fd_is_nonblocking(tor_socket_t fd)
}
#endif
+#define ERRNO_IS_EPROTO(e) (e == SOCK_ERRNO(EPROTONOSUPPORT))
+#define SOCK_ERR_IS_EPROTO(s) ERRNO_IS_EPROTO(tor_socket_errno(s))
+
+/* Test for tor_open_socket*, using IPv4 or IPv6 depending on arg. */
static void
test_util_socket(void *arg)
{
+ const int domain = !strcmp(arg, "4") ? AF_INET : AF_INET6;
tor_socket_t fd1 = TOR_INVALID_SOCKET;
tor_socket_t fd2 = TOR_INVALID_SOCKET;
tor_socket_t fd3 = TOR_INVALID_SOCKET;
@@ -3626,40 +4476,45 @@ test_util_socket(void *arg)
(void)arg;
- fd1 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 0);
- fd2 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 1);
+ fd1 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 0);
+ int err = tor_socket_errno(fd1);
+ if (fd1 < 0 && err == SOCK_ERRNO(EPROTONOSUPPORT)) {
+ /* Assume we're on an IPv4-only or IPv6-only system, and give up now. */
+ goto done;
+ }
+ fd2 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 1);
tt_assert(SOCKET_OK(fd1));
tt_assert(SOCKET_OK(fd2));
- tt_int_op(get_n_open_sockets(), ==, n + 2);
- //fd3 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 0);
- //fd4 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 1);
- fd3 = tor_open_socket(AF_INET, SOCK_STREAM, 0);
- fd4 = tor_open_socket_nonblocking(AF_INET, SOCK_STREAM, 0);
+ tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
+ //fd3 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 0);
+ //fd4 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 1);
+ fd3 = tor_open_socket(domain, SOCK_STREAM, 0);
+ fd4 = tor_open_socket_nonblocking(domain, SOCK_STREAM, 0);
tt_assert(SOCKET_OK(fd3));
tt_assert(SOCKET_OK(fd4));
- tt_int_op(get_n_open_sockets(), ==, n + 4);
+ tt_int_op(get_n_open_sockets(), OP_EQ, n + 4);
#ifdef CAN_CHECK_CLOEXEC
- tt_int_op(fd_is_cloexec(fd1), ==, 0);
- tt_int_op(fd_is_cloexec(fd2), ==, 0);
- tt_int_op(fd_is_cloexec(fd3), ==, 1);
- tt_int_op(fd_is_cloexec(fd4), ==, 1);
+ tt_int_op(fd_is_cloexec(fd1), OP_EQ, 0);
+ tt_int_op(fd_is_cloexec(fd2), OP_EQ, 0);
+ tt_int_op(fd_is_cloexec(fd3), OP_EQ, 1);
+ tt_int_op(fd_is_cloexec(fd4), OP_EQ, 1);
#endif
#ifdef CAN_CHECK_NONBLOCK
- tt_int_op(fd_is_nonblocking(fd1), ==, 0);
- tt_int_op(fd_is_nonblocking(fd2), ==, 1);
- tt_int_op(fd_is_nonblocking(fd3), ==, 0);
- tt_int_op(fd_is_nonblocking(fd4), ==, 1);
+ tt_int_op(fd_is_nonblocking(fd1), OP_EQ, 0);
+ tt_int_op(fd_is_nonblocking(fd2), OP_EQ, 1);
+ tt_int_op(fd_is_nonblocking(fd3), OP_EQ, 0);
+ tt_int_op(fd_is_nonblocking(fd4), OP_EQ, 1);
#endif
tor_close_socket(fd1);
tor_close_socket(fd2);
fd1 = fd2 = TOR_INVALID_SOCKET;
- tt_int_op(get_n_open_sockets(), ==, n + 2);
+ tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
tor_close_socket(fd3);
tor_close_socket(fd4);
fd3 = fd4 = TOR_INVALID_SOCKET;
- tt_int_op(get_n_open_sockets(), ==, n);
+ tt_int_op(get_n_open_sockets(), OP_EQ, n);
done:
if (SOCKET_OK(fd1))
@@ -3672,23 +4527,6 @@ test_util_socket(void *arg)
tor_close_socket(fd4);
}
-static void *
-socketpair_test_setup(const struct testcase_t *testcase)
-{
- return testcase->setup_data;
-}
-static int
-socketpair_test_cleanup(const struct testcase_t *testcase, void *ptr)
-{
- (void)testcase;
- (void)ptr;
- return 1;
-}
-
-static const struct testcase_setup_t socketpair_setup = {
- socketpair_test_setup, socketpair_test_cleanup
-};
-
/* Test for socketpair and ersatz_socketpair(). We test them both, since
* the latter is a tolerably good way to exersize tor_accept_socket(). */
static void
@@ -3700,18 +4538,30 @@ test_util_socketpair(void *arg)
int n = get_n_open_sockets();
tor_socket_t fds[2] = {TOR_INVALID_SOCKET, TOR_INVALID_SOCKET};
const int family = AF_UNIX;
+ int socketpair_result = 0;
+
+ socketpair_result = tor_socketpair_fn(family, SOCK_STREAM, 0, fds);
+ /* If there is no 127.0.0.1 or ::1, tor_ersatz_socketpair will and must fail.
+ * Otherwise, we risk exposing a socketpair on a routable IP address. (Some
+ * BSD jails use a routable address for localhost. Fortunately, they have
+ * the real AF_UNIX socketpair.) */
+ if (ersatz && ERRNO_IS_EPROTO(-socketpair_result)) {
+ /* In my testing, an IPv6-only FreeBSD jail without ::1 returned EINVAL.
+ * Assume we're on a machine without 127.0.0.1 or ::1 and give up now. */
+ goto done;
+ }
+ tt_int_op(0, OP_EQ, socketpair_result);
- tt_int_op(0, ==, tor_socketpair_fn(family, SOCK_STREAM, 0, fds));
tt_assert(SOCKET_OK(fds[0]));
tt_assert(SOCKET_OK(fds[1]));
- tt_int_op(get_n_open_sockets(), ==, n + 2);
+ tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
#ifdef CAN_CHECK_CLOEXEC
- tt_int_op(fd_is_cloexec(fds[0]), ==, 1);
- tt_int_op(fd_is_cloexec(fds[1]), ==, 1);
+ tt_int_op(fd_is_cloexec(fds[0]), OP_EQ, 1);
+ tt_int_op(fd_is_cloexec(fds[1]), OP_EQ, 1);
#endif
#ifdef CAN_CHECK_NONBLOCK
- tt_int_op(fd_is_nonblocking(fds[0]), ==, 0);
- tt_int_op(fd_is_nonblocking(fds[1]), ==, 0);
+ tt_int_op(fd_is_nonblocking(fds[0]), OP_EQ, 0);
+ tt_int_op(fd_is_nonblocking(fds[1]), OP_EQ, 0);
#endif
done:
@@ -3721,6 +4571,8 @@ test_util_socketpair(void *arg)
tor_close_socket(fds[1]);
}
+#undef SOCKET_EPROTO
+
static void
test_util_max_mem(void *arg)
{
@@ -3730,18 +4582,18 @@ test_util_max_mem(void *arg)
r = get_total_system_memory(&memory1);
r2 = get_total_system_memory(&memory2);
- tt_int_op(r, ==, r2);
- tt_uint_op(memory2, ==, memory1);
+ tt_int_op(r, OP_EQ, r2);
+ tt_uint_op(memory2, OP_EQ, memory1);
TT_BLATHER(("System memory: "U64_FORMAT, U64_PRINTF_ARG(memory1)));
if (r==0) {
/* You have at least a megabyte. */
- tt_uint_op(memory1, >, (1<<20));
+ tt_uint_op(memory1, OP_GT, (1<<20));
} else {
/* You do not have a petabyte. */
#if SIZEOF_SIZE_T == SIZEOF_UINT64_T
- tt_u64_op(memory1, <, (U64_LITERAL(1)<<50));
+ tt_u64_op(memory1, OP_LT, (U64_LITERAL(1)<<50));
#endif
}
@@ -3749,6 +4601,207 @@ test_util_max_mem(void *arg)
;
}
+static void
+test_util_hostname_validation(void *arg)
+{
+ (void)arg;
+
+ // Lets try valid hostnames first.
+ tt_assert(string_is_valid_hostname("torproject.org"));
+ tt_assert(string_is_valid_hostname("ocw.mit.edu"));
+ tt_assert(string_is_valid_hostname("i.4cdn.org"));
+ tt_assert(string_is_valid_hostname("stanford.edu"));
+ tt_assert(string_is_valid_hostname("multiple-words-with-hypens.jp"));
+
+ // Subdomain name cannot start with '-' or '_'.
+ tt_assert(!string_is_valid_hostname("-torproject.org"));
+ tt_assert(!string_is_valid_hostname("subdomain.-domain.org"));
+ tt_assert(!string_is_valid_hostname("-subdomain.domain.org"));
+ tt_assert(!string_is_valid_hostname("___abc.org"));
+
+ // Hostnames cannot contain non-alphanumeric characters.
+ tt_assert(!string_is_valid_hostname("%%domain.\\org."));
+ tt_assert(!string_is_valid_hostname("***x.net"));
+ tt_assert(!string_is_valid_hostname("\xff\xffxyz.org"));
+ tt_assert(!string_is_valid_hostname("word1 word2.net"));
+
+ // Test workaround for nytimes.com stupidity, technically invalid,
+ // but we allow it since they are big, even though they are failing to
+ // comply with a ~30 year old standard.
+ tt_assert(string_is_valid_hostname("core3_euw1.fabrik.nytimes.com"));
+
+ // Firefox passes FQDNs with trailing '.'s directly to the SOCKS proxy,
+ // which is redundant since the spec states DOMAINNAME addresses are fully
+ // qualified. While unusual, this should be tollerated.
+ tt_assert(string_is_valid_hostname("core9_euw1.fabrik.nytimes.com."));
+ tt_assert(!string_is_valid_hostname("..washingtonpost.is.better.com"));
+ tt_assert(!string_is_valid_hostname("so.is..ft.com"));
+ tt_assert(!string_is_valid_hostname("..."));
+
+ // XXX: do we allow single-label DNS names?
+ // We shouldn't for SOCKS (spec says "contains a fully-qualified domain name"
+ // but only test pathologically malformed traling '.' cases for now.
+ tt_assert(!string_is_valid_hostname("."));
+ tt_assert(!string_is_valid_hostname(".."));
+
+ done:
+ return;
+}
+
+static void
+test_util_ipv4_validation(void *arg)
+{
+ (void)arg;
+
+ tt_assert(string_is_valid_ipv4_address("192.168.0.1"));
+ tt_assert(string_is_valid_ipv4_address("8.8.8.8"));
+
+ tt_assert(!string_is_valid_ipv4_address("abcd"));
+ tt_assert(!string_is_valid_ipv4_address("300.300.300.300"));
+ tt_assert(!string_is_valid_ipv4_address("8.8."));
+
+ done:
+ return;
+}
+
+static void
+test_util_writepid(void *arg)
+{
+ (void) arg;
+
+ char *contents = NULL;
+ const char *fname = get_fname("tmp_pid");
+ unsigned long pid;
+ char c;
+
+ write_pidfile(fname);
+
+ contents = read_file_to_str(fname, 0, NULL);
+ tt_assert(contents);
+
+ int n = tor_sscanf(contents, "%lu\n%c", &pid, &c);
+ tt_int_op(n, OP_EQ, 1);
+
+#ifdef _WIN32
+ tt_uint_op(pid, OP_EQ, _getpid());
+#else
+ tt_uint_op(pid, OP_EQ, getpid());
+#endif
+
+ done:
+ tor_free(contents);
+}
+
+static void
+test_util_get_avail_disk_space(void *arg)
+{
+ (void) arg;
+ int64_t val;
+
+ /* No answer for nonexistent directory */
+ val = tor_get_avail_disk_space("/akljasdfklsajdklasjkldjsa");
+ tt_i64_op(val, OP_EQ, -1);
+
+ /* Try the current directory */
+ val = tor_get_avail_disk_space(".");
+
+#if !defined(HAVE_STATVFS) && !defined(_WIN32)
+ tt_i64_op(val, OP_EQ, -1); /* You don't have an implementation for this */
+#else
+ tt_i64_op(val, OP_GT, 0); /* You have some space. */
+ tt_i64_op(val, OP_LT, ((int64_t)1)<<56); /* You don't have a zebibyte */
+#endif
+
+ done:
+ ;
+}
+
+static void
+test_util_touch_file(void *arg)
+{
+ (void) arg;
+ const char *fname = get_fname("touch");
+
+ const time_t now = time(NULL);
+ struct stat st;
+ write_bytes_to_file(fname, "abc", 3, 1);
+ tt_int_op(0, OP_EQ, stat(fname, &st));
+ /* A subtle point: the filesystem time is not necessarily equal to the
+ * system clock time, since one can be using a monotonic clock, or coarse
+ * monotonic clock, or whatever. So we might wind up with an mtime a few
+ * microseconds ago. Let's just give it a lot of wiggle room. */
+ tt_i64_op(st.st_mtime, OP_GE, now - 1);
+
+ const time_t five_sec_ago = now - 5;
+ struct utimbuf u = { five_sec_ago, five_sec_ago };
+ tt_int_op(0, OP_EQ, utime(fname, &u));
+ tt_int_op(0, OP_EQ, stat(fname, &st));
+ /* Let's hope that utime/stat give the same second as a round-trip? */
+ tt_i64_op(st.st_mtime, OP_EQ, five_sec_ago);
+
+ /* Finally we can touch the file */
+ tt_int_op(0, OP_EQ, touch_file(fname));
+ tt_int_op(0, OP_EQ, stat(fname, &st));
+ tt_i64_op(st.st_mtime, OP_GE, now-1);
+
+ done:
+ ;
+}
+
+#ifndef _WIN32
+static void
+test_util_pwdb(void *arg)
+{
+ (void) arg;
+ const struct passwd *me = NULL, *me2, *me3;
+ char *name = NULL;
+ char *dir = NULL;
+
+ /* Uncached case. */
+ /* Let's assume that we exist. */
+ me = tor_getpwuid(getuid());
+ tt_assert(me != NULL);
+ name = tor_strdup(me->pw_name);
+
+ /* Uncached case */
+ me2 = tor_getpwnam(name);
+ tt_assert(me2 != NULL);
+ tt_int_op(me2->pw_uid, OP_EQ, getuid());
+
+ /* Cached case */
+ me3 = tor_getpwuid(getuid());
+ tt_assert(me3 != NULL);
+ tt_str_op(me3->pw_name, OP_EQ, name);
+
+ me3 = tor_getpwnam(name);
+ tt_assert(me3 != NULL);
+ tt_int_op(me3->pw_uid, OP_EQ, getuid());
+
+ dir = get_user_homedir(name);
+ tt_assert(dir != NULL);
+
+ done:
+ tor_free(name);
+ tor_free(dir);
+}
+#endif
+
+#define UTIL_LEGACY(name) \
+ { #name, test_util_ ## name , 0, NULL, NULL }
+
+#define UTIL_TEST(name, flags) \
+ { #name, test_util_ ## name, flags, NULL, NULL }
+
+#ifdef _WIN32
+#define UTIL_TEST_NO_WIN(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
+#define UTIL_TEST_WIN_ONLY(n, f) UTIL_TEST(n, (f))
+#define UTIL_LEGACY_NO_WIN(n) UTIL_TEST_NO_WIN(n, 0)
+#else
+#define UTIL_TEST_NO_WIN(n, f) UTIL_TEST(n, (f))
+#define UTIL_TEST_WIN_ONLY(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
+#define UTIL_LEGACY_NO_WIN(n) UTIL_LEGACY(n)
+#endif
+
struct testcase_t util_tests[] = {
UTIL_LEGACY(time),
UTIL_TEST(parse_http_time, 0),
@@ -3756,45 +4809,34 @@ struct testcase_t util_tests[] = {
UTIL_LEGACY(config_line_quotes),
UTIL_LEGACY(config_line_comment_character),
UTIL_LEGACY(config_line_escaped_content),
-#ifndef _WIN32
- UTIL_LEGACY(expand_filename),
-#endif
+ UTIL_LEGACY_NO_WIN(expand_filename),
UTIL_LEGACY(escape_string_socks),
UTIL_LEGACY(string_is_key_value),
UTIL_LEGACY(strmisc),
UTIL_LEGACY(pow2),
UTIL_LEGACY(gzip),
UTIL_LEGACY(datadir),
-#ifdef ENABLE_MEMPOOLS
- UTIL_LEGACY(mempool),
-#endif
UTIL_LEGACY(memarea),
UTIL_LEGACY(control_formats),
UTIL_LEGACY(mmap),
- UTIL_LEGACY(threads),
UTIL_LEGACY(sscanf),
+ UTIL_LEGACY(format_time_interval),
UTIL_LEGACY(path_is_relative),
UTIL_LEGACY(strtok),
UTIL_LEGACY(di_ops),
+ UTIL_TEST(di_map, 0),
UTIL_TEST(round_to_next_multiple_of, 0),
- UTIL_TEST(strclear, 0),
+ UTIL_TEST(laplace, 0),
+ UTIL_TEST(clamp_double_to_int64, 0),
UTIL_TEST(find_str_at_start_of_line, 0),
UTIL_TEST(string_is_C_identifier, 0),
UTIL_TEST(asprintf, 0),
UTIL_TEST(listdir, 0),
UTIL_TEST(parent_dir, 0),
-#ifdef _WIN32
- UTIL_TEST(load_win_lib, 0),
-#endif
-#ifndef _WIN32
- UTIL_TEST(exit_status, 0),
- UTIL_TEST(fgets_eagain, TT_SKIP),
-#endif
- UTIL_TEST(spawn_background_ok, 0),
- UTIL_TEST(spawn_background_fail, 0),
- UTIL_TEST(spawn_background_partial_read, 0),
- UTIL_TEST(spawn_background_exit_early, 0),
- UTIL_TEST(spawn_background_waitpid_notify, 0),
+ UTIL_TEST(ftruncate, 0),
+ UTIL_TEST_WIN_ONLY(load_win_lib, 0),
+ UTIL_TEST_NO_WIN(exit_status, 0),
+ UTIL_TEST_NO_WIN(fgets_eagain, 0),
UTIL_TEST(format_hex_number, 0),
UTIL_TEST(format_dec_number, 0),
UTIL_TEST(join_win_cmdline, 0),
@@ -3806,17 +4848,29 @@ struct testcase_t util_tests[] = {
UTIL_TEST(make_environment, 0),
UTIL_TEST(set_env_var_in_sl, 0),
UTIL_TEST(read_file_eof_tiny_limit, 0),
+ UTIL_TEST(read_file_eof_one_loop_a, 0),
+ UTIL_TEST(read_file_eof_one_loop_b, 0),
UTIL_TEST(read_file_eof_two_loops, 0),
+ UTIL_TEST(read_file_eof_two_loops_b, 0),
UTIL_TEST(read_file_eof_zero_bytes, 0),
UTIL_TEST(write_chunks_to_file, 0),
UTIL_TEST(mathlog, 0),
UTIL_TEST(weak_random, 0),
- UTIL_TEST(socket, TT_FORK),
- { "socketpair", test_util_socketpair, TT_FORK, &socketpair_setup,
+ { "socket_ipv4", test_util_socket, TT_FORK, &passthrough_setup,
+ (void*)"4" },
+ { "socket_ipv6", test_util_socket, TT_FORK,
+ &passthrough_setup, (void*)"6" },
+ { "socketpair", test_util_socketpair, TT_FORK, &passthrough_setup,
(void*)"0" },
{ "socketpair_ersatz", test_util_socketpair, TT_FORK,
- &socketpair_setup, (void*)"1" },
+ &passthrough_setup, (void*)"1" },
UTIL_TEST(max_mem, 0),
+ UTIL_TEST(hostname_validation, 0),
+ UTIL_TEST(ipv4_validation, 0),
+ UTIL_TEST(writepid, 0),
+ UTIL_TEST(get_avail_disk_space, 0),
+ UTIL_TEST(touch_file, 0),
+ UTIL_TEST_NO_WIN(pwdb, TT_FORK),
END_OF_TESTCASES
};
diff --git a/src/test/test_util_format.c b/src/test/test_util_format.c
new file mode 100644
index 0000000000..3d02930983
--- /dev/null
+++ b/src/test/test_util_format.c
@@ -0,0 +1,302 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#include "or.h"
+
+#include "test.h"
+
+#define UTIL_FORMAT_PRIVATE
+#include "util_format.h"
+
+#define NS_MODULE util_format
+
+#if !defined(HAVE_HTONLL) && !defined(htonll)
+#ifdef WORDS_BIGENDIAN
+#define htonll(x) (x)
+#else
+static uint64_t
+htonll(uint64_t a)
+{
+ return htonl((uint32_t)(a>>32)) | (((uint64_t)htonl((uint32_t)a))<<32);
+}
+#endif
+#endif
+
+static void
+test_util_format_unaligned_accessors(void *ignored)
+{
+ (void)ignored;
+ char buf[9] = "onionsoup"; // 6f6e696f6e736f7570
+
+ tt_u64_op(get_uint64(buf+1), OP_EQ, htonll(U64_LITERAL(0x6e696f6e736f7570)));
+ tt_uint_op(get_uint32(buf+1), OP_EQ, htonl(0x6e696f6e));
+ tt_uint_op(get_uint16(buf+1), OP_EQ, htons(0x6e69));
+ tt_uint_op(get_uint8(buf+1), OP_EQ, 0x6e);
+
+ set_uint8(buf+7, 0x61);
+ tt_mem_op(buf, OP_EQ, "onionsoap", 9);
+
+ set_uint16(buf+6, htons(0x746f));
+ tt_mem_op(buf, OP_EQ, "onionstop", 9);
+
+ set_uint32(buf+1, htonl(0x78696465));
+ tt_mem_op(buf, OP_EQ, "oxidestop", 9);
+
+ set_uint64(buf+1, htonll(U64_LITERAL(0x6266757363617465)));
+ tt_mem_op(buf, OP_EQ, "obfuscate", 9);
+ done:
+ ;
+}
+
+static void
+test_util_format_base64_encode(void *ignored)
+{
+ (void)ignored;
+ int res;
+ int i;
+ char *src;
+ char *dst;
+
+ src = tor_malloc_zero(256);
+ dst = tor_malloc_zero(1000);
+
+ for (i=0;i<256;i++) {
+ src[i] = (char)i;
+ }
+
+ res = base64_encode(NULL, 1, src, 1, 0);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_encode(dst, 1, NULL, 1, 0);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_encode(dst, 1, src, 10, 0);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_encode(dst, SSIZE_MAX-1, src, 1, 0);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_encode(dst, SSIZE_MAX-1, src, 10, 0);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_encode(dst, 1000, src, 256, 0);
+ tt_int_op(res, OP_EQ, 344);
+ tt_str_op(dst, OP_EQ, "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh"
+ "8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZH"
+ "SElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3"
+ "BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeY"
+ "mZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wM"
+ "HCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp"
+ "6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==");
+
+ res = base64_encode(dst, 1000, src, 256, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 350);
+ tt_str_op(dst, OP_EQ,
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\n"
+ "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f\n"
+ "YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P\n"
+ "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/\n"
+ "wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v\n"
+ "8PHy8/T19vf4+fr7/P3+/w==\n");
+
+ res = base64_encode(dst, 1000, src+1, 255, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 346);
+
+ for (i = 0;i<50;i++) {
+ src[i] = 0;
+ }
+ src[50] = (char)255;
+ src[51] = (char)255;
+ src[52] = (char)255;
+ src[53] = (char)255;
+
+ res = base64_encode(dst, 1000, src, 54, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 74);
+
+ res = base64_encode(dst, 1000, src+1, 53, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 74);
+
+ res = base64_encode(dst, 1000, src+2, 52, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 74);
+
+ res = base64_encode(dst, 1000, src+3, 51, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 70);
+
+ res = base64_encode(dst, 1000, src+4, 50, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 70);
+
+ res = base64_encode(dst, 1000, src+5, 49, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 70);
+
+ res = base64_encode(dst, 1000, src+6, 48, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 65);
+
+ res = base64_encode(dst, 1000, src+7, 47, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 65);
+
+ res = base64_encode(dst, 1000, src+8, 46, BASE64_ENCODE_MULTILINE);
+ tt_int_op(res, OP_EQ, 65);
+
+ done:
+ tor_free(src);
+ tor_free(dst);
+}
+
+static void
+test_util_format_base64_decode_nopad(void *ignored)
+{
+ (void)ignored;
+ int res;
+ int i;
+ char *src;
+ uint8_t *dst, *real_dst;
+ uint8_t expected[] = {0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65};
+ char real_src[] = "ZXhhbXBsZQ";
+
+ src = tor_malloc_zero(256);
+ dst = tor_malloc_zero(1000);
+ real_dst = tor_malloc_zero(10);
+
+ for (i=0;i<256;i++) {
+ src[i] = (char)i;
+ }
+
+ res = base64_decode_nopad(dst, 1, src, SIZE_T_CEILING);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_decode_nopad(dst, 1, src, 5);
+ tt_int_op(res, OP_EQ, -1);
+
+ const char *s = "SGVsbG8gd29ybGQ";
+ res = base64_decode_nopad(dst, 1000, s, strlen(s));
+ tt_int_op(res, OP_EQ, 11);
+ tt_mem_op(dst, OP_EQ, "Hello world", 11);
+
+ s = "T3BhIG11bmRv";
+ res = base64_decode_nopad(dst, 9, s, strlen(s));
+ tt_int_op(res, OP_EQ, 9);
+ tt_mem_op(dst, OP_EQ, "Opa mundo", 9);
+
+ res = base64_decode_nopad(real_dst, 10, real_src, 10);
+ tt_int_op(res, OP_EQ, 7);
+ tt_mem_op(real_dst, OP_EQ, expected, 7);
+
+ done:
+ tor_free(src);
+ tor_free(dst);
+ tor_free(real_dst);
+}
+
+static void
+test_util_format_base64_decode(void *ignored)
+{
+ (void)ignored;
+ int res;
+ int i;
+ char *src;
+ char *dst, *real_dst;
+ uint8_t expected[] = {0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65};
+ char real_src[] = "ZXhhbXBsZQ==";
+
+ src = tor_malloc_zero(256);
+ dst = tor_malloc_zero(1000);
+ real_dst = tor_malloc_zero(10);
+
+ for (i=0;i<256;i++) {
+ src[i] = (char)i;
+ }
+
+ res = base64_decode(dst, 1, src, SIZE_T_CEILING);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base64_decode(dst, SIZE_T_CEILING+1, src, 10);
+ tt_int_op(res, OP_EQ, -1);
+
+ const char *s = "T3BhIG11bmRv";
+ res = base64_decode(dst, 9, s, strlen(s));
+ tt_int_op(res, OP_EQ, 9);
+ tt_mem_op(dst, OP_EQ, "Opa mundo", 9);
+
+ memset(dst, 0, 1000);
+ res = base64_decode(dst, 100, s, strlen(s));
+ tt_int_op(res, OP_EQ, 9);
+ tt_mem_op(dst, OP_EQ, "Opa mundo", 9);
+
+ s = "SGVsbG8gd29ybGQ=";
+ res = base64_decode(dst, 100, s, strlen(s));
+ tt_int_op(res, OP_EQ, 11);
+ tt_mem_op(dst, OP_EQ, "Hello world", 11);
+
+ res = base64_decode(real_dst, 10, real_src, 10);
+ tt_int_op(res, OP_EQ, 7);
+ tt_mem_op(real_dst, OP_EQ, expected, 7);
+
+ done:
+ tor_free(src);
+ tor_free(dst);
+ tor_free(real_dst);
+}
+
+static void
+test_util_format_base16_decode(void *ignored)
+{
+ (void)ignored;
+ int res;
+ int i;
+ char *src;
+ char *dst, *real_dst;
+ char expected[] = {0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65};
+ char real_src[] = "6578616D706C65";
+
+ src = tor_malloc_zero(256);
+ dst = tor_malloc_zero(1000);
+ real_dst = tor_malloc_zero(10);
+
+ for (i=0;i<256;i++) {
+ src[i] = (char)i;
+ }
+
+ res = base16_decode(dst, 3, src, 3);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base16_decode(dst, 1, src, 10);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base16_decode(dst, SIZE_T_CEILING+2, src, 10);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base16_decode(dst, 1000, "", 0);
+ tt_int_op(res, OP_EQ, 0);
+
+ res = base16_decode(dst, 1000, "aabc", 4);
+ tt_int_op(res, OP_EQ, 0);
+ tt_mem_op(dst, OP_EQ, "\xaa\xbc", 2);
+
+ res = base16_decode(dst, 1000, "aabcd", 6);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base16_decode(dst, 1000, "axxx", 4);
+ tt_int_op(res, OP_EQ, -1);
+
+ res = base16_decode(real_dst, 10, real_src, 14);
+ tt_int_op(res, OP_EQ, 0);
+ tt_mem_op(real_dst, OP_EQ, expected, 7);
+
+ done:
+ tor_free(src);
+ tor_free(dst);
+ tor_free(real_dst);
+}
+
+struct testcase_t util_format_tests[] = {
+ { "unaligned_accessors", test_util_format_unaligned_accessors, 0,
+ NULL, NULL },
+ { "base64_encode", test_util_format_base64_encode, 0, NULL, NULL },
+ { "base64_decode_nopad", test_util_format_base64_decode_nopad, 0,
+ NULL, NULL },
+ { "base64_decode", test_util_format_base64_decode, 0, NULL, NULL },
+ { "base16_decode", test_util_format_base16_decode, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_util_process.c b/src/test/test_util_process.c
new file mode 100644
index 0000000000..45c22ef47f
--- /dev/null
+++ b/src/test/test_util_process.c
@@ -0,0 +1,82 @@
+/* Copyright (c) 2010-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define UTIL_PROCESS_PRIVATE
+#include "orconfig.h"
+#include "or.h"
+
+#include "test.h"
+
+#include "util_process.h"
+
+#include "log_test_helpers.h"
+
+#ifndef _WIN32
+#define NS_MODULE util_process
+
+static void
+temp_callback(int r, void *s)
+{
+ (void)r;
+ (void)s;
+}
+
+static void
+test_util_process_set_waitpid_callback(void *ignored)
+{
+ (void)ignored;
+ waitpid_callback_t *res1 = NULL, *res2 = NULL;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ pid_t pid = (pid_t)42;
+
+ res1 = set_waitpid_callback(pid, temp_callback, NULL);
+ tt_assert(res1);
+
+ res2 = set_waitpid_callback(pid, temp_callback, NULL);
+ tt_assert(res2);
+ expect_log_msg("Replaced a waitpid monitor on pid 42. That should be "
+ "impossible.\n");
+
+ done:
+ teardown_capture_of_logs(previous_log);
+ clear_waitpid_callback(res1);
+ clear_waitpid_callback(res2);
+}
+
+static void
+test_util_process_clear_waitpid_callback(void *ignored)
+{
+ (void)ignored;
+ waitpid_callback_t *res;
+ int previous_log = setup_capture_of_logs(LOG_WARN);
+ pid_t pid = (pid_t)43;
+
+ clear_waitpid_callback(NULL);
+
+ res = set_waitpid_callback(pid, temp_callback, NULL);
+ clear_waitpid_callback(res);
+ expect_no_log_entry();
+
+#if 0
+ /* No. This is use-after-free. We don't _do_ that. XXXX */
+ clear_waitpid_callback(res);
+ expect_log_msg("Couldn't remove waitpid monitor for pid 43.\n");
+#endif
+
+ done:
+ teardown_capture_of_logs(previous_log);
+}
+#endif /* _WIN32 */
+
+#ifndef _WIN32
+#define TEST(name) { #name, test_util_process_##name, 0, NULL, NULL }
+#else
+#define TEST(name) { #name, NULL, TT_SKIP, NULL, NULL }
+#endif
+
+struct testcase_t util_process_tests[] = {
+ TEST(set_waitpid_callback),
+ TEST(clear_waitpid_callback),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_util_slow.c b/src/test/test_util_slow.c
new file mode 100644
index 0000000000..1e7160598c
--- /dev/null
+++ b/src/test/test_util_slow.c
@@ -0,0 +1,391 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#define UTIL_PRIVATE
+#include "util.h"
+#include "util_process.h"
+#include "crypto.h"
+#include "torlog.h"
+#include "test.h"
+
+#ifndef BUILDDIR
+#define BUILDDIR "."
+#endif
+
+#ifdef _WIN32
+#define notify_pending_waitpid_callbacks() STMT_NIL
+#define TEST_CHILD "test-child.exe"
+#define EOL "\r\n"
+#else
+#define TEST_CHILD (BUILDDIR "/src/test/test-child")
+#define EOL "\n"
+#endif
+
+#ifdef _WIN32
+/* I've assumed Windows doesn't have the gap between fork and exec
+ * that causes the race condition on unix-like platforms */
+#define MATCH_PROCESS_STATUS(s1,s2) ((s1) == (s2))
+
+#else
+/* work around a race condition of the timing of SIGCHLD handler updates
+ * to the process_handle's fields, and checks of those fields
+ *
+ * TODO: Once we can signal failure to exec, change PROCESS_STATUS_RUNNING to
+ * PROCESS_STATUS_ERROR (and similarly with *_OR_NOTRUNNING) */
+#define PROCESS_STATUS_RUNNING_OR_NOTRUNNING (PROCESS_STATUS_RUNNING+1)
+#define IS_RUNNING_OR_NOTRUNNING(s) \
+ ((s) == PROCESS_STATUS_RUNNING || (s) == PROCESS_STATUS_NOTRUNNING)
+/* well, this is ugly */
+#define MATCH_PROCESS_STATUS(s1,s2) \
+ ( (s1) == (s2) \
+ ||((s1) == PROCESS_STATUS_RUNNING_OR_NOTRUNNING \
+ && IS_RUNNING_OR_NOTRUNNING(s2)) \
+ ||((s2) == PROCESS_STATUS_RUNNING_OR_NOTRUNNING \
+ && IS_RUNNING_OR_NOTRUNNING(s1)))
+
+#endif // _WIN32
+
+/** Helper function for testing tor_spawn_background */
+static void
+run_util_spawn_background(const char *argv[], const char *expected_out,
+ const char *expected_err, int expected_exit,
+ int expected_status)
+{
+ int retval, exit_code;
+ ssize_t pos;
+ process_handle_t *process_handle=NULL;
+ char stdout_buf[100], stderr_buf[100];
+ int status;
+
+ /* Start the program */
+#ifdef _WIN32
+ status = tor_spawn_background(NULL, argv, NULL, &process_handle);
+#else
+ status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
+#endif
+
+ notify_pending_waitpid_callbacks();
+
+ /* the race condition doesn't affect status,
+ * because status isn't updated by the SIGCHLD handler,
+ * but we still need to handle PROCESS_STATUS_RUNNING_OR_NOTRUNNING */
+ tt_assert(MATCH_PROCESS_STATUS(expected_status, status));
+ if (status == PROCESS_STATUS_ERROR) {
+ tt_ptr_op(process_handle, OP_EQ, NULL);
+ return;
+ }
+
+ tt_assert(process_handle != NULL);
+
+ /* When a spawned process forks, fails, then exits very quickly,
+ * (this typically occurs when exec fails)
+ * there is a race condition between the SIGCHLD handler
+ * updating the process_handle's fields, and this test
+ * checking the process status in those fields.
+ * The SIGCHLD update can occur before or after the code below executes.
+ * This causes intermittent failures in spawn_background_fail(),
+ * typically when the machine is under load.
+ * We use PROCESS_STATUS_RUNNING_OR_NOTRUNNING to avoid this issue. */
+
+ /* the race condition affects the change in
+ * process_handle->status from RUNNING to NOTRUNNING */
+ tt_assert(MATCH_PROCESS_STATUS(expected_status, process_handle->status));
+
+#ifndef _WIN32
+ notify_pending_waitpid_callbacks();
+ /* the race condition affects the change in
+ * process_handle->waitpid_cb to NULL,
+ * so we skip the check if expected_status is ambiguous,
+ * that is, PROCESS_STATUS_RUNNING_OR_NOTRUNNING */
+ tt_assert(process_handle->waitpid_cb != NULL
+ || expected_status == PROCESS_STATUS_RUNNING_OR_NOTRUNNING);
+#endif
+
+#ifdef _WIN32
+ tt_assert(process_handle->stdout_pipe != INVALID_HANDLE_VALUE);
+ tt_assert(process_handle->stderr_pipe != INVALID_HANDLE_VALUE);
+ tt_assert(process_handle->stdin_pipe != INVALID_HANDLE_VALUE);
+#else
+ tt_assert(process_handle->stdout_pipe >= 0);
+ tt_assert(process_handle->stderr_pipe >= 0);
+ tt_assert(process_handle->stdin_pipe >= 0);
+#endif
+
+ /* Check stdout */
+ pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
+ sizeof(stdout_buf) - 1);
+ tt_assert(pos >= 0);
+ stdout_buf[pos] = '\0';
+ tt_int_op(strlen(expected_out),OP_EQ, pos);
+ tt_str_op(expected_out,OP_EQ, stdout_buf);
+
+ notify_pending_waitpid_callbacks();
+
+ /* Check it terminated correctly */
+ retval = tor_get_exit_code(process_handle, 1, &exit_code);
+ tt_int_op(PROCESS_EXIT_EXITED,OP_EQ, retval);
+ tt_int_op(expected_exit,OP_EQ, exit_code);
+ // TODO: Make test-child exit with something other than 0
+
+#ifndef _WIN32
+ notify_pending_waitpid_callbacks();
+ tt_ptr_op(process_handle->waitpid_cb, OP_EQ, NULL);
+#endif
+
+ /* Check stderr */
+ pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
+ sizeof(stderr_buf) - 1);
+ tt_assert(pos >= 0);
+ stderr_buf[pos] = '\0';
+ tt_str_op(expected_err,OP_EQ, stderr_buf);
+ tt_int_op(strlen(expected_err),OP_EQ, pos);
+
+ notify_pending_waitpid_callbacks();
+
+ done:
+ if (process_handle)
+ tor_process_handle_destroy(process_handle, 1);
+}
+
+/** Check that we can launch a process and read the output */
+static void
+test_util_spawn_background_ok(void *ptr)
+{
+ const char *argv[] = {TEST_CHILD, "--test", NULL};
+ const char *expected_out = "OUT"EOL "--test"EOL "SLEEPING"EOL "DONE" EOL;
+ const char *expected_err = "ERR"EOL;
+
+ (void)ptr;
+
+ run_util_spawn_background(argv, expected_out, expected_err, 0,
+ PROCESS_STATUS_RUNNING);
+}
+
+/** Check that failing to find the executable works as expected */
+static void
+test_util_spawn_background_fail(void *ptr)
+{
+ const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
+ const char *expected_err = "";
+ char expected_out[1024];
+ char code[32];
+#ifdef _WIN32
+ const int expected_status = PROCESS_STATUS_ERROR;
+#else
+ /* TODO: Once we can signal failure to exec, set this to be
+ * PROCESS_STATUS_RUNNING_OR_ERROR */
+ const int expected_status = PROCESS_STATUS_RUNNING_OR_NOTRUNNING;
+#endif
+
+ memset(expected_out, 0xf0, sizeof(expected_out));
+ memset(code, 0xf0, sizeof(code));
+
+ (void)ptr;
+
+ tor_snprintf(code, sizeof(code), "%x/%x",
+ 9 /* CHILD_STATE_FAILEXEC */ , ENOENT);
+ tor_snprintf(expected_out, sizeof(expected_out),
+ "ERR: Failed to spawn background process - code %s\n", code);
+
+ run_util_spawn_background(argv, expected_out, expected_err, 255,
+ expected_status);
+}
+
+/** Test that reading from a handle returns a partial read rather than
+ * blocking */
+static void
+test_util_spawn_background_partial_read_impl(int exit_early)
+{
+ const int expected_exit = 0;
+ const int expected_status = PROCESS_STATUS_RUNNING;
+
+ int retval, exit_code;
+ ssize_t pos = -1;
+ process_handle_t *process_handle=NULL;
+ int status;
+ char stdout_buf[100], stderr_buf[100];
+
+ const char *argv[] = {TEST_CHILD, "--test", NULL};
+ const char *expected_out[] = { "OUT" EOL "--test" EOL "SLEEPING" EOL,
+ "DONE" EOL,
+ NULL };
+ const char *expected_err = "ERR" EOL;
+
+#ifndef _WIN32
+ int eof = 0;
+#endif
+ int expected_out_ctr;
+
+ if (exit_early) {
+ argv[1] = "--hang";
+ expected_out[0] = "OUT"EOL "--hang"EOL "SLEEPING" EOL;
+ }
+
+ /* Start the program */
+#ifdef _WIN32
+ status = tor_spawn_background(NULL, argv, NULL, &process_handle);
+#else
+ status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
+#endif
+ tt_int_op(expected_status,OP_EQ, status);
+ tt_assert(process_handle);
+ tt_int_op(expected_status,OP_EQ, process_handle->status);
+
+ /* Check stdout */
+ for (expected_out_ctr = 0; expected_out[expected_out_ctr] != NULL;) {
+#ifdef _WIN32
+ pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
+ sizeof(stdout_buf) - 1, NULL);
+#else
+ /* Check that we didn't read the end of file last time */
+ tt_assert(!eof);
+ pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
+ sizeof(stdout_buf) - 1, NULL, &eof);
+#endif
+ log_info(LD_GENERAL, "tor_read_all_handle() returned %d", (int)pos);
+
+ /* We would have blocked, keep on trying */
+ if (0 == pos)
+ continue;
+
+ tt_assert(pos > 0);
+ stdout_buf[pos] = '\0';
+ tt_str_op(expected_out[expected_out_ctr],OP_EQ, stdout_buf);
+ tt_int_op(strlen(expected_out[expected_out_ctr]),OP_EQ, pos);
+ expected_out_ctr++;
+ }
+
+ if (exit_early) {
+ tor_process_handle_destroy(process_handle, 1);
+ process_handle = NULL;
+ goto done;
+ }
+
+ /* The process should have exited without writing more */
+#ifdef _WIN32
+ pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
+ sizeof(stdout_buf) - 1,
+ process_handle);
+ tt_int_op(0,OP_EQ, pos);
+#else
+ if (!eof) {
+ /* We should have got all the data, but maybe not the EOF flag */
+ pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
+ sizeof(stdout_buf) - 1,
+ process_handle, &eof);
+ tt_int_op(0,OP_EQ, pos);
+ tt_assert(eof);
+ }
+ /* Otherwise, we got the EOF on the last read */
+#endif
+
+ /* Check it terminated correctly */
+ retval = tor_get_exit_code(process_handle, 1, &exit_code);
+ tt_int_op(PROCESS_EXIT_EXITED,OP_EQ, retval);
+ tt_int_op(expected_exit,OP_EQ, exit_code);
+
+ // TODO: Make test-child exit with something other than 0
+
+ /* Check stderr */
+ pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
+ sizeof(stderr_buf) - 1);
+ tt_assert(pos >= 0);
+ stderr_buf[pos] = '\0';
+ tt_str_op(expected_err,OP_EQ, stderr_buf);
+ tt_int_op(strlen(expected_err),OP_EQ, pos);
+
+ done:
+ tor_process_handle_destroy(process_handle, 1);
+}
+
+static void
+test_util_spawn_background_partial_read(void *arg)
+{
+ (void)arg;
+ test_util_spawn_background_partial_read_impl(0);
+}
+
+static void
+test_util_spawn_background_exit_early(void *arg)
+{
+ (void)arg;
+ test_util_spawn_background_partial_read_impl(1);
+}
+
+static void
+test_util_spawn_background_waitpid_notify(void *arg)
+{
+ int retval, exit_code;
+ process_handle_t *process_handle=NULL;
+ int status;
+ int ms_timer;
+
+ const char *argv[] = {TEST_CHILD, "--fast", NULL};
+
+ (void) arg;
+
+#ifdef _WIN32
+ status = tor_spawn_background(NULL, argv, NULL, &process_handle);
+#else
+ status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
+#endif
+
+ tt_int_op(status, OP_EQ, PROCESS_STATUS_RUNNING);
+ tt_ptr_op(process_handle, OP_NE, NULL);
+
+ /* We're not going to look at the stdout/stderr output this time. Instead,
+ * we're testing whether notify_pending_waitpid_calbacks() can report the
+ * process exit (on unix) and/or whether tor_get_exit_code() can notice it
+ * (on windows) */
+
+#ifndef _WIN32
+ ms_timer = 30*1000;
+ tt_ptr_op(process_handle->waitpid_cb, OP_NE, NULL);
+ while (process_handle->waitpid_cb && ms_timer > 0) {
+ tor_sleep_msec(100);
+ ms_timer -= 100;
+ notify_pending_waitpid_callbacks();
+ }
+ tt_int_op(ms_timer, OP_GT, 0);
+ tt_ptr_op(process_handle->waitpid_cb, OP_EQ, NULL);
+#endif
+
+ ms_timer = 30*1000;
+ while (((retval = tor_get_exit_code(process_handle, 0, &exit_code))
+ == PROCESS_EXIT_RUNNING) && ms_timer > 0) {
+ tor_sleep_msec(100);
+ ms_timer -= 100;
+ }
+ tt_int_op(ms_timer, OP_GT, 0);
+
+ tt_int_op(retval, OP_EQ, PROCESS_EXIT_EXITED);
+
+ done:
+ tor_process_handle_destroy(process_handle, 1);
+}
+
+#undef TEST_CHILD
+#undef EOL
+
+#undef MATCH_PROCESS_STATUS
+
+#ifndef _WIN32
+#undef PROCESS_STATUS_RUNNING_OR_NOTRUNNING
+#undef IS_RUNNING_OR_NOTRUNNING
+#endif
+
+#define UTIL_TEST(name, flags) \
+ { #name, test_util_ ## name, flags, NULL, NULL }
+
+struct testcase_t slow_util_tests[] = {
+ UTIL_TEST(spawn_background_ok, 0),
+ UTIL_TEST(spawn_background_fail, 0),
+ UTIL_TEST(spawn_background_partial_read, 0),
+ UTIL_TEST(spawn_background_exit_early, 0),
+ UTIL_TEST(spawn_background_waitpid_notify, 0),
+ END_OF_TESTCASES
+};
+
diff --git a/src/test/test_workqueue.c b/src/test/test_workqueue.c
new file mode 100644
index 0000000000..cbcf596b22
--- /dev/null
+++ b/src/test/test_workqueue.c
@@ -0,0 +1,453 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+#include "compat_threads.h"
+#include "onion.h"
+#include "workqueue.h"
+#include "crypto.h"
+#include "crypto_curve25519.h"
+#include "compat_libevent.h"
+
+#include <stdio.h>
+#ifdef HAVE_EVENT2_EVENT_H
+#include <event2/event.h>
+#else
+#include <event.h>
+#endif
+
+#define MAX_INFLIGHT (1<<16)
+
+static int opt_verbose = 0;
+static int opt_n_threads = 8;
+static int opt_n_items = 10000;
+static int opt_n_inflight = 1000;
+static int opt_n_lowwater = 250;
+static int opt_n_cancel = 0;
+static int opt_ratio_rsa = 5;
+
+#ifdef TRACK_RESPONSES
+tor_mutex_t bitmap_mutex;
+int handled_len;
+bitarray_t *handled;
+#endif
+
+typedef struct state_s {
+ int magic;
+ int n_handled;
+ crypto_pk_t *rsa;
+ curve25519_secret_key_t ecdh;
+ int is_shutdown;
+} state_t;
+
+typedef struct rsa_work_s {
+ int serial;
+ uint8_t msg[128];
+ uint8_t msglen;
+} rsa_work_t;
+
+typedef struct ecdh_work_s {
+ int serial;
+ union {
+ curve25519_public_key_t pk;
+ uint8_t msg[32];
+ } u;
+} ecdh_work_t;
+
+static void
+mark_handled(int serial)
+{
+#ifdef TRACK_RESPONSES
+ tor_mutex_acquire(&bitmap_mutex);
+ tor_assert(serial < handled_len);
+ tor_assert(! bitarray_is_set(handled, serial));
+ bitarray_set(handled, serial);
+ tor_mutex_release(&bitmap_mutex);
+#else
+ (void)serial;
+#endif
+}
+
+static workqueue_reply_t
+workqueue_do_rsa(void *state, void *work)
+{
+ rsa_work_t *rw = work;
+ state_t *st = state;
+ crypto_pk_t *rsa = st->rsa;
+ uint8_t sig[256];
+ int len;
+
+ tor_assert(st->magic == 13371337);
+
+ len = crypto_pk_private_sign(rsa, (char*)sig, 256,
+ (char*)rw->msg, rw->msglen);
+ if (len < 0) {
+ rw->msglen = 0;
+ return WQ_RPL_ERROR;
+ }
+
+ memset(rw->msg, 0, sizeof(rw->msg));
+ rw->msglen = len;
+ memcpy(rw->msg, sig, len);
+ ++st->n_handled;
+
+ mark_handled(rw->serial);
+
+ return WQ_RPL_REPLY;
+}
+
+static workqueue_reply_t
+workqueue_do_shutdown(void *state, void *work)
+{
+ (void)state;
+ (void)work;
+ crypto_pk_free(((state_t*)state)->rsa);
+ tor_free(state);
+ return WQ_RPL_SHUTDOWN;
+}
+
+static workqueue_reply_t
+workqueue_do_ecdh(void *state, void *work)
+{
+ ecdh_work_t *ew = work;
+ uint8_t output[CURVE25519_OUTPUT_LEN];
+ state_t *st = state;
+
+ tor_assert(st->magic == 13371337);
+
+ curve25519_handshake(output, &st->ecdh, &ew->u.pk);
+ memcpy(ew->u.msg, output, CURVE25519_OUTPUT_LEN);
+ ++st->n_handled;
+ mark_handled(ew->serial);
+ return WQ_RPL_REPLY;
+}
+
+static workqueue_reply_t
+workqueue_shutdown_error(void *state, void *work)
+{
+ (void)state;
+ (void)work;
+ return WQ_RPL_REPLY;
+}
+
+static void *
+new_state(void *arg)
+{
+ state_t *st;
+ (void)arg;
+
+ st = tor_malloc(sizeof(*st));
+ /* Every thread gets its own keys. not a problem for benchmarking */
+ st->rsa = crypto_pk_new();
+ if (crypto_pk_generate_key_with_bits(st->rsa, 1024) < 0) {
+ crypto_pk_free(st->rsa);
+ tor_free(st);
+ return NULL;
+ }
+ curve25519_secret_key_generate(&st->ecdh, 0);
+ st->magic = 13371337;
+ return st;
+}
+
+static void
+free_state(void *arg)
+{
+ state_t *st = arg;
+ crypto_pk_free(st->rsa);
+ tor_free(st);
+}
+
+static tor_weak_rng_t weak_rng;
+static int n_sent = 0;
+static int rsa_sent = 0;
+static int ecdh_sent = 0;
+static int n_received = 0;
+static int no_shutdown = 0;
+
+#ifdef TRACK_RESPONSES
+bitarray_t *received;
+#endif
+
+static void
+handle_reply(void *arg)
+{
+#ifdef TRACK_RESPONSES
+ rsa_work_t *rw = arg; /* Naughty cast, but only looking at serial. */
+ tor_assert(! bitarray_is_set(received, rw->serial));
+ bitarray_set(received,rw->serial);
+#endif
+
+ tor_free(arg);
+ ++n_received;
+}
+
+/* This should never get called. */
+static void
+handle_reply_shutdown(void *arg)
+{
+ (void)arg;
+ no_shutdown = 1;
+}
+
+static workqueue_entry_t *
+add_work(threadpool_t *tp)
+{
+ int add_rsa =
+ opt_ratio_rsa == 0 ||
+ tor_weak_random_range(&weak_rng, opt_ratio_rsa) == 0;
+
+ if (add_rsa) {
+ rsa_work_t *w = tor_malloc_zero(sizeof(*w));
+ w->serial = n_sent++;
+ crypto_rand((char*)w->msg, 20);
+ w->msglen = 20;
+ ++rsa_sent;
+ return threadpool_queue_work(tp, workqueue_do_rsa, handle_reply, w);
+ } else {
+ ecdh_work_t *w = tor_malloc_zero(sizeof(*w));
+ w->serial = n_sent++;
+ /* Not strictly right, but this is just for benchmarks. */
+ crypto_rand((char*)w->u.pk.public_key, 32);
+ ++ecdh_sent;
+ return threadpool_queue_work(tp, workqueue_do_ecdh, handle_reply, w);
+ }
+}
+
+static int n_failed_cancel = 0;
+static int n_successful_cancel = 0;
+
+static int
+add_n_work_items(threadpool_t *tp, int n)
+{
+ int n_queued = 0;
+ int n_try_cancel = 0, i;
+ workqueue_entry_t **to_cancel;
+ workqueue_entry_t *ent;
+
+ to_cancel = tor_malloc(sizeof(workqueue_entry_t*) * opt_n_cancel);
+
+ while (n_queued++ < n) {
+ ent = add_work(tp);
+ if (! ent) {
+ puts("Z");
+ tor_event_base_loopexit(tor_libevent_get_base(), NULL);
+ return -1;
+ }
+ if (n_try_cancel < opt_n_cancel &&
+ tor_weak_random_range(&weak_rng, n) < opt_n_cancel) {
+ to_cancel[n_try_cancel++] = ent;
+ }
+ }
+
+ for (i = 0; i < n_try_cancel; ++i) {
+ void *work = workqueue_entry_cancel(to_cancel[i]);
+ if (! work) {
+ n_failed_cancel++;
+ } else {
+ n_successful_cancel++;
+ tor_free(work);
+ }
+ }
+
+ tor_free(to_cancel);
+ return 0;
+}
+
+static int shutting_down = 0;
+
+static void
+replysock_readable_cb(tor_socket_t sock, short what, void *arg)
+{
+ threadpool_t *tp = arg;
+ replyqueue_t *rq = threadpool_get_replyqueue(tp);
+
+ int old_r = n_received;
+ (void) sock;
+ (void) what;
+
+ replyqueue_process(rq);
+ if (old_r == n_received)
+ return;
+
+ if (opt_verbose) {
+ printf("%d / %d", n_received, n_sent);
+ if (opt_n_cancel)
+ printf(" (%d cancelled, %d uncancellable)",
+ n_successful_cancel, n_failed_cancel);
+ puts("");
+ }
+#ifdef TRACK_RESPONSES
+ tor_mutex_acquire(&bitmap_mutex);
+ for (i = 0; i < opt_n_items; ++i) {
+ if (bitarray_is_set(received, i))
+ putc('o', stdout);
+ else if (bitarray_is_set(handled, i))
+ putc('!', stdout);
+ else
+ putc('.', stdout);
+ }
+ puts("");
+ tor_mutex_release(&bitmap_mutex);
+#endif
+
+ if (n_sent - (n_received+n_successful_cancel) < opt_n_lowwater) {
+ int n_to_send = n_received + opt_n_inflight - n_sent;
+ if (n_to_send > opt_n_items - n_sent)
+ n_to_send = opt_n_items - n_sent;
+ add_n_work_items(tp, n_to_send);
+ }
+
+ if (shutting_down == 0 &&
+ n_received+n_successful_cancel == n_sent &&
+ n_sent >= opt_n_items) {
+ shutting_down = 1;
+ threadpool_queue_update(tp, NULL,
+ workqueue_do_shutdown, NULL, NULL);
+ // Anything we add after starting the shutdown must not be executed.
+ threadpool_queue_work(tp, workqueue_shutdown_error,
+ handle_reply_shutdown, NULL);
+ {
+ struct timeval limit = { 2, 0 };
+ tor_event_base_loopexit(tor_libevent_get_base(), &limit);
+ }
+ }
+}
+
+static void
+help(void)
+{
+ puts(
+ "Options:\n"
+ " -h Display this information\n"
+ " -v Be verbose\n"
+ " -N <items> Run this many items of work\n"
+ " -T <threads> Use this many threads\n"
+ " -I <inflight> Have no more than this many requests queued at once\n"
+ " -L <lowwater> Add items whenever fewer than this many are pending\n"
+ " -C <cancel> Try to cancel N items of every batch that we add\n"
+ " -R <ratio> Make one out of this many items be a slow (RSA) one\n"
+ " --no-{eventfd2,eventfd,pipe2,pipe,socketpair}\n"
+ " Disable one of the alert_socket backends.");
+}
+
+int
+main(int argc, char **argv)
+{
+ replyqueue_t *rq;
+ threadpool_t *tp;
+ int i;
+ tor_libevent_cfg evcfg;
+ struct event *ev;
+ uint32_t as_flags = 0;
+
+ for (i = 1; i < argc; ++i) {
+ if (!strcmp(argv[i], "-v")) {
+ opt_verbose = 1;
+ } else if (!strcmp(argv[i], "-T") && i+1<argc) {
+ opt_n_threads = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "-N") && i+1<argc) {
+ opt_n_items = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "-I") && i+1<argc) {
+ opt_n_inflight = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "-L") && i+1<argc) {
+ opt_n_lowwater = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "-R") && i+1<argc) {
+ opt_ratio_rsa = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "-C") && i+1<argc) {
+ opt_n_cancel = atoi(argv[++i]);
+ } else if (!strcmp(argv[i], "--no-eventfd2")) {
+ as_flags |= ASOCKS_NOEVENTFD2;
+ } else if (!strcmp(argv[i], "--no-eventfd")) {
+ as_flags |= ASOCKS_NOEVENTFD;
+ } else if (!strcmp(argv[i], "--no-pipe2")) {
+ as_flags |= ASOCKS_NOPIPE2;
+ } else if (!strcmp(argv[i], "--no-pipe")) {
+ as_flags |= ASOCKS_NOPIPE;
+ } else if (!strcmp(argv[i], "--no-socketpair")) {
+ as_flags |= ASOCKS_NOSOCKETPAIR;
+ } else if (!strcmp(argv[i], "-h")) {
+ help();
+ return 0;
+ } else {
+ help();
+ return 1;
+ }
+ }
+
+ if (opt_n_threads < 1 ||
+ opt_n_items < 1 || opt_n_inflight < 1 || opt_n_lowwater < 0 ||
+ opt_n_cancel > opt_n_inflight || opt_n_inflight > MAX_INFLIGHT ||
+ opt_ratio_rsa < 0) {
+ help();
+ return 1;
+ }
+
+ if (opt_n_inflight > opt_n_items) {
+ opt_n_inflight = opt_n_items;
+ }
+
+ init_logging(1);
+ network_init();
+ if (crypto_global_init(1, NULL, NULL) < 0) {
+ printf("Couldn't initialize crypto subsystem; exiting.\n");
+ return 1;
+ }
+ if (crypto_seed_rng() < 0) {
+ printf("Couldn't seed RNG; exiting.\n");
+ return 1;
+ }
+
+ rq = replyqueue_new(as_flags);
+ tor_assert(rq);
+ tp = threadpool_new(opt_n_threads,
+ rq, new_state, free_state, NULL);
+ tor_assert(tp);
+
+ crypto_seed_weak_rng(&weak_rng);
+
+ memset(&evcfg, 0, sizeof(evcfg));
+ tor_libevent_initialize(&evcfg);
+
+ ev = tor_event_new(tor_libevent_get_base(),
+ replyqueue_get_socket(rq), EV_READ|EV_PERSIST,
+ replysock_readable_cb, tp);
+
+ event_add(ev, NULL);
+
+#ifdef TRACK_RESPONSES
+ handled = bitarray_init_zero(opt_n_items);
+ received = bitarray_init_zero(opt_n_items);
+ tor_mutex_init(&bitmap_mutex);
+ handled_len = opt_n_items;
+#endif
+
+ for (i = 0; i < opt_n_inflight; ++i) {
+ if (! add_work(tp)) {
+ puts("Couldn't add work.");
+ return 1;
+ }
+ }
+
+ {
+ struct timeval limit = { 180, 0 };
+ tor_event_base_loopexit(tor_libevent_get_base(), &limit);
+ }
+
+ event_base_loop(tor_libevent_get_base(), 0);
+
+ if (n_sent != opt_n_items || n_received+n_successful_cancel != n_sent) {
+ printf("%d vs %d\n", n_sent, opt_n_items);
+ printf("%d+%d vs %d\n", n_received, n_successful_cancel, n_sent);
+ puts("FAIL");
+ return 1;
+ } else if (no_shutdown) {
+ puts("Accepted work after shutdown\n");
+ puts("FAIL");
+ } else {
+ puts("OK");
+ return 0;
+ }
+}
+
diff --git a/src/test/test_zero_length_keys.sh b/src/test/test_zero_length_keys.sh
new file mode 100755
index 0000000000..f85edb68db
--- /dev/null
+++ b/src/test/test_zero_length_keys.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Check that tor regenerates keys when key files are zero-length
+
+exitcode=0
+
+"${SHELL:-sh}" "${abs_top_srcdir:-.}/src/test/zero_length_keys.sh" "${builddir:-.}/src/or/tor" -z || exitcode=1
+"${SHELL:-sh}" "${abs_top_srcdir:-.}/src/test/zero_length_keys.sh" "${builddir:-.}/src/or/tor" -d || exitcode=1
+"${SHELL:-sh}" "${abs_top_srcdir:-.}/src/test/zero_length_keys.sh" "${builddir:-.}/src/or/tor" -e || exitcode=1
+
+exit ${exitcode}
diff --git a/src/test/testing_common.c b/src/test/testing_common.c
new file mode 100644
index 0000000000..39c3d02ab1
--- /dev/null
+++ b/src/test/testing_common.c
@@ -0,0 +1,315 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2016, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/* Ordinarily defined in tor_main.c; this bit is just here to provide one
+ * since we're not linking to tor_main.c */
+const char tor_git_revision[] = "";
+
+/**
+ * \file test_common.c
+ * \brief Common pieces to implement unit tests.
+ **/
+
+#include "orconfig.h"
+#include "or.h"
+#include "control.h"
+#include "config.h"
+#include "rephist.h"
+#include "backtrace.h"
+#include "test.h"
+
+#include <stdio.h>
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#ifdef _WIN32
+/* For mkdir() */
+#include <direct.h>
+#else
+#include <dirent.h>
+#endif
+
+#include "or.h"
+
+#ifdef USE_DMALLOC
+#include <dmalloc.h>
+#include <openssl/crypto.h>
+#include "main.h"
+#endif
+
+/** Temporary directory (set up by setup_directory) under which we store all
+ * our files during testing. */
+static char temp_dir[256];
+#ifdef _WIN32
+#define pid_t int
+#endif
+static pid_t temp_dir_setup_in_pid = 0;
+
+/** Select and create the temporary directory we'll use to run our unit tests.
+ * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
+ * idempotent. */
+static void
+setup_directory(void)
+{
+ static int is_setup = 0;
+ int r;
+ char rnd[256], rnd32[256];
+ if (is_setup) return;
+
+/* Due to base32 limitation needs to be a multiple of 5. */
+#define RAND_PATH_BYTES 5
+ crypto_rand(rnd, RAND_PATH_BYTES);
+ base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
+
+#ifdef _WIN32
+ {
+ char buf[MAX_PATH];
+ const char *tmp = buf;
+ const char *extra_backslash = "";
+ /* If this fails, we're probably screwed anyway */
+ if (!GetTempPathA(sizeof(buf),buf))
+ tmp = "c:\\windows\\temp\\";
+ if (strcmpend(tmp, "\\")) {
+ /* According to MSDN, it should be impossible for GetTempPath to give us
+ * an answer that doesn't end with \. But let's make sure. */
+ extra_backslash = "\\";
+ }
+ tor_snprintf(temp_dir, sizeof(temp_dir),
+ "%s%stor_test_%d_%s", tmp, extra_backslash,
+ (int)getpid(), rnd32);
+ r = mkdir(temp_dir);
+ }
+#else
+ tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
+ (int) getpid(), rnd32);
+ r = mkdir(temp_dir, 0700);
+ if (!r) {
+ /* undo sticky bit so tests don't get confused. */
+ r = chown(temp_dir, getuid(), getgid());
+ }
+#endif
+ if (r) {
+ fprintf(stderr, "Can't create directory %s:", temp_dir);
+ perror("");
+ exit(1);
+ }
+ is_setup = 1;
+ temp_dir_setup_in_pid = getpid();
+}
+
+/** Return a filename relative to our testing temporary directory */
+const char *
+get_fname(const char *name)
+{
+ static char buf[1024];
+ setup_directory();
+ if (!name)
+ return temp_dir;
+ tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
+ return buf;
+}
+
+/* Remove a directory and all of its subdirectories */
+static void
+rm_rf(const char *dir)
+{
+ struct stat st;
+ smartlist_t *elements;
+
+ elements = tor_listdir(dir);
+ if (elements) {
+ SMARTLIST_FOREACH_BEGIN(elements, const char *, cp) {
+ char *tmp = NULL;
+ tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
+ if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
+ rm_rf(tmp);
+ } else {
+ if (unlink(tmp)) {
+ fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
+ }
+ }
+ tor_free(tmp);
+ } SMARTLIST_FOREACH_END(cp);
+ SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
+ smartlist_free(elements);
+ }
+ if (rmdir(dir))
+ fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
+}
+
+/** Remove all files stored under the temporary directory, and the directory
+ * itself. Called by atexit(). */
+static void
+remove_directory(void)
+{
+ if (getpid() != temp_dir_setup_in_pid) {
+ /* Only clean out the tempdir when the main process is exiting. */
+ return;
+ }
+
+ rm_rf(temp_dir);
+}
+
+/** Define this if unit tests spend too much time generating public keys*/
+#undef CACHE_GENERATED_KEYS
+
+static crypto_pk_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
+#define N_PREGEN_KEYS ARRAY_LENGTH(pregen_keys)
+
+/** Generate and return a new keypair for use in unit tests. If we're using
+ * the key cache optimization, we might reuse keys: we only guarantee that
+ * keys made with distinct values for <b>idx</b> are different. The value of
+ * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
+crypto_pk_t *
+pk_generate(int idx)
+{
+ int res;
+#ifdef CACHE_GENERATED_KEYS
+ tor_assert(idx < N_PREGEN_KEYS);
+ if (! pregen_keys[idx]) {
+ pregen_keys[idx] = crypto_pk_new();
+ res = crypto_pk_generate_key(pregen_keys[idx]);
+ tor_assert(!res);
+ }
+ return crypto_pk_dup_key(pregen_keys[idx]);
+#else
+ crypto_pk_t *result;
+ (void) idx;
+ result = crypto_pk_new();
+ res = crypto_pk_generate_key(result);
+ tor_assert(!res);
+ return result;
+#endif
+}
+
+/** Free all storage used for the cached key optimization. */
+static void
+free_pregenerated_keys(void)
+{
+ unsigned idx;
+ for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
+ if (pregen_keys[idx]) {
+ crypto_pk_free(pregen_keys[idx]);
+ pregen_keys[idx] = NULL;
+ }
+ }
+}
+
+static void *
+passthrough_test_setup(const struct testcase_t *testcase)
+{
+ return testcase->setup_data;
+}
+static int
+passthrough_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ (void)testcase;
+ (void)ptr;
+ return 1;
+}
+
+const struct testcase_setup_t passthrough_setup = {
+ passthrough_test_setup, passthrough_test_cleanup
+};
+
+extern struct testgroup_t testgroups[];
+
+/** Main entry point for unit test code: parse the command line, and run
+ * some unit tests. */
+int
+main(int c, const char **v)
+{
+ or_options_t *options;
+ char *errmsg = NULL;
+ int i, i_out;
+ int loglevel = LOG_ERR;
+ int accel_crypto = 0;
+
+ /* We must initialise logs before we call tor_assert() */
+ init_logging(1);
+
+#ifdef USE_DMALLOC
+ {
+ int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
+ tor_assert(r);
+ }
+#endif
+
+ update_approx_time(time(NULL));
+ options = options_new();
+ tor_threads_init();
+
+ network_init();
+
+ struct tor_libevent_cfg cfg;
+ memset(&cfg, 0, sizeof(cfg));
+ tor_libevent_initialize(&cfg);
+
+ control_initialize_event_queue();
+ configure_backtrace_handler(get_version());
+
+ for (i_out = i = 1; i < c; ++i) {
+ if (!strcmp(v[i], "--warn")) {
+ loglevel = LOG_WARN;
+ } else if (!strcmp(v[i], "--notice")) {
+ loglevel = LOG_NOTICE;
+ } else if (!strcmp(v[i], "--info")) {
+ loglevel = LOG_INFO;
+ } else if (!strcmp(v[i], "--debug")) {
+ loglevel = LOG_DEBUG;
+ } else if (!strcmp(v[i], "--accel")) {
+ accel_crypto = 1;
+ } else {
+ v[i_out++] = v[i];
+ }
+ }
+ c = i_out;
+
+ {
+ log_severity_list_t s;
+ memset(&s, 0, sizeof(s));
+ set_log_severity_config(loglevel, LOG_ERR, &s);
+ add_stream_log(&s, "", fileno(stdout));
+ }
+
+ options->command = CMD_RUN_UNITTESTS;
+ if (crypto_global_init(accel_crypto, NULL, NULL)) {
+ printf("Can't initialize crypto subsystem; exiting.\n");
+ return 1;
+ }
+ crypto_set_tls_dh_prime();
+ if (crypto_seed_rng() < 0) {
+ printf("Couldn't seed RNG; exiting.\n");
+ return 1;
+ }
+ rep_hist_init();
+ setup_directory();
+ options_init(options);
+ options->DataDirectory = tor_strdup(temp_dir);
+ options->EntryStatistics = 1;
+ if (set_options(options, &errmsg) < 0) {
+ printf("Failed to set initial options: %s\n", errmsg);
+ tor_free(errmsg);
+ return 1;
+ }
+
+ atexit(remove_directory);
+
+ int have_failed = (tinytest_main(c, v, testgroups) != 0);
+
+ free_pregenerated_keys();
+#ifdef USE_DMALLOC
+ tor_free_all(0);
+ dmalloc_log_unfreed();
+#endif
+ crypto_global_cleanup();
+
+ if (have_failed)
+ return 1;
+ else
+ return 0;
+}
+
diff --git a/src/test/vote_descriptors.inc b/src/test/vote_descriptors.inc
new file mode 100644
index 0000000000..c5ce21f744
--- /dev/null
+++ b/src/test/vote_descriptors.inc
@@ -0,0 +1,94 @@
+const char* VOTE_BODY_V3 =
+"network-status-version 3\n"
+"vote-status vote\n"
+"consensus-methods 13 14 15 16 17 18 19 20 21\n"
+"published 2015-09-02 19:34:15\n"
+"valid-after 2015-09-02 19:50:55\n"
+"fresh-until 2015-09-02 20:07:38\n"
+"valid-until 2015-09-02 20:24:15\n"
+"voting-delay 100 250\n"
+"client-versions 0.1.2.14,0.1.2.17\n"
+"server-versions 0.1.2.10,0.1.2.15,0.1.2.16\n"
+"known-flags Authority Exit Fast Guard MadeOfCheese MadeOfTin Running Stable V2Dir Valid\n"
+"flag-thresholds stable-uptime=0 stable-mtbf=0 fast-speed=0 guard-wfu=0.000% guard-tk=0 guard-bw-inc-exits=0 guard-bw-exc-exits=0 enough-mtbf=0 ignoring-advertised-bws=0\n"
+"params circuitwindow=80 foo=660\n"
+"dir-source Voter3 D867ACF56A9D229B35C25F0090BC9867E906BE69 3.4.5.6 3.4.5.6 80 9000\n"
+"contact voter@example.com\n"
+"legacy-dir-key 4141414141414141414141414141414141414141\n"
+"dir-key-certificate-version 3\n"
+"fingerprint D867ACF56A9D229B35C25F0090BC9867E906BE69\n"
+"dir-key-published 2008-12-12 18:07:24\n"
+"dir-key-expires 2009-12-12 18:07:24\n"
+"dir-identity-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIIBigKCAYEAveMpKlw8oD1YqFqpJchuwSR82BDhutbqgHiez3QO9FmzOctJpV+Y\n"
+"mpTYIJLS/qC+4GBKFF1VK0C4SoBrS3zri0qdXdE+vBGcyrxrjMklpxoqSKRY2011\n"
+"4eqYPghKlo5RzuqteBclGCHyNxWjUJeRKDWgvh+U/gr2uYM6fRm5q0fCzg4aECE7\n"
+"VP6fDGZrMbQI8jHpiMSoC9gkUASNEa6chLInlnP8/H5qUEW4TB9CN/q095pefuwL\n"
+"P+F+1Nz5hnM7fa5XmeMB8iM4RriUmOQlLBZgpQBMpEfWMIPcR9F1Gh3MxERqqUcH\n"
+"tmij+IZdeXg9OkCXykcabaYIhZD3meErn9Tax4oA/THduLfgli9zM0ExwzH1OooN\n"
+"L8rIcJ+2eBo3bQiQUbdYW71sl9w7nSPtircbJUa1mUvWYLPWQxFliPiQSetgJLMj\n"
+"VQqtPmV2hvN2Xk3lLfJO50qMTK7w7Gsaw8UtV4YDM1Hcjp/hQaIB1xfwhXgl+eUU\n"
+"btUa4c+cUTjHAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"dir-signing-key\n"
+"-----BEGIN RSA PUBLIC KEY-----\n"
+"MIGJAoGBALPSUInyuEu6NV3NjozplaniIEBzQXEjv1x9/+mqnwZABpYVmuy9A8nx\n"
+"eoyY3sZFsnYwNW/IZjAgG23pEmevu3F+L4myMjjaa6ORl3MgRYQ4gmuFqpefrGdm\n"
+"ywRCleh2JerkQ4VxOuq10dn/abITzLyaZzMw30KXWp5pxKXOLtxFAgMBAAE=\n"
+"-----END RSA PUBLIC KEY-----\n"
+"dir-key-crosscert\n"
+"-----BEGIN ID SIGNATURE-----\n"
+"FTBJNR/Hlt4T53yUMp1r/QCSMCpkHJCbYBT0R0pvYqhqFfYN5qHRSICRXaFFImIF\n"
+"0DGWmwRza6DxPKNzkm5/b7I0de9zJW1jNNdQAQK5xppAtQcAafRdu8cBonnmh9KX\n"
+"k1NrAK/X00FYywju3yl/SxCn1GddVNkHYexEudmJMPM=\n"
+"-----END ID SIGNATURE-----\n"
+"dir-key-certification\n"
+"-----BEGIN SIGNATURE-----\n"
+"pjWguLFBfELZDc6DywL6Do21SCl7LcutfpM92MEn4WYeSNcTXNR6lRX7reOEJk4e\n"
+"NwEaMt+Hl7slgeR5wjnW3OmMmRPZK9bquNWbfD+sAOV9bRFZTpXIdleAQFPlwvMF\n"
+"z/Gzwspzn4i2Yh6hySShrctMmW8YL3OM8LsBXzBhp/rG2uHlsxmIsc13DA6HWt61\n"
+"ffY72uNE6KckDGsQ4wPGP9q69y6g+X+TNio1KPbsILbePv6EjbO+rS8FiS4njPlg\n"
+"SPYry1RaUvxzxTkswIzdE1tjJrUiqpbWlTGxrH9N4OszoLm45Pc784KLULrjKIoi\n"
+"Q+vRsGrcMBAa+kDowWU6H1ryKR7KOhzRTcf2uqLE/W3ezaRwmOG+ETmoVFwbhk2X\n"
+"OlbXEM9fWP+INvFkr6Z93VYL2jGkCjV7e3xXmre/Lb92fUcYi6t5dwzfV8gJnIoG\n"
+"eCHd0K8NrQK0ipVk/7zcPDKOPeo9Y5aj/f6X/pDHtb+Dd5sT+l82G/Tqy4DIYUYR\n"
+"-----END SIGNATURE-----\n"
+"r router2 AwMDAwMDAwMDAwMDAwMDAwMDAwM Tk5OTk5OTk5OTk5OTk5OTk5OTk4 2015-09-02 19:09:15 153.0.136.1 443 8000\n"
+"s Running V2Dir\n"
+"v 0.1.2.14\n"
+"w Bandwidth=30 Measured=30\n"
+"p reject 1-65535\n"
+"id ed25519 none\n"
+"m 9,10,11,12,13,14,15,16,17 sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa0\n"
+"r router1 BQUFBQUFBQUFBQUFBQUFBQUFBQU TU1NTU1NTU1NTU1NTU1NTU1NTU0 2015-09-02 19:17:35 153.0.153.1 443 0\n"
+"a [1:2:3::4]:4711\n"
+"s Exit Fast Guard Running Stable Valid\n"
+"v 0.2.0.5\n"
+"w Bandwidth=120 Measured=120\n"
+"p reject 1-65535\n"
+"id ed25519 none\n"
+"m 9,10,11,12,13,14,15,16,17 sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa1\n"
+"r router3 MzMzMzMzMzMzMzMzMzMzMzMzMzM T09PT09PT09PT09PT09PT09PT08 2015-09-02 19:17:35 170.0.153.1 400 9999\n"
+"s Authority Exit Fast Guard Running Stable V2Dir Valid\n"
+"v 0.1.0.3\n"
+"w Bandwidth=120\n"
+"p reject 1-65535\n"
+"id ed25519 none\n"
+"m 9,10,11,12,13,14,15,16,17 "
+"sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa2\n"
+"r router4 NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ Ly8vLy8vLy8vLy8vLy8vLy8vLy8 2015-09-02 19:17:35 192.0.2.3 500 1999\n"
+"s Running V2Dir\n"
+"v 0.1.6.3\n"
+"w Bandwidth=30\n"
+"p reject 1-65535\n"
+"id ed25519 none\n"
+"m 9,10,11,12,13,14,15,16,17 sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa3\n"
+"directory-footer\n"
+"directory-signature D867ACF56A9D229B35C25F0090BC9867E906BE69 CBF56A83368A5150F1A9AAADAFB4D77F8C4170E2\n"
+"-----BEGIN SIGNATURE-----\n"
+"AHiWcHe+T3XbnlQqvqSAk6RY3XmEy1+hM2u9Xk6BNi7BpQkEQM1f0vzRpgn5Dnf2\n"
+"TXQWGUq9Z7jdSVnzWT3xqPA4zjw6eZkj+DKUtwq+oEDZGlf8eHTFmr0NAWfwZbk9\n"
+"NAjbMTUXUP37N2XAZwkoCWwFCrrfMwXrL7OhZbj7ifo=\n"
+"-----END SIGNATURE-----\n";
+
diff --git a/src/test/zero_length_keys.sh b/src/test/zero_length_keys.sh
new file mode 100755
index 0000000000..3c61f8d465
--- /dev/null
+++ b/src/test/zero_length_keys.sh
@@ -0,0 +1,126 @@
+#!/bin/sh
+# Check that tor regenerates keys when key files are zero-length
+# Test for bug #13111 - Tor fails to start if onion keys are zero length
+#
+# Usage:
+# ./zero_length_keys.sh PATH_TO_TOR
+# Run all the tests below
+# ./zero_length_keys.sh PATH_TO_TOR -z
+# Check tor will launch and regenerate zero-length keys
+# ./zero_length_keys.sh PATH_TO_TOR -d
+# Check tor regenerates deleted keys (existing behaviour)
+# ./zero_length_keys.sh PATH_TO_TOR -e
+# Check tor does not overwrite existing keys (existing behaviour)
+#
+# Exit Statuses:
+# 0: test succeeded - tor regenerated/kept the files
+# 1: test failed - tor did not regenerate/keep the files
+# 2: test failed - tor did not generate the key files on first run
+# 3: a command failed - the test could not be completed
+#
+
+if [ $# -eq 0 ] || [ ! -f ${1} ] || [ ! -x ${1} ]; then
+ echo "Usage: ${0} PATH_TO_TOR [-z|-d|-e]"
+ exit 1
+elif [ $# -eq 1 ]; then
+ echo "Testing that tor correctly handles zero-length keys"
+ "$0" "${1}" -z && "$0" "${1}" -d && "$0" "${1}" -e
+ exit $?
+else #[$# -gt 1 ]; then
+ TOR_BINARY="${1}"
+ shift
+fi
+
+DATA_DIR=`mktemp -d -t tor_zero_length_keys.XXXXXX`
+if [ -z "$DATA_DIR" ]; then
+ echo "Failure: mktemp invocation returned empty string" >&2
+ exit 3
+fi
+if [ ! -d "$DATA_DIR" ]; then
+ echo "Failure: mktemp invocation result doesn't point to directory" >&2
+ exit 3
+fi
+trap "rm -rf '$DATA_DIR'" 0
+
+touch "$DATA_DIR"/empty_torrc
+
+# DisableNetwork means that the ORPort won't actually be opened.
+# 'ExitRelay 0' suppresses a warning.
+TOR="${TOR_BINARY} --hush --DisableNetwork 1 --ShutdownWaitLength 0 --ORPort 12345 --ExitRelay 0 -f $DATA_DIR/empty_torrc"
+
+if [ -s "$DATA_DIR"/keys/secret_id_key ] && [ -s "$DATA_DIR"/keys/secret_onion_key ] &&
+ [ -s "$DATA_DIR"/keys/secret_onion_key_ntor ]; then
+ echo "Failure: Previous tor keys present in tor data directory" >&2
+ exit 3
+else
+ echo "Generating initial tor keys"
+ $TOR --DataDirectory "$DATA_DIR" --list-fingerprint
+
+ # tor must successfully generate non-zero-length key files
+ if [ -s "$DATA_DIR"/keys/secret_id_key ] && [ -s "$DATA_DIR"/keys/secret_onion_key ] &&
+ [ -s "$DATA_DIR"/keys/secret_onion_key_ntor ]; then
+ true #echo "tor generated the initial key files"
+ else
+ echo "Failure: tor failed to generate the initial key files"
+ exit 2
+ fi
+fi
+
+#ls -lh "$DATA_DIR"/keys/ || exit 3
+
+# backup and keep/delete/create zero-length files for the keys
+
+FILE_DESC="keeps existing"
+# make a backup
+cp -r "$DATA_DIR"/keys "$DATA_DIR"/keys.old
+
+# delete keys for -d or -z
+if [ "$1" != "-e" ]; then
+ FILE_DESC="regenerates deleted"
+ rm "$DATA_DIR"/keys/secret_id_key || exit 3
+ rm "$DATA_DIR"/keys/secret_onion_key || exit 3
+ rm "$DATA_DIR"/keys/secret_onion_key_ntor || exit 3
+fi
+
+# create empty files for -z
+if [ "$1" = "-z" ]; then
+ FILE_DESC="regenerates zero-length"
+ touch "$DATA_DIR"/keys/secret_id_key || exit 3
+ touch "$DATA_DIR"/keys/secret_onion_key || exit 3
+ touch "$DATA_DIR"/keys/secret_onion_key_ntor || exit 3
+fi
+
+echo "Running tor again to check if it $FILE_DESC keys"
+$TOR --DataDirectory "$DATA_DIR" --list-fingerprint
+
+#ls -lh "$DATA_DIR"/keys/ || exit 3
+
+# tor must always have non-zero-length key files
+if [ -s "$DATA_DIR"/keys/secret_id_key ] && [ -s "$DATA_DIR"/keys/secret_onion_key ] &&
+ [ -s "$DATA_DIR"/keys/secret_onion_key_ntor ]; then
+ # check if the keys are different to the old ones
+ diff -q -r "$DATA_DIR"/keys "$DATA_DIR"/keys.old > /dev/null
+ SAME_KEYS=$?
+ # if we're not testing existing keys,
+ # the current keys should be different to the old ones
+ if [ "$1" != "-e" ]; then
+ if [ $SAME_KEYS -ne 0 ]; then
+ echo "Success: test that tor $FILE_DESC key files: different keys"
+ exit 0
+ else
+ echo "Failure: test that tor $FILE_DESC key files: same keys"
+ exit 1
+ fi
+ else #[ "$1" == "-e" ]; then
+ if [ $SAME_KEYS -eq 0 ]; then
+ echo "Success: test that tor $FILE_DESC key files: same keys"
+ exit 0
+ else
+ echo "Failure: test that tor $FILE_DESC key files: different keys"
+ exit 1
+ fi
+ fi
+else
+ echo "Failure: test that tor $FILE_DESC key files: no key files"
+ exit 1
+fi